javascript max call stack exceeded explanation - javascript

var MultiArray = (function(){
var MultiArray = function(param){
var i = param.array.length;
while(i--){
param.array[i] = MultiArray({
array: new Array(dims[0]),
dims: dims.splice(1,dims.length-1)
});
}
return param.array
};
return function(){
var length = arguments.length - 1;
array = new Array(arguments[0]),
dims = [length];
for(var i = 0; i < length; i++){
dims[i] = arguments[i+1];
}
MultiArray({
array: array,
dims: dims
});
return array;
};
})();
I'm trying to write a function that will create multidimensional arrays so var mdArray = MultiArray(3,3,3); would create a 3D array of 3x3x3 elements. But I get Max call stack size exceeded when trying this method, is there a better way of making a multidimensional array function like this?

In your inner MultiArray, you always have a param.array with 1 items, which makes a endless recursion.

var MultiArray = (function() {
var MultiArray = function(param) {
var myDims, i = param.array.length;
if(param.dims.length === 0){
return;
}
while(i--) {
myDims = param.dims.slice(0);
myDims = myDims.splice(1, myDims.length - 1);
param.array[i] = new Array(param.dims[0]);
MultiArray({
array : param.array[i],
dims : myDims
});
}
};
return function() {
var length = arguments.length - 1, array = new Array(arguments[0]), dims = [length];
for(var i = 0; i < length; i++) {
dims[i] = arguments[i + 1];
}
MultiArray({
array : array,
dims : dims
});
return array;
};
})();
The code above is correct the original code was simply wrong causing an infinite recursive loop, now it works as intended, var mdArray = MultiArray(2,3,4,5); creates an array with dimensions 2x3x4x5. The recursive function now returns straight away when the dims array in the argument has zero length.

Related

How to do I unshift/shift single value and multiple values using custom methods?

I have prototypes to recreate how array methods work, pop/push/shift/etc, and I would like to extend the functionality to do the following:
Push/Pop/shift/unshift multiple values
array.push(0);
array.push(1);
array.push(2);
expect(array.pop()).to.be(2);
expect(array.pop()).to.be(1);
expect(array.pop()).to.be(0);
Push/Pop/unshift/etc single values
array.push(0);
array.push(1);
expect([0,1]);
array.pop(1);
expect([0]);
My assumption is that I would need a global array variable to store the elements. Is that the right?
Here is my code:
var mainArray = []; // array no longer destroyed after fn() runs
function YourArray(value) {
this.arr = mainArray; // looks to global for elements | function?
this.index = 0;
var l = mainArray.length;
if(this.arr === 'undefined')
mainArray += value; // add value if array is empty
else
for(var i = 0; i < l ; i++) // check array length
mainArray += mainArray[i] = value; // create array index & val
return this.arr;
}
YourArray.prototype.push = function( value ) {
this.arr[ this.index++ ] = value;
return this;
};
YourArray.prototype.pop = function( value ) {
this.arr[ this.index-- ] = value;
return this;
};
var arr = new YourArray();
arr.push(2);
console.log(mainArray);
My assumption is that I would need a global array variable to store
the elements. Is that the right?
No. That is not right.
You want each array object to have its own, independent set of data. Otherwise, how can you have multiple arrays in your program?
function YourArray(value) {
this.arr = []; // This is the data belonging to this instance.
this.index = 0;
if(typeof(value) != 'undefined')) {
this.arr = [value];
this.index = 1;
}
}
////////////////////////////////////
// Add prototype methods here
///////////////////////////////////
var array1 = new YourArray();
var array2 = new YourArray();
array1.push(2);
array1.push(4);
array2.push(3);
array2.push(9);
// Demonstrate that the values of one array
// are unaffected by the values of a different array
expect(array1.pop()).to.be(4);
expect(array2.pop()).to.be(9);
It's a bit late for this party, admitted but it nagged me. Is there no easy (for some larger values of "easy") way to do it in one global array?
The standard array functions work as in the following rough(!) sketch:
function AnotherArray() {
this.arr = [];
// points to end of array
this.index = 0;
if(arguments.length > 0) {
for(var i=0;i<arguments.length;i++){
// adapt if you want deep copies of objects
// and/or take a given array's elements as
// individual elements
this.arr[i] = arguments[i];
this.index++;
}
}
}
AnotherArray.prototype.push = function() {
// checks and balances ommitted
for(var i=0;i<arguments.length;i++){
this.arr[ this.index++ ] = arguments[i];
}
return this;
};
AnotherArray.prototype.pop = function() {
this.index--;
return this;
};
AnotherArray.prototype.unshift = function() {
// checks and balances ommitted
var tmp = [];
var alen = arguments.length;
for(var i=0;i<this.index;i++){
tmp[i] = this.arr[i];
}
for(var i=0;i<alen;i++){
this.arr[i] = arguments[i];
this.index++;
}
for(var i=0;i<tmp.length + alen;i++){
this.arr[i + alen] = tmp[i];
}
return this;
};
AnotherArray.prototype.shift = function() {
var tmp = [];
for(var i=1;i<this.index;i++){
tmp[i - 1] = this.arr[i];
}
this.arr = tmp;
this.index--;
return this;
};
AnotherArray.prototype.isAnotherArray = function() {
return true;
}
AnotherArray.prototype.clear = function() {
this.arr = [];
this.index = 0;
}
AnotherArray.prototype.fill = function(value,length) {
var len = 0;
if(arguments.length > 1)
len = length;
for(var i=0;i<this.index + len;i++){
this.arr[i] = value;
}
if(len != 0)
this.index += len;
return this;
}
// to simplify this example
AnotherArray.prototype.toString = function() {
var delimiter = arguments.length > 0 ? arguments[0] : ",";
var output = "";
for(var i=0;i<this.index;i++){
output += this.arr[i];
if(i < this.index - 1)
output += delimiter;
}
return output;
}
var yaa = new AnotherArray(1,2,3);
yaa.toString(); // 1,2,3
yaa.push(4,5,6).toString(); // 1,2,3,4,5,6
yaa.pop().toString(); // 1,2,3,4,5
yaa.unshift(-1,0).toString(); // -1,0,1,2,3,4,5
yaa.shift().toString(); // 0,1,2,3,4,5
var yaa2 = new AnotherArray();
yaa2.fill(1,10).toString(); // 1,1,1,1,1,1,1,1,1,1
Quite simple and forward and took only about 20 minutes to write (yes, I'm a slow typist). I would exchange the native JavaScript array in this.arr with a double-linked list if the content can be arbitrary JavaScript objects which would make shift and unshift a bit less memory hungry but that is obviously more complex and slower, too.
But to the main problem, the global array. If we want to use several individual chunks of the same array we need to have information about the starts and ends of the individual parts. Example:
var globalArray = [];
var globalIndex = [[0,0]];
function YetAnotherArry(){
// starts at the end of the last one
this.start = globalIndex[globalIndex.length-1][1];
this.index = this.start;
// position of the information in the global index
this.pos = globalIndex.length;
globalIndex[globalIndex.length] = [this.start,this.index];
}
So far, so well. We can handle the first array without any problems. We can even make a second one but the moment the first one wants to expand its array we get in trouble: there is no space for that. The start of the second array is the end of the first one, without any gap.
One simple solution is to use an array of arrays
globalArray = [
["first subarray"],
["second subarray"],
...
];
We can than reuse what we already wrote in that case
var globalArray = [];
function YetAnotherArray(){
// open a new array
globalArray[globalArray.length] = [];
// point to that array
this.arr = globalArray[globalArray.length - 1];
this.index = 0;
}
YetAnotherArray.prototype.push = function() {
for(var i=0;i<arguments.length;i++){
this.arr[ this.index++ ] = arguments[i];
}
return this;
};
// and so on
But for every new YetAnotherArray you add another array to the global array pool and every array you abandon is still there and uses memory. You need to manage your arrays and delete every YetAnotherArray you don't need anymore and you have to delete it fully to allow the GC to do its thing.
That will leave nothing but gaps in the global array. You can leave it as it is but if you want to use and delete thousands you are left with a very sparse global array at the end. Or you can clean up. Problem:
var globalArray = [];
function YetAnotherArray(){
// add a new subarray to the end of the global array
globalArray[globalArray.length] = [];
this.arr = globalArray[globalArray.length - 1];
this.index = 0;
this.pos = globalArray.length - 1;
}
YetAnotherArray.prototype.push = function() {
for(var i=0;i<arguments.length;i++){
this.arr[ this.index++ ] = arguments[i];
}
return this;
};
YetAnotherArray.prototype.toString = function() {
var delimiter = arguments.length > 0 ? arguments[0] : ",";
var output = "";
for(var i=0;i<this.index;i++){
output += this.arr[i];
if(i < this.index - 1)
output += delimiter;
}
return output;
}
// we need a method to delete an instance
YetAnotherArray.prototype.clear = function() {
globalArray[this.pos] = null;
this.arr = null;
this.index = null;
};
YetAnotherArray.delete = function(arr){
arr.clear();
delete(arr);
};
// probably won't work, just a hint in case of asynch. use
var mutex = false;
YetAnotherArray.gc = function() {
var glen, indexof, next_index, sub_len;
indexof = function(arr,start){
for(var i = start;i<arr.length;i++){
if (arr[i] == null || arr[i] == undefined)
return i;
}
return -1;
};
mutex = true;
glen = globalArray.length;
sublen = 0;
for(var i = 0;i<glen;i++){
if(globalArray[i] == null || globalArray[i] == undefined){
next_index = indexof(globalArray,i);
if(next_index == -1){
break;
}
else {
globalArray[i] = globalArray[next_index + 1];
globalArray[next_index + 1] = null;
sublen++;
}
}
}
globalArray.length -= sublen - 1;
mutex = false;
};
var yaa_1 = new YetAnotherArray();
var yaa_2 = new YetAnotherArray();
var yaa_3 = new YetAnotherArray();
var yaa_4 = new YetAnotherArray();
yaa_1.push(1,2,3,4,5,6,7,8,9).toString(); // 1,2,3,4,5,6,7,8,9
yaa_2.push(11,12,13,14,15,16).toString(); // 11,12,13,14,15,16
yaa_3.push(21,22,23,24,25,26,27,28,29).toString();// 21,22,23,24,25,26,27,28,29
yaa_4.push(311,312,313,314,315,316).toString(); // 311,312,313,314,315,316
globalArray.join("\n");
/*
1,2,3,4,5,6,7,8,9
11,12,13,14,15,16
21,22,23,24,25,26,27,28,29
311,312,313,314,315,316
*/
YetAnotherArray.delete(yaa_2);
globalArray.join("\n");
/*
1,2,3,4,5,6,7,8,9
21,22,23,24,25,26,27,28,29
311,312,313,314,315,316
*/
YetAnotherArray.gc();
globalArray.join("\n");
/*
1,2,3,4,5,6,7,8,9
21,22,23,24,25,26,27,28,29
311,312,313,314,315,316
*/
But, as you might have guessed already: it doesn't work.
YetAnotherArray.delete(yaa_3); // yaa_3 was 21,22,23,24,25,26,27,28,29
globalArray.join("\n");
/*
1,2,3,4,5,6,7,8,9
21,22,23,24,25,26,27,28,29
*/
We would need another array to keep all positions. Actual implementation as an exercise for the reader but if you want to implement a JavaScript like array, that is for arbitrary content you really, really, really should use a doubly-linked list. Or a b-tree. A b+-tree maybe?
Oh, btw: yes, you can do it quite easily with a {key:value} object, but that would have squeezed all the fun out of the job, wouldn't it? ;-)

Js lodash return the same sample every time

I want to generate samples with lodash and it return me the same numbers for each line. what im doing wrong?
var primaryNumsCells = _.range(50);
var extraNumsCells = _.range(20);
var lottery = {lineConfigurations: []};
var numsConfig = {lineNumbers: {}};
for( var i = 0; i < 2; i ++ ) {
numsConfig.lineNumbers.primaryNumbers = _.sample(primaryNumsCells, 5);
numsConfig.lineNumbers.secondaryNumbers = _.sample(extraNumsCells, 2);
lottery.lineConfigurations.push(numsConfig);
}
console.log(lottery);
The results of the first object and second object of the primary and secondary numbers is the same;
here is the fiddle:
http://jsbin.com/vavuhunupi/1/edit
Create a new object inside a loop. It's easy to do with a plain object literal (dropping the variable):
var lottery = {lineConfigurations: []};
for (var i = 0; i < 2; i++) {
lottery.lineConfigurations.push({
lineNumbers: {
primaryNumbers: _.sample(primaryNumsCells, 5),
secondaryNumbers: _.sample(extraNumsCells, 2)
}
});
}
As it stands, at each step of the loop you modify and push the same object (stored in numsConfig var).
And here goes a lodash way of doing the same thing:
var lottery = {
lineConfigurations: _.map(_.range(2), function() {
return {
lineNumbers: {
primaryNumbers: _.sample(primaryNumsCells, 5),
secondaryNumbers: _.sample(extraNumsCells, 2)
}
};
})
};

Are there such things as dynamic-dimensional arrays in JavaScript?

What I mean by dynamic-dimensional arrays is multidimensional arrays that can have various dimensions. I need to create a function that does something to elements of multidimensional arrays, regardless of their dimensions. I wrote a function that should loop through all elements of a multidimensional array, but I can't find a way to get them. Here's what I wrote:
function loopThrough (multiArray, dimensions) {
var i, indexes = new Array(dimensions.length);
// stores the current position in multiArray as index combination
for (i in indexes) indexes[i] = 0; // position is initialised with [0, 0, ... 0]
while (i >= 0) {
doStuff(multiArray[indexes[0], indexes[1], ... indexes[?]]); // this is where I got stuck
for (i = indexes.length - 1; i >= 0 && ++indexes[i] >= dimensions[i]; indexes[i--] = 0);
// creates the next index combination
}
}
I also need a way to create such arrays. Say in an object's constructor, like:
function MultiArray (dimensions) {
this.array = [];
// create multidimensional array
}
For example, if I want to create a 5x3x8 array I should be able to call MultiArray([5,3,8]); just the same as calling MultiArray([4,6]); for a 4x6 array, or MultiArray([7]); for a plain 7-lengthed array.
You can use something like this:
function MultiArray(dimensions) {
var a = [];
if (dimensions > 1) {
a.push(MultiArray(dimensions -1));
}
return a;
}
var m = MultiArray(4);
function MultiArray(dimensions) {
this.elements = [];
var leaf = dimensions.length == 1;
var dimension = dimensions.shift();
for (var i = 0; i < dimension; ++i) {
this.elements.push(leaf ? undefined : new MultiArray(dimensions));
}
}
MultiArray.prototype.get(indexes) {
var leaf = indexes.length == 1;
var index = indexes.shift();
return leaf ? this.elements[index] : this.elements[index].get(indexes);
}
MultiArray.prototype.set(indexes, value) {
var leaf = indexes.length == 1;
var index = indexes.shift();
if (leaf) {
this.elements[index] = value;
} else {
this.elements[index].set(indexes, value);
}
return this;
}
var m = new MultiArray([4, 3, 5]);
m.set([1, 2, 4], "i'm a value in a multi dimensional array");
m.get([1, 2, 4]); // should return "i'm a value in a multi dimensional array"
m.get([2, 0, 3]); // should return undefined
m.get([0, 1]); // should return an array of 5 elements

My array data is being corrupted somehow by my custom (Set Theory) Complements() function?

I was fed up with the limited javascript Array functions and wanted to write a few of my own handy prototype functions to perform Set Theory functions.
Below is the code I have for this so far
<script type="text/javascript">
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
Array.prototype.getIndices = function(obj){
var indices = new Array();
var i = this.length;
while (i--) {
if(this[i] === obj){
indices.push(i);
}
}
return indices;
}
Array.prototype.Union = function(arr){
//combines two arrays together to return a single array containing all elements (once)
//{1,2,3,4,5}.Union({3,4,5,6,7})
//returns: {1,2,3,4,5,6,7}
var primArray = this;
var secondArray = arr;
var i = primArray.length;
while(i--){
if(secondArray.contains(primArray[i])){
primArray.splice(i, 1);
}
}
var returnArr = primArray.concat(secondArray);
return returnArr;
}
Array.prototype.Intersection = function(arr){
//Returns an array of elements that are present in both sets
//{1,2,3,4,5}.Intersection({3,4,5,6,7})
//returns: {3,4,5}
var primArray = this;
var secondArray = arr;
var returnArr = new Array;
var i = 0;
while(i++<primArray.length){
if(secondArray.contains(primArray[i])){
returnArr.push(primArray[i]);
}
}
return returnArr;
}
Array.prototype.Complement = function(arr){
//Returns an array of elements that are only in the primary (calling) element
//{1,2,3,4,5}.Complement({3,4,5,6,7})
//return: {1,2}
var primArray = this;
var secondArray = arr;
var i = primArray.length;
while(i--){
if(secondArray.contains(primArray[i])){
primArray.splice(i, 1);
}
}
return primArray;
}
Array.prototype.SymmetricDifference = function(arr){
//Returns elements that are exclusive to each set
//{1,2,3,4,5}.SymmetricDifference({3,4,5,6,7})
//return: {1,2,6,7}
var primArray = this;
var secondArray = arr;
var i = primArray.length;
while(i--){
if(secondArray.contains(primArray[i])){
var indices = secondArray.getIndices(primArray[i]);
primArray.splice(i, 1);
var j=indices.length;
while(j--){
secondArray.splice(indices[j], 1);
}
}
}
var returnArr = primArray.concat(arr);
return returnArr;
}
function run(){
var Q = "A";
var D = [1,2,3,4,5,6,7,8,9,10];
var sets = {
"A":[1,2,3],
"B":[3,4,5],
"C":[5,6,7]
}
var R = D;
for(var el in sets){
R = R.Complement(sets[el]);
}
//if I alert D at this point I get 8,9,10 instead of 1,2,3,4,5,6,7,8,9,10 as I would expect? What am I missing here... It causes a problem when I perform D.Complement(R) later on
document.write(R + "<br/>");
R = R.Union(sets[Q]);
document.write(R + "<br/>");
//Here!
R = D.Complement(R);
document.write(R);
}
</script>
</head>
<body onload="run()">
</body>
</html>
Everything is working up to the final point when I then try to get the complement of the domain and my newly constructed set. I am expected to be getting the complement of [1,2,3,4,5,6,7,8,9,10] and [8,9,10,1,2,3] which would yield [4,5,6,7] but when I perform D.Complement(R) my D variable seems to have turned into [1,2,3]. This appears to happen after the enumeration I perform.
I thought it might be because I was using this.splice and arr.splice in my functions and when I was passing the variables to the functions they were being passed as pointers meaning I was actually working on the actual memory locations. So I then used primArray and secondArray to create a duplicate to work on... but the problem is still happening
Many Thanks
So I then used primArray and secondArray to create a duplicate to work on... but the problem is still happening
Just assigning it to a variable does not make it a new array, you are still working on the array that was passed in. You have to manually make a new copy of the array either by looping through it and copy each index or by joining and splitting.

Javascript: sort objects

function Player() {
var score;
this.getScore = function() { return score; }
this.setScore = function(sc) { score = sc; }
}
function compare(playerA, playerB) {
return playerA.getScore() - playerB.getScore();
}
var players = [];
players['player1'] = new Player();
players['player2'] = new Player();
Array(players).sort(compare);
I have code that is similar to the above. When I step through the code with a debugger, the compare function never gets called and the array isn't sorted. I'm not sure what's wrong with my code?
It's not sorting because you have specified the keys that the variables within the array belong on. Sorting will only move the objects on integer-valued keys. You should see your sorting work if you create your array as follow:
var players = [new Player(), new Player()];
though, of course, it won't be very effective since you have neither a score on which to sort or a method of identifying them. This'll do it:
function Player(name, score) {
this.getName = function() { return name; }
this.getScore = function() { return score; }
this.setScore = function(sc) { score = sc; }
}
function comparePlayers(playerA, playerB) {
return playerA.getScore() - playerB.getScore();
}
var playerA = new Player('Paul', 10);
var playerB = new Player('Lucas', 5);
var playerC = new Player('William', 7);
var players = [playerA, playerB, playerC];
for (var i = 0; i < players.length; i++)
alert(players[i].getName() + ' - ' + players[i].getScore());
players.sort(comparePlayers);
for (var i = 0; i < players.length; i++)
alert(players[i].getName() + ' - ' + players[i].getScore());
Hope that helps.
The main problem lies in this line:
Array(players).sort(compare);
Array(something) makes an array with something as its element.
console.log(Array(players)); //[[player1, player2]]
Use numeric indexed array instead of using object like array as in players['player1']
Run the following code (replace console.log with alert if you don't have Firebug).
function Player() {
var score;
//return this.score - else it returns undefined
this.getScore = function() { return this.score; }
this.setScore = function(sc) { this.score = sc; }
}
function compare(playerA, playerB) {
console.log("called " + playerA.getScore() + " " + playerB.score);
//compare method should return 0 if equal, 1 if a > b and -1 if a < b
return (playerA.getScore() == playerB.getScore()) ? 0
: ((playerA.getScore() > playerB.getScore()) ? 1 : -1);
}
var players = [];
players[0] = new Player();
players[1] = new Player();
players[2] = new Player();
players[3] = new Player();
players[0].setScore(9);
players[1].score = 14;
players[2].score = 11;
players[3].score = 10;
players.sort(compare);
console.log(players);//prints sorted array
It's probably because you don't have any "array values" inside your array - textual indexes are not regarded as array values but as object propertiest (arrays are "objects in disguise" in javascript). You can add as many properties to any object but array specific methods like sort take only "real" array members as their parameteres (i.e. only with numerical indexes)
var arr = new Array()
arr[0] = 1
arr[1] = 2
arr["textual_index"] = 3
alert(arr.length);
The last line alerts "2" not "3" since there are only two values with numeric indexes.
you can also use like below:
var a = [];
a.push(obj1);
a.push(obj2);
a.sort(compare);
so you can use push method rather than an integer index

Categories

Resources