Add findFirstN, findLastN

This commit is contained in:
Chalarangelo
2021-05-09 13:31:36 +03:00
parent 85494928d6
commit 03648b6872
2 changed files with 54 additions and 0 deletions

27
snippets/findFirstN.md Normal file
View File

@ -0,0 +1,27 @@
---
title: findFirstN
tags: array,intermediate
---
Finds the first `n` elements for which the provided function returns a truthy value.
- Use a `for..in` loop to execute the provided `matcher` for each element of `arr`.
- Use `Array.prototype.push()` to append elements to the results array and return them if its `length` is equal to `n`.
```js
const findFirstN = (arr, matcher, n = 1) => {
let res = [];
for (let i in arr) {
const el = arr[i];
const match = matcher(el, i, arr);
if (match) res.push(el);
if (res.length === n) return res;
}
return res;
};
```
```js
findFirstN([1, 2, 4, 6], n => n % 2 === 0, 2); // [2, 4]
findFirstN([1, 2, 4, 6], n => n % 2 === 0, 5); // [2, 4, 6]
```

27
snippets/findLastN.md Normal file
View File

@ -0,0 +1,27 @@
---
title: findLastN
tags: array,intermediate
---
Finds the last `n` elements for which the provided function returns a truthy value.
- Use a `for` loop to execute the provided `matcher` for each element of `arr`.
- Use `Array.prototype.unshift()` to prepend elements to the results array and return them if its `length` is equal to `n`.
```js
const findLastN = (arr, matcher, n = 1) => {
let res = [];
for (let i = arr.length - 1; i >= 0; i--) {
const el = arr[i];
const match = matcher(el, i, arr);
if (match) res.unshift(el);
if (res.length === n) return res;
}
return res;
};
```
```js
findLastN([1, 2, 4, 6], n => n % 2 === 0, 2); // [4, 6]
findLastN([1, 2, 4, 6], n => n % 2 === 0, 5); // [2, 4, 6]
```