Skip to content

Instantly share code, notes, and snippets.

@stefanfrede
Created June 7, 2016 06:03
Show Gist options
  • Save stefanfrede/4c781c532d195b96c13891d61524240d to your computer and use it in GitHub Desktop.
Save stefanfrede/4c781c532d195b96c13891d61524240d to your computer and use it in GitHub Desktop.
The “K Combinator".
/**
* 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