Jump To …

util.coffee

range = (start, stop=start, step=1) ->
  start = 0 if arguments.length == 1
  [start/step...stop/step].map (i) -> Math.floor i * step

map = (xs, fn) ->
  xs.map fn

sum = (xs) ->
  xs.reduce(((a, b) -> a + b), 0)

filter = (xs, predicate) ->
  xs.filter predicate

max = (xs) ->
  xs.reduce(((a, b) -> Math.max(a, b)), xs[0])

min = (xs) ->
  xs.reduce(((a, b) -> Math.min(a, b)), xs[0])

mean = (xs) ->
  sum(xs) / xs.length

zip = (xs, ys) ->
  map range(Math.min(xs.length, ys.length)), (i) -> [xs[i], ys[i]]

zipWith = (xs, ys, fn) ->
  map zip(xs, ys), ([x, y]) -> fn(x, y)

unzip = (xs) ->
  ys = ([] for i in [0...xs[0].length])
  for x in xs
    for y, i in x
      ys[i].push y
  ys

remove = (x, xs) ->
  if x.length?
    xs.filter (i) -> i not in x
  else
    xs.filter (i) -> i != x

append = (x, xs) ->
  ys = xs.slice(0)
  ys.push(x)
  ys

sort = (xs, cmp) ->
  xs.slice(0).sort(cmp)

last = (xs) ->
  xs[xs.length - 1]

shuffle = (xs) ->
  ys = xs.slice(0)
  for x, i in ys
    j = parseInt(Math.random() * (ys.length - i)) + i
    [ys[i], ys[j]] = [ys[j], ys[i]]
  ys

stdDev = (xs) ->
  mx = mean(xs)
  Math.sqrt mean map xs, (x) -> Math.pow x - mx, 2