Skip to content

Instantly share code, notes, and snippets.

@brigand
Created January 29, 2015 11:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brigand/09f6cb5d656149504ed9 to your computer and use it in GitHub Desktop.
Save brigand/09f6cb5d656149504ed9 to your computer and use it in GitHub Desktop.
bend a map function to do other things
// where map(x, function(y, i, z){ z === x; return y }) === x
// and i is the index/key, and z is the first argument to map
// e.g. utilsFromMap(function(array, fn){ array.map(fn) });
// e.g. utilsFromMap(React.Children.map);
function utilsFromMap(map){
var utils = {};
// herein fn is a function,
// X is the thing to be passed to map as the first argument
// and there other parameters are specific to the function
// utils.map = flip(map);
// js is weird
utils.map = function(fn, x){ return map(x, fn); };
utils.reduce = function(fn, start, X){
var acc = start;
map(X, function(x){
acc = fn(acc, x);
return null;
});
return acc;
};
utils.toArray = function(X){
var items = [];
map(X, function(x){ items.push(x); });
return items;
};
utils.reverse = function(X){
var items = utils.toArray(X);
var counter = items.length;
return map(X, function(x, i){
counter--;
return items[counter]
});
};
utils.filter = function(fn, X){
return map(X, function(x, i, X){
return fn(x, i, X) ? x : null;
});
};
utils.length = utils.reduce.bind(null, 0, function(acc){
return acc+1;
});
return utils;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment