Created
June 7, 2016 06:03
-
-
Save stefanfrede/4c781c532d195b96c13891d61524240d to your computer and use it in GitHub Desktop.
The “K Combinator".
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
/** | |
* tap takes a value and returns a function that | |
* always returns the value, but if you pass it a | |
* function, it executes the function for | |
* side-effects. | |
*/ | |
const tap = (value, fn) => { | |
const curried = (fn) => ( | |
typeof(fn) === 'function' && fn(value), | |
value | |
); | |
return fn === undefined | |
? curried | |
: curried(fn); | |
}; | |
/** | |
* Example use case: | |
* | |
* The poor-man's debugger. | |
*/ | |
// curried version | |
tap('espresso')((it) => { | |
console.log(`Our drink is '${it}'`); | |
}); | |
// uncurried version | |
tap('espresso', (it) => { | |
console.log(`Our drink is '${it}'`); | |
}); | |
// If we wish it to do nothing at all: | |
// curried version | |
tap('espresso')(); | |
// uncurried version | |
tap('espresso', null) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment