Permalink
Browse files

Allow aget to chain keys for easily extracting information from compl…

…ex objects
  • Loading branch information...
1 parent 149cf22 commit ac6406f6a6982c4d9ce2eac59a0b697fffc5c7a5 Christopher Maier committed Jun 3, 2011
Showing with 13 additions and 4 deletions.
  1. +6 −1 README.markdown
  2. +4 −2 src/com/reasonr/scriptjure.clj
  3. +3 −1 test/test_scriptjure.clj
View
@@ -119,11 +119,16 @@ Results in a new statement. The first argument is the object. All remaining item
=> "new google.visualization.Query(url)"
**aget**
- (aget obj index)
+ (aget obj & indexes)
(js (aget foo 42))
=> "foo[42]"
+Array access can also be chained. This is helpful not only for multidimensional arrays, but for reaching deep into objects using a series of keys (similar to `clojure.core/get-in`)
+
+ (js (aget foo bar "baz"))
+ => "foo[bar][\"baz\"]"
+
To set an array, combine with set!
(js (set! (aget foo 42) 13))
@@ -174,8 +174,10 @@
(defmethod emit-special 'new [type [new class & args]]
(str "new " (emit class) (comma-list (map emit args))))
-(defmethod emit-special 'aget [type [aget var idx]]
- (str (emit var) "[" (emit idx) "]"))
+(defmethod emit-special 'aget [type [aget var & idxs]]
+ (apply str
+ (emit var)
+ (interleave (repeat "[") (map emit idxs) (repeat "]"))))
(defmethod emit-special 'inc! [type [inc var]]
(str (emit var) "++"))
View
@@ -86,7 +86,9 @@
(is (= (js [1 "2" :foo]) "[1, \"2\", foo]")))
(deftest test-aget
- (is (= (js (aget foo 2)) "foo[2]")))
+ (is (= (js (aget foo 2)) "foo[2]"))
+ (is (= (js (aget foo bar baz) "foo[bar][baz]")))
+ (is (= (js (aget foo "bar" "baz") "foo[\"bar\"][\"baz\"]"))))
(deftest test-map
(is (= (strip-whitespace (js {:packages ["columnchart"]})) "{packages: [\"columnchart\"]}")))

0 comments on commit ac6406f

Please sign in to comment.