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);