Unable to retrieve the result through recursive means

Currently, I am working on the Persistent Bugger Kata and have come up with the following code. Although it successfully logs the correct value, I am facing difficulty in properly returning the final result. My approach involves using recursion.

const persistence = num => {
  x = num.toString();
  x = x.split('');
  console.log(x);

  if (x.length === 1) {
    return parseInt(x.join());
    // console.log(`num is ${x}`);
    // return x;
  }
  if (x.length > 1) {
    len = x.length;
    arr = [];
    for (i = 0; i < x.length; i++) {
      if (i === 0) {
        arr.push(x[i]);
      } else {
        arr.push(arr[0] * x[i]);
        arr.shift();
      }
      num = parseInt(arr.join());
    }
    persistence(num);
  }
};

I am striving to retrieve the final output.

Answer №1

Make sure to include the return statement before calling persistence(num);

const persistence = num => {
  x = num.toString();
  x = x.split('');
  console.log(x);

  if (x.length === 1) {
    return parseInt(x.join());
    // console.log(`num is ${x}`);
    // return x;
  }
  if (x.length > 1) {
    len = x.length;
    arr = [];
    for (i = 0; i < x.length; i++) {
      if (i === 0) {
        arr.push(x[i]);
      } else {
        arr.push(arr[0] * x[i]);
        arr.shift();
      }
      num = parseInt(arr.join());
    }
    return persistence(num);
  }
};

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

"An issue has been encountered with lastID being undefined while using sqlite3 with Node

After successfully inserting into the database, I am encountering an issue where this.lastID is undefined. Can anyone help me troubleshoot this code? app.post('/products/create', (req,res) => { upload(req, res, (err) => { c ...

Determine which scroll bar is currently in use

I'm running into an issue with multiple scrollbars on my page - they just don't seem to be functioning correctly: <div class="dates-container" v-for="id in ids"> <overlay-scrollbars :ref="`datesHeader` ...

Use javascript to automatically remove an element upon page load

Here is a snippet of code: <a id="sdffg" href="/allgemeinen/me-libe-love-y/"><p class="erfg" class="quotes"> bla bla bla </p></a> I need help deleting the a element using JavaScript: <script> window.onload=function( ...

What is the best way to incorporate a popover into a fullcalendar event displayed on a resource timeline in Vue while utilizing BootstrapVue?

I need help adding a popover to an event in a resource timeline using fullcalendar/vue ^5.3.1 in Vue ^2.6.11 with ^2.1.0 of bootstrap-vue. Although I found some guidance on Stack Overflow, the solution involving propsData and .$mount() doesn't feel l ...

What is the best way to showcase information retrieved using the Ajax Get Method?

I am currently facing an issue where I can view the data retrieved from my Controller in the Browser's console, but it is not displaying in HTML. Below is the code I am using: function GetUserInfo() { var username = readCookie("Cookie"); ...

What is the best method to eliminate the 'Unsorted' selection from the sorting options in Material React Table?

Currently utilizing the "material-react-table" library within a React JS project. In alignment with my needs, seeking to eliminate the 'Unsorted' sorting option in Material React Table. Could someone assist me in addressing this? Your help is ...

Display text tags only when hovering the mouse over the input area

I am currently utilizing the TextExt plugin for autocomplete functionality and tags creation. $('#keywords').textext({ plugins : 'autocomplete tags', itemManager: CustomItemManager, tagsItems: [{value:'a&ap ...

Using jQuery to dynamically populate select options based on JSON data

I have been testing and searching for a solution to my issue, but it still doesn't work. Any help would be greatly appreciated. I have three select options implemented in PHP like this: <div class="control-group" id="merkPrinter"> <label cl ...

Is there a way to showcase interactive HTML content similar to an ePub or eBook without the need to convert the HTML into ePub

Looking to enhance the mobile reading experience with a responsive design similar to popular ebook readers like Kindle or iBooks? Want to break long articles into full-screen sections for easy navigation on small devices? Consider using dynamic HTML to ada ...

The HTML element update event was not triggered due to the excessive load of a JavaScript function

I am currently running a JavaScript function that is quite CPU intensive. To provide visual feedback to users when it starts and stops, I am attempting to display a badge on the webpage. Below is the code snippet: function updateView() { console.log(1 ...

Is it more advantageous to pass a value as a prop to a child component, or should the child component retrieve it from Redux instead?

In my scenario, there are two components called <Parent> and <Child>. The <Parent> component is connected to a Redux state property named prop1 using the mapStateToProps() function. Now, I also need the <Child> component to have acc ...

Encountering an 'uncaught promise rejections' error in express due to a problem with the catch() statement

I encountered a problem where I keep getting an error message 'Unhandled promise rejections' every time I try to execute the following code: app.get('/standings/:tableId', async (req, res) => { const tableId = req.params.table ...

Ways to create a smooth transition in element height without a known fixed target height

Is it possible to create a smooth height transition for an element when the target height is unknown? Replacing height: unset with height: 100px allows the animation to work, but this presents a problem as the height needs to be based on content and may v ...

What is the best way to define the active <li> tab using JQuery?

Initially, my HTML code includes a set of <li> elements that I want to dynamically add to the existing <ul>. <ul class="tabs" id="modal_addquestion_ul"> <li class="tab-link current" data-tab="multipleChoice">Multiple Choice< ...

Unable to execute the method passed through props

I have a simple console.log('hello') in my app.js using react. I am passing it as a prop to the "thumbnails group" component, which maps over an array, creates thumbnails, and each one of them should trigger that method onClick. However, nothing ...

Why is it necessary in JavaScript to reset the function's prototype after resetting the function prototype constructor as well?

Code is often written in the following manner: function G() {}; var item = {...} G.prototype = item; G.prototype.constructor = G // What is the purpose of this line? Why do we need to include G.prototype = item before resetting the prototype? What exact ...

What is the best way to alter the href of menu items while excluding 2 specific items

I've successfully updated the href attribute of my menu items using jQuery based on the website address: if(window.location.href.indexOf("en") > -1) { var link = $('#main-nav a'); link.each(function(){ this.href += ' ...

Mysterious dual invocation of setState function in React

My component is designed to display a list of todos like: const todosData = [ { id: 1, text: "Take out the trash", completed: true }, { id: 2, text: "Grocery shopping", completed: false }, ]; ...

Increase or decrease values in an input field using Vue3 when typing

I am looking to implement a feature where users can input numbers that will be subtracted from a fixed total of 100. However, if the user deletes the input, I want the difference to be added back to the total of 100. Despite my attempts, the subtraction wo ...

Having trouble retrieving data from fetch operation

Having trouble with pulling and displaying search results on the Left page using the SearchFilms component? The API key has been deliberately removed, making it difficult for beginners to figure out what to do. Where should we start? import React, {Fragm ...