Created
April 25, 2020 03:46
-
-
Save ccurtin/d44777c4e210712c9b8b9a301dcb181e to your computer and use it in GitHub Desktop.
JS Currying Example
This file contains hidden or 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
function curry(func) { | |
return function curried(...args) { | |
if (args.length >= func.length) { | |
return func.apply(this, args); | |
} else { | |
return function(...args2) { | |
return curried.apply(this, args.concat(args2)); | |
} | |
} | |
} | |
} | |
// transform your function w/ curry() | |
const message = curry((date, type, message) => { | |
return `${type} : ${message} : ${date}` | |
}) | |
// now "type" and "date" aren't needed for any proceeding calls. | |
// next call to errorMessage will only affect the 3rd arg, "message" | |
const errorMessage = message(new Date(), 'error') | |
// use curried message | |
console.log(errorMessage('There was a problem')) | |
// not use curry message | |
console.log(message(new Date(), 'error', "There was a problem")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment