Skip to content

Instantly share code, notes, and snippets.

@serebano
Last active November 20, 2016 05:16
Show Gist options
  • Select an option

  • Save serebano/9231e2296a5a19f358354692a212f0c7 to your computer and use it in GitHub Desktop.

Select an option

Save serebano/9231e2296a5a19f358354692a212f0c7 to your computer and use it in GitHub Desktop.
funbox
function funbox(reducer) {
const box = ctx => box.run(ctx)
box.use = (...functions) => {
box.index = (box.index||[]).concat(...functions)
box.run = ctx => box.index.reduce(reducer, ctx)
}
return box
}
const app = funbox((ctx, fun) => {
console.group(fun.name)
console.log(ctx)
ctx = Object.assign(ctx, fun(ctx))
console.log(ctx)
console.groupEnd()
return ctx
})
app.use(function DemoFun(args) {
const ctx = {
...args,
count: 0
}
ctx.count = ctx.count || 0
ctx.xxx = { g: 3 }
ctx.x = ctx.x || 2000
try {
window.apiContext = ctx
return ctx
} catch(err) {
ctx.error = err
console.error(`demo-fun`, err)
return ctx
}
})
app.use(function Foo(ctx) {
ctx.count++
if (ctx.x > 100)
throw new Error(`x > 1000, just to test`)
ctx.foo = {
count: ctx.count || 1,
xCount: ctx.count * 10,
}
return ctx
})
app.use(function Bar(ctx) {
ctx.count++
ctx.bar = {
y: 120,
x: ctx.x,
theBar: Date.now()
}
ctx.y = 8282
return ctx
})
app.use(function Baz(ctx) {
ctx.count++
ctx.baz = {
xy: [ ctx.x, ctx.y ],
bX: ctx.x,
bY: ctx.y,
theBaz: Date.now()
}
return ctx
})
window.ctx = { x: 9, id: 'xxx' }
window.app = app
app(ctx)
//
{
"name": "funbox",
"version": "0.0.2",
"main": "funbox.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment