Skip to content

Instantly share code, notes, and snippets.

@Ynote
Last active June 14, 2016 16:46
Show Gist options
  • Save Ynote/41cf36ca5020043235aa to your computer and use it in GitHub Desktop.
Save Ynote/41cf36ca5020043235aa to your computer and use it in GitHub Desktop.
[Javascript] - forEach function implementation
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