Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env node
// utility script to count the max. nesting level on a sass file
const fs = require('fs');
const { parse } = require('scss-parser');
const createQueryWrapper = require('query-ast');
const files = process.argv.slice(2);
files.forEach(file => {
const max = maxNesting(file);
console.log(`${max} ${file}`);
});
function maxNesting(file) {
const scss = String(fs.readFileSync(file));
const ast = parse(scss);
const $ = createQueryWrapper(ast, {});
const declarations = $('declaration');
return declarations.reduce((acc, next) => {
const nesting = countBlocks(next);
return Math.max(acc, nesting);
}, 0);
}
function countBlocks(nodeWrapper, acc = 0) {
if (nodeWrapper.node.type === 'stylesheet') {
return acc;
}
if (nodeWrapper.parent.node.type === 'block') {
return acc + 1 + countBlocks(nodeWrapper.parent);
}
return acc + countBlocks(nodeWrapper.parent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment