Argument Coalescing Factory

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to customize a coalesce function that returns the first argument which is true based on the given validator. We will learn to use Array.prototype.find() to return the first argument that returns true from the provided argument validation function, valid. By the end of this lab, you will be able to create a custom coalesce function that can be used to return the first valid argument from a list of arguments.

Argument Coalescing Factory Code

To begin coding, open Terminal/SSH and type node. This function returns the first argument that evaluates to true based on the validator passed as an argument.

const coalesceFactory =
  (validator) =>
  (...args) =>
    args.find(validator);

Use Array.prototype.find() to return the first argument that returns true from the provided argument validation function, valid. For instance,

const customCoalesce = coalesceFactory(
  (v) => ![null, undefined, "", NaN].includes(v)
);
customCoalesce(undefined, null, NaN, "", "Waldo"); // 'Waldo'

Here, the coalesceFactory function is customized to create the customCoalesce function. The customCoalesce function filters out null, undefined, NaN, and empty strings from the provided arguments and returns the first argument that is not filtered out. The output of customCoalesce(undefined, null, NaN, '', 'Waldo') is 'Waldo'.

Summary

Congratulations! You have completed the Argument Coalescing Factory lab. You can practice more labs in LabEx to improve your skills.