The fiddle linked shows a function that uses recursion to flatten out an array of any dimension (thanks to users Bergi and Exlord for their help on the first part) and return the array with the highest index. I had a helluva time trying things before I could get something that worked. I'd like a couple things clarified:
- Is it code smell if you have an inner function inside a closure that explicitly accepts parameters? e.g:
- Why does the second script end with a maximum call stack size exceeded error?
-
return {
data: flatten(array),
rank: ranks.sort().reverse()[0]
//smelly code?
}
JS
//working code block
(function () {
function flattenAll(array) {
var ranks = [];
function flatten(array) {
var rank = 0;
var data = [];
$.each(array, function (index, item) {
//recursion here
typeof (item) !== 'object' ? data.push(item) : data = data.concat(flatten(item));
rank++
});
ranks.push(rank);
return data;
};
return {
data: flatten(array),
rank: ranks.sort().reverse()[0]
}
}
console.log(flattenAll([3, 4, [[[[[[4]]]]]], [[1, 4, 5]], [4]]));
})();
/****** second code block******************/
(function () {
function flattenAll(array) {
var ranks = [],
//tried different approach for returning data
//this approach of setting returnData= data
//only grabs the last element in the array
returnData = [];
function flatten() {
var rank = 0;
var data = [];
$.each(array, function (index, item) {
//recursion here
$.isArray(item) ? data = flatten(item) : data.push(item);
rank++
});
ranks.push(rank);
returnData = data;
return data;
};
return {
data: flatten(), //no parens here vs the first code block
rank: ranks.sort().reverse()[0]
}
}
console.log(flattenAll([3, 4, [[[[[[4]]]]]], [[1, 4, 5]], [4]]));
})();
Is there a proper way to handle handle recursion within closures? I'm not understanding everything that's going on here.