diff --git a/benchmarks/number/lerp.bench.ts b/benchmarks/number/lerp.bench.ts new file mode 100644 index 00000000..e04837d0 --- /dev/null +++ b/benchmarks/number/lerp.bench.ts @@ -0,0 +1,8 @@ +import * as _ from 'radashi' +import { bench } from 'vitest' + +describe('lerp', () => { + bench('with valid input', () => { + _.lerp(0, 10, 0.5) + }) +}) diff --git a/docs/number/lerp.mdx b/docs/number/lerp.mdx new file mode 100644 index 00000000..886ffd6b --- /dev/null +++ b/docs/number/lerp.mdx @@ -0,0 +1,22 @@ +--- +title: lerp +description: Smoothly transitions between two values based on a factor +--- + +## Basic usage + +The `lerp` function is used to linearly interpolate between two numbers based on a specified amount. This function is particularly useful in animations, graphics, and games for smooth transitions. + +```ts +import * as _ from 'radashi' + +_.lerp(0, 10, 0.5) // => 5 +_.lerp(5, 15, 0.2) // => 7 +_.lerp(-10, 10, 0.75) // => 5 +``` + +## Etymology + +The name `lerp` is short for "linear interpolation". It's a term from computer graphics that means "interpolate linearly between two values". + +For more information, check out the [Wikipedia article](https://en.wikipedia.org/wiki/Linear_interpolation) on linear interpolation. diff --git a/src/mod.ts b/src/mod.ts index 9d8785d8..50d657fa 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -55,6 +55,7 @@ export * from './curry/proxied.ts' export * from './curry/throttle.ts' export * from './number/inRange.ts' +export * from './number/lerp.ts' export * from './number/round.ts' export * from './number/toFloat.ts' export * from './number/toInt.ts' diff --git a/src/number/lerp.ts b/src/number/lerp.ts new file mode 100644 index 00000000..debf1d9d --- /dev/null +++ b/src/number/lerp.ts @@ -0,0 +1,12 @@ +/** + * Linearly interpolates between two numbers. + * + * ``` + * lerp(0, 10, 0.5) // => 5 + * lerp(5, 15, 0.2) // => 7 + * lerp(-10, 10, 0.75) // => 5 + * ``` + */ +export function lerp(from: number, to: number, amount: number): number { + return from + (to - from) * amount +} diff --git a/tests/number/lerp.test.ts b/tests/number/lerp.test.ts new file mode 100644 index 00000000..1b3a959e --- /dev/null +++ b/tests/number/lerp.test.ts @@ -0,0 +1,22 @@ +import * as _ from 'radashi' + +describe('lerp', () => { + test('linearly interpolate between two numbers', () => { + expect(_.lerp(0, 10, 0.5)).toBe(5) + expect(_.lerp(5, 15, 0.2)).toBe(7) + expect(_.lerp(-10, 10, 0.75)).toBe(5) + }) + test('edge cases', () => { + expect(_.lerp(0, 10, 0)).toBe(0) + expect(_.lerp(0, 10, 1)).toBe(10) + expect(_.lerp(5, 5, 0.5)).toBe(5) + }) + test('negative numbers', () => { + expect(_.lerp(-5, 5, 0.5)).toBe(0) + expect(_.lerp(-10, -5, 0.5)).toBe(-7.5) + }) + test('decimal results', () => { + expect(_.lerp(0, 1, 0.3)).toBeCloseTo(0.3, 5) + expect(_.lerp(1, 2, 0.75)).toBeCloseTo(1.75, 5) + }) +})