I'm doing a CodeWarrior.com problem (this one: http://www.codewars.com/dojo/katas/521c2db8ddc89b9b7a0000c1/play/javascript).
I implemented it in python first, and my code works fine, however in Javascript, I cannot get the lines output.push(snail(data)); return flattenArray(this.output); to work. Calling the method in a recursive fashion seems to allow the child method to edit the variables inside the parent method.
How can I prevent this (if this is what's happening)?
Here's my code:
snail = function(data) {
console.log("snail - " + data);
this.output = [];
// Get the top row
this.output.push(data.splice(0,1));
if(data.length == 0) {
return this.output;
}
// Get the right row
for(var layer=0;layer<data.length;layer++) {
this.output.push(data[layer].splice(data[layer].length - 1,1));
}
// Get the bottom row
this.output.push(data.splice(data.length - 1,1));
// Get the left row
for(var layer=0;layer<data.length;layer++) {
this.output.push(data[layer].splice(0,1));
}
if(data.length!=0) {
output.push(snail(data));
return flattenArray(this.output);
} else {
return this.output;
}
}
function flattenArray(arr) {
var r = [];
while (!arrayEqual(r, arr)) {
r = arr;
arr = [].concat.apply([], arr);
}
return arr;
}
function arrayEqual(a, b) {
var i = Math.max(a.length, b.length, 1);
while(i-- >= 0 && a[i] === b[i]);
return (i === -2);
}
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
thisinside your snail function mean? Shouldoutput.push(snail(data));bethis.output.push(snail(data));I think you have misunderstood whatthisis hereoutput.push(snail(data));calls push on a (probably non-existent) global object named output. Since you're returning something withthis.output, you probably wantthis.output.push(snail(data));.this.outputinstead of justoutputto try and stop this problem. It doesn't seem to affect the running of the program at all.this.outputinstead ofoutput? Is it supposed to be a global? What did you think addingthiswould do? Hard to help if you don't know what you were trying to dosnail()getting called? Please create runnable code in jsfiddle.net