Skip to content

Instantly share code, notes, and snippets.

@lyuehh
Created October 22, 2012 03:07
Show Gist options
  • Save lyuehh/3929431 to your computer and use it in GitHub Desktop.
Save lyuehh/3929431 to your computer and use it in GitHub Desktop.
js func
//方法调用模式
var obj = {
val: 0,
inc: function(i) {
this.val += i;
}
};
console.log(obj.val);
obj.inc(2);
obj.inc(2);
console.log(obj.val);
// 函数调用模式
var add = function(a,b) {
return a + b;
};
console.log(add(1,4));
obj.double = function () {
var that = this;
var helper = function() {
that.val = add(that.val, that.val);
};
helper();
};
obj.val = 5;
obj.double();
console.log(obj.val);
// 构造器调用
var Q = function(str) {
this.status = str;
};
Q.prototype.getStatus = function() {
return this.status;
};
var myQ = new Q('haha');
​console.log(myQ.getStatus());
// //avoid this..
// var yourQ = Q('haha');
// console.log(yourQ.getStatus());
// apply调用模式
var array = [3,4];
console.log(add.apply(null,array));
console.log(add.call(null,3,4));
var myStatus = {
status: 'ok..'
};
console.log(Q.prototype.getStatus.apply(myStatus));
@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

var Q1 = function(str) {
    this.status = str;
};
var q1 = new Q1('s1');
console.log(q1.status);// => 's1'

var Q2 = function(str) {
    this.status = str;
    return 2;
};
var q2 = new Q2('s2');
console.log(q2.status);

var Q3 = function(str) {
    this.status = str;
    return {}; // 或者 return [];如果返回值不是一个对象,则返回this,否则返回那个对象
};
var q3 = new Q3('s2');
console.log(q3.status); // => undefined

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

var add = function(a, b) {
    if(typeof a !== 'number' || typeof b !== 'number') {
        throw {
            name: 'TypeError',
            message: 'add needs numbers'        
        };
    }
    return a + b;        
};​​​​​​​​
console.log(add(1,2));
var try_it = function() {
    try {
        add('asdf','asdf');            
    } catch(e) {
        console.log(e.name + ': ' + e.message);            
    }
};
try_it();

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
};Number.method('integer', function() {
    return Math[this < 0 ? 'ceil' : 'floor'](this);
});​​​
console.log(-3.2.integer());
console.log(3.2.integer());

String.method('trim', function() {
    return this.replace(/^\s+|\s+$/g, '');
});
console.log('  asdf  '.trim());

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

var hanoi = function(disc, src, aux, dst) {
    if(disc > 0) {
        hanoi(disc - 1, src, dst, aux);
        console.log('Move disc ' + disc + ' from ' + src + ' to ' + dst);
        hanoi(disc - 1, aux, src, dst);
    }        
};
hanoi(3, 'Src', 'Aux', 'Dst');

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

var walk_dom = function walk(node, func) {
    func(node);
    node = node.firstChild;
    while(node) {
        walk(node, func);
        node = node.nextSibling;       
    }
};var getElementsByAttribute = function(att, value) {
    var results = [];
    walk_dom(document.body, function(node) {
        var actual = node.nodeType === 1 && node.getattribute(att);
        if(typeof actual === 'string' &&
           (actual === value || typeof value !== 'string')) {
               results.push(node);
           }               
    });
    return results;
};

var factorial = function factorial(i, a) {
    a = a || 1;
    if(i < 2) {
        return a;        
    }
    return factorial(i - 1, a * i);
};console.log(factorial(4));

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

var obj = function() {
    var value = 0;
    return {
        inc: function(i) {
            value += typeof i === 'number' ? i : 1;
        },
        getValue: function() {
            return value;
        }
    }
}();
obj.inc();
obj.inc();
console.log(obj.getValue());

var quo = function(status) {
    return {
        get_status: function() {
            return status;
        }
    };
};
var myQuo = quo('status ok');
console.log(myQuo.get_status());

var fade = function(node) {
    var level = 1;
    var step = function() {
        var hex = level.toString(16);
        node.style.backgroundColor = '#FFFF' + hex + hex;
        if(level < 15) {
            level += 1;
            setTimeout(step, 100);
        }
    };
    //step();
    setTimeout(step, 100);
};
fade(document.body);

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
};
/*
String.method('deentityify', function() {
    var entity = {
        quot: '"',
        lt: '<',
        gt: '>'
    };
    return function() {
        return this.replace(/&([^&;]+);/g, function(a, b) {
            console.log('a: ' + a + ' b:' + b);
            var r = entity[b];
            return typeof r === 'string' ? r : a;
        });
    }
}());
console.log('&lt;&quot;&gt;&xx;'.deentityify());
*/
String.method('deentityify', function() {
    var entity = {
        quot: '"',
        lt: '<',
        gt: '>'
    };
    return this.replace(/&([^&;]+);/g, function(a, b) {
        console.log('a: ' + a + ' b:' + b);
        var r = entity[b];
        return typeof r === 'string' ? r : a;
    });
});
console.log('&lt;&quot;&gt;&xx;'.deentityify());

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

var serial_maker = function() {
    var prefix = '';
    var seq = 0;
    return {
        set_prefix: function(p) {
            prefix = String(p);            
        },
        set_seq: function(s) {
            seq = s;
        },
        gensym: function() {
            var result = prefix + seq;
            seq += 1;
            return result;
        }
    };
};
var seqer = serial_maker();
seqer.set_prefix('Q');
seqer.set_seq(1000);
var unique = seqer.gensym();
console.log(unique);

var unique2 = seqer.gensym();
console.log(unique2);

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
};
Function.method('curry', function() {
    var slice = Array.prototype.slice,
        args = slice.apply(arguments),
        that = this;
    console.log('args: ' + args);
    return function() {
        console.log('arguments: ' + slice.apply(arguments));
        console.log(args.concat(slice.apply(arguments)));
        return that.apply(null, args.concat(slice.apply(arguments)));
    };
});
var add = function(a, b) {
    return a + b;
};
var add1 = add.curry(1);
console.log(add1(2));

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

var fibaa = function(n) {
    var memo = [0, 1];
    var fib = function(n) {
        var result = memo[n];
        if(typeof result !== 'number') {
            result = fib(n - 1) + fib(n - 2);
            memo[n] = result;
        }
        return result;
    };
    return fib;
}();
console.log(fibaa(3));

var memoizer = function(memo, func) {
    var shell = function(n) {
        var result = memo[n]; 
        if(typeof result !== 'number') {
            result = func(shell, n);
            memo[n] = result;
        }
        return result;
    };
    return shell;
};

var mem = function(func) {
  var memo = {};
  return function() {
    var n = arguments[0];
    if(typeof memo[n] === 'undefined' ) {
      memo[n] = func.apply(this,[n]);
    }
    return memo[n];
  };
};
var fib = function(n) {
    if (n === 0 || n === 1) {
        return 1;         
    } else {
        return fib(n - 1) + fib(n - 2);  
    }
};console.log(fib(7));
var fibxx = mem(fib);
console.log(fibxx(7));

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

var factorial = mem(function xx(n) {
  if(n === 0 || n === 1) {
    return 1;
  } else {
    return n * xx(n-1);
  }
});


console.log(factorial(4));​

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

Object.beget = function(obj) {
    var F = function () {};
    F.prototype = obj;
    return new F();
};
Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
};
Function.method('new', function() {
    var that = Object.beget(this.prototype);
    var other = this.apply(that, arguments);
    return (typeof other === 'object' && other) || that;
});

var M = function(name) {
  this.name = name;
}

M.prototype.get_name = function() {
  return this.name;
};
M.prototype.says = function() {
  return this.saying || '';
};
var m1 = new M('m');
console.log(m1.get_name());

var Cat = function(name) {
  this.name = name;
  this.saying = 'meow';
};
Cat.prototype = new M();
//console.log(Cat.prototype);
Cat.prototype.purr = function(n) {
  var i, s = '';
  for(i = 0; i < n; i+= 1) {
    if(s) {
      s += '-';
    }
    s += 'r';
  }
  return s;
};
//console.log(Cat.prototype);
Cat.prototype.get_name = function() {
  return this.says() + ' ' + this.name+ ' ' + this.says();
};
//console.log(Cat.prototype);
var myCat = new Cat('mycat');
var says = myCat.says();
var purr = myCat.purr(5);
var name = myCat.get_name();
console.log('says: ' + says + ' ,purr: ' + purr + ' ,name: ' + name);

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

Object.beget = function(obj) {
    var F = function () {};
    F.prototype = obj;
    return new F();
};
Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
};
Function.method('new', function() {
    var that = Object.beget(this.prototype);
    var other = this.apply(that, arguments);
    return (typeof other === 'object' && other) || that;
});

var M = function(name) {
  this.name = name;
}

M.prototype.get_name = function() {
  return this.name;
};
M.prototype.says = function() {
  return this.saying || '';
};
var m1 = new M('m');
console.log(m1.get_name());

Function.method('inherits', function(Parent) {
  this.prototype = new Parent();
  return this;
});

var Cat = function(name) {
  this.name = name;
  this.saying = 'meow';
}.inherits(M)
  .method('purr', function(n) {
    var i, s = '';
    for(i = 0; i < n; i += 1) {
      if(s) {
        s += '-';
      }
      s += 'r';
    }
    return s;
  })
  .method('get_name', function() {
    return this.says() + ' ' + this.name
      + ' ' + this.says();
  });
var myCat = new Cat('mycat');
var says = myCat.says();
var purr = myCat.purr(5);
var name = myCat.get_name();
console.log('says: ' + says + ' ,purr: ' + purr + ' ,name: ' + name);

@lyuehh
Copy link
Author

lyuehh commented Oct 22, 2012

Object.beget = function(obj) {
    var F = function () {};
    F.prototype = obj;
    return new F();
};
Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
};

var M = {
  name: 'hello, M',
  get_name: function() {
    return this.name;
  },
  says: function() {
    return this.saying || '';
  }
};

var myCat = Object.beget(M);
myCat.name = 'hello, myCat';
myCat.saying = 'meow';
myCat.purr = function(n) {
  var i, s = '';
  for(i = 0; i < n; i += 1) {
    if(s) {
      s += '-';
    }
    s += 'r';
  }
  return s;
};
myCat.get_name = function() {
  return this.says() + ' ' + this.name + ' '
    + this.says();
};
console.log(myCat.get_name());```

@lyuehh
Copy link
Author

lyuehh commented Oct 23, 2012

Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
};

var m = function(spec) {
    var that = {};

    that.get_name = function() {
        return spec.name;
    };
    that.says = function() {
        return spec.saying || '';
    };

    return that;
};
var m1 = m({name: 'Herb'});
console.log(m1.get_name());

var cat = function(spec) {
    spec.saying = spec.saying || 'meow';
    var that = m(spec);
    that.purr = function(n) {
        return n + 'ss';
    };
    that.get_name = function() {
        return 'meow name: ' + spec.name;
    };
    return that;
};
var myCat = cat({name: 'Haha'});
console.log(myCat.get_name());

Object.method('super', function(name) {
    var that = this,
        method = that[name];
    return function() {
        return method.apply(that, arguments);
    };
});

var coolcat = function(spec) {
    var that = cat(spec),
        super_get_name = that.super('get_name');
    that.get_name = function(n) {
        return 'like ' + super_get_name() + ' baby';
    };
    return that;
};

var myCoolCat = coolcat({name: 'cool'});
console.log(myCoolCat.get_name());

@lyuehh
Copy link
Author

lyuehh commented Oct 23, 2012

var eventuality = function(that) {
    var registry = {};

    that.fire = function(event) {
        var array,
            func,
            handerm,
            i,
            type = typeof event === 'string' ?
                event : event.type;
        if(registry.hasOwnProperty(type)) {
            array = registry[type];
            for (i=0; i < array.length; i++) {
                handler = array[i];
                func = handler.method;
                if(typeof func === 'string') {
                    func = this[func];
                }
                func.apply(this, handler.parameters || [event]);
            }
        }
        return this;
    };
    that.on = function(type, method, parameters) {
        var handler = {
            method: method,
            parameters: parameters
        };
        if(registry.hasOwnProperty(type)) {
            registry[type].push(handler);
        } else {
            registry[type] = [handler];
        }
        return this;
    };
    return that;
};

var a = {name: 'a'};
eventuality(a);
a.on('xx', function(s) {
    // 这里的s 是fire的参数
    console.log(this.name + s);
});
// 貌似fire不能传递自定义参数
a.fire('xx');

var b = {name: 'b',age: 21};
eventuality(b);
// on 可以设置自定义参数,fire时会自动调用,但是不能在fire时修改
b.on('xx',function(s) {
    // 这里的s是默认的参数
    console.log('xx' + s.c + s.d);
},[{c: 'c', d:'d'}]);
b.fire({type: 'xx'});

@lyuehh
Copy link
Author

lyuehh commented Oct 23, 2012

var eventuality = function(that) {
    var registry = {};
    that.fire = function(event) {
        var array, func, handerm, i, type = typeof event === 'string' ? event : event.type;
        if (registry.hasOwnProperty(type)) {
            array = registry[type];
            for (i = 0; i < array.length; i++) {
                handler = array[i];
                func = handler.method;
                if (typeof func === 'string') {
                    func = this[func];
                }
                // 如果传递了自定义参数,则使用自定义参数,否则使用默认的 
                var parameters = (typeof event === 'object' && event.parameters) ? event.parameters : null;
                //console.log('param: ' + parameters);
                func.apply(this, parameters || handler.parameters);
            }
        }
        return this;
    };
    that.on = function(type, method, parameters) {
        var handler = {
            method: method,
            parameters: parameters
        };
        if (registry.hasOwnProperty(type)) {
            registry[type].push(handler);
        } else {
            registry[type] = [handler];
        }
        return this;
    };
    return that;
};
var a = {
    name: 'a'
};
eventuality(a);
a.on('xx', function(s) { 
    console.log('name: ' + this.name + ' p: ' + s.p);
},[{p: 'default'}]);
a.fire({type: 'xx', parameters: [{p: 'new'}]});
a.fire('xx');

@lyuehh
Copy link
Author

lyuehh commented Oct 23, 2012

Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
};

Array.method('reduce', function(f, value) {
    for (var i = 0; i < this.length; i++) {
        value = f(this[i], value);
    };
    return value;
});

var add = function(a, b) {
    return a + b;
};
var mult = function(a, b) {
    return a * b;
};

var data = [1, 2, 3, 4, 5];
var sum = data.reduce(add, 0);
var mult = data.reduce(mult, 1);
console.log('sum: ' + sum);
console.log('mult: ' + mult);

data.total = function() {
    return this.reduce(add, 0);
};
console.log('total: ' + data.total());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment