Skip to content

Instantly share code, notes, and snippets.

@Gozala
Gozala / example.js
Created January 29, 2012 03:46
Workaround for lack of "tail call optimization" in JS
// Lack of tail call optimization in JS
var sum = function(x, y) {
return y > 0 ? sum(x + 1, y - 1) :
y < 0 ? sum(x - 1, y + 1) :
x
}
sum(20, 100000) // => RangeError: Maximum call stack size exceeded
// Using workaround
@michaelficarra
michaelficarra / random.c
Created June 27, 2011 22:44
fair pseudo-random number generation in C
int random(int min, int max) {
if(min == max) return min;
if(min > max) {
int tmp = max;
max = min;
min = tmp;
}
int range = max - min + 1;
int randMax = RAND_MAX - ((RAND_MAX - range + 1) % range);
@michaelficarra
michaelficarra / test.js
Created June 24, 2011 00:40
fixed-point (Y) combinator in JS
// compute factorial of 5
Y(function(self){
return function(x){
return x == 0 ? 1 : x * self(x - 1);
};
})(5); // === 120
@michaelficarra
michaelficarra / hmac.rb
Created June 17, 2011 17:13
HMAC function in ruby
require 'openssl'
def hmac key, message
sha = OpenSSL::Digest::SHA256.new
blocksize = 64 # SHA256 uses a 64 byte (512 bit) block size
def xor str0, str1 # assuming strings are of equal length
b0 = str0.bytes.to_a
b1 = str1.bytes.to_a
result = []
@michaelficarra
michaelficarra / dynamic_instantiation.js
Created December 19, 2010 19:58
instantiating a member of a class with a variable number of constructor arguments
var F = function(){};
F.prototype = klass.prototype;
var o = new F();
klass.apply(o,arguments)
return o;
@michaelficarra
michaelficarra / gist:746710
Created December 18, 2010 17:56
forkNode
forkNode = ->
args = process.argv[1..]
nodeArgs = []
while (idx = args.indexOf '--nodejs') > -1
nodeArgs = nodeArgs.concat args.splice(idx,2)[1].split(/\s+/)
spawn process.execPath, nodeArgs.concat(args),
cwd: process.cwd()
env: process.env
customFds: [0, 1, 2]
arrayEq = (a, b) ->
if a is b
# 0 isnt -0
a isnt 0 or 1/a is 1/b
else if a instanceof Array and b instanceof Array
return no unless a.length is b.length
return no for el, idx in a when not arrayEq el, b[idx]
yes
else
# NaN is NaN
@michaelficarra
michaelficarra / example.js
Created October 6, 2010 03:53
JS classical OOP
__extends = function(parent, child) {
var ctor = function(){};
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.prototype.constructor = child;
if(typeof parent.extended === 'function') parent.extended(child);
child.__super__ = parent.prototype;
return child;
};
unless Function::bind?
Function::bind = (scope, args...) ->
target = this
if typeof target isnt "function" then throw new TypeError
bound = ->
unless this intanceof bound
return target.apply scope, [args..., arguments...]
F = ->
F.prototype = target.prototype
self = new F