let<zxs>

Definition

function letz(run: (it:T)=>R) : R;
function letz(run: (it:T)=>void) : VoidRan|undefined;
function lets(run: (it:T)=>R) : R;
function lets(run: (it:T)=>void) : VoidRan|undefined;
function letx(condition: (it:T)=>boolean, run: (it:T)=>R) : R;
function letx(condition: (it:T)=>boolean, run: (it:T)=>void) : VoidRan|undefined;

Example

As the name implies, given key in object has the corresponding key-to-parse function applied to it. You may reuse the parser passed on this object to other objects

import '@marthvon/protopp';
// or
import '@marthvon/protopp/objectpp/methods/letIt.js';

function someFunction() : string|undefined;
// Say some function either returns undefined or string

someFunction()?.letz((it: string) => console.log(it));
// The following would console log the output of someFunction but when output is undefined... it does nothing

someFunction()?.letz((it: string) => console.log(it)) ??
(() => console.log('someFunction returned undefined'))()
// Same as before, except when someFunction return undefined... it prints out 'someFunction returned undefined'

The Importance of VoidRan

VoidRan is a return value used to indicate that void functions ran successfully.
let<zxs> only returns undefined when callback function did not ran successfully. Otherwise, all return statements returning undefined will be casted to VoidRan.

This is helpful when we want to add an 'else' behaviour to the let<zxs> given it doesn't fullfill a condition, like for example not being undefined, not an empty string, or should be an instanceof of this type... those type of conditions.

Key Difference letz vs lets

letz tend to execute always unless when it is called via

<variable>?.letz
, then it would fail to execute if variable is undefined or null. But lets will not execute if calling variable is a falsy value.

lets would fail to execute callback run and then return undefined when variable is falsy.
Falsy values may include undefined, null, false, zero, empty string, and empty array.

How about letx?

Simply, it takes two callback functions, one condition and the other is callback logic. When condition is not fullfilled, it returns undefined like all the other let functions and avoid executing the run callback.

function someFunction() : Set|Map;

someFunction().letx(
(it: Set|Map) => it instanceof Map,
(it: Map) => it.get('a')
);
NPM Homepage
Github Homepage
About Me