diff --git a/src/loop-do-while/__snapshots__/loop-do-while.spec.ts.snap b/src/loop-do-while/__snapshots__/loop-do-while.spec.ts.snap new file mode 100644 index 000000000..b895a617e --- /dev/null +++ b/src/loop-do-while/__snapshots__/loop-do-while.spec.ts.snap @@ -0,0 +1,11 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`loopDoWhile function is a pure function 1`] = ` +Array [ + 1, + 2, + 3, + 4, + 5, +] +`; diff --git a/src/loop-do-while/index.ts b/src/loop-do-while/index.ts new file mode 100644 index 000000000..39705102f --- /dev/null +++ b/src/loop-do-while/index.ts @@ -0,0 +1 @@ +export * from './loop-do-while'; diff --git a/src/loop-do-while/loop-do-while.spec.ts b/src/loop-do-while/loop-do-while.spec.ts new file mode 100644 index 000000000..1e40133ad --- /dev/null +++ b/src/loop-do-while/loop-do-while.spec.ts @@ -0,0 +1,21 @@ +import { loopDoWhile } from './loop-do-while'; + +describe('loopDoWhile function', () => { + const input = [1, 2, 3, 4, 5]; + + test('is a pure function', () => { + loopDoWhile>( + arr => arr.length < 10, + arr => [...arr, 0] + )(input); + expect(input).toMatchSnapshot(); + }); + + test('2 |> loopDoWhile <10, x => x² === 16', () => { + expect(loopDoWhile(x => x < 10, x => x ** 2)(2)).toBe(16); + }); + + test('2 |> loopDoWhile <10, x => x² === 16', () => { + expect(loopDoWhile(x => x < 10, x => x ** 2)(10)).toBe(100); + }); +}); diff --git a/src/loop-do-while/loop-do-while.ts b/src/loop-do-while/loop-do-while.ts new file mode 100644 index 000000000..8c6490a56 --- /dev/null +++ b/src/loop-do-while/loop-do-while.ts @@ -0,0 +1,36 @@ +/** + * @module TBD_A=>TBD_B + */ +/** + * This method loop on an input: + * - at first, output = iteratee(input) + * - while predicat(output) is true, output = iteratee(output) + * - finally, returns output + * @param predicate The function apply on each loop to decide to : + * continue (return true), or to stop (return false) + * @param iteratee The iteratee invoked on each loop. + * @return the function to apply on the input + * @example + * ``` + * loopDoWhile(x => x < 10, x => x ** 2)(10) // 100 + * ``` + * @example Using the chain + * ``` + * chain(10) + * .chain(loopDoWhile(x => x < 10, x => x ** 2)) + * .value() // 100 + * ``` + */ +export function loopDoWhile( + predicate: (element: T) => boolean, + iteratee: (element: T) => T +): (input: T) => T { + return (input: T) => { + let output = input; + do { + output = iteratee(output); + } while (predicate(output)); + + return output; + }; +} diff --git a/src/taninsam.ts b/src/taninsam.ts index f0f87cfc0..45f32ec48 100644 --- a/src/taninsam.ts +++ b/src/taninsam.ts @@ -25,6 +25,7 @@ export * from './join'; export * from './keys'; export * from './last'; export * from './length'; +export * from './loop-do-while'; export * from './loop-for'; export * from './map'; export * from './max';