Skip to content

Instantly share code, notes, and snippets.

@zkat
Last active August 27, 2016 02:43
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 zkat/e7e9380ff050302de67813ef76258cc8 to your computer and use it in GitHub Desktop.
Save zkat/e7e9380ff050302de67813ef76258cc8 to your computer and use it in GitHub Desktop.
Sketched out example of protocol library built on top of genfun
var Protocol = require('genfun-protocol')
var Eq = Protocol(['a', 'b'], {
eql: ['a', 'b'],
// Extra set of [] and you can add a default implementation!
// This will dispatch only for existing instances
// (that is, it doesn't fall through to [Object, Object] in this case)
neq: [['a', 'b'], (a, b) => !Eq.eql(a, b)]
})
Eq.impl([Number, Number], {
eql: [[Number, Number], (a, b) => a === b]
// neq [Number, Number] is automatically implemented
})
var Show = Protocol(['a'], {
show: ['a']
})
class Thing {}
class Stream {}
Show.impl([Thing], {
out: [[Thing], (x) => JSON.stringify(x)]
})
Show.impl([Stream], {
out: [[Stream], (stream) => {
var buffer = ''
stream.on('data', (chunk, enc, next) => {
buffer += chunk.toString(enc)
next()
})
return new Promise((resolve, reject) => {
stream.on('end', () => resolve(buffer))
stream.on('error', (e) => reject(e))
})
}]
})
var Read = Protocol([Show('obj'), 'exemplar'], {
in: ['obj', 'exemplar']
})
Read.impl([String, Thing], {
in: [[String, Thing], (obj) => JSON.parse(Show.show(obj))]
})
Read.impl([Stream, Thing], {
in: [[Stream, Thing], (stream) => {
return Show.show(stream).then(JSON.parse)
}]
})
// Error, because Number doesn't have a Show impl
Read.impl([Number, Thing], {
in: [[Number, Thing], (num) => '' + num]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment