diff --git a/README.md b/README.md index 036271b..525598c 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ export default { | count | `count('arrayProperty')` | no | | countBy | `countBy('arrayProperty', 'done', true)` | no | | classObject | `classObject('isPrimary', 'has-title:title', 'wide')` | yes | +| byIndex | `byIndex('arrayProperty', 0)` | no | `x` means that it can be either value or property name. If you provide a string and there will be a property with that name it's value will be used to perform the check. diff --git a/lib/index.js b/lib/index.js index 1ddafed..95ebf50 100644 --- a/lib/index.js +++ b/lib/index.js @@ -209,3 +209,11 @@ export function classObject(...args) { }, {}); } } + +export function byIndex(arg, index) { + return function() { + const isArray = Array.isArray(this[arg]) + console.assert(isArray, 'computed helper "byIndex" requires property of array type') + return isArray ? this[arg][index] : undefined + } +} \ No newline at end of file diff --git a/tests/byIndex.spec.js b/tests/byIndex.spec.js new file mode 100644 index 0000000..5bd0b71 --- /dev/null +++ b/tests/byIndex.spec.js @@ -0,0 +1,37 @@ +import * as computed from '../lib/index' + +global.console.assert = jest.fn() + +describe('byIndex', () => { + const context = { + todos: [{ + id: 1, + done: false + }, { + id: 2, + done: true + }, { + id: 3, + done: true + }], + arr: [1, 2, 3, 4], + items: 'test' + } + + it('finds an item in array by index', () => { + expect( + computed.byIndex('todos', 2).bind(context)() + ).toEqual({ id: 3, done: true }) + + expect( + computed.byIndex('arr', 0).bind(context)() + ).toEqual(1) + }) + + it('returns an undefined value when the argument is not an array', () => { + expect( + computed.byIndex('items', 0).bind(context)() + ).toEqual(undefined) + expect(console.assert.mock.calls.slice(-1)[0][0]).toBe(false) + }) +})