๐chaining rules
Last updated
Last updated
JS โฉ value โฉ object โฉ accessing properties โฉ chaining rules
all chaining rules are depicted in the following diagrams.
replit๏ผchaining rules
const { log } = console;
// โญ test if `x` is nullish
function isNullish(x) {
return x === undefined || x === null;
}
// โญ about ` a . b ?. c . d ?. e `
testAllCases({ logErrorMessage: false });
// โญ test all cases
function testAllCases({
logErrorMessage = false,
} = {}) {
// counts
let nullishCount = 0;
let nonnullishCount = 0;
let errorCount = 0;
// all cases: about ` a . b ?. c . d ?. e `
const cases = [
null,
{ b: null },
{ b: { c: null } },
{ b: { c: { d: null } } },
{ b: { c: { d: { e: null } } } },
{ b: { c: { d: { e: 'hi' } } } },
];
// iterate over all cases
for (const [i, a] of cases.entries()) {
try {
const value = a.b?.c.d?.e;
const nullish = isNullish(value);
nullish ? nullishCount += 1 : nonnullishCount += 1;
log(`case ${i + 1}: ${value} (${nullish ? 'N' : 'NN'})`);
} catch (err) {
log(`case ${i + 1}: โ ${err.name}${logErrorMessage ? `: ${err.message}` : ''}`);
errorCount += 1;
}
}
// summary
log(` cases: ${cases.length} โ N NN // N : nullish`);
log(`โโโโโโโโโโโโฝโโโโโโโโโโโโ // NN: non-nullish`);
log(`โข live: ${nullishCount + nonnullishCount} โ ${nullishCount} ${nonnullishCount}`);
log(`โข dead: ${errorCount} โ`);
}
// case 1: โ TypeError
// case 2: undefined (N)
// case 3: โ TypeError
// case 4: undefined (N)
// case 5: null (N)
// case 6: hi (NN)
// cases: 6 โ N NN // N : nullish
// โโโโโโโโโโโโฝโโโโโโโโโโโโ // NN: non-nullish
// โข live: 4 โ 3 1
// โข dead: 2 โ
โ possible errors๏ผ
SyntaxError๏ผunexpected numberโ (๐ needs valid identifier)
TypeError๏ผcannot read properties of nullishโ (๐nullish)