Created
February 5, 2017 16:34
-
-
Save benchristel/8eda05c13ad4ddcc44144bc0373b727c to your computer and use it in GitHub Desktop.
Functional stuff (pipeline, autocurry)
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
// test-driven with Ji (benchristel.github.com/ji) | |
// tests go here | |
// hint: open the javascript console for better failure messages | |
expect(start(1).done, eq, 1) | |
expect(start(2).done, eq, 2) | |
expect( | |
start(2) | |
(multiply(3)) | |
.done | |
, eq, 6) | |
expect(concatArgs([1, 2], [3, 4])[2], eq, 3) | |
expect( | |
start(2) | |
(multiply(3)) | |
(add(5)) | |
.done | |
, eq, 11) | |
expect(add3(1, 2, 3), eq, 6) | |
expect(add3(1, 2)(3), eq, 6) | |
expect(add3(1)(2)(3), eq, 6) | |
expect(add3(1)(2, 3), eq, 6) | |
expect(add3(1)(2, 3, 4), eq, 6) | |
// production code goes here | |
function start(input) { | |
var pipe = function(fn) { | |
return start(fn(input)) | |
} | |
pipe.done = input | |
return pipe | |
} | |
let multiply = autocurry(2, (a, b) => a * b) | |
let add3 = autocurry(3, (a, b, c) => a + b + c) | |
let add = autocurry(2, (a, b) => a + b) | |
function autocurry(nArgs, f) { | |
return function() { | |
var firstArgs = arguments | |
if (firstArgs.length < nArgs) { | |
return autocurry(nArgs - firstArgs.length, function() { | |
var restArgs = arguments | |
return f.apply(null, concatArgs(firstArgs, restArgs)) | |
}) | |
} else { | |
return f.apply(null, firstArgs) | |
} | |
} | |
} | |
function concatArgs(a, b) { | |
var output = [] | |
for (let item of a) { | |
output.push(item) | |
} | |
for (let item of b) { | |
output.push(item) | |
} | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment