Skip to content

Commit

Permalink
fix(toggle): handle falsy input as expected (#82)
Browse files Browse the repository at this point in the history
Co-authored-by: Alec Larson <1925840+aleclarson@users.noreply.github.com>
  • Loading branch information
Minhir and aleclarson authored Jul 9, 2024
1 parent 244823e commit 547c6f3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 17 deletions.
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])
})
})

0 comments on commit 547c6f3

Please sign in to comment.