Skip to content

Instantly share code, notes, and snippets.

@brunoguerra
Last active May 2, 2019 15:13
Show Gist options
  • Save brunoguerra/5c08fd2e466d9dca3b7ae9a9128c867d to your computer and use it in GitHub Desktop.
Save brunoguerra/5c08fd2e466d9dca3b7ae9a9128c867d to your computer and use it in GitHub Desktop.

Revisions

  1. Bruno Guerra revised this gist May 2, 2019. 1 changed file with 1 addition and 3 deletions.
    4 changes: 1 addition & 3 deletions funcional.js
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,2 @@
    export const isNumber = str => /^[0-9]*$/.test(str)
    export const numberOrString = str => isNumber(str)? parseInt(str) : str.trim()
    export const selectIt = (path, obj) => path &&
    path.split('.').reduce((mem, property) => mem && mem[numberOrString(property)], obj)
    path.split('.').reduce((mem, property) => mem && mem[property], obj)
  2. Bruno Guerra created this gist May 2, 2019.
    4 changes: 4 additions & 0 deletions funcional.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    export const isNumber = str => /^[0-9]*$/.test(str)
    export const numberOrString = str => isNumber(str)? parseInt(str) : str.trim()
    export const selectIt = (path, obj) => path &&
    path.split('.').reduce((mem, property) => mem && mem[numberOrString(property)], obj)
    15 changes: 15 additions & 0 deletions functional.test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    import { selectIt } from './functional'

    test('object member selection', () => {
    const data = {one: { number: 1 }, two: 2, three: [1,2,{ mixed: true}] };

    expect(selectIt('two', data)).toBe(2)
    expect(selectIt('one.number', data)).toBe(1)
    expect(selectIt('three.2.mixed', data)).toBeTruthy();
    });

    test('array member selection', () => {
    const arr = { array: [1,2,3,{ok: true}] }

    expect(selectIt('array.3.ok', arr)).toBeTruthy();
    });