This is an iterative review. The next iteration is located here: Utilities for Various Builtins #2 This code puts several builtins (And a few non-builtins) into the base classes.
const XtraUtils = {};
class Utility {
constructor(ofWhat){
this.utils = {};
this.aidsIn = ofWhat;
}
activate() {
for (var x in this.utils) {
window[this.aidsIn].prototype[x] = this.utils[x];
}
}
addUtil(util, name) {
this.utils[name] = util;
}
};
XtraUtils.Number = new Utility("Number");
XtraUtils.String = new Utility("String");
XtraUtils.Array = new Utility("Array");
XtraUtils.Number.addUtil(function(in_min, in_max, out_min, out_max) {
return (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}, "map");
XtraUtils.Number.addUtil(function(inputBase = 10, outputBase = 10){parseInt(this, inputBase).toString(outputBase)}, "toBaseN");
XtraUtils.Number.addUtil(function(n){
return Math.pow(this, n);
}, "toTheNthPower");
XtraUtils.Number.addUtil(function(){
return Math.ceil(this);
}, "ceil");
XtraUtils.Number.addUtil(function(){
return Math.floor(this);
}, "floor");
XtraUtils.Number.addUtil(function() {
return Math.sqrt(this);
}, "sqrt");
XtraUtils.Array.addUtil(function() {
const i = this.map(function(item) {
return typeof item == "number";
});
const isAllNums = i.indexOf(false) == -1;
if (!isAllNums) {
throw "The array must be all numbers.";
return;
};
let max = 0;
let isFirst = true;
this.forEach(function(item) {
if (isFirst || item > max) {
max = item;
isFirst = false;
};
});
return max;
}, "max");
XtraUtils.Array.addUtil(function() {
const i = this.map(function(item) {
return typeof item == "number";
});
const isAllNums = i.indexOf(false) == -1;
if (!isAllNums) {
throw "The array must be all numbers.";
return;
};
let min = 0;
let isFirst = true;
this.forEach(function(item) {
if (isFirst || item < min) {
min = item;
isFirst = false;
};
});
return min;
}, "min");
XtraUtils.Array.addUtil(function() {
let i = this.map(function(item) {
return typeof item == "number";
});
const isAllNums = i.indexOf(false) == -1;
if (!isAllNums) {
throw "The array must be all numbers.";
return;
};
let total = 0;
var isFirst = true;
this.forEach(function(item) {
total += item;
});
const mean = total / this.length;
return mean;
}, "mean");
Feel free to use the utils if you like.