Skip to content

Instantly share code, notes, and snippets.

@binyamin
Last active February 19, 2020 17:24
Show Gist options
  • Save binyamin/5bef9f0a11fb9676e1754e990c63d7d3 to your computer and use it in GitHub Desktop.
Save binyamin/5bef9f0a11fb9676e1754e990c63d7d3 to your computer and use it in GitHub Desktop.
Useful Javascript Utility Functions
module.exports = {
generateId: function() {
// Generate a semi-unique id
return '_' + Math.random().toString(36).substr(2, 9);
},
byteToString: function(blob) {
// Turn an arraybuffer into a base64 string
return btoa(new Uint8Array(blob).reduce(function (data, byte) {
return data + String.fromCharCode(byte);
}, ''))
},
walk: function(dir, fileList = []) {
// Get all files within subdirectories
const files = await fs.readdirSync(dir)
for (const file of files) {
const stat = await fs.statSync(path.join(dir, file))
if (stat.isDirectory()) fileList = await walk(path.join(dir, file), fileList)
else fileList.push(path.join(dir, file))
}
return fileList
},
getURLParams: function(url) {
url = window ? window.location : new URL(url);
const urlParamsArray = url.search.replace('?', '').split('&').map(p => p.split('='));
let params = {};
urlParamsArray.forEach(p => {params[p[0]] = p[1]})
return params;
},
filterArrOfObjs: function(obj) {
return obj.filter((v, i, self) => i === self.findIndex(t => (t.name === v.name && t.group === v.group)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment