Skip to content

Commit

Permalink
Add takeWhile
Browse files Browse the repository at this point in the history
  • Loading branch information
Vadim Filimonov committed Aug 11, 2023
1 parent 32a7b86 commit 7d4f779
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
18 changes: 18 additions & 0 deletions __tests__/takeWhile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { takeWhile } from '../src/index.js';

describe('takeWhile', () => {
test('should work', () => {
expect(takeWhile([1, 2, 3])).toEqual([1, 2, 3]);
expect(takeWhile([1, 2, 3], (n) => n < 3)).toEqual([1, 2]);
expect(takeWhile([2, 4, 5, 6, 8], (n) => n % 2 === 0)).toEqual([2, 4]);
});

test('wrong arguments', () => {
expect(takeWhile([])).toEqual([]);
expect(takeWhile([1, 2, 3], {})).toEqual([1, 2, 3]);
});

test('empty arguments', () => {
expect(takeWhile([])).toEqual([]);
});
});
3 changes: 3 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import sum from './sum.js';
import tail from './tail.js';
import take from './take.js';
import takeRight from './takeRight.js';
import takeWhile from './takeWhile.js';
import unary from './unary.js';
import uniq from './uniq.js';
import upperFirst from './upperFirst.js';
Expand Down Expand Up @@ -111,6 +112,7 @@ export {
tail,
take,
takeRight,
takeWhile,
unary,
uniq,
upperFirst,
Expand Down Expand Up @@ -170,6 +172,7 @@ export default {
tail,
take,
takeRight,
takeWhile,
unary,
uniq,
upperFirst,
Expand Down
31 changes: 31 additions & 0 deletions src/takeWhile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// @ts-check
import isFunction from './isFunction.js';
import stubTrue from './stubTrue.js';

/**
* Creates a `slice` of array with `n` elements taken from the beginning.
*
* @param {Array} array The array to query.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
*/
const takeWhile = (array, predicate) => {
// TODO: Support matches, matchesProperty and property
const processedPredicate = isFunction(predicate) ? predicate : stubTrue;

const takedItems = [];

for (let i = 0; i < array.length; i += 1) {
const item = array[i];

if (!processedPredicate(item)) {
return takedItems;
}

takedItems.push(item);
}

return takedItems;
};

export default takeWhile;

0 comments on commit 7d4f779

Please sign in to comment.