Skip to content

Instantly share code, notes, and snippets.

@Trung0246
Last active November 20, 2016 07:03
Show Gist options
  • Select an option

  • Save Trung0246/81e0f6a6b94de8232d95eb56a9d8468d to your computer and use it in GitHub Desktop.

Select an option

Save Trung0246/81e0f6a6b94de8232d95eb56a9d8468d to your computer and use it in GitHub Desktop.
A bunch of function that dirty and helpful found on stackoverflow and other sites...
var Notations = {
Short_Number_Old: 1,
Long_Number_Old: 2,
Short_Number_New: 3,
Long_Number_New: 4,
Exponential: 5,
Scientific: 6,
Engineering: 7,
};
Decimal.format = Notations.Long_Number_Old;
var Suffixes = {};
Suffixes[Notations.Short_Number_New] = [
['M', 'B', 'T', 'Qa', 'Qi', 'Sx', 'Sp', 'Oc', 'No', ],
['U', 'D', 'T', 'Qa', 'Qi', 'Sx', 'Sp', 'Oc', 'No', ],
['Dc', 'Vg', 'Tg', 'Qag', 'Qig', 'Sxg', 'Spg', 'Ocg', 'Nog', ],
['Cn', 'DCn', 'TCn', 'QaCn', 'QiCn', 'SxCn', 'SpCn', 'OcCn', 'NoCn', ],
['Mil', ],
];
Suffixes[Notations.Long_Number_New] = [
['M', 'B', 'Tr', 'Quadr', 'Quint', 'Sext', 'Sept', 'Oct', 'Non', ],
['Un', 'Duo', 'Tre', 'Quattuor', 'Quin', 'Sex', 'Septen', 'Octo', 'Novem', ],
['Dec', 'Vigin', 'Trigin', 'Quadragin', 'Quinquagin', 'Sexagin', 'Septuagin', 'Octogin', 'Nonagin', ],
['Cen', 'DuoCen', 'TreCen', 'Quadringen', 'Quingen', 'Sescen', 'Septingen', 'Octingen', 'Nongen', ],
['Millia', ],
];
Suffixes[Notations.Short_Number_Old] = [
["k", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "De"],
["Un", "Du", "Tr", "Qa", "Qi", "Se", "Sp", "Oc", "No"],
["De", "Vi"],
["Ce"],
];
Suffixes[Notations.Long_Number_Old] = [
["Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion"],
["un", "duo", "tre", "quattuor", "quinqua", "se", "septe", "octo", "nove"],
["deci", "viginti", "triginta", "quadraginta", "quinquaginta", "sexaginta", "septuaginta", "octoginta", "nonaginta"],
["centi", "ducenti", "trecenti", "quadringenti", "quingenti", "sescenti", "septingenti", "octingenti", "nongenti"],
["millini", "billini", "trillini", "quadrillini", "quintillini", "sextillini", "septillini", "octillini", "nonillini", "decillini"],
];
console.temp = [];
Math.configRandom = function(options) {
//Use with seedrandom.js found somewhere on internet I can't remember
try {
options = options || {
Function: function(seed) {
Math.seedrandom(seed);
return Math.random();
},
Seed: null,
Range: [0, 1],
Round: false,
Exception: null,
Error: {
Larger: 0,
Equal: 0
},
Gaussian: 1,
Weight: null
};
options.Function = options.Function || function(seed) {
Math.seedrandom(seed);
return Math.random();
};
options.Seed = options.Seed || null;
options.Range = options.Range || [0, 1];
options.Round = options.Round || false;
options.Exception = options.Exception || null;
options.Error = options.Error || {};
options.Error.Larger = options.Error.Larger || 0;
options.Error.Equal = options.Error.Equal || options.Range[0];
options.Gaussian = options.Gaussian || 1;
options.Weight = options.Weight || null;
if (typeof options.Function != "function" && options.Function != null) {
return console.error("options.Function is not function");
}
if (typeof options.Seed != "string" && options.Seed != null) {
return console.error("options.Seed is not string");
}
if (Object.prototype.toString.call(options.Range) !== '[object Array]' && options.Range != null) {
return console.error("options.Range is not array");
}
if (typeof options.Round != "boolean" && options.Round != null) {
return console.error("options.Round is not boolean");
}
if (Object.prototype.toString.call(options.Exception) !== '[object Array]' && options.Exception != null) {
return console.error("options.Exception is not array");
}
if (Object.prototype.toString.call(options.Error) === '[object Object]' && options.Error != null) {
if (typeof options.Error.Larger != "number" && options.Error.Larger != null) {
return console.error("options.Error.Larger is not number");
}
if (typeof options.Error.Equal != "number" && options.Error.Equal != null) {
return console.error("options.Error.Equal is not number");
}
} else if (Object.prototype.toString.call(options.Error) !== '[object Object]' && options.Error != null) {
return console.error("options.Error is not object");
}
if (typeof options.Gaussian != "number" && options.Gaussian != null) {
return console.error("options.Gaussian is not number");
}
if (Object.prototype.toString.call(options.Weight) !== '[object Array]' && options.Weight != null) {
return console.error("options.Weight is not array");
}
function PRNG() {
var Value;
if (options.Round === true) {
Value = Number(Math.floor(options.Function(options.Seed) * (options.Range[1] - options.Range[0] + 1)) + options.Range[0]);
} else if (options.Round === false || options.Round == null) {
Value = Number(options.Function(options.Seed) * (options.Range[1] - options.Range[0]) + options.Range[0]);
} else {
console.error("What happened with options.Round in Math.random.advanced ?");
}
if (options.Range[0] > options.Range[1]) {
if (options.Larger == null) {
Value = 0;
} else {
Value = options.Larger;
}
return Value;
} else if (options.Range[0] == options.Range[1]) {
if (options.Equal == null) {
Value = options.Range[0];
} else {
Value = options.Equal;
}
return Value;
} else if (options.Range[0] < options.Range[1]) {
return options.Seed != null ? Value : ((options.Exception == [] || options.Exception == null) ? Value : (options.Exception.indexOf(Value) == -1) ? Value : (options.Gaussian != null && (options.Other === false && options.Other != null) ? Value : PRNG()));
}
}
function GauRan() {
if (options.Gaussian == null || (typeof options.Gaussian == "number" && options.Gaussian <= 1)) {
return PRNG();
} else if (options.Gaussian > 1 && options.Gaussian != null) {
var Total = 0,
Times = 0;
while (Times < options.Gaussian) {
Times++;
Total += PRNG();
}
Total /= options.Gaussian;
if (options.Round == true) {
Total = Math.round(Total, 0);
}
return options.Seed != null ? console.error("Please remove parameter options.Gaussian because options.Seed is defined.") : ((options.Exception == [] || options.Exception == null) ? Total : (options.Exception.indexOf(Total) == -1) ? Total : GauRan());
}
}
var TempResult = GauRan(),
count = 0,
TempStore = "",
TempHighest = options.Range[1],
TempError = false;
if (options.Weight == null) {
return TempResult;
} else if (options.Weight != null) {
while (count < options.Weight.length) {
if (count == options.Weight.length - 1) {
TempStore += "options.Weight[" + String(count) + "].Return";
} else {
if (options.Weight[count].Chance > TempHighest) {
TempError = true;
break;
}
TempStore += "TempResult" + options.Round === true ? ">=" : ">" + "options.Weight[" + String(count) + "].Chance?options.Weight[" + String(count) + "].Return:";
TempHighest = options.Weight[count].Chance;
}
count++;
}
if (TempError === true) {
return console.error("options.Weight[" + String(count) + "].Chance is larger than options.Weight[" + String(Number(count - 1)) + "].Chance");
}
return eval(TempStore);
}
} catch (error) {
console.configLog({
Log: ["Math.configRandom function || " + error],
Type: "Error"
});
}
};
String.prototype.bigFormat = function(Is_Digits) {
//Use with decimal.js by MikeMcl
try {
var digits = new Decimal(String(this)).cmp(new Decimal(1)) <= 0 ? 0 : Decimal.log10(String(this)).floor().toNumber();
var position = 2 - digits % 3;
var r = (Math.abs(this) < 1000) ? new Decimal(String(this)).floor() : (new Decimal(String(this)).div(new Decimal(10).pow((new Decimal(digits).div(3)).floor().mul(3).sub(position))).div(new Decimal(10).pow(position).floor())).toFixed(position + 1).toString();
var thousands = Math.floor(digits / 3) - 1;
if (Decimal.format == Notations.Scientific || Decimal.format == Notations.Exponential) {
Decimal.config({
rounding: 4
});
return (new Decimal(String(this)).cmp(1000) == 1 ? numeral(this.slice(0, this.indexOf('e'))).format('0.[000]') : Number(this)) + (new Decimal(String(this)).cmp(1000) == 1 ? "e+" + digits : "");
} else if (Decimal.format == Notations.Engineering) {
return r + (digits > 2 ? "e+" + String((thousands + 1) * 3) : "");
} else {
return (Decimal.format == Notations.Short_Number_Old || Decimal.format == Notations.Long_Number_Old ? r + " " + Decimal.suffix(thousands) : digits <= 5 ? String(this) : r + " " + Decimal.suffix(digits));
}
} catch (error) {
console.configLog({
Log: ["String.prototype.bigFormat function || " + error],
Type: "Error"
});
}
};
Decimal.change = function(type) {
try {
if (type in Notations) Decimal.format = Notations[type];
} catch (error) {
console.configLog({
Log: ["Decimal.change function || " + error],
Type: "Error"
});
}
};
Decimal.suffix = function(Digits) {
try {
switch (Decimal.format) {
case Notations.Long_Number_New:
case Notations.Short_Number_New:
try {
if (Digits >= 6) {
Digits += 1;
// Attempt to get the Suffixes for the given Decimal.format
if (!(Decimal.format in Suffixes)) Decimal.format = Notations.Long_Number_New;
var suffixList = Suffixes[Decimal.format];
// Convert from digit count to latin power number
var thousands = Math.floor((Digits - 1) / 3);
var latinPower = thousands - 1;
// Compile the suffix in groups of 1000
var suffix = '';
var thousandPart = '';
for (var powersLeft = latinPower; powersLeft >= 1;) {
// Take the lowest thousand-part (ie last three Digits) from the latin power count
var newPowersLeft = Math.floor(powersLeft / 1000);
var current = powersLeft - newPowersLeft * 1000;
// Split off the hundreds, tens, and units
var hundreds = Math.floor(current / 100) % 10;
var tens = Math.floor(current / 10) % 10;
var units = Math.floor(current / 1) % 10;
// Convert into the suffix parts for hundreds, tens, and units
var hundredPart = (hundreds >= 1) ? suffixList[3][hundreds - 1] : '';
var tenPart = (tens >= 1) ? suffixList[2][tens - 1] : '';
var unitPart = (units >= 1) ? suffixList[(latinPower < 10) ? 0 : 1][units - 1] : '';
// Combine the suffix parts, and add the generated thousand-part suffix to the result
var part = hundredPart + unitPart + tenPart;
part = (part !== '') ? part + thousandPart : part;
suffix = part + suffix;
// Update the remaining latin powers, and add to the thousand suffix part
powersLeft = newPowersLeft;
thousandPart += suffixList[4][0];
}
// Compute the ending part, and return the final result
var ending = '';
if (Decimal.format === Notations.Long_Number_New) ending = (latinPower >= 20) ? 'tillion' : (latinPower >= 1) ? 'illion' : '';
return suffix + ending;
} else {
return '';
}
} catch (error) {}
break;
case Notations.Long_Number_Old:
case Notations.Short_Number_Old:
try {
var replaceChars = {};
var charAt = null;
var a0 = Suffixes[Decimal.format][0],
a1 = Suffixes[Decimal.format][1],
a2 = Suffixes[Decimal.format][2],
a3 = Suffixes[Decimal.format][3],
a4 = Suffixes[Decimal.format][4];
var Number_1000 = Math.floor(Digits / 1000) % 10;
var Number_100 = Math.floor(Digits / 100) % 10;
var Number_10 = Math.floor(Digits / 10) % 10;
var Number_1 = Math.floor(Digits / 1) % 10;
var Number_1000_String = "";
var Number_100_String = "";
var Number_10_String = "";
var Number_1_String = "";
var Number_Lillion_String = "illion";
if (Digits == -1) {
return "";
} else if (Digits <= 10) {
return "" + a0[Digits];
} else if (Digits < 10000) {
switch (Decimal.format) {
case Notations.Short_Number_Old:
Number_1000_String = (Number_1000 === 0 ? "" : a0[Number_1000]);
if (Number_1000 === 0) {
Number_1000_String = "";
} else if (Number_1000 == 1 || Number_1000 == 2 || Number_1000 == 3) {
Number_1000_String = Number_1000_String + "i";
}
if (Number_100 === 0) {
Number_100_String = "";
} else if (Number_100 == 1) {
Number_100_String = a3[0];
if (Number_10 !== 0 || Number_1 !== 0) {
if (Number_1000 === 0) {
Number_100_String = Number_100_String.replace("e", "");
}
}
} else {
Number_100_String = a1[Number_100 - 1];
replaceChars = {
2: "u",
3: "r",
8: "c",
9: "o"
};
if (Number_100 in replaceChars) {
if (Number_1000 === 0) {
Number_100_String = Number_100_String.replace(replaceChars[Number_100], "");
}
}
}
Number_10_String = Number_10 === 0 ? "" : a2[Number_10 - 1] != null ? a2[Number_10 - 1] : a1[Number_10 - 1];
if (Number_100 === 0) {
Number_10_String = Number_10 == 1 || Number_10 == 2 ? a2[Number_10 - 1] : a1[Number_10 - 1];
if (Number_1 !== 0) {
replaceChars = {
1: "e",
2: "i",
3: "r",
8: "c",
9: "o"
};
if (Number_10 in replaceChars) {
Number_10_String = Number_10_String.replace(replaceChars[Number_10], "");
}
}
}
Number_1_String = Number_1 === 0 ? "" : a1[Number_1 - 1];
if (Number_1 == 6) {
charAt = Number_10 === 0 ? Number_100_String.charAt(0) : Number_10_String.charAt(0);
if (["C", "O"].indexOf(charAt) != -1) {
Number_1_String = Number_1_String.replace("e", "x");
} else if (["Q", "T", "V"].indexOf(charAt) != -1) {
Number_1_String = Number_1_String.replace("e", "s");
}
}
if (Number_1 === 0) {
Number_1_String = "";
}
if (Number_10 === 0) {
Number_10_String = "";
}
if (Number_100 === 0) {
Number_100_String = "";
}
Number_Lillion_String = "";
break;
case Notations.Long_Number_Old:
Number_1000_String = (Number_1000 === 0 ? "" : a4[Number_1000 - 1]);
Number_100_String = Number_100 === 0 ? "" : a3[Number_100 - 1];
Number_10_String = Number_10 === 0 ? "" : a2[Number_10 - 1];
if (Number_10 == 1 || Number_10 == 2) {
Number_10_String = a2[Number_10 - 1];
if (Number_1000 === 0 || Number_100 === 0) {
Number_Lillion_String = "llion";
}
} else if ([3, 4, 5, 6, 7, 8, 9].indexOf(Number_10) != -1) {
if (Number_1000 === 0 || Number_100 === 0) {
Number_10_String = a2[Number_10 - 1].slice(0, a2[Number_10 - 1].length - 1);
} else {
Number_Lillion_String = "llion";
}
}
Number_1_String = Number_1 === 0 ? "" : a1[Number_1 - 1];
charAt = Number_10 === 0 ? Number_100_String.charAt(0) : Number_10_String.charAt(0);
if (Number_1 == 3 && ["c", "o", "q", "t", "v"].indexOf(charAt) != -1) {
Number_1_String += "s";
} else if (Number_1 == 6) {
if (["c", "o"].indexOf(charAt) != -1) {
Number_1_String += "x";
} else if (["q", "t", "v"].indexOf(charAt) != -1) {
Number_1_String += "s";
}
} else if (Number_1 == 7 || Number_1 == 9) {
if (["c", "d", "q", "s", "t"].indexOf(charAt) != -1) {
Number_1_String += "n";
} else if (["o", "v"].indexOf(charAt) != -1) {
Number_1_String += "m";
}
}
break;
}
return "" + String(Number_1_String + Number_10_String + Number_100_String + Number_1000_String + Number_Lillion_String).replace('iillion', 'illion').capFirstLetter();
} else {
return "e+" + String((Digits + 1) * 3);
}
} catch (error) {}
break;
}
} catch (error) {
console.configLog({
Log: ["Decimal.suffix function || " + error],
Type: "Error"
});
}
};
math.roundoff = function(number) {
//Use with math.js, dirty version for fixing round-off error
try {
return Math.round((number) * 1000000000000000) / 1000000000000000;
} catch (error) {
console.configLog({
Log: ["math.roundoff function || " + error],
Type: "Error"
});
}
};
console.configLog = function(options) {
try {
options = options || {};
options.Log = options.Log || [];
options.Stringify = options.Stringify || false;
options.Type = options.Type || "Log";
options.Group = options.Group || "";
options.Throw = options.Throw || false;
options.ErrorType = options.ErrorType || "Normal";
options.Clear = options.Clear || false;
if (typeof options.Log === "string") {
options.Log = [options.Log];
}
var Temp = [],
Count = 0;
if (options.Clear === true) {
console.clear();
}
switch (options.Group) {
case "Start":
console.group();
break;
case "Collapse":
console.groupCollapsed();
break;
}
if (options.Stringify === true) {
while (Count < options.Log.length) {
Temp.push(JSON.stringify(options.Log[Count]));
Count++;
}
options.Log = Temp;
}
switch (options.Type) {
case "Log":
console.log.apply(this, options.Log);
break;
case "Info":
console.info.apply(this, options.Log);
break;
case "Warn":
console.warn.apply(this, options.Log);
break;
case "Error":
if (options.Throw === true) {
throw (function() {
switch (options.ErrorType) {
case "Normal":
return new Error(options.Log);
break;
case "Eval":
return new EvalError(options.Log);
break;
case "Internal":
//check if browser is firefox
if (false) {
return new InternalError(options.Log);
} else {
return new Error(options.Log);
}
break;
case "Range":
return new RangeError(options.Log);
break;
case "Reference":
return new ReferenceError(options.Log);
break;
case "Syntax":
return new SyntaxError(options.Log);
break;
case "Type":
return new TypeError(options.Log);
break;
case "URI":
return new URIError(options.Log);
break;
}
})();
} else {
console.error.apply(this, options.Log);
}
break;
case "Table":
console.table.apply(this, options.Log);
break;
case "Assert":
console.assert.apply(this, options.Log);
break;
case "Time":
if (console.temp.indexOf(JSON.stringify(options.Log)) !== -1) {
console.time.apply(this, options.Log);
console.temp.push(JSON.stringify(options.Log));
} else {
console.temp.splice(console.temp.indexOf(JSON.stringify(options.Log)), 1);
console.timeEnd.apply(this, options.Log);
}
break;
}
if (options.Group === "End") {
console.groupEnd();
}
} catch (error) {
throw error;
}
};
//Array helper
Array.prototype.indexObject = function(options) {
try {
if (Object.prototype.toString.call(options) !== '[object Object]' && options != null) {
return console.log("options is not object");
}
var array = this;
function Object_Array_Index(ary, ads, vl) {
var result_index = null;
result_index = String(ary.map(function(obj, index) {
if (obj.getValue(ads) == vl) {
return index;
}
}).filter(isFinite));
if (result_index === "") {
return -1;
} else {
return Number(result_index);
}
}
return Object_Array_Index(array, String(Object.keys(options)), options[String(Object.keys(options))]);
} catch (error) {
console.configLog({
Log: ["Array.prototype.indexObject function || " + error],
Type: "Error"
});
}
};
Array.prototype.getMultiLength = function() {
return this.valueOf().reduce((sum, elt) => sum + (elt.length ? elt.getLength() : 1), 0);
};
Array.prototype.multiIndexOf = function(value) {
var result;
this.some(function iter(path) {
return function(a, i) {
if (a === value) {
result = path.concat(i);
return true;
};
return Array.isArray(a) && a.some(iter(path.concat(i)));
}
}([]));
return result;
}
//Object helper
Object.prototype.byString = function(s) {
try {
var o = this;
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
} catch (error) {
console.configLog({
Log: ["Object.prototype.byString function || " + error],
Type: "Error"
});
}
};
Object.prototype.getValue = function(address, value) {
try {
var object = this;
function Get_Object_Value(obj, ads, vl) {
if (typeof ads == "string") return Get_Object_Value(obj, ads.split("."), vl);
else if (ads.length == 1 && vl !== undefined) return obj[ads[0]] = vl;
else if (ads.length === 0) return obj;
else return Get_Object_Value(obj[ads[0]], ads.slice(1), vl);
}
return Get_Object_Value(object, address, value);
} catch (error) {
console.configLog({
Log: ["Object.prototype.getValue function || " + error],
Type: "Error"
});
}
};
Object.prototype.indexOf = function(name) {
try {
return Object.keys(this).indexOf(name);
} catch (error) {
console.configLog({
Log: ["Object.prototype.indexOf function || " + error],
Type: "Error"
});
}
};
Object.prototype.indexValue = function(value) {
try {
var list = [];
for (var key in this) {
list.push(this[key]);
}
return list.indexOf(value);
} catch (error) {
console.configLog({
Log: ["Object.prototype.indexValue function || " + error],
Type: "Error"
});
}
};
Object.prototype.valueName = function(value) {
try {
var location = this.indexValue(value);
var list = Object.keys(this);
if (location >= 0) {
return list[location];
} else {
return undefined;
}
} catch (error) {
console.configLog({
Log: ["Object.prototype.valueName function || " + error],
Type: "Error"
});
}
};
//String helper
String.prototype.capFirstLetter = function() {
try {
return this.charAt(0).toUpperCase() + this.slice(1);
} catch (error) {
console.configLog({
Log: ["String.prototype.capFirstLetter function || " + error],
Type: "Error"
});
}
};
String.prototype.spinTax = function(mode) {
try {
var spun = this;
var SPINTAX_PATTERN = /\{[^"\r\n\}]*\}/;
switch (mode) {
case "count":
case "true":
case true:
spun = spun.replace(/[^{|}]+/g, '1');
spun = spun.replace(/\{/g, '(');
spun = spun.replace(/\|/g, '+');
spun = spun.replace(/\}/g, ')');
spun = spun.replace(/\)\(/g, ')*(');
spun = spun.replace(/\)1/g, ')*1');
spun = spun.replace(/1\(/g, '1*(');
console.log(spun);
return eval(spun);
break;
default:
var match;
while (match == spun.match(SPINTAX_PATTERN)) {
match = match[0];
var candidates = match.substring(1, match.length - 1).split("|");
spun = spun.replace(match, candidates[Math.floor(Math.random() * candidates.length)]);
}
return spun;
break;
}
} catch (error) {
console.configLog({
Log: ["String.prototype.spinTax function || " + error],
Type: "Error"
});
}
};
String.prototype.charCount = function(to_find) {
try {
if (this == undefined || typeof this !== "string" || this.length < 0 || to_find == undefined || to_find.length != 1) {
return 0;
}
var count = -1;
var i;
for (i = 0; i < this.length; i++) {
if (this[i] == to_find[0]) {
count++;
}
}
count++;
return count;
} catch (error) {
console.configLog({
Log: ["String.prototype.charCount function || " + error],
Type: "Error"
});
}
};
String.prototype.escapeRegExp = function() {
return this.valueOf().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
};
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search.escapeRegExp(), 'g'), replacement);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment