Unfold Function in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the unfold() function in JavaScript. This function allows us to create an array by repeatedly calling an iterator function with an initial seed value until the function returns false. Through this lab, we will learn how to use the unfold() function and how it can be used to simplify certain programming tasks.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic 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/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28679{{"`Unfold Function in JavaScript`"}} javascript/data_types -.-> lab-28679{{"`Unfold Function in JavaScript`"}} javascript/arith_ops -.-> lab-28679{{"`Unfold Function in JavaScript`"}} javascript/comp_ops -.-> lab-28679{{"`Unfold Function in JavaScript`"}} javascript/loops -.-> lab-28679{{"`Unfold Function in JavaScript`"}} javascript/array_methods -.-> lab-28679{{"`Unfold Function in JavaScript`"}} end

Unfold Array

To create an array using an iterator function and an initial seed value, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use a while loop and Array.prototype.push() to call the iterator function repeatedly until it returns false.
  3. The iterator function should accept one argument (seed) and always return an array with two elements ([value, nextSeed]) or false to terminate.

Use the following code to implement the unfold function:

const unfold = (fn, seed) => {
  let result = [],
    val = [null, seed];
  while ((val = fn(val[1]))) result.push(val[0]);
  return result;
};

Here's an example of how to use the unfold function:

var f = (n) => (n > 50 ? false : [-n, n + 10]);
unfold(f, 10); // [-10, -20, -30, -40, -50]

This will produce an array with values generated by the iterator function f starting from the initial seed value of 10. The iterator function generates an array with two elements at each step: the negation of the current seed value and the next seed value, which is incremented by 10. The process continues until the seed value is greater than 50, at which point the function returns false.

Summary

Congratulations! You have completed the Unfold Array lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like