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

fix(toggle): handle falsy input as expected #82

Merged
merged 6 commits into from
Jul 9, 2024
Merged
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
19 changes: 8 additions & 11 deletions src/array/toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,22 @@ export function toggle<T>(
strategy?: 'prepend' | 'append'
},
): T[] {
if (!array && !item) {
return []
}
if (!array) {
return [item]
return item !== undefined ? [item] : []
}
if (!item) {
if (item === undefined) {
return [...array]
}

const matcher = toKey
? (x: T, idx: number) => toKey(x, idx) === toKey(item, idx)
: (x: T) => x === item

const existing = array.find(matcher)
if (existing) {

if (existing !== undefined) {
return array.filter((x, idx) => !matcher(x, idx))
}
const strategy = options?.strategy ?? 'append'
if (strategy === 'append') {
return [...array, item]
}
return [item, ...array]

return options?.strategy === 'prepend' ? [item, ...array] : [...array, item]
}
17 changes: 11 additions & 6 deletions tests/array/toggle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,13 @@ const cast = <T = any[]>(value: any): T => value

describe('toggle', () => {
test('should handle null input list', () => {
const result = _.toggle(cast(null), 'a')
let result = _.toggle(cast(null), 'a')
expect(result).toEqual(['a'])
})
test('should handle null input list and null item', () => {
const result = _.toggle(cast(null), null)
result = _.toggle(cast(null), undefined)
expect(result).toEqual([])
})
test('should handle null item', () => {
const result = _.toggle(['a'], null)
test('should skip undefined item', () => {
const result = _.toggle(['a'], undefined)
expect(result).toEqual(['a'])
})
test('should add item when it does not exist using default matcher', () => {
Expand All @@ -39,4 +37,11 @@ describe('toggle', () => {
const result = _.toggle(['a'], 'b', null, { strategy: 'prepend' })
expect(result).toEqual(['b', 'a'])
})
test('should work with falsy values', () => {
expect(_.toggle([1, 2], 0)).toEqual([1, 2, 0])

expect(_.toggle([1, 0, 2], 0)).toEqual([1, 2])

expect(_.toggle([1, 2], null)).toEqual([1, 2, null])
})
})