when()
when<
T,Result>(value,predicate,transformation):T|Result
Applies a transformation to a value when a predicate is true.
๐ Why is this a Hidden Gem?
A functional alternative to ternary operators. Applies a transformation only if the predicate is true.
Logical opposite of unless.
Type Parametersโ
T: Tโ
The type of the input value.
Result: Resultโ
The type of the transformed value.
Parametersโ
value: Tโ
The value to potentially transform.
predicate: (value) => booleanโ
Function that returns true to apply transformation.
transformation: (value) => Resultโ
The function to apply when predicate is true.
Returns: T | Resultโ
The transformed value if predicate is true, otherwise the original value.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
when (Remeda, Ramda) ยท โ (Lodash, es-toolkit, Radashi, Effect, Modern Dash, Antfu)
Exampleโ
when(4, (n) => n % 2 === 0, (n) => n * 2);
// => 8 (4 is even, predicate true, transforms)
when(3, (n) => n % 2 === 0, (n) => n * 2);
// => 3 (3 is odd, predicate false, skips)
when('hello world', (s) => s.length > 10, (s) => s.slice(0, 10) + '...');
// => 'hello worl...'
How it works?โ
Applies a transformation only when the predicate returns true.
If predicate is false, returns the original value unchanged.
when vs unlessโ
| when | unless | |
|---|---|---|
| Transforms if | predicate = true | predicate = false |
| Skips if | predicate = false | predicate = true |
Use Casesโ
Truncate text only if too long ๐โ
Add ellipsis only when text exceeds maximum length. Essential for UI text display and responsive design.
const truncate = (text, max) =>
when(text, (t) => t.length > max, (t) => t.slice(0, max) + "...");
truncate("Hello World", 5); // "Hello..."
truncate("Hi", 5); // "Hi"
Apply discount only for members ๐โ
Calculate discounted price only when user has membership. Critical for e-commerce and pricing logic. Each utility is designed to solve specific function manipulation challenges in real-world development scenarios.
const getPrice = (price, user) =>
when(price, () => user.isMember, (p) => p * 0.9);