Using Array objects as key for ES6 Map

前端 未结 3 1513
故里飘歌
故里飘歌 2020-12-06 09:42

I am trying to update my code to ES6 as I am using Node 4.0 and really like its features so far. However I have problems with the new ES6 Map data structure as

3条回答
  •  生来不讨喜
    2020-12-06 10:19

    I also had this need, so I wrote an ISC-licensed library: array-keyed-map. You can find it on npm. I think the source is quite clear, but here's how it works anyway, for posterity:


    Maintain a tree of Map objects. Each tree stores:

    • Under an internally-declared Symbol key: The value at that point in the tree (if any). The Symbol guarantees uniqueness, so no user-provided value can overwrite this key.

    • On all its other keys: all other so-far set next-trees from this tree.

    For example, on akmap.set(['a', 'b'], true), the internal tree structure would be like—

    'a':
      [value]: undefined
      'b':
        [value]: true
    

    Doing akmap.set(['a'], 'okay') after that would just change the value for the path at 'a':

    'a':
      [value]: 'okay'
      'b':
        [value]: true
    

    To get the value for an array, iterate through the array while reading the corresponding keys off the tree. Return undefined if the tree at any point is non-existent. Finally, read the internally declared [value] symbol off the tree you've gotten to.

    To delete a value for an array, do the same but delete any values under the [value]-symbol-key, and delete any child trees after the recursive step if they ended up with a size of 0.


    Why a tree? Because it's very efficient when multiple arrays have the same prefixes, which is pretty typical in real-world use, for working with e.g. file paths.

提交回复
热议问题