From ba4f0a8d5ef97a7558041627cd7f8de9134cdbc9 Mon Sep 17 00:00:00 2001 From: Sven Slootweg Date: Mon, 19 Aug 2019 22:17:48 +0200 Subject: [PATCH] Also pass index into predicate --- README.md | 18 +++++++++++++++++- index.js | 4 ++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b11c7eb..ef7a62d 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,9 @@ Splits the `array` into an object of arrays, keyed by whatever the `predicate` f - __array:__ The array to split. - __ensureCategories:__ An array of strings, indicating which categories should always exist on the result object (explained further below). Set this to an empty array (`[]`) if you don't need this feature. -- __predicate:__ The function that determines which category to sort the value into. This function should return a string, indicating the desired category for the value. +- __predicate:__ The function that determines which category to sort the value into. This function should return a string, indicating the desired category for the value. This predicate function receives two arguments, of which you'll usually only need the first one: + - __value:__ The value itself. + - __index:__ The index of the value in the array you've provided. Returns an object - one key for each category, with the corresponding value being an array of items that were sorted into that category. @@ -77,3 +79,17 @@ for (let mediumValue of medium) { Now the `for` statement will always work. __If it's an optional feature, why does it come before the required `predicate`?__ Because a predicate function will very often need to be more than one line, and having it at the end makes it easier to format your code well, regardless of what code style you use. Setting it to `[]` if you don't need it is pretty unobtrusive, and means that this library doesn't need to support overloaded syntax (which would make it unnecessarily fragile). + +## Changelog + +# 1.1.0 (August 19, 2019) + +- __New:__ Predicate function now also receives the index of the value as an argument, not just the value itself. + +# 1.0.1 (August 19, 2019) + +- Clarified `ensureCategories` documentation with additional example. + +# 1.0.0 (August 19, 2019) + +Initial release. diff --git a/index.js b/index.js index 69f9484..3632c27 100644 --- a/index.js +++ b/index.js @@ -9,8 +9,8 @@ module.exports = function splitFilter(array, ensureCategories, predicate) { } } - for (let item of array) { - let category = predicate(item); + for (let [ i, item ] of array.entries()) { + let category = predicate(item, i); if (category != null) { if (results[category] == null) {