views:

267

answers:

2
function source_of (array, up_to_dimension) {

  // Your implementation

}

source_of([1, [2, [3]]], 0) == '[1, ?]'
source_of([1, [2, [3]]], 1) == '[1, [2, ?]]'
source_of([1, [2, [3]]], 2) == '[1, [2, [3]]]'

source_of([532, 94, [13, [41, 0]], [], 49], 0) == '[532, 94, ?, ?, 49]'

I have very huge multidimensional array and I want to serialize it to string. Implementation would be obvious without up_to_dimension argument. It's required.

Function must work at least in latest versions of Firefox, Opera, Safari and IE.

Performance really important issue.

+1  A: 

something like

function to_source(a, limit) {
 if(!a.sort)
  return a;
 else if(!limit)
  return "?";
 var b = [];
 for(var i in a)
  b.push(to_source(a[i], limit - 1));
 return "[" + b.join(",") + "]";
}
stereofrog
+3  A: 
function source_of(array, up_to_dimension) {
    if (up_to_dimension < 0) {
        return "?";
    }

    var items = [];

    for (var i in array) {
        if (array[i].constructor == Array) {
            items.push(source_of(array[i], up_to_dimension - 1));
        }
        else {
            items.push(array[i]);
        }
    }

    return "[" + items.join(", ") + "]";
}
John Kugelman
mine is much nicer ;)
stereofrog