Skip to content

Instantly share code, notes, and snippets.

@pfgray
Last active September 20, 2018 03:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfgray/a8de0401e5ba2152d5586defd7d6d115 to your computer and use it in GitHub Desktop.
Save pfgray/a8de0401e5ba2152d5586defd7d6d115 to your computer and use it in GitHub Desktop.
// All works with all fantasy-land applicatives: https://github.com/fantasyland/fantasy-land#applicative
// It turns an array of applicatives into an applicative of array
function All(Type) {
return values =>
values.reduce((aggOp, aOp) => {
// crocks doesn't support ['fantasy-land/ap']
return aggOp['fantasy-land/ap'](aOp['fantasy-land/map'](a => {
return agg => agg.concat([a]);
}));
}, Type['fantasy-land/of']([]));
}
/**
* Maybe from https://github.com/origamitower/folktale
*/
const Maybe = require('folktale/maybe');
const maybe =
All(Maybe)([
Maybe.Just(5),
Maybe.Just(15)
]);
console.log(maybe);
maybe // folktale:Maybe.Just({ value: [5, 15] })
const maybe2 = All(Maybe)([
Maybe.Just(5),
Maybe.Nothing()
]);
console.log(maybe2);
maybe2 // folktale:Maybe.Nothing({ })
/**
* Async from https://evilsoft.github.io/crocks
*/
const start = Date.now();
const Async = require('crocks/src/Async');
const async =
All(Async)([
Async((rej, res) => setTimeout(() => res(5), 5000)),
Async((rej, res) => setTimeout(() => res(2 * 6), 5000))
]);
// Async Function
async.fork(err => {
console.log('failed with:', err);
}, ([a, b]) => {
const end = Date.now();
console.log('got result:', a, b);
console.log('took: ', end - start, 'ms');
});
console.log(async);
/**
* Chainable Components from https://github.com/pfgray/chainable-components
*/
const { ChainableComponent, withState } = require('chainable-components');
const React = require('react');
const composed =
All(ChainableComponent)([
withState(3),
withState(5)
]);
const element = composed.render(([outer, inner]) => (
React.createElement('div', null, `Count is: ${outer.value + inner.value}`)
))
element // is now:
// <WithState initial={3}>
// <WithState initial={5}>
// <div>Count is: 8</div>
// </WithState>
// </WithState>
/**
* Maybe from https://evilsoft.github.io/crocks
*/
const Maybe = require('crocks/src/Maybe');
const maybe =
All(Maybe)([
Maybe.Just(1),
Maybe.Just(2),
Maybe.Just(3),
Maybe.Just(4),
Maybe.Just(5),
Maybe.Just(6),
Maybe.Just(4),
Maybe.Just(5),
]);
console.log(maybe); // Just [ 1, 2, 3, 4, 5, 6, 4, 5 ]
const maybe2 =
All(Maybe)([
Maybe.Just(1),
Maybe.Just(2),
Maybe.Just(3),
Maybe.Nothing(),
Maybe.Just(5),
Maybe.Just(6),
Maybe.Just(4),
Maybe.Just(5),
]);
console.log(maybe2); // Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment