How to declare Hash.new(0) with 0 default value for counting objects in JavaScript?

后端 未结 3 1647
终归单人心
终归单人心 2021-01-24 11:48

I\'m trying to iterate through an array of digits and count how many times each digit is found in the array.

In ruby it\'s easy, I just declare a Hash.new(0)

相关标签:
3条回答
  • 2021-01-24 12:33

    ECMAScript does not have default values for missing keys in objects the same way Ruby does for Hashes. You can, however, use dynamic introspective metaprogramming to do something similar, using ECMAScript Proxy objects:

    const defaultValue = 42;
    const proxyHandler = {
        get: (target, name) => name in target ? target[name] : defaultValue
    };
    const underlyingObject = {};
    
    const hash = new Proxy(underlyingObject, proxyHandler);
    
    1 in hash
    //=> false
    1 in underlyingObject
    //=> false
    
    hash[1]
    //=> 42
    underlyingObject[1]
    //=> undefined
    

    So, you could do something like this:

    arr.reduce(
        (acc, el) => { acc[el]++; return acc }, 
        new Proxy(
            {},
            { get: (target, name) => name in target ? target[name] : 0 }
        )
    )
    //=> Proxy [ { '0': 5, '1': 3 }, { get: [Function: get] } ]
    

    However, this is still not equivalent to the Ruby version, where the keys of the Hash can be arbitrary objects whereas the property keys in an ECMAScript object can only be Strings and Symbols.

    The direct equivalent of a Ruby Hash is an ECMAScript Map.

    Unfortunately, ECMAScript Maps don't have default values either. We could use the same trick we used for objects and create a Proxy, but that would be awkward since we would have to intercept accesses to the get method of the Map, then extract the arguments, call has, and so on.

    Luckily, Maps are designed to be subclassable:

    class DefaultMap extends Map {
        constructor(iterable=undefined, defaultValue=undefined) {
            super(iterable);
            Object.defineProperty(this, "defaultValue", { value: defaultValue });
        }
    
        get(key) {
            return this.has(key) ? super.get(key) : this.defaultValue;
        }
    }
    
    const hash = new DefaultMap(undefined, 42);
    
    hash.has(1)
    //=> false
    
    hash.get(1)
    //=> 42
    

    This allows us to do something like this:

    arr.reduce(
        (acc, el) => acc.set(el, acc.get(el) + 1), 
        new DefaultMap(undefined, 0)
    )
    //=> DefaultMap [Map] { 1 => 3, 0 => 5 }
    

    Of course, once we start defining our own Map anyway, we might just go the whole way:

    class Histogram extends DefaultMap {
        constructor(iterator=undefined) {
            super(undefined, 0);
    
            if (iterator) {
                for (const el of iterator) {
                    this.set(el);
                }
            }
        }
    
        set(key) {
            super.set(key, this.get(key) + 1)
        }
    }
    
    new Histogram(arr)
    //=> Histogram [Map] { 1 => 3, 0 => 5 }
    

    This also demonstrates a very important lesson: the choice of data structure can vastly influence the complexity of the algorithm. With the correct choice of data structure (a Histogram), the algorithm completely vanishes, all we do is instantiate the data structure.

    Note that the same is true in Ruby also. By choosing the right data structure (there are several implementations of a MultiSet floating around the web), your entire algorithm vanishes and all that is left is:

    require 'multiset'
    
    Multiset[*arr]
    #=> #<Multiset:#5 0, #3 1>
    
    0 讨论(0)
  • 2021-01-24 12:38

    In Javascript you do it with Array.reduce

    const reducer = (acc, e) => acc.set(e, (acc.get(e) || 0) + 1);
    [1, 0, 0, 0, 1, 0, 0, 1].reduce(reducer, new Map())
    //⇒ Map(2) {1 => 3, 0 => 5}
    
    0 讨论(0)
  • 2021-01-24 12:40

    You can use Map,

    • initialize hash as Map
    • Loop through array, if key is already present in hash increase it's value by 1 else set it to 1

    let arr = [1, 0, 0, 0, 1, 0, 0, 1]
    let hash = new Map()
    
    arr.forEach(val => {
      hash.set(val, (hash.get(val) || 0) + 1)
    })
    
    console.log([...hash])

    0 讨论(0)
提交回复
热议问题