|
|
|
|
|
by brundolf
1126 days ago
|
|
Another short utility I often add (that I wish were a language feature): function given<T, R>(
val: T|null|undefined,
fn: (val: T) => R
): R|null|undefined {
if (val != null) {
return fn(val)
} else {
return val // null|undefined
}
}
function greet(name: string|null) {
return given(name, name => 'Hello ' + name)
}
This is equivalent to eg. Rust's .map()Can also do a version without the null check for just declaring intermediate values: function having<T, R>(
val: T,
fn: (val: T) => R
): R {
return fn(val)
}
const x =
having(2 * 2, prod =>
prod + 1)
|
|