Skip to content

Commit

Permalink
fix: work with falsy values in toggle
Browse files Browse the repository at this point in the history
  • Loading branch information
Minhir committed Jul 6, 2024
1 parent e1b72c2 commit cee87d2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 29 deletions.
20 changes: 5 additions & 15 deletions src/array/toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,15 @@ export function toggle<T>(
strategy?: 'prepend' | 'append'
},
): T[] {
if (!array && !item) {
return []
}
if (!array) {
return [item]
}
if (!item) {
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]
}
21 changes: 7 additions & 14 deletions tests/array/toggle.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,6 @@
import * as _ from 'radashi'

const cast = <T = any[]>(value: any): T => value

describe('toggle', () => {
test('should handle null input list', () => {
const result = _.toggle(cast(null), 'a')
expect(result).toEqual(['a'])
})
test('should handle null input list and null item', () => {
const result = _.toggle(cast(null), null)
expect(result).toEqual([])
})
test('should handle null item', () => {
const result = _.toggle(['a'], null)
expect(result).toEqual(['a'])
})
test('should add item when it does not exist using default matcher', () => {
const result = _.toggle(['a'], 'b')
expect(result).toEqual(['a', 'b'])
Expand All @@ -39,4 +25,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 cee87d2

Please sign in to comment.