Skip to content

Instantly share code, notes, and snippets.

@Masd925
Last active March 3, 2020 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Masd925/0b11b0afb222ac34ce2ef72db8bb38c2 to your computer and use it in GitHub Desktop.
Save Masd925/0b11b0afb222ac34ce2ef72db8bb38c2 to your computer and use it in GitHub Desktop.
Javascript ES5 helper functions
function getAllPropertyNames (obj){
var result = [];
while (obj) {
Array.prototype.push.apply(result, Object.getOwnPropertyNames(obj));
obj = Object.getPrototypeOf(obj);
}
return result;
}
function getDefiningObject (obj, propKey) {
obj = Object(obj);
while(obj && !{}.hasOwnProperty.call(obj, propKey)) {
obj = Object.getPrototypeOf(obj);
}
return obj;
}
function randomInteger(min, max) {
return Math.floor(Math.random() * (max-min+1)) + min;
}
function toDigits(value, digits) { // Rounds a number to given precision. Doesn't remove float precision problems
return Number(value.toFixed(digits));
}
function inSteps(value, step) {
return Math.round(value/step);
}
function roundToStep(value, step, decimals) {
value = inSteps(value, step) * step;
return toDigits(value, decimals);
}
function randomStep(min, max, step, digits) {
min = toDigits(min, digits);
max = toDigits(max, digits);
step = toDigits(step, digits);
var steps = inSteps(max-min, step);
var randStepNumber = randomInteger(0, steps);
var rand = min + randStepNumber*step;
return toDigits(rand, digits);
}
function quotient(num,divisor) {
return num/divisor>>0;
}
function isFiniteNumber (val) {
return typeof val==='number' && isFinite(val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment