Skip to content
Permalink
Browse files

Add better detection of functions in reduce

  • Loading branch information...
antonmedv committed Dec 7, 2018
1 parent 4bfd5cc commit 2598958557dda330acaa816bc05d8eb03587c566
Showing with 26 additions and 16 deletions.
  1. +16 −16 reduce.js
  2. +10 −0 test.js
@@ -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
10 test.js
@@ -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])

0 comments on commit 2598958

Please sign in to comment.
You can’t perform that action at this time.