Last active
April 18, 2017 04:22
-
-
Save bravelincy/2e485ee8c0bba8ce31312db7b4c221b1 to your computer and use it in GitHub Desktop.
This file contains 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
'use strict'; | |
const sliceArgs = function(args, beginIndex, endIndex) { | |
return Array.prototype.slice.call(args, beginIndex, endIndex); | |
}; | |
const _ = Symbol('placeholder'); | |
function partial(fn) { | |
let _args = sliceArgs(arguments, 1); | |
return function() { | |
let args = sliceArgs(arguments); | |
args = _args.map(x => x === _ ? args.shift() : x).concat(args); | |
return fn.apply(null, args); | |
} | |
} | |
function curry(fn, arity) { | |
isNaN(arity) && (arity = fn.length); | |
return function() { | |
let args = sliceArgs(arguments); | |
let need = args.reduce((acc, cur) => cur === _ ? acc : --acc, arity); | |
if (need > 0) { | |
return curry(partial.apply(null, [fn].concat(args)), need); | |
} | |
return fn.apply(null, args); | |
}; | |
} | |
const say = function(name, msg) { | |
console.log(`${name} says: ${msg}`) | |
} | |
const sum = function() { | |
return [].reduce.call(arguments, function(acc, cur) { | |
return acc + cur; | |
}, 0); | |
}; | |
const joenilSay = partial(say, 'Joenil'); | |
const sayHello = partial(say, _, 'hello!'); | |
const add = curry(sum, 3); | |
const addOne = add(1); | |
const addTen = addOne(9); | |
joenilSay('Good morning!') | |
joenilSay('Good night!') | |
sayHello('Joenil') | |
sayHello('Abby') | |
console.log(` | |
add(1, 2, 3): ${add(1, 2, 3)} | |
add(1)(2)(3): ${add(1)(2)(3)} | |
add(1, 2)(3): ${add(1, 2)(3)} | |
add(1)(2, 3): ${add(1)(2, 3)} | |
add(_, 2, 3)(1): ${add(_, 2, 3)(1)} | |
add(1)(_, 3)(2): ${add(1)(_, 3)(2)} | |
add(_, _)(3)(1, 2): ${add(_, _)(3)(1, 2)} | |
addOne(8, 1): ${addOne(8, 1)} | |
addTen(10): ${addTen(10)} | |
`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment