Add CoffeeScript convenience methods

Adds a number of convenience methods from CoffeeScript to aid in converting
modules to plain Javascript.
This commit is contained in:
Andrew Stewart 2014-02-25 09:34:51 -08:00
parent 0fb3d27a0d
commit 08c7da93bc
2 changed files with 103 additions and 0 deletions

40
dist/utils.js vendored
View File

@ -32,6 +32,46 @@
return _results;
};
global.slice = [].slice;
global.hasProp = {}.hasOwnProperty;
global.subclass = function(child, parent) {
var ctor, key;
for (key in parent) {
if (hasProp.call(parent, key)) {
child[key] = parent[key];
}
}
ctor = function() {
return this.constructor = child;
};
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
global.instantiate = function(func, args, ctor) {
var child, result;
ctor.prototype = func.prototype;
child = new ctor();
result = func.apply(child, args);
if (Object(result) === result) {
return result;
} else {
return child;
}
};
global.getArgs = function(args) {
if (args.length >= 1) {
return slice.call(args, 0);
} else {
return [];
}
};
global.proxyFunctionsToObject = function(methods, target, base, force) {
var method, _fn, _i, _len;
if (base == null) {

View File

@ -55,6 +55,69 @@ global.sleep = (ms) ->
while (Date.now() < start + ms)
i = 1
global.slice = [].slice
global.hasProp = {}.hasOwnProperty
# Public: Function to use for class inheritance. Copy of a CoffeeScript helper
# function.
#
# Example
#
# var Sphero = (function(klass) {
# subclass(Sphero, klass);
# // Sphero is now a subclass of Parent, and can access it's methods through
# // Sphero.__super__
# })(Parent);
#
# Returns subclass
global.subclass = (child, parent) ->
for key of parent
child[key] = parent[key] if hasProp.call(parent, key)
ctor = -> @constructor = child
ctor.prototype = parent.prototype
child.prototype = new ctor()
child.__super__ = parent.prototype
child
# Public: Function for instantiating a class with all passed arguments to
# a function
#
# Example
#
# createNewThing = function() {
# var args = getArgs(arguments);
# return instantiate(ClassToMake, args, function(){});
# }
#
# Returns an instance of the new class
global.instantiate = (func, args, ctor) ->
ctor.prototype = func.prototype
child = new ctor()
result = func.apply(child, args)
(if Object(result) is result then result else child)
# Public: Function for obtaining array of function arguments. Copied from
# a CoffeeScript utility function.
#
# Example
#
# printArgs = function() {
# console.log(getArgs(arguments));
# }
#
# printArgs();
# //=> []
#
# printArgs('hello', 'world', 3);
# //=> ['hello', 'world', 3]
#
# Returns an array of args
global.getArgs = (args) ->
if args.length >= 1 then slice.call(args, 0) else []
# Public: Proxies a list of methods from one object to another. It will not
# overwrite existing methods unless told to.
#