Skip to content

Instantly share code, notes, and snippets.

@iamaamir
Last active May 14, 2019 16:46
Show Gist options
  • Save iamaamir/34c516aaed874ceb8f039783ac0201e2 to your computer and use it in GitHub Desktop.
Save iamaamir/34c516aaed874ceb8f039783ac0201e2 to your computer and use it in GitHub Desktop.
js helper functions
// Date object to unix timestamp
function unix(date) {
return Math.round(date.getTime() / 1000);
}
// replace all from string
String.prototype.replaceAll = function(rgx, replacement) {
var self = this;
return self.replace(new RegExp(rgx, "g"), replacement);
};
// download file from api response
function downloadCSV(data, fileName) {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var blob = new Blob([data], { type: "octet/stream" }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
}
// random number in a specific range
function range(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// escape HTML
function escapeHTML(text) {
var replacements = { "<": "&lt;", ">": "&gt;", "&": "&amp;", "": "&quot;" };
return text.replace(/[<>&"]/g, function(character) {
return replacements[character];
});
}
// escape regex specific chars
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
// returns an array of the given len with numbers
function arr(len){
return Array(len).fill().map((_,i) => i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment