diff --git a/src/array/toggle.ts b/src/array/toggle.ts index a46cf41a..465f405f 100644 --- a/src/array/toggle.ts +++ b/src/array/toggle.ts @@ -30,25 +30,22 @@ export function toggle( 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] } diff --git a/tests/array/toggle.test.ts b/tests/array/toggle.test.ts index 87b83462..7769cb3d 100644 --- a/tests/array/toggle.test.ts +++ b/tests/array/toggle.test.ts @@ -4,15 +4,13 @@ const cast = (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', () => { @@ -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]) + }) })