Created
October 15, 2021 00:51
-
-
Save mvogelgesang/939532116437637f908e5639576631c2 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
/* Adopted from an example provided by Ezekiel Lawson at LogRocket. Goal was to better understand the flow of Currying functions and bind(). | |
https://blog.logrocket.com/understanding-javascript-currying/ | |
*/ | |
// new function called curry which takes a function as an argument. In this case, the totalNum function is passed and it expects 3 arguments | |
const curry = (fn) => { | |
// returns a function called curried which takes the args and spreads them ... | |
return curried = (...args) => { | |
console.log("fn length: " + fn.length); | |
console.log("args length: " + args.length); | |
console.log(`args: `,...args); | |
// compare the number of expected arguments in the passed function "fn" to the number passed in the function "curried" | |
if (fn.length !== args.length) { | |
console.log(`fn and args lengths not matching. passing: `,...args); | |
return curried.bind(null, ...args) | |
} | |
//recurse | |
// this ultimately passes the desired number of arguments to totalNu | |
console.log("recursing"); | |
return fn(...args); | |
}; | |
} | |
const totalNum = (x, y, z) => { | |
console.log("in totalNum"); | |
return x + y + z | |
} | |
const curriedTotal = curry(totalNum); | |
console.log(curriedTotal(10)(20)(30)); | |
console.log(curriedTotal(1,2,3,4,5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment