Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Avoid global variable in code involving lots of loops

I'm having a very confusing problem. I think it is best explained with code:

var length = 0; // I want to avoid this variable being global

function loop(array, func) {
	for (var i = 0; i < array.length; i++) {
		array[i].func(length);
		length += array[i].number;
		if (func) {
			func();
		}
	}
}

function bar(number) {
	this.func = function(len) {
		console.log(len);
	};
	this.number = number;
}

function main() {
	var array = [];
	for (var j = 1; j < 3; j++) {
		var foo = new bar(j);
		array.push(foo);
	}
	loop(array, function() {
		loop(array);
	});
}

main();

I have a loop similar to this in some other code. I simply cannot figure out how to make the length variable local in this code. I cannot pass it to the function because it calls itself. I cannot really move it anywhere because the loops keep messing things up.

Thank you for any help!

like image 729
MysteryPancake Avatar asked Jun 27 '26 11:06

MysteryPancake


2 Answers

I'm assuming that you want to maintain the value of length between successive function calls of loop. You can do this by returning a closure that uses the length. So, instead of defining loop as you currently do, you could do something like this:

const loop = (function() {
    var length = 0;
    return function (array, func) {
        // Your current code for loop here
    }
}) ();

Basically, what this does is it assigns loop to be a function that is returned from another anonymous function call. This ensures that the value of length persists because it is defined outside of the scope of the function that is eventually assigned to loop, but is entirely inaccessible anywhere else in the code.

like image 87
Keveloper Avatar answered Jun 29 '26 00:06

Keveloper


Not sure exactly what you're trying to accomplish with all this, but it looks like main is the caller of loop, so you can have length be an argument to loop and have main call loop with an initial length of 0 and have loop and the callback return the altered lengths:

function loop(array, length, func) {
  for (var i = 0; i < array.length; i++) {
    array[i].func(length);
    length += array[i].number;
    if (func) {
      length = func(length);
    }
  }
  return length;
}

function bar(number) {
  this.func = function(len) {
    console.log(len);
  };
  this.number = number;
}

function main() {
  var array = [];
  for (var j = 1; j < 3; j++) {
    var foo = new bar(j);
    array.push(foo);
  }
  loop(array, 0, function(newLen) {
    return loop(array, newLen);
  });
}

main();
like image 33
CertainPerformance Avatar answered Jun 29 '26 00:06

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!