Javascript calling eval on an object literal (with functions) - javascript

Disclaimer: I fully understand the risks/downsides of using eval but this is one niche case where I couldn't find any other way.
In Google Apps Scripting, there still is no built-in capability to import a script as a library so many sheets can use the same code; but, there is a facility built-in where I can import text from a plaintext file.
Here's the eval-ing code:
var id = [The-docID-goes-here];
var code = DocsList.getFileById(id).getContentAsString();
var lib = eval(code);
Logger.log(lib.fetchDate());
Here's some example code I'm using in the external file:
{
fetchDate: function() {
var d = new Date();
var dateString = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
return dateString;
}
}
What I'm aiming for is to drop a big object literal (containing all the library code) onto a local variable so I can reference it's properties/functions like they're contained in their own namespace.

Replace var lib = eval(code); with:
var lib = eval('(' + code + ')');
When the parens are omitted, the curly braces are being interpreted as markers of a block of code. As a result, the return value of eval is the fetchData function, instead of a object containing the function.
When the function name is missing, the code inside the block is read as a labelled anonymous function statement, which is not valid.
After adding the parens, the curly braces are used as object literals (as intended), and the return value of eval is an object, with the fetchData method. Then, your code will work.

You cannot evaluate
{
fetchDate: function() {
var d = new Date();
var dateString = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
return dateString;
}
}
Because it is not a valid expression (Object literals on their own are interpreted as blocks. fetch: function () { } is not a valid expression).
Try
var myLibName = {
fetchDate: function() {
var d = new Date();
var dateString = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
return dateString;
}
};

Related

Use javascript object containing functions as string in nashorn [duplicate]

Disclaimer: I fully understand the risks/downsides of using eval but this is one niche case where I couldn't find any other way.
In Google Apps Scripting, there still is no built-in capability to import a script as a library so many sheets can use the same code; but, there is a facility built-in where I can import text from a plaintext file.
Here's the eval-ing code:
var id = [The-docID-goes-here];
var code = DocsList.getFileById(id).getContentAsString();
var lib = eval(code);
Logger.log(lib.fetchDate());
Here's some example code I'm using in the external file:
{
fetchDate: function() {
var d = new Date();
var dateString = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
return dateString;
}
}
What I'm aiming for is to drop a big object literal (containing all the library code) onto a local variable so I can reference it's properties/functions like they're contained in their own namespace.
Replace var lib = eval(code); with:
var lib = eval('(' + code + ')');
When the parens are omitted, the curly braces are being interpreted as markers of a block of code. As a result, the return value of eval is the fetchData function, instead of a object containing the function.
When the function name is missing, the code inside the block is read as a labelled anonymous function statement, which is not valid.
After adding the parens, the curly braces are used as object literals (as intended), and the return value of eval is an object, with the fetchData method. Then, your code will work.
You cannot evaluate
{
fetchDate: function() {
var d = new Date();
var dateString = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
return dateString;
}
}
Because it is not a valid expression (Object literals on their own are interpreted as blocks. fetch: function () { } is not a valid expression).
Try
var myLibName = {
fetchDate: function() {
var d = new Date();
var dateString = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
return dateString;
}
};

how can call javascript from c# ext.net

in my project when i run it in chrome it is showing wrong time. explorer it is showing true. So i write this js code but it is still doesnt working.
This is my js;
var FormatTrxStartDate = function (value, record) {
var processDate = new Date(value);
return processDate.getDate() + "." + (processDate.getMonth() + 1) + "." +
processDate.getFullYear() + " " + processDate.getHours() + ":" +
processDate.getMinutes() + ":" + processDate.getSeconds();
};
And this is where i use it;
<ext:ModelField Name="TrxStartDate" Type="String" >
<Convert Fn='FormatTrxStartDate' />
</ext:ModelField>
Pass Parameter Value in not proper Date Format
Use processDate.getFullYear()==> processDate.getFullYear().toDateString() date data convert into String
X.Js.Call("FormatTrxStartDate ",value,record);
please try this code

Modify angular grid component format exported columns

I'm using the ag-grid component in my code and would like to ensure that date columns are formatted according to the customers needs when exported as CSV. A default format for a js Date object is used currently. The code can be found here:
https://github.com/ceolter/ag-grid/blob/master/src/ts/csvCreator.ts
I could make the following change to the code directly, but this is obviously bad practice. I'm fairly new to JavaScript and was wondering if there is a standard way to extend/override functionality in a library like this.
Proposed change (Note this shows the change I made to the js version not the github version which uses ts):
--- Common/scripts/agGrid/ag-grid.js (revision b0e7d54e61e6371b0cab94428cb4329f9f62db11)
+++ Common/scripts/agGrid/ag-grid.js (revision )
## -1848,7 +1848,11 ##
+ var exportDateAs = function(dt){if (dt instanceof Date)
+ return dt.getFullYear() + "/" + (dt.getMonth()+1) + "/" + dt.getDate();
+ };
## -1883,6 +1887,9 ##
+ if (valueForCell instanceof Date){
+ valueForCell = exportDateAs(valueForCell);
+ }
It looks like this functionality was added in a newer version:
https://www.ag-grid.com/javascript-grid-export/
My solution was to update the function in the ag grid component manually as follows. It appears to work, but not sure if it is best practice. Anyone willing to comment?
Replace function in object with my own:
ag.grid.CsvCreator.prototype.getDataAsCsv = agCustom.getDataAsCsv;
New function
var agCustom;
(function (agCustom) {
// This is a modified version of the getDataAsCsv from
// agGrid to allow date formatting in csv export
agCustom.getDataAsCsv = function (params) {
var LINE_SEPARATOR = '\r\n';
...
var exportDateAs = function(dt){if (dt instanceof Date)
return dt.getFullYear() + "/" + (dt.getMonth()+1) + "/" + dt.getDate();
...
else {
valueForCell = _this.valueService.getValue(column.colDef, node.data, node);
if (valueForCell instanceof Date){
valueForCell = exportDateAs(valueForCell);
}
...
})(agCustom || (agCustom = {}));

Convert Date in to custom format in javascript

I have a Date format like this
2014-11-18T20:50:01.462Z
I need to convert to the custom format like "20:50 2014-18-11" using Javascript date function
I need result like
20:50 2014-18-11
How to get this , Thanks in Advance :)
Assuming you're able to include new libraries on your project, I'd highly recommend moment.js (MIT license) instead of writing this yourself. It solves problems like zero padding etc. for you.
Example
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script>
// Use an existing date object
var date = new Date("2014-11-18T20:50:01.462Z");
console.log(moment(date).format('HH:mm YYYY-DD-MM'));
// or use string directly
console.log(moment.utc("2014-11-18T20:50:01.462Z").format('HH:mm YYYY-DD-MM'));
</script>
Note by default moment will use your current timezone for output, this can be overridden using the zone() function
console.log(moment.utc("2014-11-18T20:50:01.462Z").zone(0).format('HH:mm YYYY-DD-MM'));
console.log(moment.utc("2014-11-18T20:50:01.462Z").zone('UTC+05:30').format('HH:mm YYYY-DD-MM'));
Output
20:50 2014-18-11
Try moment js its very nice plugin to play around dates and times
so all you need to do is import moment js and put this line in your js code
using moment.js will also help you in future for your code
moment.utc("2014-11-18T20:50:01.462Z").format("HH:mm YYYY-DD-MM")
Use this Demo JsFiddler
var d = new Date,
dformat = [ d.getHours().padLeft(), d.getMinutes().padLeft()].join(':')
+ ' ' +
[d.getFullYear(), d.getDate().padLeft(), (d.getMonth()+1).padLeft()].join('-')
;
Date.prototype._padding = function(v, w) {
var f = "0000" + v;
return ("0000" + v).substr(f.length-w, f.length)
}
Date.prototype.MyDateString = function() {
return this._padding(this.getUTCHours(), 2) + ":" + this._padding(this.getUTCMinutes(), 2) + " " + this.getUTCFullYear() + "-" + this._padding(this.getUTCDate(), 2) + "-" + this._padding((this.getUTCMonth() + 1), 2);
}
console.log(new Date('2014-11-18T20:50:01.462Z').MyDateString())
console.log(new Date('2014-11-08T02:05:01.462Z').MyDateString())
getUTCMonth return 10, as the month is 0 based.

Is there any way of making this function more efficient in a standard browser?

While profiling my web app in Chrome I found that the following function function was taking a large percentage of the total runtime for my app (which is reasonable considering how often it is used - maybe 1000 times each page load). I therefore wonder if anyone has any suggestions of how it could be improved to increase the performance?
function getDate(dateString) {
re = dateString.split(/\-|\s/);
return new Date(re.slice(0, 3).join('/') + ' ' + re[3]);
}
This function is given a string in the form: "YYYY-MM-DD HH:MM:SS", for example: "2014-06-06 23:45:00", and returns a Javascript date.
I am using jQuery so that is an option.
Checkout the following code:
function getDate(dateString) {
re = dateString.split(/\-|\s/);
return new Date(re.slice(0, 3).join('/') + ' ' + re[3]);
}
function getDate2(d) {
return new Date(
d.substr(0, 4) +
'/' +
d.substr(5, 2) +
'/' +
d.substr(8, 2) +
' ' +
d.substr(11, 8)
);
}
function getDate3(d) {
return new Date(d);
}
function benchmark(func, times) {
var start = new Date();
for (var i = 0; i < times; i++) {
var temp = eval(func);
}
var end = new Date();
console.log(func + 'took ' + (end - start) + ' microseconds to execute ' + times + ' times.');
}
var str = '2014-06-06 23:45:15';
benchmark("getDate(str)", 1000000);
benchmark("getDate2(str)", 1000000);
benchmark("getDate3(str)", 1000000);
This gave me the following results:
LOG: getDate(str)took 2215 microseconds to execute 1000000 times.
LOG: getDate2(str)took 940 microseconds to execute 1000000 times.
LOG: getDate3(str)took 270 microseconds to execute 1000000 times.
So, you can see the regex engine takes a high penalty in Javascript. Using substr reduces the execution time by more than 50%, and using the direct string (which is valid in modern Javascript runtimes) reduces the execution time by almost 90%. :-)
Not using that many array operations, and especially not using a global re variable, should help:
function getDate(dateString) {
return new Date(dateString.replace(/-/g, "/"));
}
However, notice that YYYY-MM-DD HH:MM:SS is a valid date format which will be parsed by the Date constructor directly (OK, maybe not in older IEs), but in a standard browser this will work as well:
function getDate(dateString) {
return new Date(dateString);
}

Categories