Working equivalent for method .some() in javascript or jquery? - javascript

Was looking for "equivalent for some method in javascript" and "return just one value if is in array", but saw only the answers to the way in which to determine the type of variables or too many unnecessary.
I bypass all inputs in html and i want something like this:
$('#goodsFilter')
.find('input[type="number"]')
.some(function(i,el){
return (isNumber($(el).val())) ? 1 : 0;
});
But it throws an error:
"TypeError: 'undefined' is not a function" (eg. Safari 6.0.4).
UPD: Error comes from the last line, yeah, where });.
isNumber:
function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); }
This should check for the presence of each input information, and, if at least one of them is not empty, return 1, otherwise 0.
How can I replace it to work in most modern browsers?
UPD:
Problem was solved. I'm a little confused in choosing the answer. The code of #RobG implementation of .some() is more understandable for beginners (and I am) so I switched my vote.

For anyone else who comes to this thread, you can use some() on a jQuery object this way:
$.makeArray($(...)).some(function(x) { ... })
jQuery.makeArray() converts the jQuery object into an Array, so you can use some() on it.
As suggested by #alf-eaton, you could use:
$(…).toArray().some(function(node) { … })

Array.prototype.some returns true or false, so you can do:
.some(function(el){
return !isNaN(el.value);
}
You don't say where the error comes from, is it from the call to isNumber?
Edit
Ah, so your issue is with some.
If you want a jQuery some method, then it should at least mimic the built–in ECMAScript some, which takes two arguments: a callback function and an optional this argument.
The callback function should take three arguments: the value, the index (optional) and an optional value to use as the this argument. It should access the numeric members in ascending order and only visit members that actually exist.
So it should be something like (noting that jQuery.fn === jQuery.prototype):
jQuery.fn.some = function(fn, thisArg) {
var result;
for (var i=0, iLen = this.length; i<iLen; i++) {
if (this.hasOwnProperty(i)) {
if (typeof thisArg == 'undefined') {
result = fn(this[i], i, this);
} else {
result = fn.call(thisArg, this[i], i, this);
}
if (result) return true;
}
}
return false;
}
So if you want now you can do:
var result = $('#goodsFilter')
.find('input[type="number"]')
.some(function(el) {
return isNumber(el.value);
})? 1 : 0;
or you can do either of the following to coerce true to 1 and false to 0:
var result = Number($('#goodsFilter')
.find('input[type="number"]')
.some(function(el) {
return isNumber(el.value);
}));
or
var result = +($('#goodsFilter')
.find('input[type="number"]')
.some(function(el) {
return isNumber(el.value);
}));
The above is only lightly tested, the optional thisArg parameter might be redundant.

You could use the .filter method, and then check the length.
$('#goodsFilter')
.find('input[type="number"]')
.filter(function(i,el){ return isNumber($(el).val())); })
.length > 0

$(...).is(function) should work too. The jQuery API documentation states (emphasis mine):
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
So using the example in the question, we would have something like:
var result = $('#goodsFilter')
.find('input[type="number"]')
.is(function(idx, el) {
return isNumber(el.value);
})? 1 : 0;

. . In the most basic version, you can just create a "some" function:
function eSome(arr, f) { var i = 0, n = arr.length;
for (;i<n;i++) { if (!i in arr) { continue }
if (f(i, arr[i])) { return true; }
} return false;
}
var list = [0, 1, 2, 3, 4, 5];
var testFunction = function (i, e) { return e === 2; };
console.log(eSome(list, testFunction));
//returns true and the loop ran only for the necessary three times.
. . If you want to chain the .some call in a jQuery object, you can add it as a jQuery function as well, using something like this (now tested and fixed) example:
jQuery.fn.some = function (f) { var i = 0, n = this.length;
for (;i<n;i++) { if (!i in this) { continue }
if (f(i, this[i])) { return true; }
}
return false;
}
$('.a').some(function (i, el) { return ($(el).text() == 'weeee!'); });
. . As #RobG pointed out in the comments, the native Array.prototype.some implementation calls your callback with a different set of parameters. I'm following the OP's sample code, but you can mimic the ECMA implementation's parameter with if (f(this[i], i, this)) { return true; } inside the loop.
. . You can also shim it on Array.prototype.some, but I strongly advise against any direct modifications to the built-in prototypes.

Implementation in Vanilla Javascript( with arrow syntax)
function some(arr,callback){
for(let i=0;i<arr.length;i++){
if(callback(arr[i],i,arr)){
return true;
}
}
return false;
}
some use:
check if an array has an even number:
function hasEvenNum(arr){
return arr.some(value=>{
return value % 2 === 0;
});
}

Try to use [].prototype.call method, the first argument will be an Array-like value, the second one is a function that will be called on each element.
[].some.call($('#goodsFilter').find('input[type="number"]'), function (el) {
return isNumber($(el).val());
});

Related

Javascript game collision not working with more than one platform in the array [duplicate]

[1,2,3].forEach(function(el) {
if(el === 1) break;
});
How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.
There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.
var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.
Use Array#some
Instead, use Array#some:
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.
some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.
Use Array#every
[1, 2, 3].every(v => {
if (v > 2) {
return false // "break"
}
console.log(v);
return true // must return true if doesn't break
});
There is now an even better way to do this in ECMAScript2015 (aka ES6) using the new for of loop. For example, this code does not print the array elements after the number 5:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (const el of arr) {
console.log(el);
if (el === 5) {
break;
}
}
From the docs:
Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of an object, in original insertion order. The for...of statement iterates over data that iterable object defines to be iterated over.
Need the index in the iteration? You can use Array.entries():
for (const [index, el] of arr.entries()) {
if ( index === 5 ) break;
}
You can use every method:
[1,2,3].every(function(el) {
return !(el === 1);
});
ES6
[1,2,3].every( el => el !== 1 )
for old browser support use:
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
more details here.
Quoting from the MDN documentation of Array.prototype.forEach():
There is no way to stop or break a forEach() loop other than
by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead.
For your code (in the question), as suggested by #bobince, use Array.prototype.some() instead. It suits very well to your usecase.
Array.prototype.some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns false. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Unfortunately in this case it will be much better if you don't use forEach.
Instead use a regular for loop and it will now work exactly as you would expect.
var array = [1, 2, 3];
for (var i = 0; i < array.length; i++) {
if (array[i] === 1){
break;
}
}
From your code example, it looks like Array.prototype.find is what you are looking for: Array.prototype.find() and Array.prototype.findIndex()
[1, 2, 3].find(function(el) {
return el === 2;
}); // returns 2
Consider to use jquery's each method, since it allows to return false inside callback function:
$.each(function(e, i) {
if (i % 2) return false;
console.log(e)
})
Lodash libraries also provides takeWhile method that can be chained with map/reduce/fold etc:
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']
// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']
// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []
If you would like to use Dean Edward's suggestion and throw the StopIteration error to break out of the loop without having to catch the error, you can use the following the function (originally from here):
// Use a closure to prevent the global namespace from be polluted.
(function() {
// Define StopIteration as part of the global scope if it
// isn't already defined.
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
// The original version of Array.prototype.forEach.
var oldForEach = Array.prototype.forEach;
// If forEach actually exists, define forEach so you can
// break out of it by throwing StopIteration. Allow
// other errors will be thrown as normal.
if(oldForEach) {
Array.prototype.forEach = function() {
try {
oldForEach.apply(this, [].slice.call(arguments, 0));
}
catch(e) {
if(e !== StopIteration) {
throw e;
}
}
};
}
})();
The above code will give you the ability to run code such as the following without having to do your own try-catch clauses:
// Show the contents until you get to "2".
[0,1,2,3,4].forEach(function(val) {
if(val == 2)
throw StopIteration;
alert(val);
});
One important thing to remember is that this will only update the Array.prototype.forEach function if it already exists. If it doesn't exist already, it will not modify the it.
Short answer: use for...break for this or change your code to avoid breaking of forEach. Do not use .some() or .every() to emulate for...break. Rewrite your code to avoid for...break loop, or use for...break. Every time you use these methods as for...break alternative God kills kitten.
Long answer:
.some() and .every() both return boolean value, .some() returns true if there any element for which passed function returns true, every returns false if there any element for which passed function returns false. This is what that functions mean. Using functions for what they doesn't mean is much worse then using tables for layout instead of CSS, because it frustrates everybody who reads your code.
Also, the only possible way to use these methods as for...break alternative is to make side-effects (change some vars outside of .some() callback function), and this is not much different from for...break.
So, using .some() or .every() as for...break loop alternative isn't free of side effects, this isn't much cleaner then for...break, this is frustrating, so this isn't better.
You can always rewrite your code so that there will be no need in for...break. You can filter array using .filter(), you can split array using .slice() and so on, then use .forEach() or .map() for that part of array.
As mentioned before, you can't break .forEach().
Here's a slightly more modern way of doing a foreach with ES6 Iterators. Allows you to get direct access to index/value when iterating.
const array = ['one', 'two', 'three'];
for (const [index, val] of array.entries()) {
console.log('item:', { index, val });
if (index === 1) {
console.log('break!');
break;
}
}
Output:
item: { index: 0, val: 'one' }
item: { index: 1, val: 'two' }
break!
Links
Array.prototype.entries()
Iterators and generators
Destructuring assignment
Another concept I came up with:
function forEach(array, cb) {
var shouldBreak;
function _break() { shouldBreak = true; }
for (var i = 0, bound = array.length; i < bound; ++i) {
if (shouldBreak) { break; }
cb(array[i], i, array, _break);
}
}
// Usage
forEach(['a','b','c','d','e','f'], function (char, i, array, _break) {
console.log(i, char);
if (i === 2) { _break(); }
});
This is just something I came up with to solve the problem... I'm pretty sure it fixes the problem that the original asker had:
Array.prototype.each = function(callback){
if(!callback) return false;
for(var i=0; i<this.length; i++){
if(callback(this[i], i) == false) break;
}
};
And then you would call it by using:
var myarray = [1,2,3];
myarray.each(function(item, index){
// do something with the item
// if(item != somecondition) return false;
});
Returning false inside the callback function will cause a break. Let me know if that doesn't actually work.
If you don't need to access your array after iteration you can bail out by setting the array's length to 0. If you do still need it after your iteration you could clone it using slice..
[1,3,4,5,6,7,8,244,3,5,2].forEach(function (item, index, arr) {
if (index === 3) arr.length = 0;
});
Or with a clone:
var x = [1,3,4,5,6,7,8,244,3,5,2];
x.slice().forEach(function (item, index, arr) {
if (index === 3) arr.length = 0;
});
Which is a far better solution then throwing random errors in your code.
Found this solution on another site. You can wrap the forEach in a try / catch scenario.
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
try {
[1,2,3].forEach(function(el){
alert(el);
if(el === 1) throw StopIteration;
});
} catch(error) { if(error != StopIteration) throw error; }
More details here: http://dean.edwards.name/weblog/2006/07/enum/
This is a for loop, but maintains the object reference in the loop just like a forEach() but you can break out.
var arr = [1,2,3];
for (var i = 0, el; el = arr[i]; i++) {
if(el === 1) break;
}
try with "find" :
var myCategories = [
{category: "start", name: "Start", color: "#AC193D"},
{category: "action", name: "Action", color: "#8C0095"},
{category: "exit", name: "Exit", color: "#008A00"}
];
function findCategory(category) {
return myCategories.find(function(element) {
return element.category === category;
});
}
console.log(findCategory("start"));
// output: { category: "start", name: "Start", color: "#AC193D" }
Yet another approach:
var wageType = types.filter(function(element){
if(e.params.data.text == element.name){
return element;
}
});
console.dir(wageType);
I use nullhack for that purpose, it tries to access property of null, which is an error:
try {
[1,2,3,4,5]
.forEach(
function ( val, idx, arr ) {
if ( val == 3 ) null.NULLBREAK;
}
);
} catch (e) {
// e <=> TypeError: null has no properties
}
//
Use the array.prototype.every function, which provide you the utility to break the looping. See example here Javascript documentation on Mozilla developer network
Agree with #bobince, upvoted.
Also, FYI:
Prototype.js has something for this purpose:
<script type="text/javascript">
$$('a').each(function(el, idx) {
if ( /* break condition */ ) throw $break;
// do something
});
</script>
$break will be catched and handled by Prototype.js internally, breaking the "each" cycle but not generating external errors.
See Prototype.JS API for details.
jQuery also has a way, just return false in the handler to break the loop early:
<script type="text/javascript">
jQuery('a').each( function(idx) {
if ( /* break condition */ ) return false;
// do something
});
</script>
See jQuery API for details.
If you want to keep your forEach syntax, this is a way to keep it efficient (although not as good as a regular for loop). Check immediately for a variable that knows if you want to break out of the loop.
This example uses a anonymous function for creating a function scope around the forEach which you need to store the done information.
(function(){
var element = document.getElementById('printed-result');
var done = false;
[1,2,3,4].forEach(function(item){
if(done){ return; }
var text = document.createTextNode(item);
element.appendChild(text);
if (item === 2){
done = true;
return;
}
});
})();
<div id="printed-result"></div>
My two cents.
If you need to break based on the value of elements that are already in your array as in your case (i.e. if break condition does not depend on run-time variable that may change after array is assigned its element values) you could also use combination of slice() and indexOf() as follows.
If you need to break when forEach reaches 'Apple' you can use
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var fruitsToLoop = fruits.slice(0, fruits.indexOf("Apple"));
// fruitsToLoop = Banana,Orange,Lemon
fruitsToLoop.forEach(function(el) {
// no need to break
});
As stated in W3Schools.com the slice() method returns the selected elements in an array, as a new array object. The original array will not be changed.
See it in JSFiddle
Hope it helps someone.
Why don't you try wrapping the function in a Promise?
The only reason I bring it up is that I am using a function in an API that acts in a similar manner to forEach. I don't want it to keep iterating once it finds a value, and I need to return something so I am simply going to resolve a Promise and do it that way.
traverseTree(doc): Promise<any> {
return new Promise<any>((resolve, reject) => {
this.gridOptions.api.forEachNode((node, index) => {
//the above function is the one I want to short circuit.
if(node.data.id === doc.id) {
return resolve(node);
}
});
});
}
Then all you need to do is do something with the result like
this.traverseTree(doc).then((result) => {
this.doSomething(result);
});
My above example is in typescript, simply ignore the types. The logic should hopefully help you "break" out of your loop.
This isn't the most efficient, since you still cycle all the elements, but I thought it might be worth considering the very simple:
let keepGoing = true;
things.forEach( (thing) => {
if (noMore) keepGoing = false;
if (keepGoing) {
// do things with thing
}
});
you can follow the code below which works for me:
var loopStop = false;
YOUR_ARRAY.forEach(function loop(){
if(loopStop){ return; }
if(condition){ loopStop = true; }
});
Breaking out of built-in Array.prototype.map function esp in React
The key thing to note here is the use of statement return to BREAK
let isBroken = false;
colours.map(item => {
if (isBroken) {
return;
}
if (item.startsWith("y")) {
console.log("The yessiest colour!");
isBroken = true;
return;
}
});
More information here: https://www.codegrepper.com/code-examples/javascript/break+out+of+map+javascript
I know it not right way. It is not break the loop.
It is a Jugad
let result = true;
[1, 2, 3].forEach(function(el) {
if(result){
console.log(el);
if (el === 2){
result = false;
}
}
});
You can create a variant of forEach that allows for break, continue, return, and even async/await: (example written in TypeScript)
export type LoopControlOp = "break" | "continue" | ["return", any];
export type LoopFunc<T> = (value: T, index: number, array: T[])=>LoopControlOp;
Array.prototype.ForEach = function ForEach<T>(this: T[], func: LoopFunc<T>) {
for (let i = 0; i < this.length; i++) {
const controlOp = func(this[i], i, this);
if (controlOp == "break") break;
if (controlOp == "continue") continue;
if (controlOp instanceof Array) return controlOp[1];
}
};
// this variant lets you use async/await in the loop-func, with the loop "awaiting" for each entry
Array.prototype.ForEachAsync = async function ForEachAsync<T>(this: T[], func: LoopFunc<T>) {
for (let i = 0; i < this.length; i++) {
const controlOp = await func(this[i], i, this);
if (controlOp == "break") break;
if (controlOp == "continue") continue;
if (controlOp instanceof Array) return controlOp[1];
}
};
Usage:
function GetCoffee() {
const cancelReason = peopleOnStreet.ForEach((person, index)=> {
if (index == 0) return "continue";
if (person.type == "friend") return "break";
if (person.type == "boss") return ["return", "nevermind"];
});
if (cancelReason) console.log("Coffee canceled because: " + cancelReason);
}
I use return false and it works for me.
const Book = {"Titles":[
{"Book3" : "BULLETIN 3"},
{"Book1" : "BULLETIN 1"},
{"Book2" : "BULLETIN 2"}
]}
const findbystr = function(str) {
Book.Titles.forEach(function(data) {
if (typeof data[str] != 'undefined') {
return data[str];
}
}, str)
}
book = findbystr('Book1');
console.log(book);

new Function() constructor within loops/Array.map() in Javascript? [duplicate]

[1,2,3].forEach(function(el) {
if(el === 1) break;
});
How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.
There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.
var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.
Use Array#some
Instead, use Array#some:
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.
some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.
Use Array#every
[1, 2, 3].every(v => {
if (v > 2) {
return false // "break"
}
console.log(v);
return true // must return true if doesn't break
});
There is now an even better way to do this in ECMAScript2015 (aka ES6) using the new for of loop. For example, this code does not print the array elements after the number 5:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (const el of arr) {
console.log(el);
if (el === 5) {
break;
}
}
From the docs:
Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of an object, in original insertion order. The for...of statement iterates over data that iterable object defines to be iterated over.
Need the index in the iteration? You can use Array.entries():
for (const [index, el] of arr.entries()) {
if ( index === 5 ) break;
}
You can use every method:
[1,2,3].every(function(el) {
return !(el === 1);
});
ES6
[1,2,3].every( el => el !== 1 )
for old browser support use:
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
more details here.
Quoting from the MDN documentation of Array.prototype.forEach():
There is no way to stop or break a forEach() loop other than
by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead.
For your code (in the question), as suggested by #bobince, use Array.prototype.some() instead. It suits very well to your usecase.
Array.prototype.some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns false. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Unfortunately in this case it will be much better if you don't use forEach.
Instead use a regular for loop and it will now work exactly as you would expect.
var array = [1, 2, 3];
for (var i = 0; i < array.length; i++) {
if (array[i] === 1){
break;
}
}
From your code example, it looks like Array.prototype.find is what you are looking for: Array.prototype.find() and Array.prototype.findIndex()
[1, 2, 3].find(function(el) {
return el === 2;
}); // returns 2
Consider to use jquery's each method, since it allows to return false inside callback function:
$.each(function(e, i) {
if (i % 2) return false;
console.log(e)
})
Lodash libraries also provides takeWhile method that can be chained with map/reduce/fold etc:
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']
// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']
// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []
If you would like to use Dean Edward's suggestion and throw the StopIteration error to break out of the loop without having to catch the error, you can use the following the function (originally from here):
// Use a closure to prevent the global namespace from be polluted.
(function() {
// Define StopIteration as part of the global scope if it
// isn't already defined.
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
// The original version of Array.prototype.forEach.
var oldForEach = Array.prototype.forEach;
// If forEach actually exists, define forEach so you can
// break out of it by throwing StopIteration. Allow
// other errors will be thrown as normal.
if(oldForEach) {
Array.prototype.forEach = function() {
try {
oldForEach.apply(this, [].slice.call(arguments, 0));
}
catch(e) {
if(e !== StopIteration) {
throw e;
}
}
};
}
})();
The above code will give you the ability to run code such as the following without having to do your own try-catch clauses:
// Show the contents until you get to "2".
[0,1,2,3,4].forEach(function(val) {
if(val == 2)
throw StopIteration;
alert(val);
});
One important thing to remember is that this will only update the Array.prototype.forEach function if it already exists. If it doesn't exist already, it will not modify the it.
Short answer: use for...break for this or change your code to avoid breaking of forEach. Do not use .some() or .every() to emulate for...break. Rewrite your code to avoid for...break loop, or use for...break. Every time you use these methods as for...break alternative God kills kitten.
Long answer:
.some() and .every() both return boolean value, .some() returns true if there any element for which passed function returns true, every returns false if there any element for which passed function returns false. This is what that functions mean. Using functions for what they doesn't mean is much worse then using tables for layout instead of CSS, because it frustrates everybody who reads your code.
Also, the only possible way to use these methods as for...break alternative is to make side-effects (change some vars outside of .some() callback function), and this is not much different from for...break.
So, using .some() or .every() as for...break loop alternative isn't free of side effects, this isn't much cleaner then for...break, this is frustrating, so this isn't better.
You can always rewrite your code so that there will be no need in for...break. You can filter array using .filter(), you can split array using .slice() and so on, then use .forEach() or .map() for that part of array.
As mentioned before, you can't break .forEach().
Here's a slightly more modern way of doing a foreach with ES6 Iterators. Allows you to get direct access to index/value when iterating.
const array = ['one', 'two', 'three'];
for (const [index, val] of array.entries()) {
console.log('item:', { index, val });
if (index === 1) {
console.log('break!');
break;
}
}
Output:
item: { index: 0, val: 'one' }
item: { index: 1, val: 'two' }
break!
Links
Array.prototype.entries()
Iterators and generators
Destructuring assignment
Another concept I came up with:
function forEach(array, cb) {
var shouldBreak;
function _break() { shouldBreak = true; }
for (var i = 0, bound = array.length; i < bound; ++i) {
if (shouldBreak) { break; }
cb(array[i], i, array, _break);
}
}
// Usage
forEach(['a','b','c','d','e','f'], function (char, i, array, _break) {
console.log(i, char);
if (i === 2) { _break(); }
});
This is just something I came up with to solve the problem... I'm pretty sure it fixes the problem that the original asker had:
Array.prototype.each = function(callback){
if(!callback) return false;
for(var i=0; i<this.length; i++){
if(callback(this[i], i) == false) break;
}
};
And then you would call it by using:
var myarray = [1,2,3];
myarray.each(function(item, index){
// do something with the item
// if(item != somecondition) return false;
});
Returning false inside the callback function will cause a break. Let me know if that doesn't actually work.
If you don't need to access your array after iteration you can bail out by setting the array's length to 0. If you do still need it after your iteration you could clone it using slice..
[1,3,4,5,6,7,8,244,3,5,2].forEach(function (item, index, arr) {
if (index === 3) arr.length = 0;
});
Or with a clone:
var x = [1,3,4,5,6,7,8,244,3,5,2];
x.slice().forEach(function (item, index, arr) {
if (index === 3) arr.length = 0;
});
Which is a far better solution then throwing random errors in your code.
Found this solution on another site. You can wrap the forEach in a try / catch scenario.
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
try {
[1,2,3].forEach(function(el){
alert(el);
if(el === 1) throw StopIteration;
});
} catch(error) { if(error != StopIteration) throw error; }
More details here: http://dean.edwards.name/weblog/2006/07/enum/
This is a for loop, but maintains the object reference in the loop just like a forEach() but you can break out.
var arr = [1,2,3];
for (var i = 0, el; el = arr[i]; i++) {
if(el === 1) break;
}
try with "find" :
var myCategories = [
{category: "start", name: "Start", color: "#AC193D"},
{category: "action", name: "Action", color: "#8C0095"},
{category: "exit", name: "Exit", color: "#008A00"}
];
function findCategory(category) {
return myCategories.find(function(element) {
return element.category === category;
});
}
console.log(findCategory("start"));
// output: { category: "start", name: "Start", color: "#AC193D" }
Yet another approach:
var wageType = types.filter(function(element){
if(e.params.data.text == element.name){
return element;
}
});
console.dir(wageType);
I use nullhack for that purpose, it tries to access property of null, which is an error:
try {
[1,2,3,4,5]
.forEach(
function ( val, idx, arr ) {
if ( val == 3 ) null.NULLBREAK;
}
);
} catch (e) {
// e <=> TypeError: null has no properties
}
//
Use the array.prototype.every function, which provide you the utility to break the looping. See example here Javascript documentation on Mozilla developer network
Agree with #bobince, upvoted.
Also, FYI:
Prototype.js has something for this purpose:
<script type="text/javascript">
$$('a').each(function(el, idx) {
if ( /* break condition */ ) throw $break;
// do something
});
</script>
$break will be catched and handled by Prototype.js internally, breaking the "each" cycle but not generating external errors.
See Prototype.JS API for details.
jQuery also has a way, just return false in the handler to break the loop early:
<script type="text/javascript">
jQuery('a').each( function(idx) {
if ( /* break condition */ ) return false;
// do something
});
</script>
See jQuery API for details.
If you want to keep your forEach syntax, this is a way to keep it efficient (although not as good as a regular for loop). Check immediately for a variable that knows if you want to break out of the loop.
This example uses a anonymous function for creating a function scope around the forEach which you need to store the done information.
(function(){
var element = document.getElementById('printed-result');
var done = false;
[1,2,3,4].forEach(function(item){
if(done){ return; }
var text = document.createTextNode(item);
element.appendChild(text);
if (item === 2){
done = true;
return;
}
});
})();
<div id="printed-result"></div>
My two cents.
If you need to break based on the value of elements that are already in your array as in your case (i.e. if break condition does not depend on run-time variable that may change after array is assigned its element values) you could also use combination of slice() and indexOf() as follows.
If you need to break when forEach reaches 'Apple' you can use
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var fruitsToLoop = fruits.slice(0, fruits.indexOf("Apple"));
// fruitsToLoop = Banana,Orange,Lemon
fruitsToLoop.forEach(function(el) {
// no need to break
});
As stated in W3Schools.com the slice() method returns the selected elements in an array, as a new array object. The original array will not be changed.
See it in JSFiddle
Hope it helps someone.
Why don't you try wrapping the function in a Promise?
The only reason I bring it up is that I am using a function in an API that acts in a similar manner to forEach. I don't want it to keep iterating once it finds a value, and I need to return something so I am simply going to resolve a Promise and do it that way.
traverseTree(doc): Promise<any> {
return new Promise<any>((resolve, reject) => {
this.gridOptions.api.forEachNode((node, index) => {
//the above function is the one I want to short circuit.
if(node.data.id === doc.id) {
return resolve(node);
}
});
});
}
Then all you need to do is do something with the result like
this.traverseTree(doc).then((result) => {
this.doSomething(result);
});
My above example is in typescript, simply ignore the types. The logic should hopefully help you "break" out of your loop.
This isn't the most efficient, since you still cycle all the elements, but I thought it might be worth considering the very simple:
let keepGoing = true;
things.forEach( (thing) => {
if (noMore) keepGoing = false;
if (keepGoing) {
// do things with thing
}
});
you can follow the code below which works for me:
var loopStop = false;
YOUR_ARRAY.forEach(function loop(){
if(loopStop){ return; }
if(condition){ loopStop = true; }
});
Breaking out of built-in Array.prototype.map function esp in React
The key thing to note here is the use of statement return to BREAK
let isBroken = false;
colours.map(item => {
if (isBroken) {
return;
}
if (item.startsWith("y")) {
console.log("The yessiest colour!");
isBroken = true;
return;
}
});
More information here: https://www.codegrepper.com/code-examples/javascript/break+out+of+map+javascript
I know it not right way. It is not break the loop.
It is a Jugad
let result = true;
[1, 2, 3].forEach(function(el) {
if(result){
console.log(el);
if (el === 2){
result = false;
}
}
});
You can create a variant of forEach that allows for break, continue, return, and even async/await: (example written in TypeScript)
export type LoopControlOp = "break" | "continue" | ["return", any];
export type LoopFunc<T> = (value: T, index: number, array: T[])=>LoopControlOp;
Array.prototype.ForEach = function ForEach<T>(this: T[], func: LoopFunc<T>) {
for (let i = 0; i < this.length; i++) {
const controlOp = func(this[i], i, this);
if (controlOp == "break") break;
if (controlOp == "continue") continue;
if (controlOp instanceof Array) return controlOp[1];
}
};
// this variant lets you use async/await in the loop-func, with the loop "awaiting" for each entry
Array.prototype.ForEachAsync = async function ForEachAsync<T>(this: T[], func: LoopFunc<T>) {
for (let i = 0; i < this.length; i++) {
const controlOp = await func(this[i], i, this);
if (controlOp == "break") break;
if (controlOp == "continue") continue;
if (controlOp instanceof Array) return controlOp[1];
}
};
Usage:
function GetCoffee() {
const cancelReason = peopleOnStreet.ForEach((person, index)=> {
if (index == 0) return "continue";
if (person.type == "friend") return "break";
if (person.type == "boss") return ["return", "nevermind"];
});
if (cancelReason) console.log("Coffee canceled because: " + cancelReason);
}
I use return false and it works for me.
const Book = {"Titles":[
{"Book3" : "BULLETIN 3"},
{"Book1" : "BULLETIN 1"},
{"Book2" : "BULLETIN 2"}
]}
const findbystr = function(str) {
Book.Titles.forEach(function(data) {
if (typeof data[str] != 'undefined') {
return data[str];
}
}, str)
}
book = findbystr('Book1');
console.log(book);

Javascript forEach function confusion [duplicate]

[1,2,3].forEach(function(el) {
if(el === 1) break;
});
How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.
There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.
var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.
Use Array#some
Instead, use Array#some:
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.
some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.
Use Array#every
[1, 2, 3].every(v => {
if (v > 2) {
return false // "break"
}
console.log(v);
return true // must return true if doesn't break
});
There is now an even better way to do this in ECMAScript2015 (aka ES6) using the new for of loop. For example, this code does not print the array elements after the number 5:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (const el of arr) {
console.log(el);
if (el === 5) {
break;
}
}
From the docs:
Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of an object, in original insertion order. The for...of statement iterates over data that iterable object defines to be iterated over.
Need the index in the iteration? You can use Array.entries():
for (const [index, el] of arr.entries()) {
if ( index === 5 ) break;
}
You can use every method:
[1,2,3].every(function(el) {
return !(el === 1);
});
ES6
[1,2,3].every( el => el !== 1 )
for old browser support use:
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
more details here.
Quoting from the MDN documentation of Array.prototype.forEach():
There is no way to stop or break a forEach() loop other than
by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead.
For your code (in the question), as suggested by #bobince, use Array.prototype.some() instead. It suits very well to your usecase.
Array.prototype.some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns false. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Unfortunately in this case it will be much better if you don't use forEach.
Instead use a regular for loop and it will now work exactly as you would expect.
var array = [1, 2, 3];
for (var i = 0; i < array.length; i++) {
if (array[i] === 1){
break;
}
}
From your code example, it looks like Array.prototype.find is what you are looking for: Array.prototype.find() and Array.prototype.findIndex()
[1, 2, 3].find(function(el) {
return el === 2;
}); // returns 2
Consider to use jquery's each method, since it allows to return false inside callback function:
$.each(function(e, i) {
if (i % 2) return false;
console.log(e)
})
Lodash libraries also provides takeWhile method that can be chained with map/reduce/fold etc:
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']
// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']
// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []
If you would like to use Dean Edward's suggestion and throw the StopIteration error to break out of the loop without having to catch the error, you can use the following the function (originally from here):
// Use a closure to prevent the global namespace from be polluted.
(function() {
// Define StopIteration as part of the global scope if it
// isn't already defined.
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
// The original version of Array.prototype.forEach.
var oldForEach = Array.prototype.forEach;
// If forEach actually exists, define forEach so you can
// break out of it by throwing StopIteration. Allow
// other errors will be thrown as normal.
if(oldForEach) {
Array.prototype.forEach = function() {
try {
oldForEach.apply(this, [].slice.call(arguments, 0));
}
catch(e) {
if(e !== StopIteration) {
throw e;
}
}
};
}
})();
The above code will give you the ability to run code such as the following without having to do your own try-catch clauses:
// Show the contents until you get to "2".
[0,1,2,3,4].forEach(function(val) {
if(val == 2)
throw StopIteration;
alert(val);
});
One important thing to remember is that this will only update the Array.prototype.forEach function if it already exists. If it doesn't exist already, it will not modify the it.
Short answer: use for...break for this or change your code to avoid breaking of forEach. Do not use .some() or .every() to emulate for...break. Rewrite your code to avoid for...break loop, or use for...break. Every time you use these methods as for...break alternative God kills kitten.
Long answer:
.some() and .every() both return boolean value, .some() returns true if there any element for which passed function returns true, every returns false if there any element for which passed function returns false. This is what that functions mean. Using functions for what they doesn't mean is much worse then using tables for layout instead of CSS, because it frustrates everybody who reads your code.
Also, the only possible way to use these methods as for...break alternative is to make side-effects (change some vars outside of .some() callback function), and this is not much different from for...break.
So, using .some() or .every() as for...break loop alternative isn't free of side effects, this isn't much cleaner then for...break, this is frustrating, so this isn't better.
You can always rewrite your code so that there will be no need in for...break. You can filter array using .filter(), you can split array using .slice() and so on, then use .forEach() or .map() for that part of array.
As mentioned before, you can't break .forEach().
Here's a slightly more modern way of doing a foreach with ES6 Iterators. Allows you to get direct access to index/value when iterating.
const array = ['one', 'two', 'three'];
for (const [index, val] of array.entries()) {
console.log('item:', { index, val });
if (index === 1) {
console.log('break!');
break;
}
}
Output:
item: { index: 0, val: 'one' }
item: { index: 1, val: 'two' }
break!
Links
Array.prototype.entries()
Iterators and generators
Destructuring assignment
Another concept I came up with:
function forEach(array, cb) {
var shouldBreak;
function _break() { shouldBreak = true; }
for (var i = 0, bound = array.length; i < bound; ++i) {
if (shouldBreak) { break; }
cb(array[i], i, array, _break);
}
}
// Usage
forEach(['a','b','c','d','e','f'], function (char, i, array, _break) {
console.log(i, char);
if (i === 2) { _break(); }
});
This is just something I came up with to solve the problem... I'm pretty sure it fixes the problem that the original asker had:
Array.prototype.each = function(callback){
if(!callback) return false;
for(var i=0; i<this.length; i++){
if(callback(this[i], i) == false) break;
}
};
And then you would call it by using:
var myarray = [1,2,3];
myarray.each(function(item, index){
// do something with the item
// if(item != somecondition) return false;
});
Returning false inside the callback function will cause a break. Let me know if that doesn't actually work.
If you don't need to access your array after iteration you can bail out by setting the array's length to 0. If you do still need it after your iteration you could clone it using slice..
[1,3,4,5,6,7,8,244,3,5,2].forEach(function (item, index, arr) {
if (index === 3) arr.length = 0;
});
Or with a clone:
var x = [1,3,4,5,6,7,8,244,3,5,2];
x.slice().forEach(function (item, index, arr) {
if (index === 3) arr.length = 0;
});
Which is a far better solution then throwing random errors in your code.
Found this solution on another site. You can wrap the forEach in a try / catch scenario.
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
try {
[1,2,3].forEach(function(el){
alert(el);
if(el === 1) throw StopIteration;
});
} catch(error) { if(error != StopIteration) throw error; }
More details here: http://dean.edwards.name/weblog/2006/07/enum/
This is a for loop, but maintains the object reference in the loop just like a forEach() but you can break out.
var arr = [1,2,3];
for (var i = 0, el; el = arr[i]; i++) {
if(el === 1) break;
}
try with "find" :
var myCategories = [
{category: "start", name: "Start", color: "#AC193D"},
{category: "action", name: "Action", color: "#8C0095"},
{category: "exit", name: "Exit", color: "#008A00"}
];
function findCategory(category) {
return myCategories.find(function(element) {
return element.category === category;
});
}
console.log(findCategory("start"));
// output: { category: "start", name: "Start", color: "#AC193D" }
Yet another approach:
var wageType = types.filter(function(element){
if(e.params.data.text == element.name){
return element;
}
});
console.dir(wageType);
I use nullhack for that purpose, it tries to access property of null, which is an error:
try {
[1,2,3,4,5]
.forEach(
function ( val, idx, arr ) {
if ( val == 3 ) null.NULLBREAK;
}
);
} catch (e) {
// e <=> TypeError: null has no properties
}
//
Use the array.prototype.every function, which provide you the utility to break the looping. See example here Javascript documentation on Mozilla developer network
Agree with #bobince, upvoted.
Also, FYI:
Prototype.js has something for this purpose:
<script type="text/javascript">
$$('a').each(function(el, idx) {
if ( /* break condition */ ) throw $break;
// do something
});
</script>
$break will be catched and handled by Prototype.js internally, breaking the "each" cycle but not generating external errors.
See Prototype.JS API for details.
jQuery also has a way, just return false in the handler to break the loop early:
<script type="text/javascript">
jQuery('a').each( function(idx) {
if ( /* break condition */ ) return false;
// do something
});
</script>
See jQuery API for details.
If you want to keep your forEach syntax, this is a way to keep it efficient (although not as good as a regular for loop). Check immediately for a variable that knows if you want to break out of the loop.
This example uses a anonymous function for creating a function scope around the forEach which you need to store the done information.
(function(){
var element = document.getElementById('printed-result');
var done = false;
[1,2,3,4].forEach(function(item){
if(done){ return; }
var text = document.createTextNode(item);
element.appendChild(text);
if (item === 2){
done = true;
return;
}
});
})();
<div id="printed-result"></div>
My two cents.
If you need to break based on the value of elements that are already in your array as in your case (i.e. if break condition does not depend on run-time variable that may change after array is assigned its element values) you could also use combination of slice() and indexOf() as follows.
If you need to break when forEach reaches 'Apple' you can use
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var fruitsToLoop = fruits.slice(0, fruits.indexOf("Apple"));
// fruitsToLoop = Banana,Orange,Lemon
fruitsToLoop.forEach(function(el) {
// no need to break
});
As stated in W3Schools.com the slice() method returns the selected elements in an array, as a new array object. The original array will not be changed.
See it in JSFiddle
Hope it helps someone.
Why don't you try wrapping the function in a Promise?
The only reason I bring it up is that I am using a function in an API that acts in a similar manner to forEach. I don't want it to keep iterating once it finds a value, and I need to return something so I am simply going to resolve a Promise and do it that way.
traverseTree(doc): Promise<any> {
return new Promise<any>((resolve, reject) => {
this.gridOptions.api.forEachNode((node, index) => {
//the above function is the one I want to short circuit.
if(node.data.id === doc.id) {
return resolve(node);
}
});
});
}
Then all you need to do is do something with the result like
this.traverseTree(doc).then((result) => {
this.doSomething(result);
});
My above example is in typescript, simply ignore the types. The logic should hopefully help you "break" out of your loop.
This isn't the most efficient, since you still cycle all the elements, but I thought it might be worth considering the very simple:
let keepGoing = true;
things.forEach( (thing) => {
if (noMore) keepGoing = false;
if (keepGoing) {
// do things with thing
}
});
you can follow the code below which works for me:
var loopStop = false;
YOUR_ARRAY.forEach(function loop(){
if(loopStop){ return; }
if(condition){ loopStop = true; }
});
Breaking out of built-in Array.prototype.map function esp in React
The key thing to note here is the use of statement return to BREAK
let isBroken = false;
colours.map(item => {
if (isBroken) {
return;
}
if (item.startsWith("y")) {
console.log("The yessiest colour!");
isBroken = true;
return;
}
});
More information here: https://www.codegrepper.com/code-examples/javascript/break+out+of+map+javascript
I know it not right way. It is not break the loop.
It is a Jugad
let result = true;
[1, 2, 3].forEach(function(el) {
if(result){
console.log(el);
if (el === 2){
result = false;
}
}
});
You can create a variant of forEach that allows for break, continue, return, and even async/await: (example written in TypeScript)
export type LoopControlOp = "break" | "continue" | ["return", any];
export type LoopFunc<T> = (value: T, index: number, array: T[])=>LoopControlOp;
Array.prototype.ForEach = function ForEach<T>(this: T[], func: LoopFunc<T>) {
for (let i = 0; i < this.length; i++) {
const controlOp = func(this[i], i, this);
if (controlOp == "break") break;
if (controlOp == "continue") continue;
if (controlOp instanceof Array) return controlOp[1];
}
};
// this variant lets you use async/await in the loop-func, with the loop "awaiting" for each entry
Array.prototype.ForEachAsync = async function ForEachAsync<T>(this: T[], func: LoopFunc<T>) {
for (let i = 0; i < this.length; i++) {
const controlOp = await func(this[i], i, this);
if (controlOp == "break") break;
if (controlOp == "continue") continue;
if (controlOp instanceof Array) return controlOp[1];
}
};
Usage:
function GetCoffee() {
const cancelReason = peopleOnStreet.ForEach((person, index)=> {
if (index == 0) return "continue";
if (person.type == "friend") return "break";
if (person.type == "boss") return ["return", "nevermind"];
});
if (cancelReason) console.log("Coffee canceled because: " + cancelReason);
}
I use return false and it works for me.
const Book = {"Titles":[
{"Book3" : "BULLETIN 3"},
{"Book1" : "BULLETIN 1"},
{"Book2" : "BULLETIN 2"}
]}
const findbystr = function(str) {
Book.Titles.forEach(function(data) {
if (typeof data[str] != 'undefined') {
return data[str];
}
}, str)
}
book = findbystr('Book1');
console.log(book);

Understanding callback.call function in jquery

Please go through the below code.
I am not able to exactly what's calllback.call is doing.
Also, I am not able to know what is the difference between this and this[i] and how if(callback.call(this, this[i])) is evaluated to true or false.
Array.prototype.each = function(callback) {
var i = 0;
while (i < this.length) {
callback.call(this, this[i]);
i++;
}
return this;
};
Array.prototype.map = function(callback) {
var i = this.length;
var found = []
while (i--) {
if(callback.call(this, this[i])) {
found.push(this[i]);
}
}
return found;
};
The functions are called below:
Array.each(function(value){
...
})
Array.map(function(value){
...
})
I am not able to exactly what's calllback.call is doing.
Function.prototype.call lets you invoke a function with an explicit value for this
callback.call(this, this[i]);
is the same as
callback(this[i])
except that inside the callback the value of this is the set to be the same as it was in the current context.
Also am not able to know what is the difference between this and this[i].
In this context, this is the current array. So this means the whole array, this[i] gets the i'th element of the array.
The .each function you have will loop through an array and call a function for each of them. This is similar to javascript's built in Array.prototype.forEach.
The .map is named as though it were a polyfill for Array.protoype.map but is actually doing a .filter operation. Strange.

How to overload functions in javascript?

Classical (non-js) approach to overloading:
function myFunc(){
//code
}
function myFunc(overloaded){
//other code
}
Javascript wont let more than one function be defined with the same name. As such, things like this show up:
function myFunc(options){
if(options["overloaded"]){
//code
}
}
Is there a better workaround for function overloading in javascript other than passing an object with the overloads in it?
Passing in overloads can quickly cause a function to become too verbose because each possible overload would then need a conditional statement. Using functions to accomplish the //code inside of those conditional statements can cause tricky situations with scopes.
There are multiple aspects to argument overloading in Javascript:
Variable arguments - You can pass different sets of arguments (in both type and quantity) and the function will behave in a way that matches the arguments passed to it.
Default arguments - You can define a default value for an argument if it is not passed.
Named arguments - Argument order becomes irrelevant and you just name which arguments you want to pass to the function.
Below is a section on each of these categories of argument handling.
Variable Arguments
Because javascript has no type checking on arguments or required qty of arguments, you can just have one implementation of myFunc() that can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments.
jQuery does this all the time. You can make some of the arguments optional or you can branch in your function depending upon what arguments are passed to it.
In implementing these types of overloads, you have several different techniques you can use:
You can check for the presence of any given argument by checking to see if the declared argument name value is undefined.
You can check the total quantity or arguments with arguments.length.
You can check the type of any given argument.
For variable numbers of arguments, you can use the arguments pseudo-array to access any given argument with arguments[i].
Here are some examples:
Let's look at jQuery's obj.data() method. It supports four different forms of usage:
obj.data("key");
obj.data("key", value);
obj.data();
obj.data(object);
Each one triggers a different behavior and, without using this dynamic form of overloading, would require four separate functions.
Here's how one can discern between all these options in English and then I'll combine them all in code:
// get the data element associated with a particular key value
obj.data("key");
If the first argument passed to .data() is a string and the second argument is undefined, then the caller must be using this form.
// set the value associated with a particular key
obj.data("key", value);
If the second argument is not undefined, then set the value of a particular key.
// get all keys/values
obj.data();
If no arguments are passed, then return all keys/values in a returned object.
// set all keys/values from the passed in object
obj.data(object);
If the type of the first argument is a plain object, then set all keys/values from that object.
Here's how you could combine all of those in one set of javascript logic:
// method declaration for .data()
data: function(key, value) {
if (arguments.length === 0) {
// .data()
// no args passed, return all keys/values in an object
} else if (typeof key === "string") {
// first arg is a string, look at type of second arg
if (typeof value !== "undefined") {
// .data("key", value)
// set the value for a particular key
} else {
// .data("key")
// retrieve a value for a key
}
} else if (typeof key === "object") {
// .data(object)
// set all key/value pairs from this object
} else {
// unsupported arguments passed
}
},
The key to this technique is to make sure that all forms of arguments you want to accept are uniquely identifiable and there is never any confusion about which form the caller is using. This generally requires ordering the arguments appropriately and making sure that there is enough uniqueness in the type and position of the arguments that you can always tell which form is being used.
For example, if you have a function that takes three string arguments:
obj.query("firstArg", "secondArg", "thirdArg");
You can easily make the third argument optional and you can easily detect that condition, but you cannot make only the second argument optional because you can't tell which of these the caller means to be passing because there is no way to identify if the second argument is meant to be the second argument or the second argument was omitted so what's in the second argument's spot is actually the third argument:
obj.query("firstArg", "secondArg");
obj.query("firstArg", "thirdArg");
Since all three arguments are the same type, you can't tell the difference between different arguments so you don't know what the caller intended. With this calling style, only the third argument can be optional. If you wanted to omit the second argument, it would have to be passed as null (or some other detectable value) instead and your code would detect that:
obj.query("firstArg", null, "thirdArg");
Here's a jQuery example of optional arguments. both arguments are optional and take on default values if not passed:
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
Here's a jQuery example where the argument can be missing or any one of three different types which gives you four different overloads:
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
Named Arguments
Other languages (like Python) allow one to pass named arguments as a means of passing only some arguments and making the arguments independent of the order they are passed in. Javascript does not directly support the feature of named arguments. A design pattern that is commonly used in its place is to pass a map of properties/values. This can be done by passing an object with properties and values or in ES6 and above, you could actually pass a Map object itself.
Here's a simple ES5 example:
jQuery's $.ajax() accepts a form of usage where you just pass it a single parameter which is a regular Javascript object with properties and values. Which properties you pass it determine which arguments/options are being passed to the ajax call. Some may be required, many are optional. Since they are properties on an object, there is no specific order. In fact, there are more than 30 different properties that can be passed on that object, only one (the url) is required.
Here's an example:
$.ajax({url: "http://www.example.com/somepath", data: myArgs, dataType: "json"}).then(function(result) {
// process result here
});
Inside of the $.ajax() implementation, it can then just interrogate which properties were passed on the incoming object and use those as named arguments. This can be done either with for (prop in obj) or by getting all the properties into an array with Object.keys(obj) and then iterating that array.
This technique is used very commonly in Javascript when there are large numbers of arguments and/or many arguments are optional. Note: this puts an onus on the implementating function to make sure that a minimal valid set of arguments is present and to give the caller some debug feedback what is missing if insufficient arguments are passed (probably by throwing an exception with a helpful error message).
In an ES6 environment, it is possible to use destructuring to create default properties/values for the above passed object. This is discussed in more detail in this reference article.
Here's one example from that article:
function selectEntries({ start=0, end=-1, step=1 } = {}) {
···
};
Then, you can call this like any of these:
selectEntries({start: 5});
selectEntries({start: 5, end: 10});
selectEntries({start: 5, end: 10, step: 2});
selectEntries({step: 3});
selectEntries();
The arguments you do not list in the function call will pick up their default values from the function declaration.
This creates default properties and values for the start, end and step properties on an object passed to the selectEntries() function.
Default values for function arguments
In ES6, Javascript adds built-in language support for default values for arguments.
For example:
function multiply(a, b = 1) {
return a*b;
}
multiply(5); // 5
Further description of the ways this can be used here on MDN.
Overloading a function in JavaScript can be done in many ways. All of them involve a single master function that either performs all the processes, or delegates to sub-functions/processes.
One of the most common simple techniques involves a simple switch:
function foo(a, b) {
switch (arguments.length) {
case 0:
//do basic code
break;
case 1:
//do code with `a`
break;
case 2:
default:
//do code with `a` & `b`
break;
}
}
A more elegant technique would be to use an array (or object if you're not making overloads for every argument count):
fooArr = [
function () {
},
function (a) {
},
function (a,b) {
}
];
function foo(a, b) {
return fooArr[arguments.length](a, b);
}
That previous example isn't very elegant, anyone could modify fooArr, and it would fail if someone passes in more than 2 arguments to foo, so a better form would be to use a module pattern and a few checks:
var foo = (function () {
var fns;
fns = [
function () {
},
function (a) {
},
function (a, b) {
}
];
function foo(a, b) {
var fnIndex;
fnIndex = arguments.length;
if (fnIndex > foo.length) {
fnIndex = foo.length;
}
return fns[fnIndex].call(this, a, b);
}
return foo;
}());
Of course your overloads might want to use a dynamic number of parameters, so you could use an object for the fns collection.
var foo = (function () {
var fns;
fns = {};
fns[0] = function () {
};
fns[1] = function (a) {
};
fns[2] = function (a, b) {
};
fns.params = function (a, b /*, params */) {
};
function foo(a, b) {
var fnIndex;
fnIndex = arguments.length;
if (fnIndex > foo.length) {
fnIndex = 'params';
}
return fns[fnIndex].apply(this, Array.prototype.slice.call(arguments));
}
return foo;
}());
My personal preference tends to be the switch, although it does bulk up the master function. A common example of where I'd use this technique would be a accessor/mutator method:
function Foo() {} //constructor
Foo.prototype = {
bar: function (val) {
switch (arguments.length) {
case 0:
return this._bar;
case 1:
this._bar = val;
return this;
}
}
}
You cannot do method overloading in strict sense. Not like the way it is supported in java or c#.
The issue is that JavaScript does NOT natively support method overloading. So, if it sees/parses two or more functions with a same names it’ll just consider the last defined function and overwrite the previous ones.
One of the way I think is suitable for most of the case is follows -
Lets say you have method
function foo(x)
{
}
Instead of overloading method which is not possible in javascript you can define a new method
fooNew(x,y,z)
{
}
and then modify the 1st function as follows -
function foo(x)
{
if(arguments.length==2)
{
return fooNew(arguments[0], arguments[1]);
}
}
If you have many such overloaded method consider using switch than just if-else statements.
(more details)
PS: Above link goes to my personal blog that has additional details on this.
I am using a bit different overloading approach based on arguments number.
However i believe John Fawcett's approach is also good.
Here the example, code based on John Resig's (jQuery's Author) explanations.
// o = existing object, n = function name, f = function.
function overload(o, n, f){
var old = o[n];
o[n] = function(){
if(f.length == arguments.length){
return f.apply(this, arguments);
}
else if(typeof o == 'function'){
return old.apply(this, arguments);
}
};
}
usability:
var obj = {};
overload(obj, 'function_name', function(){ /* what we will do if no args passed? */});
overload(obj, 'function_name', function(first){ /* what we will do if 1 arg passed? */});
overload(obj, 'function_name', function(first, second){ /* what we will do if 2 args passed? */});
overload(obj, 'function_name', function(first,second,third){ /* what we will do if 3 args passed? */});
//... etc :)
I tried to develop an elegant solution to this problem described here. And you can find the demo here. The usage looks like this:
var out = def({
'int': function(a) {
alert('Here is int '+a);
},
'float': function(a) {
alert('Here is float '+a);
},
'string': function(a) {
alert('Here is string '+a);
},
'int,string': function(a, b) {
alert('Here is an int '+a+' and a string '+b);
},
'default': function(obj) {
alert('Here is some other value '+ obj);
}
});
out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);
The methods used to achieve this:
var def = function(functions, parent) {
return function() {
var types = [];
var args = [];
eachArg(arguments, function(i, elem) {
args.push(elem);
types.push(whatis(elem));
});
if(functions.hasOwnProperty(types.join())) {
return functions[types.join()].apply(parent, args);
} else {
if (typeof functions === 'function')
return functions.apply(parent, args);
if (functions.hasOwnProperty('default'))
return functions['default'].apply(parent, args);
}
};
};
var eachArg = function(args, fn) {
var i = 0;
while (args.hasOwnProperty(i)) {
if(fn !== undefined)
fn(i, args[i]);
i++;
}
return i-1;
};
var whatis = function(val) {
if(val === undefined)
return 'undefined';
if(val === null)
return 'null';
var type = typeof val;
if(type === 'object') {
if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
return 'array';
if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
return 'date';
if(val.hasOwnProperty('toExponential'))
type = 'number';
if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
return 'string';
}
if(type === 'number') {
if(val.toString().indexOf('.') > 0)
return 'float';
else
return 'int';
}
return type;
};
In javascript you can implement the function just once and invoke the function without the parameters myFunc() You then check to see if options is 'undefined'
function myFunc(options){
if(typeof options != 'undefined'){
//code
}
}
https://github.com/jrf0110/leFunc
var getItems = leFunc({
"string": function(id){
// Do something
},
"string,object": function(id, options){
// Do something else
},
"string,object,function": function(id, options, callback){
// Do something different
callback();
},
"object,string,function": function(options, message, callback){
// Do something ca-raaaaazzzy
callback();
}
});
getItems("123abc"); // Calls the first function - "string"
getItems("123abc", {poop: true}); // Calls the second function - "string,object"
getItems("123abc", {butt: true}, function(){}); // Calls the third function - "string,object,function"
getItems({butt: true}, "What what?" function(){}); // Calls the fourth function - "object,string,function"
No Problem with Overloading in JS , The pb how to maintain a clean code when overloading function ?
You can use a forward to have clean code, based on two things:
Number of arguments (when calling the function).
Type of arguments (when calling the function)
function myFunc(){
return window['myFunc_'+arguments.length+Array.from(arguments).map((arg)=>typeof arg).join('_')](...arguments);
}
/** one argument & this argument is string */
function myFunc_1_string(){
}
//------------
/** one argument & this argument is object */
function myFunc_1_object(){
}
//----------
/** two arguments & those arguments are both string */
function myFunc_2_string_string(){
}
//--------
/** Three arguments & those arguments are : id(number),name(string), callback(function) */
function myFunc_3_number_string_function(){
let args=arguments;
new Person(args[0],args[1]).onReady(args[3]);
}
//--- And so on ....
How about using a proxy (ES6 Feature)?
I didn't find anywhere mentioning this method of doing it. It might be impractical but it's an interesting way nonetheless.
It's similar to Lua's metatables, where you can "overload" the call operator with the __call metamethod in order to achieve overloading.
In JS, it can be done with the apply method in a Proxy handler. You can check the arguments' existence, types, etc. inside the said method, without having to do it in the actual function.
MDN: proxy apply method
function overloads() {}
overloads.overload1 = (a, b) => {
return a + b;
}
overloads.overload2 = (a, b, c) => {
return a + b + c;
}
const overloadedFn = new Proxy(overloads, { // the first arg needs to be an Call-able object
apply(target, thisArg, args) {
if (args[2]) {
return target.overload2(...args);
}
return target.overload1(...args);
}
})
console.log(overloadedFn(1, 2, 3)); // 6
console.log(overloadedFn(1, 2)); // 3
Check this out:
http://www.codeproject.com/Articles/688869/Overloading-JavaScript-Functions
Basically in your class, you number your functions that you want to be overloaded and then with one function call you add function overloading, fast and easy.
Since JavaScript doesn't have function overload options object can be used instead. If there are one or two required arguments, it's better to keep them separate from the options object. Here is an example on how to use options object and populated values to default value in case if value was not passed in options object.
function optionsObjectTest(x, y, opts) {
opts = opts || {}; // default to an empty options object
var stringValue = opts.stringValue || "string default value";
var boolValue = !!opts.boolValue; // coerces value to boolean with a double negation pattern
var numericValue = opts.numericValue === undefined ? 123 : opts.numericValue;
return "{x:" + x + ", y:" + y + ", stringValue:'" + stringValue + "', boolValue:" + boolValue + ", numericValue:" + numericValue + "}";
}
here is an example on how to use options object
For this you need to create a function that adds the function to an object, then it will execute depending on the amount of arguments you send to the function:
<script >
//Main function to add the methods
function addMethod(object, name, fn) {
var old = object[name];
object[name] = function(){
if (fn.length == arguments.length)
return fn.apply(this, arguments)
else if (typeof old == 'function')
return old.apply(this, arguments);
};
}
 var ninjas = {
values: ["Dean Edwards", "Sam Stephenson", "Alex Russell"]
};
//Here we declare the first function with no arguments passed
addMethod(ninjas, "find", function(){
return this.values;
});
//Second function with one argument
addMethod(ninjas, "find", function(name){
var ret = [];
for (var i = 0; i < this.values.length; i++)
if (this.values[i].indexOf(name) == 0)
ret.push(this.values[i]);
return ret;
});
//Third function with two arguments
addMethod(ninjas, "find", function(first, last){
var ret = [];
for (var i = 0; i < this.values.length; i++)
if (this.values[i] == (first + " " + last))
ret.push(this.values[i]);
return ret;
});
//Now you can do:
ninjas.find();
ninjas.find("Sam");
ninjas.find("Dean", "Edwards")
</script>
How about using spread operator as a parameter? The same block can be called with Multiple parameters. All the parameters are added into an array and inside the method you can loop in based on the length.
function mName(...opt){
console.log(opt);
}
mName(1,2,3,4); //[1,2,3,4]
mName(1,2,3); //[1,2,3]
I like to add sub functions within a parent function to achieve the ability to differentiate between argument groups for the same functionality.
var doSomething = function() {
var foo;
var bar;
};
doSomething.withArgSet1 = function(arg0, arg1) {
var obj = new doSomething();
// do something the first way
return obj;
};
doSomething.withArgSet2 = function(arg2, arg3) {
var obj = new doSomething();
// do something the second way
return obj;
};
What you are trying to achieve is best done using the function's local arguments variable.
function foo() {
if (arguments.length === 0) {
//do something
}
if (arguments.length === 1) {
//do something else
}
}
foo(); //do something
foo('one'); //do something else
You can find a better explanation of how this works here.
(() => {
//array that store functions
var Funcs = []
/**
* #param {function} f overload function
* #param {string} fname overload function name
* #param {parameters} vtypes function parameters type descriptor (number,string,object....etc
*/
overloadFunction = function(f, fname, ...vtypes) {
var k,l, n = false;
if (!Funcs.hasOwnProperty(fname)) Funcs[fname] = [];
Funcs[fname].push([f, vtypes?vtypes: 0 ]);
window[fname] = function() {
for (k = 0; k < Funcs[fname].length; k++)
if (arguments.length == Funcs[fname][k][0].length) {
n=true;
if (Funcs[fname][k][1]!=0)
for(i=0;i<arguments.length;i++)
{
if(typeof arguments[i]!=Funcs[fname][k][1][i])
{
n=false;
}
}
if(n) return Funcs[fname][k][0].apply(this, arguments);
}
}
}
})();
//First sum function definition with parameter type descriptors
overloadFunction(function(a,b){return a+b},"sum","number","number")
//Second sum function definition with parameter with parameter type descriptors
overloadFunction(function(a,b){return a+" "+b},"sum","string","string")
//Third sum function definition (not need parameter type descriptors,because no other functions with the same number of parameters
overloadFunction(function(a,b,c){return a+b+c},"sum")
//call first function
console.log(sum(4,2));//return 6
//call second function
console.log(sum("4","2"));//return "4 2"
//call third function
console.log(sum(3,2,5));//return 10
//ETC...

Categories

Resources