From 03648b687220b79f89fe8214ef05f69290080968 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Sun, 9 May 2021 13:31:36 +0300 Subject: [PATCH] Add findFirstN, findLastN --- snippets/findFirstN.md | 27 +++++++++++++++++++++++++++ snippets/findLastN.md | 27 +++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 snippets/findFirstN.md create mode 100644 snippets/findLastN.md diff --git a/snippets/findFirstN.md b/snippets/findFirstN.md new file mode 100644 index 000000000..97da01bdf --- /dev/null +++ b/snippets/findFirstN.md @@ -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] +``` diff --git a/snippets/findLastN.md b/snippets/findLastN.md new file mode 100644 index 000000000..f8ee1f74b --- /dev/null +++ b/snippets/findLastN.md @@ -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] +```