-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Vadim Filimonov
committed
Aug 11, 2023
1 parent
32a7b86
commit 7d4f779
Showing
3 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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([]); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |