Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add byIndex helper #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
8 changes: 8 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
37 changes: 37 additions & 0 deletions tests/byIndex.spec.js
Original file line number Diff line number Diff line change
@@ -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)
})
})