A collection of usefull tips in your evry day JS coding

Javascript ES6

2018

Fill an Array with random values (here 100 values between 0 and 1)

let values = Array(100).fill().map(Math.random);

Deep copy

let cloneObj = Object.create( JSON.parse(JSON.stringify(Obj)) );

Shorthand for Console.log

var log = console.log;
// then use log("chicken !");

2D Quasi-random number generator

static plastic(index){
    const p1 = 0.7548776662466927; // inverse of plastic number
    const p2 = 0.5698402909980532;
    return {x:(p1 * index) % 1, y:(p2 * index) % 1};
}

1D Quasi-random number generator

static golden(index) {
    const p = 0.618033988749894848; // inverse of golden ratio
    return p * index % 1;
}

shuffle an array

static shuffle(arr){
	let i, p, tmp;
	for (i = arr.length - 1; i > 0; --i) {
		p = (Math.random() * (i + 1)) >> 0;
		if (p === i) {
			continue;
		}
		tmp = arr[i];
		arr[i] = arr[p];
		arr[p] = tmp;
	}
}

Get random values in interval

static getRandomInt(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

static getRandomFloat(min, max) {
	return Math.random() * (max - min) + min;
}

Clamping values

static clamp (value, min, max, loop = false) {
	if (loop === true) {
		if (value < min) {
			return max - ((min - value) % (max - min));
		}
		if (value > max) {
			return min + ((value - max) % (max - min));
		}
	}

	return Math.max(Math.min(value, max), min);
};

Smoothstep

static smoothstep(x, e0 = 0, e1 = 1) {
	x = Math.min(Math.max((x - e0) / (e1 - e0), 0.0), 1.0);
	return x * x * (3 - 2 * x);
}

static smoothstep2(x, e0 = 0, e1 = 1)
{
	// Scale, bias and saturate x to 0..1 range
	x = Math.min(Math.max((x - e0) / (e1 - e0), 0.0), 1.0);
	// Evaluate polynomial
	return x * x * x * (x * (x * 6 - 15) + 10);
}

Sleep

static sleep(timeMs) {
	return new Promise((resolve) => setTimeout(resolve, timeMs));
}

“Flash style” easing

object.x += (targetX – object.x) * easingFactor;
object.y += (targetY – object.y) * easingFactor;

Constraint value

angle360 = ((angle % 360) + 360) % 360;
angle180 = ((angle % 360) + 540) % 360 - 180;

Fast sign change

i = -i;
i = ~i + 1; // faster
i = (i ^ -1) + 1; // fastest

Fast modulo
If the divisor is a power of 2, the modulo operation can be done with : modulus = numerator & (divisor – 1);

mod = 131 % 4;
mod = 131 & (4 - 1); // faster

Fast modulo lead to Fast parity test

isEven = (i % 2) == 0;
isEven = (i & 1) == 0; // faster

Fast absolute value

absX = Math.abs(x);
absX = x < 0 ? -x : x; // faster
absX = (x ^ (x >> 31)) - (x >> 31); // fastest

Fast distance comparaison
Compare squared distance instead of real distance

Approximation of PI

22/7 
355/113
103993/33102

Approximation of the golden number

987/610

Vote in HexoSearch