Commit 168716b7

mo <mo.khan@gmail.com>
2017-09-04 00:58:18
add class to resolve object from path.
1 parent 8863c9d
Changed files (2)
app
assets
javascripts
spec
javascripts
app/assets/javascripts/lib/proxy.js.coffee
@@ -0,0 +1,31 @@
+class CakeSide.Proxy
+  @create: do ->
+    parse = (object, path) ->
+      return unless CakeSide.Proxy.typeOf(object) == 'object' and path?
+      return [object, path] if path.indexOf('.') == -1
+      path = path.split('.')
+      tail = path.pop()
+      for property in path
+        return unless object.hasOwnProperty(property)
+        object = object[property]
+      [object, tail]
+
+    read = (object, path) ->
+      parts = parse(object, path)
+      return parts[0][parts[1]] if parts
+
+    write = (object, path, value) ->
+      parts = parse(object, path)
+      if parts
+        parts[0][parts[1]] = value
+        value
+
+    (object, path, value) ->
+      return read(object, path) if arguments.length == 2
+      return write(object, path, value) if arguments.length == 3
+      console.error '[CakeSide.Proxy.create] incorrect number of arguments'
+
+  @typeOf: (object) ->
+    return 'array' if _.isArray(object)
+    return 'regexp' if _.isRegExp(object)
+    typeof(object)
spec/javascripts/lib/proxy_spec.js.coffee
@@ -0,0 +1,29 @@
+describe "CakeSide.Proxy", ->
+  subject = null
+
+  describe "#create", ->
+    object = null
+    subject = CakeSide.Proxy
+
+    beforeEach ->
+      object =
+        top: 'one'
+        more:
+          stuff: ['a','b']
+
+    it 'gets the value of a shallow object reference', ->
+      expect(subject.create(object, 'top')).toEqual(object.top)
+
+    it 'gets the value of a deep object reference', ->
+      expect(subject.create(object, 'more.stuff')).toEqual(object.more.stuff)
+
+    it 'sets the value of a shallow object reference', ->
+      subject.create(object, 'top', 'two')
+      expect(object.top).toEqual('two')
+
+    it 'sets the value of a deep object reference', ->
+      subject.create(object, 'more.stuff', 5)
+      expect(object.more.stuff).toEqual(5)
+
+    it "returns undefined if a reference doesn't exist", ->
+      expect(subject.create(object, 'non.existent.path')).toEqual(undefined)