w3resource

JavaScript: Get a customized coalesce function that returns the first argument that returns true from the provided argument validation function

JavaScript fundamental (ES6 Syntax): Exercise-42 with Solution

Custom Coalesce Function

Write a JavaScript program to get a customized coalesce function that returns the first argument that returns true from the provided argument validation function.

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

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2
// Define a function 'coalesceFactory' that takes a validity check function 'valid' as input and returns another function.
const coalesceFactory = valid => 
  // The returned function takes any number of arguments 'args'.
  (...args) => 
    // Find and return the first argument that passes the validity check.
    args.find(valid);

// Define a custom coalesce function 'customCoalesce' using 'coalesceFactory'.
const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));

// Test the 'customCoalesce' function with various arguments and output the result.
console.log(customCoalesce(undefined, null, NaN, '', 'Waldo')); // Output: 'Waldo'

Output:

Waldo

Flowchart:

flowchart: Get a customized coalesce function that returns the first argument that returns true from the provided argument validation function

Live Demo:

See the Pen javascript-basic-exercise-1-42 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that returns the first argument for which a given validation function returns true.
  • Write a JavaScript function that accepts multiple arguments and a predicate, then returns the first non-null value satisfying the predicate.
  • Write a JavaScript program that simulates a coalesce operator by checking each argument with a custom test function.

Go to:


PREV : Object from Key-Value Pairs.
NEXT : Change Function to Variadic.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.