Utilities for javascript, optimized for the server environment.
Property | Type | Default Value | Description |
bindAll | property | hitchAll | Binds all methods or a specified array of function to the scope of the object |
define | property | define | Defines a new class to be used Class methods
|
singleton | property | singleton | Defines a singleton instance of a Class. See define |
Binds a method to the scope of the first argument.
This is useful if you have async actions and you just want to run a method or retrieve a property on the object.
var arr = [], push = comb.applyFirst("push"), length = comb.applyFirst("length");
push(arr, 1, 2,3,4);
console.log(length(arr)); //4
console.log(arr); //1,2,3,4
Arguments
the method to invoke in the scope of the first arument.
optional args to pass to the callback
Function
a function that will execute the method in the scope of the first argument.
function (method,args){ args = Array.prototype.slice.call(arguments).slice(1); if (!isString(method) && !isFunction(method)) { throw new Error(method + " must be the name of a property or function to execute"); } if (isString(method)) { return function () { var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift(); var func = scope[method]; if (isFunction(func)) { scopeArgs = args.concat(scopeArgs); return spreadArgs(func, scopeArgs, scope); } else { return func; } }; } else { return function () { var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift(); scopeArgs = args.concat(scopeArgs); return spreadArgs(method, scopeArgs, scope); }; } }
Converts an arguments object to an array
Examplefunction test(){ return comb.argsToArray(arguments); } function testSlice(){ return comb.argsToArray(arguments, 3); } console.log(test(1,2,3)); //[1,2,3] console.log(test(1,2,3,4,5,6)); //[4,5,6]Arguments
the arguments object to convert
0
] : the number of arguments to slice.
Array
array version of the arguments object
function (args,slice){ slice = slice || 0; return arraySlice.call(args, slice); }
Object
: the scope to bind the callback to
String|Function
: the method to callback
optional args to pass to the callback
Function
the hitched function
hitch
Object
: the scope to bind the callback to
String|Function
: the method to callback
optional args to pass to the callback
Function
the hitched function
hitchIgnore
Broadcasts an event to all listeners NOTE : the function takes a variable number of arguments i.e. all arguments after the topic will be passed to the listeners
Examplecomb.broadcast("hello", "hello world"); //the args "hello" and "world" will be passed to any listener of the topic //"hello" comb.broadcast("hello", "hello", "world");Arguments
String
: the topic to brodcast
the information to bradcast
function (){ var args = Array.prototype.slice.call(arguments); var topic = args.splice(0, 1)[0]; if (topic) { var list = listeners[topic]; if (list) { for (var i = list.length - 1; i >= 0; i--) { var han = list[i], cb = han.cb; if (cb) { cb.apply(this, args); } } } } }
Converts a string to camelcase
Examplecomb.camelize('hello_world') => helloWorld comb.camelize('column_name') => columnName comb.camelize('columnName') => columnName comb.camelize(null) => null comb.camelize() => undefinedArguments
the string to camelize
String
the camelized version of the string
function (str){ var ret = str; if (!misc.isUndefinedOrNull(str)) { ret = str.replace(CAMELIZE_CONVERT_REGEXP, function (a, b) { return b.toUpperCase(); }); } return ret; }
Works just like comb.Promise#chain method, allowing you to propogate results from one funciton to another. This is different than comb.serial in that it propogates results from one promise to the next, where comb.serial does not.
Examplefunction asyncAction(add, timeout) { return function (num) { num = num || 0; var ret = new comb.Promise(); setTimeout(function () { ret.callback(num + add); }, timeout); return ret; } } comb.chain([ asyncAction(1, 100), asyncAction(2, 100), asyncAction(3, 100), asyncAction(4, 100), asyncAction(5, 100), ]).then(function(results){ console.log(results); //15 });Arguments
an array of function to call.
comb.Promise
a promise that will resolve with the results of the last function in the list.
function (list){ if (base.isArray(list)) { return callNext(list, [], true); } else { throw new Error("When calling comb.serial the first argument must be an array"); } }
Singularizes and camelizes the string. Also strips out all characters preceding and including a period (".").
Examplecomb.classify('egg_and_hams') => "eggAndHam" comb.classify('post') => "post" comb.classify('schema.post') => "post"Arguments
the string to classify
String
the classified version of the string
function (str){ var ret = str; if (!misc.isUndefinedOrNull(str)) { ret = comb.camelize(comb.singularize(str.replace(/.*\./g, ''))); } return ret; }
Function to listen when other functions are called
Examplecomb.connect(obj, "event", myfunc); comb.connect(obj, "event", "log", console);Arguments
the object in which the method you are connecting to resides
the name of the method to connect to
the function to callback
the scope to call the specified cb in
Array
handle to pass to comb.disconnect
function (obj,method,cb,scope){ var index, listeners; if (typeof method !== "string") { throw new Error("When calling connect the method must be string"); } if (!func.isFunction(cb)) { throw new Error("When calling connect callback must be a string"); } scope = obj || global; if (typeof scope[method] === "function") { listeners = scope[method].__listeners; if (!listeners) { var newMethod = wrapper(); newMethod.func = obj[method]; listeners = (newMethod.__listeners = []); scope[method] = newMethod; } index = listeners.push(cb); } else { throw new Error("unknow method " + method + " in object " + obj); } return [obj, method, index]; }
Curries a function
Examplevar curried = comb.curry(4, function(a,b,c,d){ return [a,b,c,d].join(","); } curried("a"); curried("b"); curried("c"); curried("d") => "a,b,c,d" //OR curried("a")("b")("c")("d") => "a,b,c,d"Arguments
the number of args you expect
the function to call once all args are gathered
what scope to call the function in
Function
the curried version of the function
function (depth,cb,scope){ var f; if (scope) { f = hitch(scope, cb); } else { f = cb; } if (depth) { var len = depth - 1; for (var i = len; i >= 0; i--) { f = curryFunc(f, i === len); } } return f; }
Subtracts the specified day/s from the current date.
Argumentsthe number of days to subtract
Date
a date with the number of days subtracted
function (val){ return date.add(new Date(), "days", -val); }
Adds the specified day/s to the current date.
Argumentsthe number of days to add
Date
a date with the number of days added
function (val){ return date.add(new Date(), "days", val); }
Determines if two things are deep equal.
Examplecomb.deepEqual({a : 1, b : 2}, {a : 1, b : 2}) => true comb.deepEqual({a : 1}, {a : 1, b : 2}) => falseArguments
the first thing to compare
the second thing to compare
Boolean
function (o1,o2){ return _deepEqual(o1, o2); }
Merges objects together only overriding properties that are different. NOTE: this function takes a variable number of objects to merge
Examplevar myObj = {my : {cool : {property1 : 1, property2 : 2}}}; comb.deepMerge(myObj, {my : {cool : {property3 : 3}}}); myObj.my.cool.property1 => 1 myObj.my.cool.property2 => 2 myObj.my.cool.property3 => 3Arguments
the object to merge into
variable number of objects to merge into the obj
Object
the merged object
function (obj,props){ if (!obj) { obj = {}; } for (var i = 1, l = arguments.length; i < l; i++) { deepMerge(obj, arguments[i]); } return obj; // Object }
Disconnects a listener to a function
Argumentshandle
: handle returned from comb.connect
function (handle){ if (handle && handle.length === 3) { var obj = handle[0], method = handle[1], cb = handle[2]; if (typeof method !== "string") { throw "comb.disconnect : When calling disconnect the method must be string"; } var scope = obj || global, ls; if (typeof scope[method] === "function") { ls = scope[method].__listeners; if (ls && cb-- > 0) { //we dont want to splice it because our indexing will get off ls[cb] = null; } } else { throw new Error("unknown method " + method + " in object " + obj); } } else { throw new Error("comb.disconnect : invalid handle"); } }
Extends the prototype of an object if it exists otherwise it extends the object.
Examplevar MyObj = function(){}; MyObj.prototype.test = true; comb.extend(MyObj, {test2 : false, test3 : "hello", test4 : "world"}); var myObj = new MyObj(); myObj.test => true myObj.test2 => false myObj.test3 => "hello" myObj.test4 => "world" var myObj2 = {}; myObj2.test = true; comb.extend(myObj2, {test2 : false, test3 : "hello", test4 : "world"}); myObj2.test => true myObj2.test2 => false myObj2.test3 => "hello" myObj2.test4 => "world"Arguments
the parent object to extend
Object
: the extension object to mixin to the parent
Object
returns the extended object
function (parent,ext){ var proto = parent.prototype || parent; merge(proto, ext); return parent; }
Binds a method to a particular scope
Argumentsthe scope to bind the callback to
the method to callback
optional args to pass to the callback
Function
the hitched function
function (scope,method,args){ args = Array.prototype.slice.call(arguments).slice(2); if ((isString(method) && !(method in scope))) { throw new Error(method + " property not defined in scope"); } else if (!isString(method) && !isFunction(method)) { throw new Error(method + " is not a function"); } if (isString(method)) { return function () { var func = scope[method]; if (isFunction(func)) { var scopeArgs = args.concat(Array.prototype.slice.call(arguments)); return spreadArgs(func, scopeArgs, scope); } else { return func; } }; } else { return function () { var scopeArgs = args.concat(Array.prototype.slice.call(arguments)); return spreadArgs(method, scopeArgs, scope); }; } }
Binds all methods or a specified array of function to the scope of the object
Examplevar f = { a: function(){ return "a"; }, b: function(){ return "b"; } } comb.hitchAll(f, "a", "b"); //or comb.hitchAll(f);Arguments
the object to bind methods on
...
: varargs of methods to bind
Object
the originally scoped object.
function (scope){ var funcs = Array.prototype.slice.call(arguments, 1); if (!isObject(scope) && !isFunction(scope)) { throw new TypeError("scope must be an object"); } if (funcs.length === 1 && isArray(funcs[0])) { funcs = funcs[0]; } if (!funcs.length) { funcs = []; for (var k in scope) { if (scope.hasOwnProperty(k) && isFunction(scope[k])) { funcs.push(k); } } } for (var i = 0, l = funcs.length; i < l; i++) { scope[funcs[i]] = hitch(scope, scope[funcs[i]]); } return scope; }
Binds a method to a particular scope ignoring any new arguments passed into the function. This is useful if you want to force particular arguments and ignore any new ones
Argumentsthe scope to bind the callback to
the method to callback
optional args to pass to the callback
Function
the hitched function
function (scope,method,args){ args = Array.prototype.slice.call(arguments).slice(2); if ((isString(method) && !(method in scope))) { throw new Error(method + " property not defined in scope"); } else if (!isString(method) && !isFunction(method)) { throw new Error(method + " is not a function"); } if (isString(method)) { return function () { var func = scope[method]; if (isFunction(func)) { return spreadArgs(func, args, scope); } else { return func; } }; } else { return function () { return spreadArgs(method, args, scope); }; } }
Subtracts the specified hour/s from the current date.
Argumentsthe number of hours to subtract
Date
a date with the number of hours subtracted
function (val){ return date.add(new Date(), "hours", -val); }
Adds the specified hour/s to the current date.
Argumentsthe number of hours to add
Date
a date with the number of hours added
function (val){ return date.add(new Date(), "hours", val); }
Determines if obj is an Arguments object;
ArgumentsAnything
: the thing to test if it is null
Boolean
true if it is an Arguments Object false otherwise
function (object){ return !isUndefinedOrNull(object) && Object.prototype.toString.call(object) === '[object Arguments]'; }
Determines if obj is a boolean
Argumentsthe thing to test if it is a boolean
Boolean
true if it is a boolean false otherwise
function (obj){ var undef, type = typeof obj; return obj !== undef && type === "boolean" || type === "Boolean"; }
Determines if obj is a Date
Argumentsthe thing to test if it is a Date
Boolean
true if it is a Date false otherwise
function (obj){ var undef; return (obj !== undef && typeof obj === "object" && obj instanceof Date); }
Determins if the obj is not undefined
Argumentsthe thing to test if it is not undefined
Boolean
true if it is defined false otherwise
function (obj){ return !isUndefined(obj); }
Determines if an object is empty
Examplecomb.isEmpty({}) => true comb.isEmpty({a : 1}) => falseArguments
the object to test
Boolean
true if the object is empty;
function (object){ if (comb.isObject(object)) { for (var i in object) { if (object.hasOwnProperty(i)) { return false; } } } return true; }
Determines if something is a function
Argumentsthe thing to test if it is a function
Boolean
true if the obj is a function false otherwise
function (obj){ return typeof obj === "function"; }
Determines if an object is just a hash and not a qualified Object such as Number
Examplecomb.isHash({}) => true comb.isHash({1 : 2, a : "b"}) => true comb.isHash(new Date()) => false comb.isHash(new String()) => false comb.isHash(new Number()) => false comb.isHash(new Boolean()) => false comb.isHash() => false comb.isHash("") => false comb.isHash(1) => false comb.isHash(false) => false comb.isHash(true) => falseArguments
the thing to test if it is a hash
Boolean
true if it is a hash false otherwise
function (obj){ var ret = comb.isObject(obj); return ret && obj.constructor === Object; }
Determines if obj is an instance of a particular class
Argumentsthe thing to test if it and instance of a class
Object
: used to determine if the object is an instance of
Boolean
true if it is an instance of the clazz false otherwise
function (obj,clazz){ return argsToArray(arguments, 1).some(function (c) { return isInstance(obj, c); }); }
Determines if obj is null
Argumentsthe thing to test if it is null
Boolean
true if it is null false otherwise
function (obj){ var undef; return obj !== undef && obj == null; }
Determines if obj is a number
Argumentsthe thing to test if it is a Number
Boolean
true if it is a number false otherwise
function (obj){ var undef; return obj !== undef && obj != null && (typeof obj === "number" || obj instanceof Number); }
Determines if obj is an object
Argumentsthe thing to test if it is an object
Boolean
true if it is an object false otherwise
function (obj){ var undef; return obj !== null && obj !== undef && typeof obj === "object"; }
Tests if an object is like a promise (i.e. it contains then, addCallback, addErrback)
Argumentsobject to test
function (obj){ return isObject(obj, Promise) && typeof obj.then === "function"; }
Tests if something is a regular expression.
Examplecomb.isRegExp(/hello/); //true comb.isRegExp("hello"); //falseArguments
the thing to test.
Boolean
function (obj){ var undef; return obj !== undef && obj != null && (obj instanceof RegExp); }
Tests if something is a string.
Examplecomb.isString("true") //true comb.isString(true) //falseArguments
the thing to test
Boolean
returns true if the argument is a string.
function (obj){ return toStr.call(obj) === '[object String]'; }
Determines if obj is undefined
Argumentsthe thing to test if it is undefined
Boolean
true if it is undefined false otherwise
function (obj){ var undef; return obj !== null && obj === undef; }
Determines if obj is undefined or null
Argumentsthe thing to test if it is undefined or null
Boolean
true if it is undefined or null false otherwise
function (obj){ return isUndefined(obj) || isNull(obj); }
Listen for the broadcast of certain events
Examplecomb.listen("hello", function(arg1, arg2){ console.log(arg1); console.log(arg2); });Arguments
the topic to listen for
the funciton to call when the topic is published
a handle to pass to comb.unListen
function (topic,callback){ if (!func.isFunction(callback)) { throw new Error("callback must be a function"); } var handle = { topic: topic, cb: callback, pos: null }; var list = listeners[topic]; if (!list) { list = (listeners[topic] = []); } list.push(handle); handle.pos = list.length - 1; return handle; }
Adds listeners to process.exit without having to change setMaxListeners useful if you are writing a library and do not want to change core setting.
Argumentsfunciton to call when process is exiting
function (cb){ setupListener(); listeners.push(cb); }
Merges objects together NOTE: this function takes a variable number of objects to merge
Examplevar myObj = {}; comb.merge(myObj, {test : true}); myObj.test => true comb.merge(myObj, {test : false}, {test2 : false}, {test3 : "hello", test4 : "world"}); myObj.test => false myObj.test2 => false myObj.test3 => "hello" myObj.test4 => "world"Arguments
the object to merge into
variable number of objects to merge into the obj
Object
the merged object
function (obj,props){ if (!obj) { obj = {}; } for (var i = 1, l = arguments.length; i < l; i++) { merge(obj, arguments[i]); } return obj; // Object }
Subtracts the specified minute/s from the current date.
Argumentsthe number of minutes to subtract
Date
a date with the number of minutes subtracted
function (val){ return date.add(new Date(), "minutes", -val); }
Adds the specified minute/s to the current date.
Argumentsthe number of minutes to add
Date
a date with the number of minutes added
function (val){ return date.add(new Date(), "minutes", val); }
Subtracts the specified month/s from the current date.
Argumentsthe number of months to subtract
Date
a date with the number of months subtracted
function (val){ return date.add(new Date(), "months", -val); }
Adds the specified month/s to the current date.
Example//assuming that current month is february comb.yearsFromNow(2); //yyyy-04-dd hh:MM:ssArguments
the number of months to add
Date
a date with the number of years added
function (val){ return date.add(new Date(), "months", val); }
Allows the passing of additional arguments to a function when it is called especially useful for callbacks that you want to provide additional parameters to
Argumentsthe method to callback
variable number of arguments to pass
Function
partially hitched function
function (method,args){ args = Array.prototype.slice.call(arguments).slice(1); if (!isString(method) && !isFunction(method)) { throw new Error(method + " must be the name of a property or function to execute"); } if (isString(method)) { return function () { var func = this[method]; if (isFunction(func)) { var scopeArgs = args.concat(Array.prototype.slice.call(arguments)); return spreadArgs(func, scopeArgs, this); } else { return func; } }; } else { return function () { var scopeArgs = args.concat(Array.prototype.slice.call(arguments)); return spreadArgs(method, scopeArgs, this); }; } }
Returns the plural form of the word in the string.
Examplecomb.pluralize("post") => "posts" comb.pluralize("octopus") => "octopi" comb.pluralize("sheep") => "sheep" comb.pluralize("words") => "words" comb.pluralize("the blue mailman") => "the blue mailmen" comb.pluralize("CamelOctopus") => "CamelOctopi"Arguments
the string to pluralize
String
the pluralized version of the string
function (str){ var ret = str; if (!misc.isUndefinedOrNull(str)) { if (UNCOUNTABLES.indexOf(str) === -1) { for (var i in PLURALS) { var s = PLURALS[i], rule = s[0], replacement = s[1]; if ((ret = ret.replace(rule, replacement)) !== str) { break; } } } } return ret; }
Wraps a stream in a promise waiting for either the "end"
or "error"
event to be triggered.
comb.promisfyStream(fs.createdReadStream("my.file")).chain(function(){
console.log("done reading!");
});
Arguments
stream to wrap
comb.Promise
a Promise is resolved if "end"
is triggered before "error"
or rejected if "error"
is triggered.
function (stream){ var ret = new Promise(), called; function errorHandler() { if (!called) { called = true; spreadArgs(ret.errback, arguments, ret); stream.removeListener("error", endHandler); stream.removeListener("end", endHandler); stream = ret = null; } } function endHandler() { if (!called) { called = true; spreadArgs(ret.callback, arguments, ret); stream.removeListener("error", endHandler); stream.removeListener("end", endHandler); stream = ret = null; } } stream.on("error", errorHandler).on("end", endHandler); return ret.promise(); }
Creates a new comb.Promise that is rejected with the given value.
comb.resolved(new Error("error!")).chain(null, function(err){
console.error(err.stack);
});
If you give it a promise it will wait for the promise to resolve or error but with reject either way.
comb.resolved(new comb.Promise().callback(1)).chain(null, function(err){
//err === 1
});
Arguments
comb.Promise
a rejected promise with the specified value.
function (val){ var ret = new Promise(); when(val).chain(ret.errback, ret.errback); return ret.promise(); }
Creates a new comb.Promise that is resolved with the given value.
comb.resolved(1).chain(function(val){
//val === 1
});
If you give it a promise it will wait for the promise to resolve or error.
comb.resolved(new comb.Promise().callback(1)).chain(function(val){
//val === 1
});
Arguments
comb.Promise
a promisfied version of the value.
function (val){ var ret = new Promise(); when(val).chain(ret.callback, ret.errback); return ret.promise(); }
Subtracts the specified second/s from the current date.
Argumentsthe number of seconds to subtract
Date
a date with the number of seconds subtracted
function (val){ return date.add(new Date(), "seconds", -val); }
Adds the specified second/s to the current date.
Argumentsthe number of seconds to add
Date
a date with the number of seconds added
function (val){ return date.add(new Date(), "seconds", val); }
Executes a list of items in a serial manner. If the list contains promises then each promise will be executed in a serial manner, if the list contains non async items then the next item in the list is called.
Examplevar asyncAction = function(item, timeout){ var ret = new comb.Promise(); setTimeout(comb.hitchIgnore(ret, "callback", item), timeout); return ret.promise(); }; comb.serial([ comb.partial(asyncAction, 1, 1000), comb.partial(asyncAction, 2, 900), comb.partial(asyncAction, 3, 800), comb.partial(asyncAction, 4, 700), comb.partial(asyncAction, 5, 600), comb.partial(asyncAction, 6, 500) ]).then(function(results){ console.log(results); // [1,2,3,4,5,6]; });Arguments
function (list,callback,errback){ if (base.isArray(list)) { return callNext(list, [], false); } else { throw new Error("When calling comb.serial the first argument must be an array"); } }
The reverse of pluralize, returns the singular form of a word in a string.
Examplecomb.singularize("posts") => "post" comb.singularize("octopi")=> "octopus" comb.singularize("sheep") => "sheep" comb.singularize("word") => "word" comb.singularize("the blue mailmen") => "the blue mailman" comb.singularize("CamelOctopi") => "CamelOctopus"Arguments
the string to singularize
String
the singularized version of the string
function (str){ var ret = str; if (!misc.isUndefinedOrNull(str)) { if (UNCOUNTABLES.indexOf(str) === -1) { for (var i in SINGULARS) { var s = SINGULARS[i], rule = s[0], replacement = s[1]; if ((ret = ret.replace(rule, replacement)) !== str) { break; } } } } return ret; }
Disconnects a listener
Argumentsa handle returned from comb.listen
function (handle){ if (handle) { var topic = handle.topic, list = listeners[topic]; if (list) { for (var i = list.length - 1; i >= 0; i--) { if (list[i] === handle) { list.splice(i, 1); } } if (!list.length) { delete listeners[topic]; } } } }
The reverse of camelize. Makes an underscored form from the expression in the string.
Examplecomb.underscore('helloWorld') => hello_world comb.underscore('column_name') => column_name comb.underscore('columnName') => column_name comb.underscore(null) => null comb.underscore() => undefinedArguments
The string to underscore
String
the underscored version of the string
function (str){ var ret = str; if (!misc.isUndefinedOrNull(str)) { ret = str.replace(UNDERSCORE_CONVERT_REGEXP1, UNDERSCORE_CONVERT_REPLACE) .replace(UNDERSCORE_CONVERT_REGEXP2, UNDERSCORE_CONVERT_REPLACE) .replace(DASH, UNDERSCORE).toLowerCase(); } return ret; }
Ensures that a promise is resolved before a the function can be run.
For example suppose you have to ensure that you are connected to a database before you execute a function.
var findUser = comb.wait(connect(), function findUser(id){
//this wont execute until we are connected
return User.findById(id);
});
comb.when(findUser(1), findUser(2)).then(function(users){
var user1 = users[0], user2 = users[1];
});
Arguments
variable number of arguments to wait on. See comb.when.
function that will wait.
Function
a function that will wait on the args to resolve.
function (args,fn){ var resolved = false; args = argsToArray(arguments); fn = args.pop(); var p = when(args); return function waiter() { if (!resolved) { var args = arguments; return p.chain(function () { resolved = true; p = null; return fn.apply(this, args); }.bind(this)); } else { return when(fn.apply(this, arguments)); } }; }
Subtracts the specified weekday/s from the current date.
Argumentsthe number of weekdays to subtract
Date
a date with the number of weekdays subtracted
function (val){ return date.add(new Date(), "weekdays", -val); }
Adds the specified weekday/s to the current date.
Argumentsthe number of weekdays to add
Date
a date with the number of weekdays added
function (val){ return date.add(new Date(), "weekdays", val); }
Waits for promise and non promise values to resolve and fires callback or errback appropriately. If you pass in an array of promises then it will wait for all promises in the list to resolve.
Examplevar a = "hello"; var b = new comb.Promise().callback(world); comb.when(a, b) => called back with ["hello", "world"];Arguments
variable number of arguments to wait for.
the callback function
the errback function
comb.Promise
a promise that is fired when all values have resolved
function (args,cb,eb){ var p; args = argsToArray(arguments); eb = base.isFunction(args[args.length - 1]) ? args.pop() : null; cb = base.isFunction(args[args.length - 1]) ? args.pop() : null; if (eb && !cb) { cb = eb; eb = null; } if (!args.length) { p = new Promise().callback(args); } else if (args.length === 1) { args = args.pop(); if (isPromiseLike(args)) { p = args; } else if (isArray(args) && array.every(args, isPromiseLike)) { p = new PromiseList(args, true); } else { p = new Promise().callback(args); } } else { p = new PromiseList(args.map(function (a) { return isPromiseLike(a) ? a : new Promise().callback(a); }), true); } if (cb) { p.addCallback(cb); } if (eb) { p.addErrback(eb); } return p.promise(); }
Wraps traditional node style functions with a promise.
Examplevar fs = require("fs"); var readFile = comb.wrap(fs.readFile, fs); readFile(__dirname + "/test.json").then( function(buffer){ console.log(contents); }, function(err){ } console.error(err); );Arguments
function to wrap
scope to call the function in
Funciton
a wrapped function
function (fn,scope){ return function () { var ret = new Promise(); var args = argsToArray(arguments); args.push(ret.resolve.bind(ret)); fn.apply(scope || this, args); return ret.promise(); }; }
Subtracts the specified year/s from the current date.
Argumentsthe number of years to subtract
Date
a date with the number of years subtracted
function (val){ return date.add(new Date(), "years", -val); }
Adds the specified year/s to the current date.
Example//assuming that current year is 2012 comb.yearsFromNow(1); //2013-mm-dd hh:MM:ssArguments
the number of years to add
Date
a date with the number of years added
function (val){ return date.add(new Date(), "years", val); }
MIT https://github.com/C2FO/comb/raw/master/LICENSE
git clone git://github.com/C2FO/comb.git