Skip to content

Instantly share code, notes, and snippets.

@maxwellb
Last active April 24, 2020 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxwellb/c65302f7052d446d0d61638c99f5f82a to your computer and use it in GitHub Desktop.
Save maxwellb/c65302f7052d446d0d61638c99f5f82a to your computer and use it in GitHub Desktop.
JavaScript snippet
/**
* Custom projection of a derived value from a source value
* @callback ProjectionCallback
* @param {*} src
* @returns {*}
*/
/**
* Filter for grouping
* @callback FilterCallback
* @param {*} src - The object
* @param {string} key - The grouping key to be assigned
* @param {number} index - The index in the source set
* @param {number} count - The index in the destination set (the current group size)
* @returns {boolean}
*/
/**
* Group values by a custom key projection
* @param {*} src
* @param {ProjectionCallback} cbKey
* @param {FilterCallback} cbFilter
* @param {ProjectionCallback} cbMap
*/
function group(src, cbKey, cbFilter, cbMap) {
const set = Array.from(src);
const initial = {};
const result = set.reduce(function Grouper(curr, next, index) {
const keyer = cbKey || (()=>index);
const filter = cbFilter || (()=>true);
const mapper = cbMap || (x=>x);
const key = keyer.call(next, next);
const target = curr[key] || [];
if (filter.call(next, next, key, index, target.length)) {
const mapped = mapper.call(next, next);
target.push(mapped);
curr[key] = target;
}
return curr;
}, initial);
return result;
}
/**
* Group querySelector results by a custom key projection
* @param {string} [selectors="*"]
*/
function querySelectorGroup(selectors) {
return group(document.querySelectorAll(selectors||"*"), _=>_.localName);
}
(function querySelectorByName(selectors) {
return Array.from(document.querySelectorAll(selectors || "*"))
.reduce((x,y) => { (x[y.localName]=x[y.localName]||[]).push(y); return x; }, {});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment