Skip to content

Instantly share code, notes, and snippets.

@awto
Last active May 28, 2016 10:16
Show Gist options
  • Select an option

  • Save awto/e726f60d6a3f0ecbc2ce09e372d246e8 to your computer and use it in GitHub Desktop.

Select an option

Save awto/e726f60d6a3f0ecbc2ce09e372d246e8 to your computer and use it in GitHub Desktop.
most used with burrido as do notation
/**
* This demonstrates problems of using burrido with most (and in fact with any
* other multi-answer monads). It works only if `most` doesn't contain other
* effect besides pure stream comprehension effects, or effects we don't care
* about.
*/
import {from,of,fromPromise} from 'most'
import Monad from 'burrido'
const MM = Monad({
pure: of,
bind: (a, f) => a.chain(f)
})
let cnt = 0
/**
* This is a symple and typical use case, we want to update something
* in DB before some other actions. It is simulated just with promise
* with timeout
*/
function updateDb() {
return new Promise(resolve => {
setTimeout(
() => {
console.log(`DB UPDATED ${cnt}`)
resolve(cnt++)
}, 0)
})
}
MM.Do(function*() {
// first we want to update something in DB
const m = yield fromPromise(updateDb())
const x = yield from([1,2])
return `${x} ${m}`
}).observe(function(res) {
console.log(res)
})
/*
and the output is
```
DB UPDATED 0
1 0
2 0
DB UPDATED 1
DB UPDATED 2
DB UPDATED 3
```
so we updated DB 4 times instead of 1
*/
/*
Things are much worth if the block contains JS side effects. It is of course
nice if there is none, but I don't see why not to use this useful tool in
right places. It also may be accidental making debugging to be very painful.
*/
let i = 0;
MM.Do(function*() {
const x = yield from([1,2])
if (i++) {
const y = yield from(['in then'])
return `then ${x} ${y}`
} else {
const y = yield from(['in else'])
return `else ${x} ${y}`
}
}).observe(function(res) {
console.log(res)
})
/*
outputs:
```
then 1 in else
then 2 in then
```
so it combined output of `then` branch with value yielded in `else` branch
*/
/**
* And alternative is to use [mfjs compiler](https://github.com/awto/mfjs-compiler),
* it has optionally support for generators syntax. So the source code for generators
* is absolutely the same like in burrido but outpurs correct results in both cases.
* https://gist.github.com/awto/abb08236e36507df39ea7428c8e24b15
*
* Namely:
* ```
* DB UPDATED 0
* 1 0
* 2 0
* ```
* and
* ```
* else 1 in else
* then 2 in then
* ```
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment