2024-09-15

coffeescript

a collection of oneliners and other useful functions.

# create an object mapping element ids to their corresponding dom elements
dom = (dom[a.id] = a for a in document.querySelectorAll("[id]"))

delete_duplicates = (a) -> (new Set a)...
random_integer = (min, max) -> (Math.random() * (max - min + 1) + min) // 1
random_element = (a) -> a[Math.random() * a.length // 1]
n_times = (n, f) -> (f i for i in [0...n])
median = (a) -> a.slice().sort((a, b) -> a - b)[a.length / 2 | 0]
sum = (a) -> a.reduce (a, b) -> a + b
mean = (a) -> a.reduce (a, b) -> a + b) / a.length
intersection = (a, b) -> (a for a in a when a in b)

# add value to an array stored under key in object
object_array_add = (object, key, value) -> (object[key] ?= []).push value

# sort elements in array by the given example order in sorting
sort_by_array = (a, sorting) -> a.sort (a, b) -> sorting.indexOf a - sorting.indexOf b

# delete duplicates while keeping the order the same
delete_duplicates_stable = (a) ->
  existing = {}
  (existing[a] = true; a for a in a when not existing[a])

# array shuffle
randomize = (a) ->
  for i in [a.length - 1..0]
    i2 = (Math.random() * (i + 1)) // 1
    [a[i], a[i2]] = [a[i2], a[i]]
  a