Create a roster of numbers that are multiples using a systematic approach

Is the following code a functional way to return multiples of 5?

function Mul(start,array,Arr)
{
    Arr[start]=array[start]*5;
 
    if(start>array.length-2){
    return Arr;
    }
   
    return Mul(start+1,array,Arr);
 }    
var numbers =[1,2,3,4,5,6,7,8,9,10];
var Arr=[]; 

The values are stored in an empty array.

console.log("table ", Mul(0,numbers,Arr));

Answer №1

This code is not entirely functional as it involves mutating the argument passed.

To make it more functional, you can utilize the built-in .map function to transform each element in the array:

const multiplyBy5 = arr => arr.map(item => item * 5);
const modifiedArray = (start, input) => input.slice(0, start).concat(multiplyBy5(input.slice(start)));

console.log("resulting array ", modifiedArray(0, [1,2,3,4,5,6,7,8,9,10]));

(It should be noted that this approach still has a side effect with the console.log)

If you intend to transform the entire array, without the need for the parameter start:

const modifiedArray = arr => arr.map(item => item * 5);

console.log("resulting array ", modifiedArray([1,2,3,4,5,6,7,8,9,10]));

Answer №2

Your initial attempt wouldn't be considered functional because it alters the original input.

This presents a problem as, in addition to managing program execution flow, you must also consider data manipulation. For instance:


const last = arr => arr.pop();
const sum = ([a, b]) => a + b;  

const x = [4, 2];
const y = [4, 2];

// Expected Behavior

sum(x);  //=> 6
last(x); //=> 2

// Issue!

last(y); //=> 2
sum(y);  //=> NaN

The problem lies in the fact that Array#pop modifies the array. It becomes apparent that the order of execution now impacts the outcome for the same inputs. This unnecessary complexity leads to program instability and introduces bugs that can be challenging to identify and resolve.

If your goal is to multiply all elements in an array by 5, the most straightforward and functional approach would be using xs.map(x => x * 5).

In functional programming, there's a concept called unfold which generates a list by repeatedly applying a function on a value until a condition is met:

unfold(mult5, 1); // starting with 1 and multiplying by 5 up to 10.
//=> [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

However, when the boundaries are known beforehand, such as needing the first n multiples of 5, we can optimize the process:

Let's set aside 10 slots for our multiples of five:

const xs = Array(10);
//=> An array of 10 empty values

Note: Mapping over this kind of array won't work!

const ys = xs.map(x => x * 5);
//=> Still an array of 10 empty values!

To address this, use Array.from:

const ys = Array.from(xs, (_, i) => (i + 1) * 5);
//=> [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

Answer №3

Don't overlook the power of using recursion in this scenario!

const findFactorial = (num) => {
  if (num <= 1) { return 1; }
  
  return num * findFactorial(num - 1);
};

console.log(
  findFactorial(5),
);

console.log(
  findFactorial(8),
);

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

Simple method to toggle between elements using jQuery

After creating a script using jQuery to show/hide content when tabs are clicked (which also changes the color of the clicked tab), everything is functioning smoothly. However, I believe there may be a more efficient way to switch between content that allow ...

JavaScript Filter Function: filtering based on multiple conditions (either one can evaluate to true)

I seem to be missing something very simple here. I am working with an array of objects that contains various information. Depending on user interaction, I want to filter out certain objects; let arr = [ {'num': 1, 'name': 'joe&a ...

Implementing reCAPTCHA in Spring MVC with Ajax

I've been attempting to implement Google reCAPTCHA service with Spring MVC, but I keep encountering this error in the console: http://localhost:8080/spapp/ajaxtest.htm?name=frfr&surname=frfr&phone=edede…nGi3CCrD9GprYZDn8VHc-pN--SK-u_xoRKOrn ...

Creating a Dynamic Input Validation Range with JQuery

Greetings and thank you for taking the time to review this! :-) The form validation is functioning correctly with required fields, but I am facing a challenge with setting up numeric range validation dynamically for an autocomplete feature. The JQuery val ...

How to modify a variable in the Config.json using a Discord.js command

Lately, I enhanced my bot's functionality by allowing it to retrieve the color for embeds from a file specified in my config.json. All I need to do is modify something like: "embedcolor": "00A950" to "embedcolor": "0 ...

How can I efficiently locate identical sequences of cells in two or more arrays?

Unique Example 1 We can explore an interesting scenario by considering two arrays: ('m','o','o','n','s','t','a','r','d') ('s','t','a', ...

Using mongoose to execute a join operation

Currently, I have organized 2 collections named Dates and Streets. The goal is to query Streets using a parameter StreetName, find its unique ID, and then use that ID to query the other collection for dates that match. The route is configured as /wasteDa ...

"Internet Explorer naturally selects the submit button when users press the enter key to submit a

In my current application, I have implemented a form with a hidden button to address issues with the numeric keyboard on Android. Essentially, pressing enter or focusing on the invisible button will trigger form submission. Pressing enter works fine in Ch ...

Vue component input form not providing expected result

Here is the code snippet for my "ecedata" component with an input field: <template> <div class="col-l-4"> <p style="text-align: center">Data/day (GB)</p> <div class="form-input-set" style="background: white"& ...

Unable to view HTML without an internet connection

I have encountered an issue where my files work fine when uploaded to an online server, but do not work when accessed locally offline. An error message about a cross-origin issue appears. How can I solve this problem? Error message: Security Error: Conte ...

Adding AngularJS to Syncfusion grid or making the rows clickable and running AngularJS functions can be achieved by following these steps

I'm currently incorporating angularJs and Syncfusion to display data in a table using the Syncfusion grid (). However, I'm encountering difficulties in utilizing angularjs functions within this grid: <div class="table-responsive grid-tog ...

To display the user's input value in the console log upon clicking

Having trouble displaying the user's input value in the console when the button is clicked. function submit(){ var userInput = document.getElementById('input_text').value; console.log(userInput); } ...

Comparing identical elements in JavaScript

Crucial Note I want to clarify that I have no intentions of scamming, phishing, or causing any harm. My goal is to develop a website magnifier similar to using a magnifier on paper. Dilemma Let me paint the picture for you. I've effectively copied ...

Choosing between cjs and esm for a React components library

I'm working on a components library that will soon be published to npm for use in a razzle app. My main query revolves around the best practices for building these packages - should they be built with CommonJS (cjs) or ECMAScript Modules (esm)? And wh ...

Ajax successful event fails to trigger

Having Trouble Implementing Okta Authentication with WebForms The login functionality is working, but the redirect part is not functioning correctly I have attempted to use void and return a JSON object/string, but it does not seem to work If I remove th ...

Retrieving display format or formatted value from an object with Moment.js

I am currently working on a project using Angular and Material2. Within this project, I have created a moment object in the following way: myDate = moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss"); This object is then passed as an argument to ano ...

Having trouble displaying form in a different view, form is not appearing as expected

I am facing an issue with rendering a form inside a modal. The form is being rendered but the form_for does not show up, only the inputs are visible. This prevents me from targeting the submit button, which I need for ajax functionality. My file path: Adg ...

Establish a global variable within the utils.js module in a Node.js environment

Hey there, I'm currently in the process of trying to figure out how to properly define a global variable in node.js. I am aware that it's not considered best practice, but in this specific scenario, it seems like the only way to go without involv ...

ReactJS: Want to update card design by utilizing the onClick event handler

Currently, I am aware that there will be a need to refactor this code later on to separate things into their own components. However, due to time constraints, I have to wire this up as is at the moment. To achieve this, I utilized array.map() to create car ...

Using shortcode to enhance wordpress post content

I am trying to implement a feature similar to the one found at http://jsfiddle.net/theimaginative/gA63t/ within a wordpress post. I have attempted to create a shortcode for inserting this into a post, but I am encountering difficulties. While I have been s ...