JanetDocsPlaygroundI'm feeling luckyGitHub sign in

compare



    function
    boot.janet on line 755, column 1

    (compare x y)

    Polymorphic compare. Returns -1, 0, 1 for x < y, x = y, x > y 
    respectively. Differs from the primitive comparators in that it 
    first checks to see whether either x or y implement a `compare` 
    method which can compare x and y. If so, it uses that method. If 
    not, it delegates to the primitive comparators.


1 exampleSign in to add an example
Loading...
(def error-levels {:red 3 :orange 2 :yellow 1})

# Create a new prototype object called ErrorProto with one method, :compare
(def ErrorProto
  @{:level nil

    # Returns -1, 0, 1 for x < y, x = y, x > y respectively.
    :compare (fn [self other]
               (let [lx (error-levels (self :level))
                     ly (error-levels (other :level))]
                 (cond
                   (< lx ly) -1
                   (> lx ly) 1
                   :else 0)))})

# Factory function to create new Error objects 
(defn make-error
  [level]
  (table/setproto @{:level level} ErrorProto))


(def err-red (make-error :red))
(def err-yell (make-error :yellow))
(def err-orange (make-error :orange))

# calls of the polymorphic compare function
(compare err-red err-orange) # 1
(compare err-orange err-red) # -1
(compare err-red err-red)    # 0

# These following functions call internally 
# the polymorphic compare function, but return a boolean value
(compare> err-red err-orange)  # true
(compare> err-yell err-orange) # false
(compare= err-yell err-yell)   # true

#-------------------------------------------------------------------------------
# sort the objects with compare> and compare<

(def errors-unsorted @[err-red err-yell err-orange])

# ascending order
(sort errors-unsorted compare<) 
# => @[@{:level :yellow} @{:level :orange} @{:level :red}]

# descending order
(sort errors-unsorted compare>) 
# => @[@{:level :red} @{:level :orange} @{:level :yellow}]

# without compare
(sort-by |(error-levels ($ :level)) errors-unsorted)
# => @[@{:level :yellow} @{:level :orange} @{:level :red}]

# Note!!!, the following does not work as expected. 
# sort alone does not automatically use the compare function (the comparator)
(sort errors-unsorted) # result is not sorted!
leobmPlayground