Last active
April 21, 2016 03:19
-
-
Save nponeccop/9de969e517a336559fd7de9d6ba20ed9 to your computer and use it in GitHub Desktop.
swizard task in Node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var parse = require('sexpr-plus').parse | |
var Q = require('q') | |
var ops = { | |
'+' : (a, b) => a + b | |
, '-' : (a, b) => a - b | |
, '*' : (a, b) => a * b | |
} | |
function eval(p) | |
{ | |
switch (p.type) | |
{ | |
case 'list': | |
var op = ops[p.content[0].content] | |
var args = p.content.slice(1) | |
return op.apply(null, args.map(eval)) | |
case 'atom': | |
return parseInt(p.content) | |
} | |
} | |
var foo = '(* (+ 1 2) (+ 3 4))' | |
console.log(eval(parse(foo)[0])) | |
var opsA = { | |
'+' : (a, b) => Q.delay(2000).then(() => a + b) | |
, '-' : (a, b) => Q.delay(3000).then(() => a - b) | |
, '*' : (a, b) => Q.delay(10000).then(() => a * b) | |
} | |
function evalA(p) | |
{ | |
switch (p.type) | |
{ | |
case 'list': | |
var op = opsA[p.content[0].content] | |
var args = p.content.slice(1) | |
console.log(p.content[0].content) | |
return Q | |
.all(args.map(evalA)) | |
.then((args) => op.apply(null, args)) | |
case 'atom': | |
return parseInt(p.content) | |
} | |
} | |
evalA(parse(foo)[0]).then(console.log) | |
var queue = require("promise-task-queue")() | |
queue.define | |
( "heavy" | |
, (o) => o.op.apply(null, o.args) | |
, { concurrency: 1 } | |
) | |
function evalQ(p) | |
{ | |
switch (p.type) | |
{ | |
case 'list': | |
var op = opsA[p.content[0].content] | |
var args = p.content.slice(1) | |
return Q | |
.all(args.map(evalQ)) | |
.then((args) =>queue.push("heavy", {op : op, args :args})) | |
case 'atom': | |
return parseInt(p.content) | |
} | |
} | |
var s = Date.now() | |
evalQ(parse(foo)[0]).then((x) => console.log("Q", x, Date.now() - s, "ms")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment