Skip to content

Instantly share code, notes, and snippets.

@M1TKO
Last active May 20, 2020 08:38
Show Gist options
  • Save M1TKO/b89a4f960bc837ed19050dfab19ee613 to your computer and use it in GitHub Desktop.
Save M1TKO/b89a4f960bc837ed19050dfab19ee613 to your computer and use it in GitHub Desktop.
Range number to range, find min, max and average number of arrays helper functions
var mapNumberToRange = function (num, in_min, in_max, out_min, out_max) {
return (((num - in_min) * (out_max - out_min)) / (in_max - in_min) + out_min) || out_min;
}
var maxNum = function (arr) {
return Math.max.apply(null, arr);
}
var minNum = function (arr) {
return Math.min.apply(null, arr);
}
var sumArray = function (arr, key) {
return arr.reduce(function (total, num) {
return (key !== undefined) ? total + (num[key] || 0) : total + (num || 0);
}, 0);
}
var avgNum = function (arr, key) {
var notZeroElements = 1;
return arr.reduce(function (total, num) {
if (num != 0) notZeroElements++;
return (key !== undefined) ? total + (num[key] || 0) : total + (num || 0);
}, 0) / notZeroElements;
}
var getUniqueElementsByKey = function (arr, key) {
var newArray = [];
for (var i = 0; i < arr.length; i++) {
var unique = true;
var length = newArray.length;
for (var j = 0; j < length; j++) {
if (newArray[j][key] === arr[i][key]) {
unique = false;
break;
}
}
if (unique) {
newArray.push(arr[i]);
}
}
return newArray;
}
// Checks of an object is empty and returns true/false
function isEmpty (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
if (Object.hasOwnProperty.call(obj, keys[i])) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment