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

Decreased storage space requirements following transfer to S3 bucket using nodejs

I am currently facing an issue with uploading files from a specific folder location to an S3 bucket using the nodejs aws-sdk. The files I am working with are deepzoom images (.dzi). While the files seem to be successfully uploaded to my S3 bucket, I have n ...

I have successfully implemented ngCordova local notifications, but now I am looking for a way to make it trigger for each individual

Is there a way to trigger a notification on every logged-in user's mobile device when a value is changed and saved in Firebase? Currently, I am able to send a local notification using ngCordova when a user enters text in an ionicPopup with textarea. H ...

The 'this' variable is malfunctioning when trying to assign a JSONP array to an AngularJS controller

I'm working with a REST service in my angular controller and using JSONP to make the call. I need to store the array that is returned from the service into a variable. This is what I currently have: this.testTheRest = function() { $http.jsonp(&a ...

Content in tab remains stagnant

I am having trouble creating different tabs on a page with unique content in each tab's body. Whenever I click on a new tab, the body content remains the same. I'm not sure if it's an issue with how the tabs are set up in the HTML or if ther ...

What could be causing my node-statsd client script to not terminate?

When attempting to log a metric to a StatsD server using the node-statsd library, I encountered an issue where the script did not exit automatically. The code snippet in question is as follows: var StatsD = require('node-statsd').StatsD; var cli ...

Enhance results by combining data from user input with data retrieved asynchronously from server-side APIs

In the process of developing a web application, I am facing a challenge. There is an input field where users can enter a number and next to it, I want to display the double of that number as the output. While this can be easily achieved using client-side J ...

Htmlunit driver encounters difficulty executing Javascript

Recently, I switched my Selenium test from using FirefoxDriver to HtmlunitDriver in Java. The test was running smoothly in the Firefox browser but encountered an issue when I made this change: driver = new FirefoxDriver(); to driver = new HtmlUnitDriver ...

Why does it appear that Angular is undefined in this straightforward Angular demonstration?

I'm completely new to AngularJS and I've encountered an issue. Yesterday, I ran a very simple AngularJS application that I downloaded from a tutorial and it worked perfectly. The application consists of 2 files: 1) index.htm: <!DOCTYPE htm ...

Using ExtJS to populate a panel with data from various sources

I am currently working with an Ext.grid.GridPanel that is connected to a Ext.data.JsonStore for data and Ext.grid.ColumnModel for grid specifications. Out of the 10 columns in my grid, 9 are being populated by the json store without any issues. However, I ...

What is the best way to access data stored in the state of the store.js within a Vue application?

Currently, I am working on my initial project using Vue.js. The application involves a multi-step form that shares a common header and footer. As the user progresses through each step, the data entered is sent to store.js for storage. However, I have encou ...

Determine the value of a field by utilizing the values of two other fields through an onChange event

Setting the Stage: Imagine a scenario with 3 key fields: quantity, singlePrice, and totalPrice. I want these fields to be part of my form, with totalPrice being dynamically recalculated whenever quantity or singlePrice changes. My Approach: I created ...

What is the purpose of defining the initialState in Redux?

As per the Redux documentation, it is considered a best practice to establish an initialState for your reducer. However, maintaining this initialState can become challenging when the state relies on data from an API response, leading to discrepancies betwe ...

Is it possible to create a multi-page single-page application using Vue js SSR?

It may appear contradictory, but I struggle to find a better way to express it. When using vue server-side rendering, it seems you are limited to single page applications. However, for various reasons, I require an application with multiple real server-s ...

Creating a dynamic JSTree that loads data on demand using Stored Procedures

Currently in my SQL Server database, I have two Stored Procedures that are responsible for extracting data from a tree structure: One procedure retrieves all nodes at a specific level based on the provided level number. The other procedure retrieves th ...

Access to data retrieval was restricted by CORS policies on my Node.js/Express REST API server

I am currently running a localhost node/express server that is designed to accept any post request with a body and then return the same body along with a message. To enable Cross-Origin Resource Sharing (CORS), I have integrated the cors node package into ...

Can I safely keep a JWT in localStorage while using ReactJS?

As I work on developing a single page application with ReactJS, one question comes to mind. I came across information indicating that using localStorage may pose security risks due to XSS vulnerabilities. However, given that React escapes all user input, ...

Viewing the JSON Data

Support: $scope.createTimeSlots = function(interval, field) { var startingTime = moment().hours(8).minutes(0); field.timeslots = []; for (var i = 0; i < interval; i++) { $scope.intervals = 60; field.timeslots.push(startingTi ...

The nth-child selector fails to function properly with a customized MUI component in CSS

I've created a styled component as shown below: const FormBox = styled(Box)(({ theme }) => ({ width: "47vw", height: "25vh", backgroundColor: theme.palette.grey[100], borderRadius: theme.shape.borderRadius, marginLeft: ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Obtain the value of a JavaScript form with a dynamically generated field name

I am struggling with a simple javascript code and for some reason, it's not working. var number = 5; var netiteration = "net"+number; // now netiteration is equal to net5 var formvalue = document.forms.myformname.netiteration.value; Why is this co ...