Skip to content

Instantly share code, notes, and snippets.

View knjname's full-sized avatar
💭
🐙

knjname knjname

💭
🐙
View GitHub Profile
satisfy = (fn) ->
_f = (args, length) ->
return fn args... if length is 0
more = (bool) -> _f [args..., bool], length - 1
more(true) or more(false)
_f [], fn.length
console.log (satisfy (a, b) -> a and b)
console.log (satisfy (a) -> false )
@withGlobals = (prop, fn) =>
swap = => [@[k], prop[k]] = [prop[k], @[k]] for k of prop
try
do swap
do fn
finally
do swap
@withGlobals {alert : (v) -> console.log(v) }, =>
# requires underscore.js
foldl = (ls, fn, head) ->
head = fn head, e for e in ls
head
console.log foldl [1..10], ((l,r)->l+r), 0
accessPropByNames = (obj, names) ->
foldl names, ((l,r)-> l?[r]), obj
firstNumber = (taken) ->
unless taken[num = Math.floor( Math.random() * 100 )]
taken[num] = true
num
else
firstNumber taken
class BingoCell
constructor : (@num) ->
bingoMaxNumber = 75
firstNumber = (taken) ->
unless taken[num = Math.floor( Math.random() * bingoMaxNumber )]
taken[num] = true
num
else
firstNumber taken
bingoMaxNumber = 75
firstNumber = (taken) ->
unless taken[num = 1 + Math.floor( Math.random() * (bingoMaxNumber - 1) )]
taken[num] = true
num
else
firstNumber taken
bingoMaxNumber = 75
firstNumber = (taken, l = 1, h = bingoMaxNumber) ->
unless taken[num = l + Math.floor( Math.random() * (h - l) )]
taken[num] = true
num
else
firstNumber taken
deferredize = (obj)->
obj = obj() if typeof obj is 'function'
def = $.Deferred()
obj.onsuccess = (args...)-> def.resolve args...
obj.onerror = (args...) -> def.reject args...
wrap = (wrapped, wrapper) -> (args...)-> wrapper.apply(wrapped, args)
# wrapper can invoke wrapped with @().
asc = (l,r) -> l - r
med = (list) ->
sorted = [list...].sort(asc)
prev = Math.floor((sorted.length - 1) / 2)
next = Math.ceil((sorted.length - 1) / 2)
(sorted[prev] + sorted[next]) / 2
most = (list) ->