Skip to content

Instantly share code, notes, and snippets.

@jayantbh
Created April 3, 2016 14:02
Show Gist options
  • Save jayantbh/dea5f4ae6bd7cb0d0bbf5267dc603300 to your computer and use it in GitHub Desktop.
Save jayantbh/dea5f4ae6bd7cb0d0bbf5267dc603300 to your computer and use it in GitHub Desktop.
Some commonly used JS utility functions I use regularly.
Array.prototype.getItemCount = function (val) {
var count = 0, i = -1;
while ((i = this.indexOf(val, i + 1)) != -1) {
count++;
}
return count;
};
Array.prototype.sortObjectsWithSingleKeyByValue = function (isAscending) {
return (isAscending) ? this.sort((a, b) => a[Object.keys(a)[0]] - b[Object.keys(b)[0]]) : this.sort((a, b) => b[Object.keys(b)[0]] - a[Object.keys(a)[0]]);
};
Array.prototype.sortObjectsWithSingleKeyByKey = function (isAscending) {
return (isAscending) ? this.sort((a, b) => Object.keys(a)[0] > Object.keys(b)[0]) : this.sort((a, b) => Object.keys(b)[0] > Object.keys(a)[0]);
};
Array.prototype.unique = function () {
return this.filter((v, i) => ( this.indexOf(v) == i ));
};
Array.prototype.getFrequencyObjectArray = function () {
var x = [];
var arr = this;
arr.unique().forEach(function (v, i) {
var y = {};
y.name = v;
y.y = arr.getItemCount(v);
x.push(y);
});
return x;
};
Array.prototype.getFrequencyObject = function () {
var x = {};
var arr = this;
arr.unique().forEach(function (v, i) {
x[v] = arr.getItemCount(v);
});
return x;
};
function objectsWithSingleKeyToObjectArrayA(obj) {
return Object.keys(obj).map((v, i) => {
var x = {};
x[v] = obj[v];
return x;
});
}
function executeAsynchronously(functions, timeout) {
for (var i = 0; i < functions.length; i++) {
setTimeout(functions[i], timeout * i);
}
}
//Function might have some mistakes
function parseCSV(data,hasHeaders) {
data = data.split("\n").map(function (d) {
return d.split(",");
});
if(data[data.length - 1] == ""){
data.pop();
}
if(hasHeaders){
var headers = data.splice(0, 1)[0];
data = data.map(function (v, i) {
var x = {};
headers.forEach(function (h, i) {
x[h] = v[i];
});
return x;
});
}
//Do stuff with `data` and/or `headers`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment