From 6079fe45f14ade7bc5baa0773e5e814a1c9082ce Mon Sep 17 00:00:00 2001 From: Vladimir Ivakin Date: Thu, 4 Jul 2024 22:54:27 +0200 Subject: [PATCH] fix: work with falsy values in toggle --- src/array/toggle.ts | 20 +++++--------------- tests/array/toggle.test.ts | 21 +++++++-------------- 2 files changed, 12 insertions(+), 29 deletions(-) diff --git a/src/array/toggle.ts b/src/array/toggle.ts index a46cf41a7..67e49d81e 100644 --- a/src/array/toggle.ts +++ b/src/array/toggle.ts @@ -30,25 +30,15 @@ export function toggle( 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] } diff --git a/tests/array/toggle.test.ts b/tests/array/toggle.test.ts index 87b834627..188f63064 100644 --- a/tests/array/toggle.test.ts +++ b/tests/array/toggle.test.ts @@ -1,20 +1,6 @@ import * as _ from 'radashi' -const cast = (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']) @@ -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]) + }) })