diff --git a/src/functions/reduce.spec.ts b/src/functions/reduce.spec.ts new file mode 100644 index 0000000..9bf83ae --- /dev/null +++ b/src/functions/reduce.spec.ts @@ -0,0 +1,23 @@ +import {reduceTruthy, reduceFalsy} from '../index' + +describe('Reduce Functions', () => { + it('should reduce truthy', () => { + expect(reduceTruthy([true, true, false, true], e => e)).toBeFalsy() + expect(reduceTruthy([true, true, true, true], e => e)).toBeTruthy() + expect(reduceTruthy([false, true, true, true], e => e)).toBeFalsy() + }) + + it('should only call the check function until it hits a false', () => { + const check = jest.fn(e => e) + + reduceTruthy([true, true, false, true, true, true, false, true], check) + + expect(check).toHaveBeenCalledTimes(3) + }) + + it('should reuce falsey', () => { + expect(reduceFalsy([false, false, true, false], e => e)).toBeFalsy() + expect(reduceFalsy([false, false, false, false], e => e)).toBeTruthy() + expect(reduceFalsy([true, false, true, false], e => e)).toBeFalsy() + }) +}) diff --git a/src/functions/reduce.ts b/src/functions/reduce.ts new file mode 100644 index 0000000..0a20676 --- /dev/null +++ b/src/functions/reduce.ts @@ -0,0 +1,29 @@ +/** + * Reduce the array into a single boolean value for if the check function returns true. + * + * _once the first `false` is encountered `check` is not run again_ + * + * @param array The array to test + * @param check The function to check the array entries with + * @returns `true` if `check` only ever returned `true`, otherwise `false` + */ +export const reduceTruthy = (array: T[], check: (entry: T) => boolean) => { + return array.reduce((result, entry) => { + if (!result) return false + + return check(entry) + }, true) +} + +/** + * Reduce the array into a single boolean value for if the check function returns false. + * + * _once the first `true` is encountered `check` is not run again_ + * + * @param array The array to test + * @param check The function to check the array entries with + * @returns `true` if `check` only ever returned `false`, otherwise `false` + */ +export const reduceFalsy = (array: T[], check: (entry: T) => boolean) => { + return reduceTruthy(array, e => !check(e)) +} diff --git a/src/index.ts b/src/index.ts index fdbfb32..3439645 100644 --- a/src/index.ts +++ b/src/index.ts @@ -33,6 +33,7 @@ export {indexedBy, IndexedArray, IndexedByOptions} from './functions/indexed-by' export {keys} from './functions/keys' export {mapProperty} from './functions/map-property' export {rangeAsString, rangeAsArray} from './functions/range-as-string' +export {reduceTruthy, reduceFalsy} from './functions/reduce' export {propIs, propIsNot} from './functions/selectors' export {nl2br} from './functions/nl2br' export {parameterize} from './functions/parameterize'