How to insert one node into an abstract syntax tree by javascript (esprima) - abstract-syntax-tree

there is a question about esprima and inserting an ast node.
I try to generate one ast node to replace other node with new node , (node = newNode) , but It does't work.
estraverse.traverse(tree, {
enter(node, parent) {
try {
if (node.type === "ExpressionStatement") {
if(node.expression.right.type == "FunctionExpression"){
// the id attribution can be replaced
node.expression.right.id = node.expression.left;
// but node can not be replaced
node = node.expression.right;
node.type = "FunctionDeclaration";
}
}
} catch (error) {
}
},});

Based on the code snippet you shared, you are using estraverse to parse through the AST. For replacing a node, you need to use the estraverse.replace API. You can check the details in the documentation for estraverse.replace, but in general when you find the node to replace (Ex. if(node=='Expression Statement'){ .... }) you need to return the new node to this function which will replace the current node.
//node is replaced by Newnode
result = estraverse.replace(AST, {
leave: function (node) {
if (node.type == 'Expression Statement')
return Newnode;
}
});
One point you need to take care is to make sure the Newnode does not break the AST syntax in anyway. Best way I found was to get the Newnode by converting a code snippet into AST and then grabbing the respective node out of it. This makes sure the structure remains ecmascript compliant.

Related

MVC minification seems to creating duplicate variable names

This question seems to be more or less a duplicate of this one, but that one received no answers and is over 2 years old so I don't know what the protocol is (I tried to find out).
Anyway, I've written an ASP.NET MVC5 web app and it all works fine in debug. After publishing to the server with the Release configuration I started seeing the error "Uncaught ReferenceError: Cannot access 'n' before initialization".
After many hours of trawling through the code I think I've isolated the issue. I have this small function (it's a Knockout view model, but that's irrelevant):
eventIndexViewModel = function (params) {
let self = this;
// Map values from params object to properties of self
for (const [key, value] of Object.entries(params)) {
self['_' + key] = value;
}
self.eventsView = ko.observable(self._eventsView);
self.calendarToggleButtonClass = ko.pureComputed(function () {
return self.eventsView() === "calendar" ? "active" : "";
});
self.tableToggleButtonClass = ko.pureComputed(function () {
return self.eventsView() === "table" ? "active" : "";
});
};
After being minified and published to the server, if I view the source in the dev tools console it looks like this:
eventIndexViewModel = function(n) {
let t = this;
for (const [n,i] of Object.entries(n))
t["_" + n] = i;
t.eventsView = ko.observable(t._eventsView);
t.calendarToggleButtonClass = ko.pureComputed(function() {
return t.eventsView() === "calendar" ? "active" : ""
});
t.tableToggleButtonClass = ko.pureComputed(function() {
return t.eventsView() === "table" ? "active" : ""
})
}
It is overkill to map the properties for the params object in this way in this particular instance, but I have much larger view models with many more properties in the same project and I want to keep them code consistent, so go with it.
Unless I'm misunderstanding something, the minified version has renamed both the params variable and the key variable in the for statement to n, and I think that is what is causing my error. Certainly, that line with the for statement is where the error is thrown.
Am I understanding the cause of this problem correctly? If so, is it a bug in the minification process? And either way, how can I get around it?

Update collection with an array in firebase

I need to update a collection in values like this :
{
"email" : "x#gmail.com",
"fullName" : "Mehr",
"locations" : ["sss","dsds","adsdsd"]
}
Locations needs to be an array. in firebase how can I do that ... and also it should check duplicated.
I did like this :
const locations=[]
locations.push(id)
firebase.database().ref(`/users/ + ${userId}`).push({ locations })
Since you need to check for duplicates, you'll need to first read the value of the array, and then update it. In the Firebase Realtime Database that combination can is done through a transaction. You can run the transaction on the locations node itself here:
var locationsRef = firebase.database().ref(`/users/${userId}/locations`);
var newLocation = "xyz";
locationsRef.transaction(function(locations) {
if (locations) {
if (locations.indexOf(newLocation) === -1) {
locations.push(newLocation);
}
}
return locations;
});
As you can see, this loads the locations, ensures the new location is present once, and then writes it back to the database.
Note that Firebase recommends using arrays for set-like data structures such as this. Consider using the more direct mapping of a mathematical set to JavaScript:
"locations" : {
"sss": true,
"dsds": true,
"adsdsd": true
}
One advantage of this structure is that adding a new value is an idempotent operation. Say that we have a location "sss". We add that to the location with:
locations["sss"] = true;
Now there are two options:
"sss" was not yet in the node, in which case this operation adds it.
"sss" was already in the node, in which case this operation does nothing.
For more on this, see best practices for arrays in Firebase.
you can simply push the items in a loop:
if(locations.length > 0) {
var ref = firebase.database().ref(`/users/ + ${userId}`).child('locations');
for(i=0; i < locations.length; i++) {
ref.push(locations[i]);
}
}
this also creates unique keys for the items, instead of a numerical index (which tends to change).
You can use update rather than push method. It would much easier for you. Try it like below
var locationsObj={};
if(locations.length > 0) {
for(i=0; i < locations.length; i++) {
var key= firebase.database().ref(`/users/ + ${userId}`).child('locations').push().key;
locationsObj[`/users/ + ${userId}` +'/locations/' + key] =locations[i];
}
firebase.database().ref().update(locationsObj).then(function(){// which return the promise.
console.log("successfully updated");
})
}
Note : update method is used to update multiple paths at a same time. which will be helpful in this case, but if you use push in the loop then you have to wait for the all the push to return the promises. In the update method it will take care of the all promises and returns at once. Either you get success or error.

Looping api calls in redux-thunk (React redux application)

I have a JSON object similar to this in the redux store of my application:
tables: [
{
"id":"TableGroup1",
"objs":[
{"tableName":"Table1","fetchURL":"www.mybackend.[....]/get/table1"},
{"tableName":"Table2","fetchURL":"www.mybackend.[....]/get/table2"},
{"tableName":"Table3","fetchURL":"www.mybackend.[....]/get/table3"}
]
},{
"id":"TableGroup2",
"objs":[
{"tableName":"Table4","fetchURL":"www.mybackend.[....]/get/table4"},
{"tableName":"Table5","fetchURL":"www.mybackend.[....]/get/table5"},
{"tableName":"Table6","fetchURL":"www.mybackend.[....]/get/table6"}
]
}
];
To load it, i use the following call (TableApi is a mock api loaded locally, beginAjaxCalls keeps track of how many Ajax calls are currently active);
export function loadTables(){
return function(dispatch,getState){
dispatch(beginAjaxCall());
return TableApi.getAllTables().then(tables => {
dispatch(loadTablesSuccess(tables));
}).then(()=>{
//Looping through the store to execute sub requests
}).catch(error => {
throw(error);
});
};
}
I then want to loop through my tables, call the different URLs and populate a new field called data so that an object after a call looks like this;
{"tableName":"Table1","fetchURL":"www.mybackend.[....]/get/table1","data":[{key:"...",value:"..."},{key:"...",value:"..."},{key:"...",value:"..."},.....]}
The data will be frequently updated by recalling the fetch url, and the table should then re-render in the view.
Which leads me to my questions:
- Is this architecturally sound?
- How would redux handle frequent changes? (because of immutability, will i get performance issues by frequently deep copying a table instance with 10,000+ data entries)
And more importantly, what code could i place to substitute the comment so that it serves its intended purpose? Ive tried;
let i;
for(i in getState().tables){
let d;
for(d in getState().tables[i].objs){
dispatch(loadDataForTable(d,i));
}
}
This code, however doesn't seem like the best implementation and I get errors.
Any suggestions are welcome, thanks!
First of all, you don't need to make a deep copy of all tables.
For sake of immutability you need to copy only changed items.
For your data structure it would look like this:
function updateTables(tables, table) {
return tables.map(tableGroup => {
if(tableGroup.objs.find(obj => table.tableName === obj.tableName)) {
// if the table is here, copy group
retrun updateTableGroup(tableGroup, table);
} else {
// otherwise leave it unchanged
return tableGroup;
}
})
}
function updateTableGroup(tableGroup, table) {
return {
...tableGroup,
objs: tableGroup.objs.map(obj => {
return table.tableName === obj.tableName ? table : obj;
})
};
}

Have knockout observable check for null

I was wondering if there was a way to have knockout check to see if data is null before it tries to put it into an observable?
Right now I do this:
if (!data.Filename) {
this.FileName = ko.observable("");
}
else {
this.FileName = ko.observable(data.Filename);
}
Otherwise a null value in the data will cause the entire property not to show up. Is there a way to use extenders or something that I can add a null check to without having to do this with every property? My data has nulls in random places that I can't control and I don't want the property not to show up because one row in the dataset has a null value for that property.
Seems like there should be a better way to do this.
heh
There are a number of ways to do this. What I would do is
var self = this;
self.fileName = ko.observable(data.Filename);
self.fileNameComputed = ko.computed(function(){
return self.fileName() || ""
});
Then, in your mark up reference the computed instead if the observable.
In Javascript there are other patterns available to do this.
The first, and simplest, is akin to the ?? operator in C#:
function ViewModel(data) {
data = data || {};
this.Filename .observable(data.Filename || "");
}
The || operator will return the left operand unless it is falsy, then it'll fall back to the second argument. My example above will:
Make sure data itself is "at least" an empty object (where .Filename would be undefined);
Make sure that the input to ko.observable(...) is "at least" the empty string.
A second option would be to use default options. An example that utilizes jQuery to merge input data and default options:
var defaultData = {
Filename: "enter-a-file" // could also be empty string of course!
};
function ViewModel(data) {
var dto = $.extend({}, defaultData, data);
this.Filename = ko.observable(dto.Filename);
}
This will "fold" data into defaultData, and fold that result into an empty, fresh object, making sure the dto variable holds the merged result. The rest of your function can then safely assume a fully populated input variable.
The third and final option I'll mention is a remix of QBM5's answer, but I agree with the commenter's there that if you can use a pureComputed (which, in your example, is perfectly fine), you probably should:
function ViewModel(data) {
var self = this;
data = data || {};
this.Filename = ko.observable(data.Filename);
this.FilenameText = ko.pureComputed(function() {
return self.Filename() || "";
});
}
PS. You didn't have the underlying issue you mention because you spell FileName and Filename with different capitalization on this and data respectively, didn't you? ;-)

How do I add or remove collection document fields server side in Meteor?

I need to add or remove fields to a doc before insert or update in the allow or deny methods. I had presumed that the transform function would provide the needed functionality.
The meteor docs state
"An optional transformation function. Documents will be passed through
this function before being returned from fetch or findOne, and before
being passed to callbacks of observe, allow, and deny."
Whenever I tried to transform and return the doc from the function either from allow or deny the transformed version of the document was not what was inserted into the mongodb. I tried transforming via 2 strategies.
Strategy 1
var ts = new Date();
return _.extend(_.pick(doc, 'name', 'discounts', 'locations', 'url_map', 'client_updated_td', '_id'), { created_td:
ts, updated_td: ts, });
Strategy 2
// Discountsroutings.fields is in /lib/Discountroutings.js
Discountsroutings.fields = ['_id', 'created_td', 'updated_td', 'client_updated_td', 'name', 'discounts', 'locations', 'url_map'];
// this is in /server/discountsroutings.js var ts = new Date();
doc.created_td = ts; doc.updated_td = ts; return _.each(doc,function(value, key, list){
if(Discountsroutings.fields.indexOf(key) == -1 ){
delete doc[key];
}
});
Neither worked. In both cases fields were not removed though fields were added.
Interestingly, I tried the same two strategies from inside an insert allow and an insert deny and only Strategy #2 worked. So, for now I am just using Strategy #2 inside Deny insert/update methods. Works fine and isn't that difficult to wire up.
Am I doing this correctly? I want to add or remove fields from a collection server side the correct way.
Steeve have you tried my collection-hooks package? Sounds like what you need
you seem to know the list of fields you want to remove. So why don't you use $set and $unset to add and remove fields?
Recently needed to do the same thing and found no example here... thought I'd share how I did it:
Using
https://atmospherejs.com/matb33/collection-hooks
http://arasatasaygin.github.io/is.js/
Prospects.before.update(function (userId, doc, fieldNames, modifier, options) {
//check existence of other segment property and make sure to delete it if segment is updated from 'Other...' to something else
if (is.existy(doc.other_segment)) {
var segment = Segments.findOne({_id: modifier.$set.segment});
if (is.not.undefined(segment) && is.not.empty(segment)) {
if (is.not.equal(segment.name, 'Other...')) {
Prospects.update( {_id: doc._id} , {$unset: { other_segment : '' } } );
}
}
}});
Hope this helps! :)

Resources