Last active
June 14, 2016 16:46
-
-
Save Ynote/41cf36ca5020043235aa to your computer and use it in GitHub Desktop.
[Javascript] - forEach function implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function forEach(list, callback, endIndex) | |
{ | |
if (!list instanceof Array) console.error('forEach method accepts an instanceof Array as first parameter!') | |
var end = endIndex || list.length - 1, | |
args = [[list, callback, endIndex], Array.prototype.slice.call(arguments, 3)], | |
args = args.reduce(function(a,b){ return a.concat(b); }); | |
for(var i = 0; i <= end; i++) | |
{ | |
args.unshift(i); | |
callback.apply(list[i], args); | |
} | |
} | |
// Test | |
function assert(value, desc) | |
{ | |
var result = value ? 'pass' : 'fail'; | |
console.log(result + ' => ' + desc); | |
} | |
var charcuteries = ['rosette', 'coppa', 'mortadelle']; | |
forEach( | |
charcuteries, | |
function(index) | |
{ | |
assert(this == charcuteries[index], 'Expected value of ' + charcuteries[index]) | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment