0

I have a function -- let's call it test(arg1,arg2), called from program1, which does a number of things and is working correctly. Within test there is a loop:

for(j=1;j<=top;j++) {
   stuff happens based on j 
}

I would like to call test(arg1,arg2) from a different program, say program2. Everything about test is the same for these two programs except the for loop. For program2 I need that loop to be

for(j=2;j<=top;j+=2) {
   stuff happens based on j 
}

Otherwise everything else is exactly the same.

The second argument, arg2 tells us whether the script was called from program1 or program2. But I can't figure out how to write a variable "for" statement. I tried an if statement based on arg2

var jstart = 1 or 2 
var jincr = '++' or '+=2'

and then wrote the loop as

for(j=jstart;j<=top;j jincr) {

This did not work, although it is an approach that works in other languages.

Can someone suggest I way I can do this without writing an entirely separate script for the two cases?

1
  • Couldn't you just put if(jStart == 1) { j++; } else { j += 2; }? Evaling code just to accomplish something like this is extremely hacky, even if other languages allow it (JS allows it too). Commented May 27, 2018 at 0:34

2 Answers 2

3

As simple as that

jstart = 1 // or 2
jincr = 1 // or 2;
for(j=jstart;j<=top;j += jincr) {
Sign up to request clarification or add additional context in comments.

1 Comment

This is very nice.
1

The most reusable way would be to put your loop in a function that accepts increment as an argument:

function doStuff (inc) {
  for(var j = inc; j <= top; j += inc) {
    // stuff happens based on j 
  }
}

// Program 1
doStuff(1)

// Program 2
doStuff(2)

1 Comment

For my situation it is the easiest, although the answer below is very helpful also.

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.