unless()
unless<
T,Result>(value,predicate,transformation):T|Result
Applies a transformation to a value when a predicate is false, otherwise returns the original value.
This is the logical opposite of when.
๐ Why is this a Hidden Gem?
The logical inverse of when. Applies a transformation only if the predicate is false.
Logical opposite of when.
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โ
A function that determines when NOT to apply the transformation.
transformation: (value) => Resultโ
The function to apply when the predicate is false.
Returns: T | Resultโ
The transformed value if predicate is false, otherwise the original value.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
unless (Ramda) ยท โ (Lodash, es-toolkit, Remeda, Radashi, Effect, Modern Dash, Antfu)
Exampleโ
unless(4, (n) => n % 2 !== 0, (n) => n * 2);
// => 8 (4 is not odd, so transformation applies)
unless(3, (n) => n % 2 !== 0, (n) => n * 2);
// => 3 (3 is odd, so no transformation)
unless('hello', (s) => s.trim() === '', (s) => s.toUpperCase());
// => 'HELLO' (not empty, so transformation applies)
unless('', (s) => s.trim() === '', (s) => s.toUpperCase());
// => '' (empty, so no transformation)
How it works?โ
Applies a transformation only when the predicate returns false.
If predicate is true, returns the original value unchanged. Logical opposite of when.
Predicate False (transforms)โ
Predicate True (skips)โ
unless vs whenโ
| Input | when(x, isOdd, double) | unless(x, isOdd, double) |
|---|---|---|
| 3 (odd) | transforms โ 6 | skips โ 3 |
| 4 (even) | skips โ 4 | transforms โ 8 |
Use Casesโ
Add defaults only when missing ๐โ
Add 'https://' prefix only when URL doesn't already have it. Essential for URL normalization and ensuring valid links.
const ensureProto = (url) =>
unless(url, (u) => u.startsWith("http"), (u) => `https://${u}`);
ensureProto("google.com"); // "https://google.com"
ensureProto("https://site.com"); // "https://site.com"
Skip validation for admin usersโ
Apply validation rules only for non-admin users. Critical for permission systems and role-based logic.
const validate = (user) =>
unless(user, (u) => u.isAdmin, (u) => {
if (!u.email) throw new Error("Email required");
return u;
});
transforms โ 6
skips โ 3