1

In C, you can do something like this:

#define NESTEDFOR(i,j,n) for(i=0; i<n; i++) for(j=0; j<n; j++)

So you can use NESTEDFOR(x,y,200) to save time, because it will be replaced with for(x=0; x<200; x++) for(y=0; y<200; y++)

I suppose there is no way to do this in JavaScript since it's an Interpreted language, but I'm not sure.

Is there any way to do it in JavaScript?

2
  • 1
    It's true you can do horrible things like this in C, but I don't agree that they save time, and in general that sort of thing is very much not recommended. Commented May 5, 2013 at 19:10
  • 2
    Well, you can define functions to abstract it. It isn't any different. Commented May 5, 2013 at 19:12

2 Answers 2

3

JavaScript doesn't support an exact equivalent, but you can define it as an iterator -- similar to iterator methods for Arrays:

function nestedFor(n, fn) {
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < n; j++) {
            if (false === fn(i, j)) {
                return;
            }
        }
    }
}

nestedFor(200, function (i, j) {
    // etc.
    // `return false` to stop looping
});

Also, one option for some argument validation:

function nestedFor(n, fn) {
    if (typeof n !== 'number' || !isFinite(n)) {
        throw new TypeError('Invalid argument: Expected a finite number.');
    }
    if (typeof fn !== 'function') {
        throw new TypeError('Invalid argument: Expected a function.');
    }

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

2 Comments

I think you should add a test to make sure that fn is function before starting the loops.
@Mohamed-Ted Yeah, there's a lot you can add to it. It should probably check that n is a Number at least, and possibly that it's positive (or adjust to support decrementing) and isn't Infinity or NaN. But, was just trying to show the simplest form and keep it close to the snippets in the question.
2

Technically, that isn't actually C either - it is the cpp macro language. You can configure your system to use the cpp processor on your Javascript but many here would consider that an act of great evil. I actually do that for all of my Javascript code.

Comments

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.