module Language.Sunroof.JS.Array
( JSArray
, array, newArray
, length'
, lookup'
, insert'
, push, pop
, shift, unshift
, forEach
, empty
) where
import Prelude hiding ( lookup, length )
import Data.List ( intercalate )
import Data.Boolean ( BooleanOf, IfB(..) )
import Language.Sunroof.JavaScript ( Expr, showExpr, literal )
import Language.Sunroof.Types
import Language.Sunroof.Classes ( Sunroof(..), SunroofValue(..), SunroofArgument(..) )
import Language.Sunroof.Selector ( JSSelector, index, (!) )
import Language.Sunroof.JS.Bool ( JSBool, jsIfB )
import Language.Sunroof.JS.Number ( JSNumber )
data JSArray a = JSArray Expr
instance Show (JSArray a) where
show (JSArray v) = showExpr False v
instance (Sunroof a) => Sunroof (JSArray a) where
box = JSArray
unbox (JSArray o) = o
type instance BooleanOf (JSArray a) = JSBool
instance (Sunroof a) => IfB (JSArray a) where
ifB = jsIfB
array :: (SunroofValue a, Sunroof (ValueOf a)) => [a] -> JS t (JSArray (ValueOf a))
array l = evaluate $ box $ literal $ "[" ++ intercalate "," (fmap (showExpr False . unbox . js) l) ++ "]"
newArray :: (SunroofArgument args, Sunroof a) => args -> JS t (JSArray a)
newArray args = cast `fmap` new "Array" args
empty :: (Sunroof a) => JS t (JSArray a)
empty = evaluate $ box $ literal "[]"
length' :: JSSelector JSNumber
length' = attr "length"
lookup' :: (Sunroof a) => JSNumber -> JSArray a -> a
lookup' n e = e ! index n
insert' :: (Sunroof a) => JSNumber -> a -> JSArray a -> JS t ()
insert' n a e = e # index n := a
push :: (SunroofArgument a, Sunroof a) => a -> JSArray a -> JS t ()
push a = invoke "push" a
unshift :: (SunroofArgument a, Sunroof a) => a -> JSArray a -> JS t ()
unshift a = invoke "unshift" a
pop :: (Sunroof a) => JSArray a -> JS t a
pop = invoke "pop" ()
shift :: (Sunroof a) => JSArray a -> JS t a
shift = invoke "shift" ()
forEach :: (Sunroof a, SunroofArgument a) => (a -> JS A ()) -> JSArray a -> JS t ()
forEach body arr = do
f <- function body
arr # invoke "forEach" f :: JS t ()
return ()