I have the following two blocks of code that I am trying to debug.
function getSectionId(target){
let element = target;
if(element.hasAttribute('id')){
console.log(element.id);
return element.id;
}
else {
getSectionId(element.parentElement);
}
};
function coverageLimitHandler(event) {
const target = event.target;
if (target.getAttribute('data-status') !== 'set') {
let itemBlock = addLineItem();
let sectionId = getSectionId(target);
let attribute = '';
console.log(sectionId);
}
}
The event fires and the functions run, but the above gives the unexpected following results
//first-coverage-section (this one is expected.)
//undefined (this is expected to be the same, but is not.)
And I cannot for the life of me figure out why this is happening.
the problem is that your recursive call is not returning anything.
when you do:
getSectionId(element.parentElement);
it will call the function and maybe some day, the if above
if(element.hasAttribute('id')){
console.log(element.id);
return element.id;
}
will return something, but that won't be returned to the previous calls therefore your main call wont have anything to return, so to solve this you need to do this:
function getSectionId(target){
let element = target;
if(element.hasAttribute('id')){
console.log(element.id);
return element.id;
}
else {
// add this return and your function will work correctly.
return getSectionId(element.parentElement);
}
};
basically you have something like this:
function recursiveNotWorking(n) {
if (n === 5) {
return "something"
} else {
// you dont return anything, then something never bubbles up
recursiveNotWorking(n + 1);
}
}
function recursiveWorking(n) {
if (n === 5) {
return "something"
} else {
// we return something
return recursiveWorking(n + 1);
}
}
console.log("NW: ", recursiveNotWorking(1));
console.log("Working: ", recursiveWorking(1));
You need to return the result of the recursive call:
const getSectionId = target => {
if (target.hasAttribute('id') {
return target.id;
}
// You should also check that parentElement exist
// Otherwise you might reach the root node and then parentElement could become null
return getSectionId(target.parentElement);
};
Alos, this can be re-written as well as one liner:
const getSectionId = t => t.id || getSectionId(t.parentElement)
You don't have return in the first function and you don't check on undefined. Also you don't need to use the element variable. It's useless.
Maybe this will work:
function getSectionId(target){
if (typeof target === 'undefined') return null;
if(target.hasAttribute('id')){
console.log(target.id);
return target.id;
}
return getSectionId(target.parentElement);
}
Related
I have one problem statement.
Implement a function propertyExists(obj, path) that takes in an object and a path (string) as arguments and returns ‘False’ if the property doesn’t exist on that object or is null, else returns the value of the property.
And here is solution.
function propertyExists(obj,path) {
// Write logic here
let result = obj.hasOwnProperty(path);
if(result)
{
return (obj.path);
}
else
{
return result;
}
}
Is this correct way of doing it?
Multiple issues:
the first name of the function should represent what it is doing,
Path as variable name is vague but propertyName as a variable is clear.
what you should do is either:
write function called, "getValue" it returns value if exist or null
function getValue(obj,propertyName) {
if(!obj) { // if object not exist
return null;
}
return obj[propertyName];
}
write function called, "propertyExists" should return true if exist else false.
function propertyExists(obj,propertyName) {
if(!obj) { // if object not exist
return false;
}
return obj.hasOwnProperty(propertyName);
}
function propertyExists(obj,path) {
// Write logic here
for(i in path){
if(obj.hasOwnProperty(path[i]) === true){
obj = obj[path[i]];
}else{
return false;
}
}
return obj;
}
object->obj,propertyname->path
function propertyExist(obj, path){
if (obj.hasOwnProperty(path)) return obj[path];
else return false;
};
Here, as far as I can understand, the objects could be nested also.
Let's take obj as {"a":{"b":"dadsa"}} and path as ab
Now, the the solution which you have posted will not work. Ideally, it should return dadsa, but it will return false.
Try the below code, it will work for nested objects also.
function propertyExists(obj,path) {
// Write logic here
var val=obj;
for(a of path){
val=val[a];
if(!val)
return false;
}
return val;
}
function propertyExists(obj,path) {
var val = obj;
for (a of path) {
val = val[a];
if (!val){
return false;
}
return val;
}
I have a function that returns boolean if tree has at least one enebled value:
treeHasEnabledNode(): Function {
let enabled = false;
return function isNodeEnabled(node: T): boolean {
if (!node || !node.children || !node.children.length) return enabled;
if (node.enabled && node.enabled !== undefined) return true;
node.children.forEach((node: T) => {
enabled = isNodeEnabled(node);
});
return enabled;
};
}
Using is:
let hasEnabled = treeHasEnabledNode()(this.tree);
How to return result not calling outher functon (this.tree)?
You can go about this a few ways. The most simple one would probably be to invoke the internal function within the outer function, and return the result:
function treeHasEnabledNode(node) {
let enabled = false;
function isNodeEnabled(node) {
// do whatever. for example:
return enabled
}
return isNodeEnabled(node);
}
const node = {};
console.log(treeHasEnabledNode(node));
However, as #sledetman mentioned in the comments below your question, the code snippet you provided does not "return a boolean if tree has at least one enabled value".
I've got this issue with passing a variable to an IFFE. did some reading, still didn't figure it out. would really appreciate some guidance here.
i have a click event handler function that gets a certain ID from the
DOM when clicked.
i need to pass that ID to an IIFE
that IFFE needs to either add/remove that ID from an array,
depending if it's already there or not.
This is what I got:
Event:
$(document).on('click', 'input[type="checkbox"]', check);
Click Handler:
function check() {
var id = $(this).closest('ul').attr('data-id');
return id;
}
IIFE:
var checkID = (function (val) {
var arr = [];
return function () {
var i = arr.indexOf(val);
if (i === -1) {
arr.push(val);
} else {
arr.splice(i, 1);
}
return arr;
}
})(id);
right now i'm getting the ID, but returning it to nowhere.
in my IIFE, i did pass an id variable, but it's undefined.
so, how do I pass the ID variable im getting from check() to checkID IIFE?
other solutions are also welcome.
Thanks
In your clickHandler
function check() {
var id = $(this).closest('ul').attr('data-id');
checkID(id);
}
and change checkID to
var checkID = (function () {
var arr = [];
return function (val) {
var i = arr.indexOf(val);
if (i === -1) {
arr.push(val);
} else {
arr.splice(i, 1);
}
return arr;
}
})();
I think you need to do things sort of the other way around. Your check function would return a function used by the event handler, but it would also take a callback to be called after the click handler has run, passing your array.
The check function would look like a mash-up of both your functions:
function check(callback){
var arr = [];
return function(){
var id = $(this).closest('ul').attr('data-id');
var i = arr.indexOf(id);
if (i === -1) {
arr.push(id);
} else {
arr.splice(i, 1);
}
callback(arr);
}
}
As you can see, it takes as a parameter a callback function, which will be called on each execution, passing the current array arr. For example, this is my test callback:
function handler(arr){
alert("Array has " + arr.length + " elements");
}
Finally, your event handler would look like this:
$(document).on('click', 'input[type="checkbox"]', check(handler));
Live example: https://jsfiddle.net/src282d6/
Using getter/setter-like functions in your IIFE function makes it much more organized and readable. Then, use these functions to pass, store, and read data across your IIFE function.
var checkID = (function () {
// your array
var arr = [];
// public
return {
// get
getArray: function(){
return arr;
},
// set value
setArray: function(val) {
var i = arr.indexOf(val);
if (i === -1) {
arr.push(val);
} else {
arr.splice(i, 1);
}
}
}
})();
Use it as follows:
checkID.getArray(); // returns default empty array []
checkID.setArray('car1');
checkID.setArray('car2');
checkID.setArray('car3');
checkID.setArray('car4');
checkID.setArray('car4'); // test splice()
checkID.getArray(); // returns ["car1", "car2", "car3"]
I'm having a hard time understanding how promises works. I've seen some examples and some of it makes sense. However, when I try to actually use it I get stuck. I have the following example:
(I'm using q and nodejs. getItem() returns a promise, but my function doesn't wait for it.)
function calculate(id, item) {
var calcId = id ? id : getItem(item);
if (!id && calcId) { calcId = calcId.Id; }
if (calcId) {
update(calcId);
} else {
insert(item);
}
}
Based on the examples, I don't see how to do it without code duplication.
Promises are resolved asynchronously, so you can't treat them as synchronous as in your example. What you want to do is coerce the value is a Q promise if needed, then proceed from there, that way you have deterministic behavior and no code duplication.
I'm making some assumptions here about update and insert returning promises and returning them when needed so that calculate itself returns a promise.
function calculate( id, item ) {
return Q( id || getItem(item) ).then(function( calcId ) {
// Code seems weird to be, but it's based on the original example.
// Might want to review this.
if ( !id && calcId ) {
calcId = calcId.Id;
}
return calcId ?
update( calcId ) :
insert( item );
});
}
Don’t duplicate your id checks:
function calculate(id, item) {
var calcId;
if (id) {
calcId = id;
} else {
calcId = getItem(item).Id;
}
if (calcId) {
update(calcId);
} else {
insert(item);
}
}
Now make calcId consistently a promise holding an Id:
function calculate(id, item) {
var p;
if (id) {
p = Promise.resolve({ Id: id });
} else {
p = getItem(item);
}
return p.then(function (calcId) {
if (calcId.Id) {
return update(calcId.Id);
} else {
return insert(item);
}
});
}
Where, in the case of Q, Promise.resolve is Q.resolve, or just Q.
Bonus: as a generator!
function calculate(id, item) {
var calcId = id ? id : yield getItem(item);
if (!id && calcId) { calcId = calcId.Id; }
if (calcId) {
update(calcId);
} else {
insert(item);
}
}
Several points :
Promise-wrapped results need to be handled with a function specified as a parameter of a promise method (eg .then(fn))
Q(x) can be used to ensure that x is Promise-wrapped. The operation is transparent if x is already a promise - it won't be double wrapped
you need safety in case both id and item are empty or missing
you need further safety in case calcId is falsy and item was not provided
id versus calcId.Id can be more elegantly catered for.
function calculate(id, item) {
if(!id && !item) {
throw new Error("'calculate(): parameters empty or missing'");
}
return Q(id ? {Id:id} : getItem(item)).then(function(resultObj) {
var calcId = resultObj.Id;
if(calcId) {
update(calcId);
} else {
if(item) {
insert(item);
} else {
throw new Error("'calculate(): `calcId` is falsy and `item` is empty of missing'");
}
}
return calcId; //in case you need to chain calculate(...).then(...)
//(Alternatively, if update() and insert() return promises, then return them instead as per dherman's answer)
});
}
Call as follows :
calculate(myId, myItem).then(function(calcId) {
//(optional) anything else you wish to do with `calcId`
}).catch(function(e) {
console.error(e);
});
Sorry for the title but I don't know how to explain it.
The function takes an URI, eg: /foo/bar/1293. The object will, in case it exists, be stored in an object looking like {foo: { bar: { 1293: 'content...' }}}. The function iterates through the directories in the URI and checks that the path isn't undefined and meanwhile builds up a string with the code that later on gets called using eval(). The string containing the code will look something like delete memory["foo"]["bar"]["1293"]
Is there any other way I can accomplish this? Maybe store the saved content in something other than
an ordinary object?
remove : function(uri) {
if(uri == '/') {
this.flush();
return true;
}
else {
var parts = trimSlashes(uri).split('/'),
memRef = memory,
found = true,
evalCode = 'delete memory';
parts.forEach(function(dir, i) {
if( memRef[dir] !== undefined ) {
memRef = memRef[dir];
evalCode += '["'+dir+'"]';
}
else {
found = false;
return false;
}
if(i == (parts.length - 1)) {
try {
eval( evalCode );
} catch(e) {
console.log(e);
found = false;
}
}
});
return found;
}
}
No need for eval here. Just drill down like you are and delete the property at the end:
parts.forEach(function(dir, i) {
if( memRef[dir] !== undefined ) {
if(i == (parts.length - 1)) {
// delete it on the last iteration
delete memRef[dir];
} else {
// drill down
memRef = memRef[dir];
}
} else {
found = false;
return false;
}
});
You just need a helper function which takes a Array and a object and does:
function delete_helper(obj, path) {
for(var i = 0, l=path.length-1; i<l; i++) {
obj = obj[path[i]];
}
delete obj[path.length-1];
}
and instead of building up a code string, append the names to a Array and then call this instead of the eval. This code assumes that the checks to whether the path exists have already been done as they would be in that usage.