Last active
August 30, 2015 22:25
-
-
Save Gwash3189/b2046a422220353e8ca9 to your computer and use it in GitHub Desktop.
Kofta currying library
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
const kofta = function(func) { | |
const OrEqualTo = (func, x, y) => func(x, y) || Equals(x, y); | |
const GreaterThan = (x, y) => x > y; | |
const Equals = (x, y) => x === y; | |
const True = (x) => Equals(x, true); | |
const Null = (n) => Equals(n, null); | |
const Maybe = (bool, func) => !!bool ? func() : undefined; | |
const MaybeOrElse = (bool, m, e) => Maybe(bool, m) || Maybe(!bool, e) | |
const handle = function(func) { | |
const inner = (...args, prevArgs = []) => { | |
let length = getParamNames(func); | |
const holes = handleHoles(args); | |
prevArgs = constructArrayFromHoles(holes); | |
return MaybeOrElse( | |
OrEqualTo( | |
GreaterThan, removeKofta(args).length, length), | |
() => func.apply(null, args), | |
() => (...more) => console.log(prevArgs) | |
) | |
}; | |
return inner | |
}; | |
const removeKofta = function(argsArray) { | |
return argsArray.filter(x => x !== kofta); | |
} | |
const constructArrayFromHoles = function(holesArray){ | |
let prevArgs = []; | |
holesArray.map(x => prevArgs[prevArgs.pos] = prevArgs.value); | |
return prevArgs; | |
} | |
const handleHoles = function(argsArray) { | |
return argsArray.map((x, i) => { | |
if(x !== kofta){ | |
return { | |
pos: i, | |
value: x | |
} | |
} | |
}) | |
.filter(x => True(x)) | |
} | |
const getParamNames = function(func) { | |
const ARGUMENT_NAMES = /([^\s,]+)/g; //this will isolate the argument names | |
//getting the argument names back in an array will allow us to track how many arguments the function takes | |
const fnStr = func.toString(); | |
const result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); | |
return Null(result) ? 0 : result.length; | |
}; | |
return handle(func); | |
}; | |
let k = kofta((a, b) => a + b); | |
k(kofta, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment