Proposal: `maxDepth` on objects
robjtede at icloud.com
Mon Oct 22 10:19:06 UTC 2018
Ahh yes, the updating aspect is tricky (call it an early-morning oversight), and not one that I think could have a practical solution if spreading out the calculation over the life of the object is not viable. Maybe my Array comparison was being a bit too optimistic about this usefulness of this feature.
You are correct. A parent object should not have to care about its children objects. I’m not aware that JS engines even keep any kind of reverse lookup table that would accommodate this, right now.
On reference cycles, would it not make sense to have the depth of an object with cyclic references be Infinity, this would be useful information and easy to compute given that garbage collectors already detect them.
(To be clear, I’m not a huge fan of this proposal but it is fun to think about how this could be implemented in userland and wether it could benefit from being a built-in.)
> On 22 Oct 2018, at 11:03, Tab Atkins Jr. <jackalmage at gmail.com> wrote:
> On Mon, Oct 22, 2018 at 2:42 AM Rob Ede <robjtede at icloud.com> wrote:
>> Calculating this on plain objects could be a O(1) operation:
>> Empty objects are initialized with maxDepth 0 and are set to 1 when a primitive property is added.
>> If an object property is added the maxDepth is set to 1 + maxDepth(newObjectProperty)`instead of it being calculated Ïevery time .maxDepth is accessed (much like how Array#length works).
> That's not enough. Any time you add/change/remove a property that
> would alter the depth of an object, you also need to update the depth
> of every *parent* object containing it.
> This isn't "actually" O(1) - it's O(1) on *access*, but only because
> it's amortized the cost over every mutation instead. We don't
> generally consider that trade-off worthwhile, particularly for things
> like this that would have fairly specialized/limited use-cases in the
> first place.
> (Plus, it still doesn't answer what the depth is of an object with a
> cyclic reference.)
More information about the es-discuss