Last active
October 7, 2017 20:40
-
-
Save noxecane/20f44c2534ed1a10325d35e73b422ead to your computer and use it in GitHub Desktop.
Code I can't do without on 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
var argsToArr = function (args) { | |
return Array.prototype.slice.call(args, 0); | |
}; | |
var argFn = function (fn) { | |
return function () { | |
return fn(argsToArr(arguments)); | |
}; | |
}; | |
exports.curry = function (fn) { | |
return argFn(function curried (args) { | |
if (args.length >= fn.length) { | |
return fn.apply(null, args); | |
} else { | |
return argFn(function (args2) { | |
return curried.apply(null, args.concat(args2)); | |
}); | |
} | |
}); | |
}; | |
exports.compose = argFn(function (args) { | |
if (args.length === 1) { | |
return args[0]; | |
} | |
return args.reduce(function (f, g) { | |
return function () { | |
return f(g.apply(null, arguments)); | |
}; | |
}); | |
}); | |
exports.threadFirst = argFn(function (args) { | |
return function (initialValue) { | |
return args.reduce(function (prev, curr) { | |
if (curr instanceof Array) { | |
var fn = curr.shift(); | |
curr.unshift(prev); | |
return fn.apply(null, curr); | |
} else { | |
return curr(prev); | |
} | |
}, initialValue); | |
}; | |
}); | |
exports.threadLast = argFn(function (args) { | |
return function (initialValue) { | |
return args.reduce(function (prev, curr) { | |
if (curr instanceof Array) { | |
var fn = curr.shift(); | |
curr.push(prev); | |
return fn.apply(null, curr); | |
} else { | |
return curr(prev); | |
} | |
}, initialValue); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment