Skip to content

Latest commit

 

History

History
72 lines (58 loc) · 1.73 KB

get_in.markdown

File metadata and controls

72 lines (58 loc) · 1.73 KB

Get-In / KeyPath

We frequently deal with nested, map-like data structures in programming. For example:

{ an_outer: "hash",
  with_another: {
    inner: "hash",
    and_another: {
      inside: "that"
    }
  }
}

This approach gives us a flexible, convenient way to organize ad-hoc information. But it can be a bit tedious to retrieve data from something like this. In the example above, to get to the inner key, we would need:

our_hash[:with_another][:and_another][:inside]

To facilitate this, many languages support a function for retrieving a "path" through a nested data structure, such as Clojure's get-in or Objective-C's valueForKeyPath.

For this exercise, practice writing your own get_in method using either Ruby or Javascript. The function should:

  • Take a Hash and an Array as an argument
  • Go through the array retrieving successive values from the hash until values are exhausted

For example:

data = { an_outer: "hash",
  with_another: {
    inner: "hash",
    and_another: {
      inside: "that"
    }
  }
}

get_in(data, [:with_another, :and_another, :inside])
=> "that"

Extension

See if you can support "branching" in your method. Anywhere in the keypath, I should be able to provide an array of keys. This would represent 2 branches in the path to retrieve. For example:

data = { an_outer: "hash",
  with_another: {
    inner: "hash",
    and_another: {
      inside: "that"
    }
  }
}

get_in(data, [:with_another, [:inner, [:and_another, :inside]])
=> ["hash", "that"]