0

Looking to create a function in (vanilla) JavaScript that generates an array with n values between a min and max value, where n is a specified number of steps. The first value should be the min, the last should be the max.

i.e.

function returnAllSteps(min,max,totalSteps) {
  var steps = new Array(totalSteps);
  for (i = 0; i < totalSteps; i++) {
    steps[i] = // HELP: return number value between min and max?
  }
  console.log(steps);
}
returnAllSteps(0,10,30); // min = 0, max = 10, totalSteps = 30 (give me an array with 30 steps between 0 and 10)

I would also like to be able to return a single step value within the range. Does this have to happen in a different function?

i.e.

function returnStep(min,max,totalSteps,stepNumberToReturn) {
  // HELP: do I even need another function to do this?
}
returnStep(0,10,30,20); // min = 0, max = 10, totalSteps = 30, stepNumberToReturn = 20
// Return the value at array[20 - 1]

Any help would be much appreciated!

5

1 Answer 1

1

Only one function is needed to generate and return an array with all steps:

function returnAllSteps(min, max, totalSteps) {
  let steps = new Array(totalSteps);
  let distance = max - min;
  for (i = 0; i < totalSteps; i++) {
    steps[i] = min + distance * (i / (totalSteps - 1));
  }
  return steps;
}

let mySteps = returnAllSteps(0, 10, 30); // min = 0, max = 10, totalSteps = 30 (give me an array with 30 steps between 0 and 10)
console.log(mySteps);

Then just get the step you need from mySteps directly. For example: mySteps[20]

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe let step = (max - min) / (totalSteps - 1) and steps[i] = min + step * i
Also maybe explain why the for loop should not be for (i = min; i <= max; i += step)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.