Posted over 6 years ago. Visible to the public. Linked content.

Infinitely nested hashes in Javascript (Coffeescript)

The NestedHash class allows you to read and write hashes of any depth. Examples:

hash = {} NestedHash.write hash, 'a', 'b', 'c', 'value' # => { a: { b: { c: 'value' } } } hash, 'a', 'b', 'c' # => 'value' hash, 'a' # => { b: { c: 'value' } } hash, 'foo', 'bar' # => undefined

Inspired by victusfate Archive .


class @NestedHash @read: (objekt, keys...) -> if objekt and keys.length @read objekt[keys[0]], keys[1...]... else objekt @write: (objekt, keys..., value) -> objekt ?= {} if keys.length key = keys[0] objekt[key] = @write(objekt[key], keys[1...]..., value) objekt else objekt = value


describe 'NestedHash', -> describe '.write()', -> it 'writes nested values to a hash', -> hash = {} NestedHash.write hash, 'level1', 'level2', 'value' expect(hash).toEqual level1: level2: 'value' it 'overwrites existing values', -> hash = level1: level2: 'value' NestedHash.write hash, 'level1', 'level2', 'new value' expect(hash).toEqual level1: level2: 'new value' describe '.read()', -> it 'reads nested values from a hash', -> hash = level1: level2: 'value' value = hash, 'level1', 'level2' expect(value).toEqual 'value' it 'reads nested trees from a hash', -> hash = level1: level2: 'value' value = hash, 'level1' expect(value).toEqual level2: 'value' it 'returns undefined when any of the keys is missing', -> value = {}, 'foo', 'bar' expect(value).not.toBeDefined()

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Dominik Schöler
Last edit:
over 6 years ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more