This is Charming1. For Charming2, go to charmingjs.org. This is v1. For v2, go to charmingjs.org.

Math

Processing numbers, randomness, etc.

cm.clamp(value, min, max)

Constrains the input value within the specified range [min, max].

const x = 10;
cm.clamp(10, 2, 8); // 8
cm.clamp(10, 2, 12); // 10
cm.clamp(10, 12, 20); // 12

cm.random([min[, max]])

Generates random number with a uniform distribution, which is within range [min, max). If min is not specified, it defaults to 0; if max is not specified, it defaults to 1.

cm.random(); // 0.4418278691734798
cm.random(10); // 3.747820060823679
cm.random(2, 10); // 6.649642684087617

cm.randomInt([min[, max]])

Like cm.random, expect returns integers.

cm.randomInt(0, 10); // 5

cm.randomNoise(min[, max[, options]])

Returns a function with the specified options for generating random numbers with a smooth, continuous random-like distribution, commonly referred to as [Perlin Noise](Perlin Noise), which is within range [min, max). If min is not specified, it defaults to 0; if max is not specified, it defaults to 1.

Supports following options:

  • octaves - layers of noise, default to 4.
  • seed - seed for generated sequence, a real number or as any integer, defaults to random number.
  • falloff - falloff factor for each octave, a real number or as any integer, defaults to 0.5.

Increasing the number of octaves results in a more variable sequence, and two generators instanced with the same seed and octaves generate the same sequence.

The returned function accept two parameters: x is x coordinate in noise space; y is y coordinate in noise space.

cm.randomNoise()(0.2, 0.1); // 0.04076453205333332
cm.randomNoise(6, 2)(0.2, 0.1); // -0.08489767172063487
cm-randomNoise

cm.randomNormal([mu[, sigma]])

Returns a function for generating random numbers with a [normal(Gaussian) distribution](normal(Gaussian) distribution). The expected value of the generated number is mu, with given standard deviation sigma. If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1.

cm.randomNormal()(); // -2.0897431210663022
cm.randomNormal(30, 10)(); // 31.94829616303788
cm-randomNormal

cm.randomChar()

Returns a random printable and non-empty character.

cm.randomChar(); // 'A'