Skip to content

Instantly share code, notes, and snippets.

View kevincennis's full-sized avatar
💭
this is dumb

Kevin Ennis kevincennis

💭
this is dumb
View GitHub Profile
@kevincennis
kevincennis / birthday.js
Created March 8, 2016 04:21
Birthday Problem
// Birthday problem
// https://en.wikipedia.org/wiki/Birthday_problem
// given n possible values and a set size of k,
// determine the probability of a collision
function odds( n, k ) {
return 1 - Math.exp( -0.5 * k * ( k - 1 ) / n );
}
// given n possible values and a probability of p,
@kevincennis
kevincennis / memoize.js
Created October 24, 2015 03:40
Generic Memoize
function memoize( fn ) {
const map = new Map();
const key = Symbol('key');
return function() {
let item = map;
let cached = false;
for ( let i = 0; i < arguments.length; ++i ) {
let cache = item.get( arguments[ i ] );
@kevincennis
kevincennis / composition.js
Last active August 28, 2015 07:28
composition
function compose() {
var fns = Array.prototype.slice.call( arguments );
return function( arg ) {
return fns.reduceRight(function( result, fn ) {
return fn( result );
}, arg );
};
}
function double( n ) {
map([ 'a', 'b', 'c' ], function( value ) {
return value.toUpperCase();
}); // [ 'A', 'B', 'C' ]
@kevincennis
kevincennis / map.js
Last active August 29, 2015 14:25
map
function map( arr, fn ) {
if ( arr.length === 0 ) {
return [];
}
return [ fn( arr[ 0 ] ) ].concat( map( arr.slice( 1 ), fn ) );
}
function reverse( str ) {
if ( str.length <= 1 ) {
return str;
}
return reverse( str.substr( 1 ) ) + str[ 0 ];
}
function factorial( n ) {
if ( n === 1 ) {
return 1;
}
return n * factorial( n - 1 );
}
@kevincennis
kevincennis / curry.js
Last active February 12, 2021 00:33
curry.js
function curry( fn ) {
var arity = fn.length;
return (function resolver() {
var mem = Array.prototype.slice.call( arguments );
return function() {
var args = mem.slice();
Array.prototype.push.apply( args, arguments );
return ( args.length >= arity ? fn : resolver ).apply( null, args );
};
@kevincennis
kevincennis / EventEmitter.js
Last active August 29, 2015 14:14
Proxy Model
var EventEmitter = (function() {
var cache = new WeakMap();
function EventEmitter( obj ) {
cache.set( this, {} );
}
EventEmitter.prototype = {
@kevincennis
kevincennis / EventEmitter.js
Last active August 29, 2015 14:14
EventEmitter
var EventEmitter = (function() {
var cache = new WeakMap();
function EventEmitter() {
cache.set( this, {} );
}
EventEmitter.prototype = {