Add better detection of functions in reduce

js-version
Anton Medvedev 6 years ago
parent 4bfd5ccc42
commit 2598958557

@ -1,12 +1,18 @@
'use strict'
function reduce(json, code) {
if (/^\w+\s*=>/.test(code)) {
const fx = eval(code)
return fx(json)
if (/^\./.test(code)) {
const fx = eval(`function fn() {
return ${code === '.' ? 'this' : 'this' + code}
}; fn`)
return fx.call(json)
}
if (/yield/.test(code)) {
if ('?' === code) {
return Object.keys(json)
}
if (/yield\*?\s/.test(code)) {
const fx = eval(`function fn() {
const gen = (function*(){
${code.replace(/\\\n/g, '')}
@ -16,21 +22,15 @@ function reduce(json, code) {
return fx.call(json)
}
if ('?' === code) {
return Object.keys(json)
}
if (/^\./.test(code)) {
const fx = eval(`function fn() {
return ${code === '.' ? 'this' : 'this' + code}
}; fn`)
return fx.call(json)
}
const fx = eval(`function fn() {
return ${code}
}; fn`)
return fx.call(json)
const fn = fx.call(json)
if (typeof fn === 'function') {
return fn(json)
}
return fn
}
module.exports = reduce

@ -12,10 +12,20 @@ test('pass', t => {
})
test('anon func', t => {
const r = fx({"key": "value"}, "'function (x) { return x.key }'")
t.deepEqual(r, 'value\n')
})
test('arrow func', t => {
const r = fx({"key": "value"}, "'x => x.key'")
t.deepEqual(r, 'value\n')
})
test('arrow func ()', t => {
const r = fx({"key": "value"}, "'(x) => x.key'")
t.deepEqual(r, 'value\n')
})
test('this bind', t => {
const r = fx([1, 2, 3, 4, 5], "'this.map(x => x * this.length)'")
t.deepEqual(JSON.parse(r), [5, 10, 15, 20, 25])

Loading…
Cancel
Save