Skip to content

Instantly share code, notes, and snippets.

@buzzdecafe
Last active December 7, 2017 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzzdecafe/e0bd995c4c04b780e8ddc5eeff6b8d05 to your computer and use it in GitHub Desktop.
Save buzzdecafe/e0bd995c4c04b780e8ddc5eeff6b8d05 to your computer and use it in GitHub Desktop.
const S = {
fromArray: xs => sink => {
for (let i=0; i<xs.length; ++i)
if (sink(xs[i]))
return true
},
map: fn => stream => sink => stream(x => sink(fn(x))),
chain: fn => stream => sink => stream(x => fn(x)(sink)),
take: n => stream => sink => {
let i = 0
return stream(x => {
if (i === n || (++i, sink(x)) || i === n)
return true
})
},
toArray: stream => {
const xs = []
stream(x => { xs.push(x) })
return xs
}
};
const suits = ['♠', '♥', '♦', '♣']
const ranks = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A']
S.toArray(
S.take(2)(
S.chain(suit => S.map(rank => suit+rank)(S.fromArray(ranks)))
(S.fromArray(suits))))
// credit to Vesa Karvonen (@polytypic) for this implementation
//
const suits = ['♠', '♥', '♦', '♣']
const ranks = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A']
// Processes one item at a time. Does not fuse in V8,
// which requires you to use methods to achieve fusion.
const S_fromArray = xs => sink => {
for (let i=0; i<xs.length; ++i)
if (sink(xs[i]))
return true
}
const S_map = fn => stream => sink => stream(x => sink(fn(x)))
const S_chain = fn => stream => sink => stream(x => fn(x)(sink))
const S_take = n => stream => sink => {
let i = 0
return stream(x => {
if (i === n || (++i, sink(x)) || i === n)
return true
})
}
const S_toArray = stream => {
const xs = []
stream(x => { xs.push(x) })
return xs
}
S_toArray(
S_take(2)(
S_chain(suit => S_map(rank => suit+rank)(S_fromArray(ranks)))
(S_fromArray(suits))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment