Also pass index into predicate

master
Sven Slootweg 5 years ago
parent b91d628c66
commit ba4f0a8d5e

@ -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.

@ -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) {

Loading…
Cancel
Save