Skip to content

Instantly share code, notes, and snippets.

View chrisbnt's full-sized avatar

Chris Barnett chrisbnt

  • Sydney, Australia
View GitHub Profile
@chrisbnt
chrisbnt / simplelrucache.coffee
Created November 10, 2015 01:00
Dirt simple LRU cache
module.exports = (options = {})->
cache = {}
cacheSize = 0
maxKeys = options.maxKeys || 50
seq = 1
get: (key)->
if c = cache[key]
c.used = seq++
return c.value
@chrisbnt
chrisbnt / time-em-http-request.rb
Created August 31, 2011 00:59
How to handle timeouts decently with em-http-request 0.3.0
require 'eventmachine'
require 'em-http'
EM::run do
rq = EM::HttpRequest.new("http://www.slow.com").get
def rq.timed_out?
@timed_out
end
@chrisbnt
chrisbnt / longest_common_prefix.rb
Created June 21, 2011 02:24
Enumerable#longest_common_prefix
module Enumerable
def longest_common_prefix
common = first
self[1..-1].each do |item|
length_to_test = [item.length, common.length].min
while length_to_test > 0
if item[0..(length_to_test-1)] === common[0..(length_to_test-1)]
common = common[0..(length_to_test-1)]
break
end
@chrisbnt
chrisbnt / murder.sh
Created March 14, 2011 06:57
Murder - it's killall, but it really means it. Starts with SIGINT, if that doesn't work, tries a SIGQUIT, and if that doesn't work, it pulls out the SIGKILL hammer
#! /bin/bash
SIGNAL="SIGINT"
while killall -${SIGNAL} "$@"; do
if [ $SIGNAL = SIGINT ]; then
SIGNAL="SIGQUIT"
else
SIGNAL="SIGKILL"
fi
@chrisbnt
chrisbnt / round_to_nearest.rb
Created October 26, 2010 05:01
Nuumeric#round_to_nearest
class Numeric
def round_to_nearest(delta = 0.25)
return self if delta.to_f == 0.0
((to_f / delta.to_f).round * delta.to_f)
end
def floor_to_nearest(delta = 0.25)
return self if delta.to_f == 0.0
((to_f / delta.to_f).floor * delta.to_f)
end
@chrisbnt
chrisbnt / split_where.rb
Created October 19, 2010 13:06
Enumerable#split_where
module Enumerable
def split_where(&block)
inject([[]]) do |result, item|
if block.call(item)
result.push []
else
result.last.push item
end
result
end
@chrisbnt
chrisbnt / split_digits.rb
Created September 20, 2010 13:03
Integer#split_digits
# Efficient way of splitting digits in positive integers
class Integer
def split_digits(base = 10)
digits = []
head = self
while head >= base
digits.push head % base
head /= base
end
digits.push(head)