Skip to content

Instantly share code, notes, and snippets.

@tmcw
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/fa858878cf84f5029848 to your computer and use it in GitHub Desktop.
Save tmcw/fa858878cf84f5029848 to your computer and use it in GitHub Desktop.
Gist from mistakes.io
// Array.find
function find(array, tester) {
return array.reduce(function(memo, value) {
return memo || tester(value);
}, false);
}
find([1, 2, 3], function(value) { return value > 2; });
// Array.map
function map(array, fn) {
return array.reduce(function(memo, value) {
return memo.concat([fn(value)]);
}, []);
}
map([1, 2, 3], function(value) { return value + 1; });
// Array.filter
function filter(array, fn) {
return array.reduce(function(memo, value) {
return fn(value) ? memo.concat([value]) : memo;
}, []);
}
filter([1, 2, 3], function(value) { return value > 1; });
// .length
function length(array) {
return array.reduce(function(length, value) {
return ++length;
}, 0);
}
length([1, 2, 3]);
// zip
function zip(array) {
return array.reduce(function(obj, value) {
obj[value[0]] = value[1];
return obj;
}, {});
}
zip([['foo', 'bar'], ['apples', 'grapes']]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment