Janet Notes and Examples

Arrays

(def a @[44 55 66])
(length a)  #=> 3

# Can also make an array with:
(array 44 55 66)

(keys a)    #=> @[0 1 2]

(a 1)               #=> 55  (like `(in a 1)` below)
(get a 1)           # same
(get a 5)           #=> nil
(get a 5 :default)  #=> :default
(in  a 5)           # ERROR (not in range)

# This works too, though it makes me shift uneasily in my chair.
(1 a)  #=> 55

(put a 1 100)       # @[44 100 66]
(array/push a 200)  # @[44 100 66 200]

# Fills in the empty slots with `nil`s.
(put a 6 99)        # @[44 100 66 200 nil nil 99]

(array/pop a)       #=> 99

# You can also use the `set` special.
# a                   @[44 100 66 200 nil nil]
(set (a 5) 88)      # @[44 100 66 200 nil 88 ]

# Get (but don't remove) last element (like Python's `a[-1]`).
(array/peek a)            #=> 88
# a is still @[44 100 66 200 nil 88]
# Get the third element from the end.
(get a (- (length a) 3))  #=> 200

# To get a slice of an array:
(def b                    @[44 55 66 77 88 99])
(array/slice b 2 5)  #=>  @[      66 77 88   ]  --- `b` is unchanged.

# These work just like you'd expect they should:
array/concat   # Concats everything into the first arg.
array/fill

# To insert single or multiple values into an array starting at a given index:
# b                            @[44 55         66 77 88         99]
(array/insert b  2 100 200)  # @[44 55 100 200 66 77 88         99]
(array/insert b -2 440 540)  # @[44 55 100 200 66 77 88 440 540 99]

(array/new-filled 5 :hi)   #=> @[:hi :hi :hi :hi :hi]

# `array/remove` by default removes only one element.
# b                      @[44 55 100 200 66 77 88 440 540 99]
(array/remove b 6  )   # @[44 55 100 200 66 77    440 540 99]
(array/remove b 1 3)   # @[44 66            77    440 540 99]
(array/remove b 2 99)  # @[44 66                            ]  --- Ok going past end.
# Can also use negative index for index from end of array.

# So, to add and remove from the *front*:
(def a3 @[44 55])
(array/insert a3 0 11)  # @[11 44 55]
(array/remove a3 0)     # @[44 55]

# See also:
map
filter
interpose
frequencies