JavaScript: Everyday Utilities and Recipes
Table Of Content
· String
∘ isString
∘ Generate UUID
· Math
∘ isNumber
∘ Random Numbers
∘ Reverse Number
· Array
∘ Remove Duplicate values from an Array
∘ Concat one array to another, without creating a new one.
∘ Shuffle an array
∘ Generate and Fill Array
· Object
∘ Mixin
∘ Object to Map
∘ Map to Object
String
isString
function isString(value) {
return typeof value === "string" || value instanceof String;
}
/* TEST */
console.log(isString("abc") === true);
console.log(isString(new String("abc")) === true); // just typeof value === "string" will miss the String Objects
Generate UUID
window.crypto.randomUUID() // '95a1faba-54c3-498f-8e9f-30968cc5d93f'
Math
isNumber
function isNumber(value) {
return typeof value === "number" && isFinite(value);
}
isNumber(10); // true
isNumber(5.1); // true
isNumber(NaN); // false, just typeof value === "number" will fail here
Random Numbers
Simple: Simple Random Number Generator (Good for most of the cases)
const genRandomNumbers = (max, min = 0) => {
const baseRandomNo = Math.floor(Math.random() * (max - min));
return min + baseRandomNo;
};
genRandomNumbers(10); // any number between 0 <= no < 10
genRandomNumbers(10, 5);// any number between 5 <= no < 10
It’s important to understand that numbers generated by
Math.random()
are pseudorandom, which means they can be guessed or reverse engineered. They are not random enough for cryptography, lotteries, or complex modeling
Advanced: A true random number generator
const genRandomNumbers = (max, min = 0) => {
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer); // Replace it with crypto module in NodeJs
const [randomNo] = randomBuffer; // No between 0 - 2^32
const randomFraction = randomNo / (0xffffffff + 1);
const randomNumber = Math.floor(randomFraction * (max - min)) + min;
return randomNumber;
};
genRandomNumbers(10); // any number between 0 <= no < 10
genRandomNumbers(10, 5); // any number between 5 <= no < 10
Reverse Number
Array
Remove Duplicate values from an Array
Concat one array to another, without creating a new one.
Shuffle an array
Using Fisher-Yates shuffle Algorithm