Improve map

pull/251/head
Anton Medvedev 1 year ago
parent 0833d11919
commit 68e28e7627
No known key found for this signature in database

@ -68,7 +68,7 @@ function transform(json, code) {
let s = code.substring(4, code.length - 1)
if (s[0] === '.') s = 'x' + s
return eval(`(function () {
return this.map(x => apply(x, ${s}))
return this.map((x, i) => apply(${s}, x, i))
})`).call(json)
}
@ -76,11 +76,11 @@ function transform(json, code) {
return ${code}
})`).call(json)
return apply(json, fn)
return apply(fn, json)
}
function apply(json, fn) {
if (typeof fn === 'function') return fn(json)
function apply(fn, ...args) {
if (typeof fn === 'function') return fn(...args)
return fn
}

@ -63,6 +63,11 @@ void async function main() {
t.deepEqual(JSON.parse(stdout), ['bar'])
})
await test('map passes index', async t => {
const {stdout} = await run([1, 2, 3], `'map((x, i) => x * i)'`)
t.deepEqual(JSON.parse(stdout), [0, 2, 6])
})
await test('flat map works', async t => {
const {stdout} = await run({master: {foo: [{bar: [{val: 1}]}]}}, '.master.foo[].bar[].val')
t.deepEqual(JSON.parse(stdout), [1])

Loading…
Cancel
Save