Skip to content

Instantly share code, notes, and snippets.

@dinocarl
Created March 6, 2020 18:17
Show Gist options
  • Save dinocarl/6beebcd8a046f8ff12733a9b05586444 to your computer and use it in GitHub Desktop.
Save dinocarl/6beebcd8a046f8ff12733a9b05586444 to your computer and use it in GitHub Desktop.
Vanilla JS groupBy implementation
// 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