Skip to content

Instantly share code, notes, and snippets.

@abozhilov
abozhilov / gist:3889708
Created October 14, 2012 20:22
Set-builder based times
function times(n, fn) {
var arr = [];
for (var i = 0; i < n; i++) {
var res = fn(i);
if (typeof res != 'undefined') {
arr.push(res);
}
}
return arr;
};
function ctor(fn) {
function F () {
var obj = Object.create(F.prototype);
fn.apply(obj, arguments);
return obj;
}
F.prototype = Object.create(fn.prototype);
return F;
}
function getType(obj) {
var type = typeof obj;
return (type == 'object' && obj === null) ? 'null' : type;
}
@abozhilov
abozhilov / gist:2997730
Created June 26, 2012 18:23
Wildcard to RegExp
/**
* Convert wildcard pattern to RegExp
* Pattern:
* * - Zero or more characters
* ? - Exactly one character
*
* @param {String} pattern Wildcard pattern
* @returns {RegExp} regular expression for wildcard matching
*/
function wc2reg(pattern) {
var lib = {
/*
* PRNG - Linear congruential generator
* The random cycle is 2^32
* @retuns {unsigned integer} Next random seed
*/
rand : (function () {
var seed = new Date;
return function () {
seed = (seed * 69069 + 1) >>> 0;
@abozhilov
abozhilov / gist:2594795
Created May 4, 2012 13:27
State machine
var GO = 'GO',
OK = 'OK',
SIGN = 'SIGN',
LZERO = 'LZERO',
INT = 'INT',
FRAC = 'FRAC',
FDIG = 'FDIG',
EXP = 'EXP',
XSIGN = 'XSIGN',
EDIG = 'EDIG',
@abozhilov
abozhilov / gist:2553803
Created April 29, 2012 23:09
Function.prototype.factory
Function.prototype.factory = function () {
var cnt = this;
return function () {
var obj = Object.create(cnt.prototype);
cnt.apply(obj, arguments);
return obj;
};
};
var PROTO_TYPE = {
'[object String]' : String,
'[object Number]' : Number,
'[object Boolean]' : Boolean
};
function applyNew(f, a) {
var construct = PROTO_TYPE[{}.toString.call(f.prototype)];
if (construct) {
return new construct(a[0]);
@abozhilov
abozhilov / gist:1925932
Created February 27, 2012 18:16
JSON.stringify reflection
function StatNode() {
this.dns = 0;
this.connect = 0;
this.first = 0;
this.last = 0;
}
StatNode.prototype.setParam = function (param, value) {
//...
};
@abozhilov
abozhilov / gist:1917462
Created February 26, 2012 16:01
ID mapping
function getId () {
return getId.id++;
}
getId.id = 0;
function Foo() {
this.__id__ = getId();
}
Foo.prototype.valueOf = function () {