Niro* by cho45

#20 Multiple values per key object for JavaScript. hash-multivalue.js

In some cases, I want an object which can have multiple values for a key, for example, a parsed object of query parameters or HTTP headers. Here is an implement of the object, hash-multivalue.js.

npm install hash-multivalue
var hash = HashMultiValue({ foo : ['aaa', 'bbb'], bar : ['111', '222', '333'] });
hash; //=> { foo: 'bbb', bar: '333' } //=> 'bbb'
hash.get('foo') //=> 'bbb'
hash.getAll('foo') //=> ['aaa', 'bbb']

hash-multivalue.js is very inspired from Perl's Hash::MultiValue. So I need specs as following:

  • The object is like plain object. In other words, a value for a key must be accessed by property access syntax.

So I use a bit trick to realizing to do it.

  • An instance is normal key / value which is last value of the array of a key.
    • This is able to access a value by property access syntax.
  • An instance has each prototype for it.
    • The instance methods are implemented on it. The prototype object must be instance-specific, so this creates constructor function for each instance.
  • Use closure to retain original key / values (array) pair.
    • Properties are as less as possible.

JavaScript does not distinguish a method or a propety, so the names of methods (eg. 'get', 'getAll') cannot be accessed by property syntax (Use the methods instead). This is restriction of language.

blog comments powered by Disqus