Skip to content

Instantly share code, notes, and snippets.

@trafium
Last active September 3, 2019 10:29
Show Gist options
  • Save trafium/b21437bb0c13dbb808dcfb7a13d94155 to your computer and use it in GitHub Desktop.
Save trafium/b21437bb0c13dbb808dcfb7a13d94155 to your computer and use it in GitHub Desktop.
/*
* Monad is a container with some value and ability to perform mapping operation
* on that value while returning result wrapped in a new Monad
*/
const Monad = value => ({
// Return mapped (transformed via passed func) value
flatMap: func => func(value),
// Return mapped (transformed via passed func) value wrapped in new Monad
map (func) {;
const newValue = this.flatMap(func);
return Monad( newValue );
},
// For simple access
value,
});
// ---------------------------------------------------------------------------------
// Example use:
// Utilities
const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);
const map = func => mappable => mappable.map(func);
const trace = label => value => {
console.log(`${ label }:`, value);
return value;
};
// Create monad
const five = Monad(5)
// Define pipeline of composed functions
const inc = v => v + 1;
const double = v => v * 2;
const incThenDouble = compose(
trace('Result'),
double,
inc
)
// Do something with monad
const result = five.map(incThenDouble); // Result: 12
console.log(result); // {flatMap: ƒ, map: ƒ, value: 12}
// Purpose of this all is still a mistery to me...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment