-
-
Save luislee818/6b7badde02b6d4756796 to your computer and use it in GitHub Desktop.
Poor man's Ramda, dependent on underscore.js
This file contains hidden or 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
// Dependencies | |
// _ | |
// Some helper functions to be used in composition, inspired by Ramda | |
window.r = (function(_) { | |
var curry, | |
flip2, | |
invoke, | |
split, | |
map, | |
drop; | |
// (* -> a) -> (* -> a) | |
// Returns a curried equivalent of the provided function | |
curry = function(fn) { | |
var context = this; | |
return function wrapped() { | |
var arity = fn.length; | |
var later = function() { | |
var args = _.toArray(arguments); | |
if (args.length >= arity) { | |
return fn.apply(context, args); | |
} else { | |
return function() { | |
var accumulatedArgs = args.concat(_.toArray(arguments)); | |
return later.apply(context, accumulatedArgs); | |
}; | |
} | |
}; | |
return later.apply(context, _.toArray(arguments)); | |
}; | |
}; | |
// (a -> b -> c) -> (b -> a -> c) | |
// Returns a function with the two arguments flipped | |
flip2 = curry(function(fn) { | |
var context = this; | |
return function(a, b) { | |
return fn.apply(context, [b, a]); | |
}; | |
}); | |
// (* -> a) -> * -> Object -> * | |
// Invokes function with arguments and context | |
invoke = function(fn) { | |
return function() { | |
var args = _.toArray(arguments); | |
return function(target) { | |
return fn.apply(target, args); | |
}; | |
}; | |
}; | |
// (String | RegExp) -> String -> [String] | |
// Splits a string into an array of strings based on the given separator. | |
split = invoke(String.prototype.split); | |
// (a -> b) -> [a] -> [b] | |
// Map a transformation function over a collection | |
map = curry(flip2(_.map)); | |
// Number -> String -> String | |
// Drops the first n characters of the string | |
drop = curry(function(num, str) { | |
return str.substring(num); | |
}); | |
return { | |
flip2: flip2, | |
curry: curry, | |
split: split, | |
map: map, | |
drop: drop, | |
compose: _.compose | |
}; | |
})(_); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment