Skip to content

Instantly share code, notes, and snippets.

@irudoy
Last active April 4, 2019 15:06
Show Gist options
  • Save irudoy/dce4e7356868eee196d26a32a2d36478 to your computer and use it in GitHub Desktop.
Save irudoy/dce4e7356868eee196d26a32a2d36478 to your computer and use it in GitHub Desktop.
BEM deps to import
function depsToImport(deps) {
const uniq = a => [...new Set(a)];
return Object.values(
deps
.map(({ block, ...rest }) => ({ block: Array.isArray(block) ? block[0] : block, ...rest }))
.reduce((res, { block, elem, mod, val }) => {
const key = elem ? `${block}__${elem}` : block;
const cur = res[key] || {};
return {
...res,
[key]: {
...cur,
block,
...(elem && { elem }),
...(mod && {
mod: {
...cur.mod,
...(val && {
[mod]: uniq([...((cur.mod && cur.mod[mod]) ? cur.mod[mod] : []), val]),
})
},
})
},
};
}, {})
).map(({ block, elem, mod }) => {
const res = [`b:${block}`];
if (elem) {
res.push(`e:${elem}`);
}
if (mod && Object.keys(mod).length) {
res.push(
Object
.entries(mod)
.map(
([key, values]) =>
((values.length === 1 && values[0] === true) ? `m:${key}` : `m:${key}=${values.join('|')}`)
)
.join(' ')
);
}
return `import '${res.join(' ')}';`;
}).sort().join('\n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment