Canop / JSON.prune

A pruning version of JSON.stringify, allowing for example to stringify window or any big or recursive object
MIT License
163 stars 27 forks source link

Is it possible to convert depth-first to breadth-first approach? #2

Closed cihadturhan closed 10 years ago

cihadturhan commented 10 years ago

Hi Canop, Thanks for the library. It helps me too much.

Currently, I came across this bug/feature. If you have an object referenced by a key inside an object which is in an array, it always assigns the following elements as -pruned-.

To clarify, let me explain it by example

var foo = {...};

var bar = 
[
  {
    a: 1, 
    b: foo
  },
  foo
];

JSON.prune(bar)

will yield [{ a:1, b:{...} }, '-pruned-']

however, I expect it to be [{a:1, b:'-pruned-', {...}]

It goes deeper as much as possible and goes top checks if the current element is found before. This occurs because the algorithm uses depth-first and what I need is to use breadth-first algorithm.

Would you mind to add this algorithm too or point me the right direction as the code seemed to me a bit complicated so I could find my own way.

Canop commented 10 years ago

Depth first was easy to implement and is much more efficient, it's done with recursive calls of the str function. If we were to allow two algorithms, there would be an optional argument ("algorithm"?) whose choice would lead to the choice between two different implementations of the str function.

cihadturhan commented 10 years ago

Thanks Canop,

I've tried to implement breadth-first but it's more challenging I imagine. Scanning an object with breadth-first is easy and found here but putting braces to start and end of an object needs loads of extra work.

Therefore, I've found another solution to the problem. There is a library JSON.js and has two cool functions to cycle and retrocycle an object which made my work very easy.

So, I'm closing this issue.