Add more advance map

pull/251/head
Anton Medvedev 1 year ago
parent 02c9e99949
commit 956d1ab624
No known key found for this signature in database

@ -50,10 +50,14 @@ echo `{"name": "world"}` | fx 'Object.keys'
## Advanced Usage
Fx has a shortcut for the map function. Fox example `.map(x => x.commit.message)`
can be written without leading dot and without `x =>` parts.
can be written without leading dot and without `x => x` parts.
```sh
curl https://api.github.com/repos/antonmedv/fx/commits | fx 'map(x.commit.message)'
curl https://api.github.com/repos/antonmedv/fx/commits | fx 'map(.commit.message)'
```
```sh
echo '[{"name": "world"}]' | fx 'map(`Hello, ${x.name}!`)'
```
Fx has a special syntax for the flatMap function. Fox example,

@ -64,10 +64,13 @@ function transform(json, code) {
return this${code}
})`).call(json)
if (/^map\(.+?\)$/.test(code))
if (/^map\(.+?\)$/.test(code)) {
let s = code.substring(4, code.length - 1)
if (s[0] === '.') s = 'x' + s
return eval(`(function () {
return this.map(x => apply(x, ${code.substring(4, code.length - 1)}))
return this.map(x => apply(x, ${s}))
})`).call(json)
}
const fn = eval(`(function () {
return ${code}

@ -34,20 +34,35 @@ void async function main() {
})
await test('works with arrow func with param brackets', async t => {
const {stdout} = await run({'key': 'value'}, '\'(x) => x.key\'')
const {stdout} = await run({'key': 'value'}, `'(x) => x.key'`)
t.equal(stdout, 'value\n')
})
await test('this is json', async t => {
const {stdout} = await run([1, 2, 3, 4, 5], '\'this.map(x => x * this.length)\'')
const {stdout} = await run([1, 2, 3, 4, 5], `'this.map(x => x * this.length)'`)
t.deepEqual(JSON.parse(stdout), [5, 10, 15, 20, 25])
})
await test('args chain works', async t => {
const {stdout} = await run({'items': ['foo', 'bar']}, '\'this.items\' \'.\' \'x => x[1]\'')
const {stdout} = await run({'items': ['foo', 'bar']}, `'this.items' '.' 'x => x[1]'`)
t.equal(stdout, 'bar\n')
})
await test('map works', async t => {
const {stdout} = await run([1, 2, 3], `'map(x * 2)'`)
t.deepEqual(JSON.parse(stdout), [2, 4, 6])
})
await test('map works with dot', async t => {
const {stdout} = await run([{foo: 'bar'}], `'map(.foo)'`)
t.deepEqual(JSON.parse(stdout), ['bar'])
})
await test('map works with func', async t => {
const {stdout} = await run([{foo: 'bar'}], `'map(x => x.foo)'`)
t.deepEqual(JSON.parse(stdout), ['bar'])
})
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])
@ -62,7 +77,7 @@ void async function main() {
const json = {foo: 'bar'}
const code = '".foo.toUpperCase("'
const {stderr, status} = await run(json, code)
t.strictEqual(status, 1)
t.equal(status, 1)
t.ok(stderr.includes(`SyntaxError: Unexpected token '}'`))
})
}()

Loading…
Cancel
Save