Last active
February 19, 2020 17:24
-
-
Save binyamin/5bef9f0a11fb9676e1754e990c63d7d3 to your computer and use it in GitHub Desktop.
Useful Javascript Utility Functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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