Skip to content

Instantly share code, notes, and snippets.

@yattias
Created September 15, 2017 20:25
Show Gist options
  • Save yattias/bc45e2293457bceaac05817090fe989a to your computer and use it in GitHub Desktop.
Save yattias/bc45e2293457bceaac05817090fe989a to your computer and use it in GitHub Desktop.
Utility function to flatten an object with varied inner structure (Array, Object, string) into one flat array
// Utility function to flatten an object with varied inner structure.
// Particularly useful in gulp when setting up a watch to listen for any file change.
// Arbitrary file path object
const paths = {
module1: {
js: [
'src/app/**/*.js',
'some_package/foo.js',
'some_package/bar.js',
'some_package/baz.js'
],
html: [
'src/app/index.html'
],
css: [
'src/app/styles.css'
]
},
module2: {
js: [
'src/app2/javascripts/**/*'
]
},
module3: {
js: [
'src/app/popup/**/*.js'
],
html: 'src/app/popup/index.html'
},
webComponents: {
html: ['src/web_components/**/*.html'],
js: ['src/web_components/foo/foo.js'],
sass: ['src/web_components/**/*.scss']
},
manifest: 'src/config/manifest.json'
};
// This function will recursively traverse and flatten the paths object
const flattenPaths = (paths) => {
const recursiveLookupHelper = (pathObj) =>{
if (typeof(pathObj) === 'string') {
fullPathList.push(pathObj);
}
else if (Array.isArray(pathObj)) {
pathObj.map(innerPathObj => {
recursiveLookupHelper(innerPathObj);
});
}
else if (typeof(pathObj) === 'object') {
Object.keys(pathObj).map(k => {
recursiveLookupHelper(pathObj[k]);
});
}
};
let fullPathList = [];
recursiveLookupHelper(paths);
return fullPathList;
}
console.log(flattenPaths(paths));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment