Does Ember have a some() method like Dojo - javascript

Does Ember have a some() method like Dojo
I am trying to run the below code;
obj.view = someObj.forEach(function(tempArr){
return (tempArr.actionName == "view") ? true : false ;
});
But since forEach does not terminate, the code does not work properly.
I want to exit at the first find (return true) So I want something similar to what DojoJS has dojo.some() https://dojotoolkit.org/reference-guide/1.7/quickstart/arrays.html#quickstart-arrays
In simple terms, I want to break and return true for the variable on first condition that is true (else return false for the variable)

You can use find, findBy to get first element or any if you only need to have true/false.
obj.view = someArray.findBy('actionName', 'view');
// es6 shortened - carefull with implicit return statement
obj.view = someArray.find(item => item.get('actionName') === 'view');
obj.view = someArray.any(item => item.get('actionName') === 'view');
// es6 with () and {}
obj.view = someArray.find((item) => {
return item.get('actionName') === 'view';
});
// es5
obj.view = someArray.find(function(item){
return item.get('actionName') === 'view';
});

Related

I can't change a variable value in object.entries foreach from parent scope

I want to get a boolean from an Object.entries(b).foreach but I don't know how to retrieve it.
Like :
const body = {a:1,b:2}
function handle() {
let myBool = true;
Object.entries(body).forEach(([key, value]) => {
myBool = false;
});
return myBool;
}
So, that's always return true, I tried something like
const body = {a:1,b:2}
function handle() {
return Object.entries(body).forEach(([key, value]) => {
return false;
});
}
But it doesn't work.
it's probably a lack of understanding JS, can you give me a hint ?
Unlike Array.prototype.map(), Array.prototype.forEach() always returns undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.
More details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

How can I fix ES6 Eslint errors while trying to return a ternary operator in arrow function?

I understand that () => {} does not need return, however if it is not there then Eslint complains about unused expressions.
export const isInInterval = (from, to, target) => {
if (isNaN(Date.parse(to)) && isNaN(Date.parse(from)) === true) {
return
}
const toUnixTimestamp = time => new Date(time).getTime()
toUnixTimestamp(to) - target > toUnixTimestamp(from) ? true : false
}
Here is the function: it tries to find out whether some specified date(to) minus specified period(target) is later in time than from. It should return true if so and false in the opposite case.
I keep bumping into eslint error expected assignment to a function call and instead saw expression.
I tried to rewrite it several times, but in most iterations I got `arrow function expects no return error, ex.:
return (toUnixTimestamp(to) - target > toUnixTimestamp(from)) ? true : false
I understand that () => {} does not need return
That's not the case. Arrow functions only implicitly return when what followed the => is a single expression. If you use => {, the opening bracket { indicates the start of a function block, and you do indeed need to explicitly return at the end of the block (or wherever else you want to return something).
At the moment, your code isn't returning anything at all - that's what the linting error is trying to tell you - the true : false is going unused at the moment, it's just an orphaned expression.
So, just add the return statement to the beginning of your conditional:
export const isInInterval = (from, to, target) => {
if (isNaN(Date.parse(to)) && isNaN(Date.parse(from)) === true) {
return
}
const toUnixTimestamp = time => new Date(time).getTime()
return toUnixTimestamp(to) - target > toUnixTimestamp(from)
? true
: false
}
Or, because > evaluates to a boolean already, you might omit the conditional operator entirely:
return toUnixTimestamp(to) - target > toUnixTimestamp(from)
Here's an example of how you would write an arrow function that does use implicit return:
export const isEarlyTimestamp = (timestamp) => (
timestamp < 4000000
? true
: false
);
try this:
export const isInInterval = (from, to, target) => {
if (isNaN(Date.parse(to)) && isNaN(Date.parse(from)) === true) {
return false
}
const toUnixTimestamp = time => new Date(time).getTime()
return toUnixTimestamp(to) - target > toUnixTimestamp(from);
}

How to Reassign Function Parameters

I understand that it can be bad to reassign function parameters but I don't quite see how it would be done in this case? I'm using a forEach loop to cycle through the todo list array (which is on an object) todos and alter the completed property and I don't see how I can not reuse eachTodo
How would this be rewritten so that it has the same functionality but doesn't reuse eachTodo?
this.todos.forEach((eachTodo) => {
if (completedTodos === totalTodos) {
eachTodo.completed = false;
} else {
eachTodo.completed = true;
}
});
Full project here
You are not reassigning parameters here. If you were reassigning them, there would be some line with eachTodo = in it - but that's not the case here. Rather, you're mutating the eachTodo parameter.
If you want to avoid mutating the parameter as well, one option would be to use .map to create a copy of each eachTodo, and then reassign this.todos outside of the forEach call:
this.todos = this.todos.map((eachTodo) => {
if (completedTodos === totalTodos) {
return { ...eachTodo, completed: false };
} else {
return { ...eachTodo, completed: true };
}
});
(make sure there are no other references to individual todos to avoid memory leaks)
Your code doesn't assign to eachTodo, so I don't see how the link to the discussion about reassigning parameters is relevant.
What do you mean by "reuse eachTodo"? If you mean you want code that mentions the variable name less often, here's one way:
if (completedTodos === totalTodos) {
eachTodo.completed = false;
} else {
eachTodo.completed = true;
}
can be reduced (by pulling out the common eachTodo.completed = part) to:
eachTodo.completed = completedTodos === totalTodos ? false : true;
This line can be simplified further (as a general rule, whenever you have a ?: operator where one of the branches is just true or false, it can be simplified):
eachTodo.completed = completedTodos !== totalTodos;

One-Liner with Return Statement

Is there a way to write the JavaScript code below as a one-liner?
this.isContactPage = (window.location.pathname === '/contact');
if (!this.isContactPage) return false;
The method continues on if this.isContactPage is true.
The property this.isContactPage is needed in other places in the script.
return !(this.isContactPage = (window.location.pathname === '/contact'));
Another example:
console.log(window.prop); // undefined
console.log(!(window.prop = true) || undefined); // undefined
console.log(!(window.prop = true)); // false
console.log(window.prop); // true
It'll be fairly dense and "obscured" code, but you can inline assignments in conditionals:
if ( !this.isContactPage = ( window.location.pathname == '/contact' ) ) return false;
This will only return the function if this.isContactPage is assigned the value false otherwise the function is not returned and continues on execution, as opposed to:
return ( this.isContactPage = ( window.location.pathname == '/contact' ) );
Which will return true or false immediately.
return !this.isContactPage = (window.location.pathname === '/contact')
I have something makes your code as short as possible!
return !(this.isContactPage=location.pathname=='/contact')
You don't need "Window"
You don't need returning false or true directly through your code
You don't need ===, then change it to ==
The shortest way guys suggested has 88 letters and this suggestion has just 68 letter and is more readable and understandable!
with this you will not have errors!
this.isContactPage = /contact/gi.test(window.location.pathname);
if (!this.isContactPage) return false;
or
return !(/contact/gi.test(window.location.pathname))

How to match an empty dictionary in Javascript?

From the node REPL thing,
> d = {}
{}
> d === {}
false
> d == {}
false
Given I have an empty dictionary, how do I make sure it is an empty dictionary ?
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
You could extend Object.prototype with this isEmpty method to check whether an object has no own properties:
Object.prototype.isEmpty = function() {
for (var prop in this) if (this.hasOwnProperty(prop)) return false;
return true;
};
How about using jQuery?
$.isEmptyObject(d)
Since it has no attributes, a for loop won't have anything to iterate over. To give credit where it's due, I found this suggestion here.
function isEmpty(ob){
for(var i in ob){ return false;}
return true;
}
isEmpty({a:1}) // false
isEmpty({}) // true
This is what jQuery uses, works just fine. Though this does require the jQuery script to use isEmptyObject.
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
}
//Example
var temp = {};
$.isEmptyObject(temp); // returns True
temp ['a'] = 'some data';
$.isEmptyObject(temp); // returns False
If including jQuery is not an option, simply create a separate pure javascript function.
function isEmptyObject( obj ) {
for ( var name in obj ) {
return false;
}
return true;
}
//Example
var temp = {};
isEmptyObject(temp); // returns True
temp ['b'] = 'some data';
isEmptyObject(temp); // returns False
I'm far from a JavaScript scholar, but does the following work?
if (Object.getOwnPropertyNames(d).length == 0) {
// object is empty
}
It has the advantage of being a one line pure function call.
var SomeDictionary = {};
if(jQuery.isEmptyObject(SomeDictionary))
// Write some code for dictionary is empty condition
else
// Write some code for dictionary not empty condition
This Works fine.
If performance isn't a consideration, this is a simple method that's easy to remember:
JSON.stringify(obj) === '{}'
Obviously you don't want to be stringifying large objects in a loop, though.
You'd have to check that it was of type 'object' like so:
(typeof(d) === 'object')
And then implement a short 'size' function to check it's empty, as mentioned here.
If you try this on Node.js use this snippet, based on this code here
Object.defineProperty(Object.prototype, "isEmpty", {
enumerable: false,
value: function() {
for (var prop in this) if (this.hasOwnProperty(prop)) return false;
return true;
}
}
);

Categories