Skip to content

Commit

Permalink
Polyfill Object.groupBy()
Browse files Browse the repository at this point in the history
  • Loading branch information
tomayac authored Sep 23, 2024
1 parent 9432b85 commit 0a60e1a
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions features.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,30 @@
tBody
);

/*! groupby-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */

/**
* Groups elements from an iterable into an object based on a callback function.
*
* @template T, K
* @param {Iterable<T>} iterable - The iterable to group.
* @param {function(T, number): K} callbackfn - The callback function to
* determine the grouping key.
* @returns {Object.<string, T[]>} An object where keys are the grouping keys
* and values are arrays of grouped elements.
*
* This was introduced because of https://github.com/GoogleChromeLabs/wasm-feature-detect/issues/82.
*/
Object.groupBy ??= function groupBy (iterable, callbackfn) {
const obj = Object.create(null)
let i = 0
for (const value of iterable) {
const key = callbackfn(value, i++)
key in obj ? obj[key].push(value) : (obj[key] = [value])
}
return obj
}

let featureGroups = Object.groupBy(
Object.entries(features).map(([name, feature]) => Object.assign(feature, { name })),
f => f.phase,
Expand Down

0 comments on commit 0a60e1a

Please sign in to comment.