Function that solves problems through recursion

Why does the code print both dots in the array simultaneously instead of printing dot, pausing, then printing dash, and finally printing dot? Is there an issue with my conditional statement?

function morseCode(code) {
  if (code.length === 0) {
    return;
  }
  let ele = code[code.length - 1];
  if (ele === "dot") {
    setTimeout(() => {
      console.log("dot");
    }, 100);
  } else {
    setTimeout(() => {
      console.log("dash");
    }, 300);
  }
  return morseCode(code.slice(0, -1));
}
let code = ["dot", "dash", "dot"];

morseCode(code);
// print 'dot'
// pause for 100ms
// print 'dash'
// pause for 300ms
// print 'dot'
// pause for 100ms

Answer №1

The use of setTimeout does not cause your code to be blocked. This means that you are essentially lining up three functions to execute almost simultaneously, each with the same time interval: a dot after 100ms, a dash after 300ms, followed by another dot after 100ms.

After 100ms, you will see two dots being printed, and after 300ms, you will see one dash being printed.

Answer №2

Consider placing morseCode(code.slice(0, -1)); within the confines of a setTimeout. Since setTimeout operates in a non-blocking manner, invoking morseCode through it will allow you to accomplish your objective.

Answer №3

Here's a different method to accomplish the task:

let morseCode = '...-..---..-..--.---'
  .split('')
  .map(char => char === '.' ? 'dot' : 'dash');

function convertToMorse(arr){
  const letter = arr.shift();
  const delayTime = letter === 'dot' ? 100 : 500;

  console.log(letter);

  if (arr.length) {
    setTimeout(convertToMorse, delayTime, arr);
  }  
}

convertToMorse(morseCode);
.as-console-wrapper { min-height: 100%!important; top: 0; }

It's crucial to initiate the timing for the "next" character from within the timeout callback function to ensure that each setTimeout call is scheduled relative to its own starting point in time.

Answer №4

Here is a revised version of the function without a timeout:

function morseCode(code) {
        let time = 0;
        if (code.length === 0) {
          return;
        }
        let ele = code[code.length - 1];
        if (ele === "dot") {
            console.log("dot");
            time = 100;
        } else {
            console.log("dash");
            time = 300;
        }
        return morseCode(code.slice(0, -1));
}
let code = ["dot", "dash", "dot"];

morseCode(code);

I hope this revised version helps you with your requirements!

Answer №5

Here is another way to approach this problem recursively:

const morseCode = ([char, ...rest]) => {
  if (char !== undefined) {
    setTimeout(() => morseCode(rest), char === '.' ? 100 : char === '-' ? 500 : 1000);
    console.log(char === '.' ? 'dot' : char === '-' ? 'dash' : '');
  }
};

morseCode('.... . .-.. .-.. ---')
.as-console-wrapper {max-height: 100% !important; top: 0}

This code destructures a string parameter and checks if the current character exists. If it does, it sets a timeout with a delay based on the character type and logs the appropriate message ('dot', 'dash', or blank).

If you prefer a different style, here is an equivalent version:

const morseCode = ([char, ...rest]) => {
  if (char !== undefined) {
    const signal = char === '.' ? 'dot' : char === '-' ? 'dash' : '';
    const duration = char === '.' ? 100 : char === '-' ? 400 : 800;
    setTimeout(() => morseCode(rest), duration);
    console.log(signal);
  }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am encountering an issue where the JSON data is not being properly loaded into my Angular 8 application

Here is the structure of my JSON data: { "content": [ { "id": 1, "name": "test name", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbbfaeb8bf8bbfaeb8bfe5a8a4a6"&g ...

Why does NPM keep flagging dependencies as unmet even though they are clearly installed and met?

Currently, I am in the process of setting up angular2 with typescript and node. However, I keep receiving warnings about unmet peer dependencies even though they seem to be available: tyler@tyler-Blade-Stealth:~/projects/mockups$ npm install -g @angular/c ...

What is the best way to trigger a jQuery UI dialog using an AJAX request?

My website includes a jQuery UI Dialog that opens a new window when I click the "create new user" button. Is there a way to open this window using an AJAX request? It would be useful if I could open the dialog-form from another page, such as dialog.html ...

When using the .after() method to add jQuery elements, keep in mind that they will not trigger any

Here is the snippet of code provided: <s:file name="upload" id="upload"></s:file> $('input[id^="upload"]').change(function(){ alert("aa"); $(this).after('<input type="file" name="upload_3" id="upload_3"/> ...

What could be causing the undefined index error when utilizing a basic array function?

Presenting a sample array: $arrayy[0]=48.72; $arrayy[1]=21.32; $arrayy[2]=48.62; $arrayy[3]=21.31; $arrayy[4]=48.62; $arrayy[5]=21.31; This custom function function writeDouble($array){ for($curr = 0; $curr<count($array)-1; $curr++){ ...

Creating a Full Page Background Image That Fits Perfectly Without Resizing or Cropping

Can someone help me achieve the same effect as the website linked below, where the background image fades instead of being a slideshow? The image should be 100% in width and height without any cropping. I have managed to set this up with the codes provided ...

Discover the cumulative sum of subarrays divided by indices in a numpy array in a fast and effective manner

How can I efficiently calculate the cumulative sum of sub-arrays from a given array 'array' and set of indices 'indices' in a vectorized manner? To illustrate, consider the following: >>> array = np.arange(20) >>> ar ...

Unusual patterns of shadow manipulation in ThreeJS

I am currently working on a threeJS scene with multiple spheres (multimaterial) and a directional light. The code snippet for adding the directional light is as follows: this.light = new THREE.DirectionalLight( 0xFFFFFF, 1 ); this.light.position.set( 2, ...

Automated validation and submission within an Adobe PDF document

After clicking the "submit" button on my PDF form, I want to perform a specific action (such as making a field readonly) based on whether the form validation and submission processes are successful: if (form.isValid()) { submitForm(...); if (form. ...

What makes this invalid in the context of C programming with arrays?

#include<stdio.h> int main(){ int size; printf("Please provide the value for size:\n"); scanf("%d",&size); int array[size]; } What is the reason behind being unable to assign the array size directly from user input? ...

What steps are involved in linking Java with JavaScript?

After attempting to connect html and javascript using applet, unfortunately it was unsuccessful. I am curious if there is an alternative method besides applet to establish this connection. ...

What is the best way to structure a JSON object to support conditional statements?

My goal is to develop a JSON object capable of handling conditionals/branching. My workflow involves multiple steps where the user's choices determine the subsequent set of options. This branching logic continues throughout different stages. I envisi ...

retrieving the value of a field within an array

Here is my code snippet: <div class="label">{{ item.data[0] }}</div> and in the view, this is what I have: { "id": 6, "firtname": "JHON ", "lastname": "SCALA", "fullname& ...

How can you turn off CSS3 animations for browsers that don't support them

Upon page load, a fade-in animation is applied to the main container. Although it functions properly in most browsers, it seems to have an issue in IE(9). Is there a method to identify if the user's browser does not support CSS3 animations and disabl ...

What could be causing the issue with this jQuery selector for the parent form element?

I created a form that connects a button with an attribute, but it's not hiding the parent("form"). However, when I try this, it works. $($("[editFormContent]").attr("editFormContent")).click(function(e) { e.preventDe ...

Having trouble fetching JSON data from a URL in my React Native project, the response is not as expected

getData() { return fetch("http://bitcfeedcms.rf.gd/script.php") .then(response => { console.log(response); response.json(); }) .then(responseJson => { this.setState({ data: responseJson }); }) .catch(error => { console.er ...

How can I conduct AngularJS debugging within Chrome's developer tools?

I am currently troubleshooting a $http issue in our application. When I step into $http.get, the debugger does not display the values of any AngularJS local variables. Hovering over them shows nothing and right-clicking 'Evaluate in console' thro ...

What is the process for generating a comprehensive HTML table using AngularJS?

I have a set of data that needs to be dynamically loaded into an HTML page. Currently, I am using AngularJS to populate each table on the page. As of now, there are 8 tables in total. My goal is to make the table counts completely dynamic so that I can e ...

Is your gallery compatible with all browsers and experiencing a .load() problem?

I'm currently experiencing some issues with cross-browser compatibility. Instead of overwhelming you with all the code details here, I've provided a link to the page in question: On the bottom left side of the page, there is a small photo gal ...

Curious about learning the Xpath?

This is the HTML content <dd id="_offers2" itemprop="offers" itemscope="" itemtype="http://schema.org/Offer" class="wholesale nowrap "> <span itemprop="price" class="Hover Hover Hover">$46.29</span> / each <meta itempr ...