...
Last active
April 24, 2020 20:14
-
-
Save maxwellb/c65302f7052d446d0d61638c99f5f82a to your computer and use it in GitHub Desktop.
JavaScript snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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