Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

lerp

Performs linear interpolation between two numbers.

TypeScript
Copied!
1/**
2 * Performs linear interpolation between two numbers.
3 *
4 * @param a - The start value.
5 * @param b - The end value.
6 * @param t - A number between 0 and 1 indicating the interpolation factor.
7 * @returns The interpolated value.
8 */
9export function lerp(a: number, b: number, t: number): number {
10  return a + (b - a) * t;
11}
  • Mathematically Standard

    Implements the canonical formula for linear interpolation, used widely in graphics, animation, and physics.

  • Simple and Efficient

    A one-liner expression that offers excellent performance and high readability.

  • Smooth Transitions

    Provides smooth value interpolation based on a normalized factor t, ideal for easing and blending.

  • Precision Friendly

    Uses arithmetic directly rather than iterative methods, minimizing rounding errors.

Tests | Examples

TypeScript
Copied!
1test('lerp - start point (t = 0)', () => {
2  expect(lerp(10, 20, 0)).toBe(10);
3});
4
5test('lerp - end point (t = 1)', () => {
6  expect(lerp(10, 20, 1)).toBe(20);
7});
8
9test('lerp - midpoint (t = 0.5)', () => {
10  expect(lerp(10, 20, 0.5)).toBe(15);
11});
12
13test('lerp - negative range', () => {
14  expect(lerp(-10, 10, 0.5)).toBe(0);
15});
16
17test('lerp - t > 1 (extrapolation)', () => {
18  expect(lerp(10, 20, 1.5)).toBe(25);
19});
20
21test('lerp - t < 0 (reverse extrapolation)', () => {
22  expect(lerp(10, 20, -0.5)).toBe(5);
23});

Common Use Cases

  • Animation and Motion

    Interpolate between positions, rotations, or opacity values for smooth visual transitions.

  • Game Development

    Move characters, cameras, or objects incrementally between states based on frame time or input.

  • Data Smoothing and Blending

    Blend numerical values like temperatures, sensor data, or statistical readings.

  • UI Transitions

    Gradually animate layout changes, progress bars, or theme adjustments over time.

  • Procedural Generation

    Interpolate terrain heights, color gradients, or parameters during content generation.

Codebase: Utilities -> Numbers -> lerp | Yevhen Klymentiev