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