-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhls.js
More file actions
72 lines (67 loc) · 1.61 KB
/
Copy pathhls.js
File metadata and controls
72 lines (67 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
const esprima = require('esprima');
const escodegen = require('escodegen');
const estraverse = require('estraverse');
const fhyper = require('./fhyper');
const ops = {
'+': {
name: 'add',
fn: (a, b) => a + b
},
'-': {
name: 'sub',
fn: (a, b) => a - b
}
};
function opGen(g, lut) {
const res = {};
Object.keys(lut).forEach(function(key) {
const e = lut[key];
res[e.name] = function(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return e.fn(a, b);
}
const aEdge = (typeof a === 'function') ? a : g(a)({});
const bEdge = (typeof b === 'function') ? b : g(b)({});
const resNode = g(e.name);
aEdge(resNode);
bEdge(resNode);
return resNode({});
};
});
// console.log(res);
return res;
}
function hls(fn) {
const fnText = fn.toString();
// console.log(fnText);
const ast = esprima.parse(fnText);
// console.log(JSON.stringify(ast, null, 4));
const newAst = estraverse.replace(ast, {
leave: function(node) {
if (node.type === 'BinaryExpression') {
return {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: ops[node.operator].name
},
arguments: [node.left, node.right]
};
}
}
});
// console.log(JSON.stringify(newAst, null, 4));
const newFnText = escodegen.generate(newAst);
// console.log(newFnText);
const _g = fhyper();
const {
add,
sub
} = opGen(_g, ops);
let _res;
eval('_res = ' + newFnText);
return _res;
}
module.exports = hls;
/* eslint no-unused-vars: 0 */