Skip to content

Commit

Permalink
issue-#57, #81 - Update 'takeWhile' impl. to return 'T[]'.
Browse files Browse the repository at this point in the history
  • Loading branch information
elycruz committed Feb 26, 2024
1 parent 1f85e4c commit 2e0b5ae
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 25 deletions.
11 changes: 5 additions & 6 deletions packages/fjl/src/list/takeWhile.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import {TernaryPred} from "../types";
import {instanceOf} from "../_platform";

export const

/**
* Returns items upto point where predicate doesn't hold.
* For string type returns a string.
*/
takeWhile = <T>(pred: TernaryPred, xs: Iterable<T>): typeof xs | T[] => {
takeWhile = <T>(pred: TernaryPred, xs: Iterable<T>): T[] => {
let i = 0;
const out = [];
for (const x of xs) {
if (!pred(x, i, xs)) break;
out.push(x);
i += 1;
}
return instanceOf(xs, String) ? out.join('') as typeof xs : out;
return out;
},

$takeWhile = <T>(pred: TernaryPred) =>
(xs: Iterable<T>): typeof xs | T[] =>
takeWhile(pred, xs);
(xs: Iterable<T>): T[] => takeWhile(pred, xs)

;
44 changes: 25 additions & 19 deletions packages/fjl/tests/list/test-takeWhile.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
import {
alphabetArray,
alphabetString,
isVowel,
nonAlphaNums,
nonAlphaNumsArray,
vowelsArray,
vowelsString
} from "../helpers";
import {range} from "../../src/list/range";
import {takeWhile} from "../../src/list";

const {stringify} = JSON;

describe('#takeWhile', () => {
it('should take elements while predicate is fulfilled and vice-versa', () => {
(<[Parameters<typeof takeWhile>, ReturnType<typeof takeWhile>][]>[
[[isVowel, vowelsString], vowelsString],
[[isVowel, vowelsArray], vowelsArray],
[[isVowel, alphabetString], 'a'],
[[isVowel, alphabetArray], ['a']],
[[isVowel, range(0, 5)], []],
[[isVowel, nonAlphaNums], ''],
[[isVowel, nonAlphaNumsArray], []],
[[isVowel, ''], ''],
[[isVowel, []], []],
])
.forEach(([args, expected]) => {
function* numRange() {
let i = 0;
while (i++ <= 5) {
yield i;
}
}

(<[Parameters<typeof takeWhile>, ReturnType<typeof takeWhile>][]>[
[[isVowel, vowelsArray], vowelsArray],
[[isVowel, alphabetArray], ['a']],
[[isVowel, numRange()], []],
[[isVowel, nonAlphaNumsArray], []],
[[isVowel, []], []],
])
.forEach(([args, expected]) => {
it(`takeWhile(isVowel, ${stringify(args.slice(1))}) === ${stringify(expected)}`, () => {
expect(takeWhile(args[0], args[1])).toEqual(expected);
});
});
// @todo add failing case(s) here
});

[null, undefined, 0, {}].forEach(x =>
it(`should throw when: takeWhile(() => null, ${x + ''})`, () => {
expect(() => takeWhile(() => null, x as Iterable<any>)).toThrow()
})
);
});

0 comments on commit 2e0b5ae

Please sign in to comment.