Maf.js

A library for doin’ maf innit

Maf.js implements many common useful functions that are not supported in the JavaScript Math library. Instead of adding methods to Math.prototype and risking potential conflicts with future implementations, let’s create a Math library with those methods.

There’s a mix of GLSL, HLSL, Unity and other libraries and languages.

npm

Demo

2026 update

Disclaimer: this library is from 2015. Math still doesn’t have most of these, so it’s as useful as it was. If you use three.js, check MathUtils first (it’s had that name since r113, 2020): it has clamp, lerp, inverseLerp, mapLinear, smoothstep, degToRad, isPowerOfTwo and others

The library has been reviewed and has grown. What was fixed from version 1:

And what is new:

One thing is as it was, and worth knowing: the value goes last in the functions that come from GLSL, like step() and map(), and first in the others.

How to use

Use npm to install it

npm i spite-maf

and import what you need, or all of it

import { clamp, lerp, smoothStep } from 'spite-maf';
import * as Maf from 'spite-maf';

Maf.clamp( 1.5, 0, 1 ); // 1

It’s a single ES module with no dependencies, Maf.js, so it also works without npm or a bundler. It has types for TypeScript, and npm test runs its tests.

Methods

Clamping and steps

Mixing and mapping

The plain ones do the maths and nothing else: outside of their range they keep going. The ones that say Clamped stop at its ends.

Moving towards a target

Shaping, from the functions of Inigo Quilez and others

Angles, in degrees unless they say Rad

Random

All of them take the function that gives the numbers as their last parameter, Math.random by default:

const random = seededRandom( 'my sketch' );

randomInRange( 0, 10, random );
shuffle( cards, random );

Noise

The rest

Discarded

License

MIT licensed

Copyright (C) 2015 Jaume Sanchez Elias https://twitter.com/thespite

https://www.clicktorelease.com