Last active
June 2, 2024 12:33
-
-
Save luijar/ce6b96f13e31cb153093 to your computer and use it in GitHub Desktop.
Functional Programming in JavaScript Chapter 01 - run function
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
/* | |
* Functional Programming in JavaScript | |
* Chapter 01 | |
* Magical -run- function in support of Listing 1.1 | |
* Author: Luis Atencio | |
*/ | |
// -run- with two functions | |
var run2 = function(f, g) { | |
return function(x) { | |
return f(g(x)); | |
}; | |
}; | |
// -run- with three functions | |
var run3 = function(f, g, h) { | |
return function(x) { | |
return f(g(h(x))); | |
}; | |
}; | |
// Test this magical function | |
var add1 = function(x) {return x + 1;}; | |
var mult2 = function(x) {return x * 2;}; | |
var square = function(x) {return x * x;}; | |
var negate = function(x) {return -x;}; | |
var double = run2(add1, add1); | |
console.log(double(2)); //-> 4 | |
var testRun = run3(negate, square, mult2); | |
console.log(testRun(2)); //->-16 |
JavaScript functional programming chapter one. Examples, run(console.log, repeat(3),h2, echo)
. I can't think solutions, maybe, there are good idea?
And since run is just an alias for compose, you can also use this:
function compose = ( ...fns ) => fns.reduce( ( f, g ) => ( ...args ) => f( g( ...args ) ) );
Usage: compose(fn3, fn2, fn1);
this run can't not do anying?
And since run is just an alias for compose, you can also use this:
function compose = ( ...fns ) => fns.reduce( ( f, g ) => ( ...args ) => f( g( ...args ) ) );
Usage: compose(fn3, fn2, fn1);
maybe this
const compose = ( ...fns ) => fns.reduce( ( f, g ) => ( ...args ) => f( g( ...args ) ) );
In Listing 1.4, the curry
is not given, So I found this code below
const curry = function(f) {
const var_num = f.length
return function(...args) {
if (args.length >= var_num) {
return f.apply(null, args)
}
return function(...new_args) {
return f.apply(null, args.concat(new_args))
}
}
}
Hope I can help someone who is a beginner like me, good luck!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Scroll up the mouse wheel 5 times, it's right there, lol