Skip to main content

Guard

.guard() is closely related to .case() and they will often be used in combination

Whilst .case() maps over a collection, .guard() operates on the collection itself

e.g.

node.c.case(is.leaf, "No Children", "Children")

Returns the text string "No Children" if any children of the selected node are a leaf else it returns "Children"

image

However if the selected node is a leaf the expression stops as it cannot evaluate the children nodes that do not exist

image

Using the guard() statement allows for this condition as well

node.guard(is.not.leaf)?.
c.case(is.leaf, "No More Children", "More Children") ?? "No Children"

The node.guard(is.not.leaf)?. sets the initial condition to be met

before evaluating the c.case(is.leaf, "No More Children", "More Children") part of the expression

with the final ?? "No Children part providing the fallback option using the Nullish coalescing operator

image

.guard() provides the option to simplify expressions when working with links too

node.links.
guard(is.not.empty)?.
case(l=>l.value == "R", "Responsible", "Not Responsible") ?? "No Links"

In this example node.links.guard(is.not.empty)? sets the initial condition to be met (that the links exist) before evaluating the case(l=>l.value == "R", "Responsible", "Not Responsible") part where the text "Responsible" is returned if the links value is "R" and "Not Responsible" returned for all other link values.

The ?? "No Links" provides the final fallback else option if the links are empty

info

.guard() is an advanced technique using conditional chaining and nullish coalescing, features of ES2020.

Nullish coalescing operatorโ€‹

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand

It takes the generic form leftExpression ?? rightExpression

In the example expression

node.guard(is.not.leaf)?.c.case(is.leaf, "No More Children", "More Children") ?? "No Children"

The expression node.guard(is.not.leaf)?.c.case(is.leaf, "No More Children", "More Children") represents the left expression

and if this returns null or undefined the the right expression "No Children" is returned