Skip to content

Instantly share code, notes, and snippets.

@jampekka
Created April 3, 2015 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jampekka/5169b946901dd6f599e1 to your computer and use it in GitHub Desktop.
Save jampekka/5169b946901dd6f599e1 to your computer and use it in GitHub Desktop.
{zipWith, fold, map, zipAll, findIndex, objsToLists} = require "prelude-ls"
fobj = -> (...args) ->
me = {}
callable = f.apply(me, args) ? me
me.__proto__ = callable.__proto__
callable.__proto__ = me
return callable
export isScalar = (v) -> typeof v == 'number'
cwise = (f) --> (a, b) ->
| isScalar a and isScalar b => f a, b
| isScalar a => map f(a, _), b
| isScalar b => map f(_, b), a
| _ => zipWith f, a, b
export
add = cwise (+)
sub = cwise (-)
mul = cwise (*)
div = cwise (/)
pow = cwise (**)
sqrt = pow _, 0.5
sum = fold (+), 0, _
norm = (a) -> sqrt sum (pow a, 2)
cmap = (f, v) -->
| isScalar v => f v
| _ => f `map` v
getDim = (d) -> map (x) -> x[d]
searchAscending = (ts, t) -->
# TODO: Could use binary or interpolation search
findIndex (>= t), ts
LinInterp = fobj (@ts, @xs) ->
ts = @ts
@interpOne = (t) ~>
return NaN if t < ts[0]
return NaN if t > ts[*-1]
i = (searchAscending ts, t) - 1
return @xs[0] if i < 0
dt = ts[i+1] - ts[i]
w = (t - ts[i])/(ts[i+1] - ts[i])
dx = (@xs[i+1] `sub` @xs[i]) `mul` w
return @xs[i] `add` dx
(ts) ~>
cmap @interpOne, ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment