Argument Coalescing Factory

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28136{{"`Argument Coalescing Factory`"}} javascript/data_types -.-> lab-28136{{"`Argument Coalescing Factory`"}} javascript/arith_ops -.-> lab-28136{{"`Argument Coalescing Factory`"}} javascript/comp_ops -.-> lab-28136{{"`Argument Coalescing Factory`"}} javascript/spread_rest -.-> lab-28136{{"`Argument Coalescing Factory`"}} end

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.

Other JavaScript Tutorials you may like