Proposal: `Math.lerp` (Linear Interpolate)

Linear interpolation (lerp ) is a widely used operation in many domains, including graphics, animation, simulations, and numeric computations. In JavaScript, it is commonly implemented by developers manually. The large number of implementations are found in public repositories on GitHub (Code search results · GitHub),

Despite it is simple appearance, lerp can be subtle in practice. A naive implementation may not always behave as expected, particularly when dealing with values of t outside the range [0, 1] . Sometimes extrapolation is desired (e.g., animations that overshoot), while in other cases it is not (e.g., UI values). Developers often find themselves reimplementing variants of lerp to address these different needs.

For example, in C++, lerp looks like this.

int main() {
    std::cout << std::lerp(0, 10, 0.5) << std::endl; // 5
    std::cout << std::lerp(0, 10, 1.5) << std::endl; // 15 (extrapolation)
    std::cout << std::lerp(10, 0, 1.5) << std::endl; // -5
}

To improve consistency and reduce repetitive boilerplate code, it would be highly beneficial to introduce a standardized version such as Math.lerp(a, b, t).

Optionally, we could consider an additional parameter to clamp the result within the [a, b] range when desired, which could cover a common use case:

Math.lerp(0, 10, 1.5, true)

Or even adding the base for t

Math.lerp(0, 100, 10, false, 10) // 100
1 Like

You may be interested in the Range proposal, although it provides a fixed sequence rather than allowing you to choose an arbitrary point.

Thank you for the info. I still believe lerp has its own value. The Range proposal doesn’t necessarily cover the same use cases.

lerp is unrelated to Range, yeah. There's just some conceptual linkages, but in every practical concern they're completely unconnected.

I think lerping is a pretty useful little utility, yeah. Note CSS's recent addition of calc-interpolate(), which is lerping (but in a more complicated fashion) - in the minimal form you would write calc-interpolate(.5, 0, 10) and get 5 back.

1 Like

I agree that linear interpolation would be useful to standardize, although it fits into the category of “proposals that are easy to reimplement in userland so someone could ask whether there’s a big benefit to standardizing it”.

I don’t have the bandwidth to champion this, but I would voice support for it if a committee champion did propose it.

1 Like

How do we usually find a champion?
And the original proposer also need to do some work for the official proposal?