Mocha-Script
overview
Declarations
(def treats ["cookies" "candy" "ice cream"]) (def date (Date)) (def answer 42) (def double (fn (n) (* 2 n))) (def things (+ "Today is: " date " and the answer is " answer " which doubled is " (double answer))) (alert things)
Compile & Run
Functions
; define a function and save it in the variable "sqaure" (def square (fn (n) (* n n))) ; call a function (square 8) ; create and call an anonymous function ((fn (n) (* n n)) 2) ; shortcut function definition (defn shorter (n) (* n n)) ; alert the cubes (alert (map (fn (n) (* n n n)) [2 4 6 8]))
Compile & Run
Objects
; define an object literal (def arnold { name:{first:"Arnold" last:"Schwarzenegger"} age:(- (.getFullYear (new Date)) 1947) occupation:"badass" greet:(fn () "Hello") }) ; reference a field in an object (:age arnold) ; call a method of an object (.greet arnold) ; alternative way to call a method of an object ((:greet arnold)) ; alert age (alert (:age arnold)) ; anonymous object literal (log {first:1 second:2})
Compile & Run
Arrays / Objects continued
; define an array (def movies ["Freddy got Fingered" "Road Trip" "Stealing Harvard" "Bob the Butler"]) ; get an element (get movies 0) ; define an object with custom keys (def obj {"goofy key": "value"}) ; get a custom field (get obj "goofy key") ; alert field (alert (get movies 2))
Compile & Run
JS Interop
; get the latest answers on Stack Overflow ; and alert the author's names (def api "http://api.stackexchange.com/2.1/answers?key=U4DMV*8nvpm3EOpvf69Rxw((&site=stackoverflow&order=desc&sort=activity&filter=default") (.get $ api (fn (data) (alert (pluck (pluck (:items data) 'owner') 'display_name'))))
Compile & Run
Looping and Branching
(if (> 2 1) (alert "2 is greater than 1") ; if true case (alert "2 is less than 1?")) ; else case (def result (if true "true" "false")) (times 6 (fn () (log "hello"))) ; log hello 6 times (log (loop (z 1) (when (< z 5) (log z) (recur (+ z 1))) )) (foreach [1 2 3 4] log)
Compile & Run
Types, Inheritance, Mixins
; define a type (deftype Animal (eat (food) (log food)) (sleep (duration) (setTimeout (fn () (log "slept")) duration)) ) ; define a type that inherits from another (deftype Tiger {extend: (:prototype Animal)} (prowl () (alert "prowling")) ) ; define a type as an expression that can be passed and/or saved (def Lion (type Lion {extend: (:prototype Animal)} (roar () (alert "ROAR!!!")) )) ; define a type that mixes in other types (deftype Liger { extend: (:prototype Animal) mix: [(:prototype Lion) (:prototype Tiger)]} ) (let (liger (new Liger)) (.roar liger) (.prowl liger) )
Compile & Run
Standard Library
; map ; pluck ; reduce ; foldr ; concat ; zip ; find ; every ; each ; shuffle ; times ; where .... TODO TODOCUMENT
Compile & Run