Created
March 6, 2020 18:17
-
-
Save dinocarl/6beebcd8a046f8ff12733a9b05586444 to your computer and use it in GitHub Desktop.
Vanilla JS groupBy implementation
This file contains hidden or 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
// utilities | |
const includes = (needle) => (haystack) => (haystack.indexOf(needle) > -1); | |
const includesAtPos = (needle) => (position) => (haystack) => (haystack.indexOf(needle) === position); | |
const testFor = (re) => (str) => re.test(str); | |
const and = (...fnList) => (data) => fnList.every((fn) => fn(data)); | |
const groupBy = (fn) => (arr) => arr.reduce( | |
(out, val) => { | |
let by = fn(val); | |
(out[by] = out[by] || []).push(val); | |
return out; | |
}, | |
{} | |
); | |
const tagAttrSorter = (str) => ( | |
includesAtPos('.')(0)(str) ? 'classes' | |
: includesAtPos('#')(0)(str) ? 'ids' | |
: and(includes('='), testFor(/^(?!on)/))(str) ? 'attrs' | |
: 'remainder'); | |
const groupByTagAttrs = groupBy(tagAttrSorter); | |
groupByTagAttrs([ | |
'.this', | |
'.that', | |
'#id1', | |
'#id2', | |
'data-key=val', | |
'onclick=alert()' | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment