Last active
March 3, 2020 10:14
-
-
Save Masd925/0b11b0afb222ac34ce2ef72db8bb38c2 to your computer and use it in GitHub Desktop.
Javascript ES5 helper functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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