diff --git a/lib/cylon.js b/lib/cylon.js index 76a3b5e..a1cf22f 100644 --- a/lib/cylon.js +++ b/lib/cylon.js @@ -6,262 +6,222 @@ * Licensed under the Apache 2.0 license. */ +"use strict"; -(function() { - 'use strict'; - var Cylon, - __slice = [].slice, - __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; - require('./config'); +require('./config'); +require('./utils'); +require('./logger'); +require('./driver'); +require('./adaptor'); - require('./utils'); +Logger.setup(); - require('./logger'); +// Cylon is the global namespace for the project, and also in charge of +// maintaining the Master singleton that controls all the robots. +var Cylon = (function() { + function Cylon() {} - require('./driver'); + var instance = null; - require('./adaptor'); - Logger.setup(); + // Public: Fetches singleton instance of Master, or creates a new one if it + // doesn't already exist + // + // Returns a Master instance + Cylon.getInstance = function() { + return new Master(); + }; - // Cylon is the global namespace for the project, and also in charge of - // maintaining the Master singleton that controls all the robots. - Cylon = (function() { - var Master, instance; + var bind = function(fn, me) { + return function() { return fn.apply(me, arguments); } + } - function Cylon() {} + // The Master class is our puppeteer that manages all the robots, as well as + // starting them and the API. + var Master = (function() { + var robots = [], + api = null, + api_config = { host: '127.0.0.1', port: '3000' }; - instance = null; - - // Public: Fetches singleton instance of Master, or creates a new one if it - // doesn't already exist + // Public: Creates a new Master // // Returns a Master instance - Cylon.getInstance = function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return instance != null ? instance : instance = (function(func, args, ctor) { - ctor.prototype = func.prototype; - var child = new ctor, result = func.apply(child, args); - return Object(result) === result ? result : child; - })(Master, args, function(){}); - }; + function Master() { + this.robot = bind(this.robot, this); - // The Master class is our puppeteer that manages all the robots, as well as - // starting them and the API. - Master = (function() { - var api, api_config, robots; + this.self = this; - robots = []; + if (process.platform === "win32") { + var readline = require("readline"); - api = null; - - api_config = { - host: '127.0.0.1', - port: '3000' - }; - - // Public: Creates a new Master - // - // Returns a Master instance - function Master() { - this.robot = __bind(this.robot, this); - var readLine, rl; - this.self = this; - if (process.platform === "win32") { - readLine = require("readline"); - rl = readLine.createInterface({ - input: process.stdin, - output: process.stdout - }); - rl.on("SIGINT", function() { - return process.emit("SIGINT"); - }); - } - process.on("SIGINT", function() { - Cylon.getInstance().stop(); - return process.kill(); + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout }); + + rl.on("SIGINT", function() { return process.emit("SIGINT"); }); } - // Public: Creates a new Robot - // - // opts - hash of Robot attributes - // - // Returns a shiny new Robot - // Examples: - // Cylon.robot - // connection: { name: 'arduino', adaptor: 'firmata' } - // device: { name: 'led', driver: 'led', pin: 13 } - // - // work: (me) -> - // me.led.toggle() - Master.prototype.robot = function(opts) { - var Robot, robot; - Robot = require("./robot"); - opts.master = this; - robot = new Robot(opts); - robots.push(robot); - return robot; - }; + process.on("SIGINT", function() { + Cylon.getInstance().stop(); + process.kill(); + }); + } - // Public: Returns all Robots the Master knows about - // - // Returns an array of all Robot instances - Master.prototype.robots = function() { - return robots; - }; + // Public: Creates a new Robot + // + // opts - hash of Robot attributes + // + // Returns a shiny new Robot + // Examples: + // Cylon.robot + // connection: { name: 'arduino', adaptor: 'firmata' } + // device: { name: 'led', driver: 'led', pin: 13 } + // + // work: (me) -> + // me.led.toggle() + Master.prototype.robot = function(opts) { + var Robot = require("./robot"); + opts.master = this; - // Public: Configures the API host and port based on passed options - // - // opts - object containing API options - // host - host address API should serve from - // port - port API should listen for requests on - // - // Returns the API configuration - Master.prototype.api = function(opts) { - if (opts == null) { - opts = {}; + var robot = new Robot(opts); + + robots.push(robot); + return robot; + }; + + // Public: Returns all Robots the Master knows about + // + // Returns an array of all Robot instances + Master.prototype.robots = function() { + return robots; + }; + + // Public: Configures the API host and port based on passed options + // + // opts - object containing API options + // host - host address API should serve from + // port - port API should listen for requests on + // + // Returns the API configuration + Master.prototype.api = function(opts) { + if (opts == null) { opts = {}; } + + api_config.host = opts.host || "127.0.0.1"; + api_config.port = opts.port || "3000"; + + return api_config; + }; + + // Public: Finds a particular robot by name + // + // name - name of the robot to find + // callback - optional callback to be executed + // + // Returns the found Robot or result of the callback if it's supplied + Master.prototype.findRobot = function(name, callback) { + var error, + robot = null; + + for (var i = 0; i < robots.length; i++) { + var bot = robots[i]; + if (bot.name === name) { robot = bot; } + } + + if (robot == null) { + error = { error: "No Robot found with the name " + name }; + } + + return callback ? callback(error, robot) : robot; + }; + + // Public: Finds a particular Robot's device by name + // + // robotid - name of the robot to find + // deviceid - name of the device to find + // callback - optional callback to be executed + // + // Returns the found Device or result of the callback if it's supplied + Master.prototype.findRobotDevice = function(robotid, deviceid, callback) { + return this.findRobot(robotid, function(err, robot) { + var error, + device = null; + + if (err) { return callback(err, robot); } + + if (robot.devices[deviceid]) { device = robot.devices[deviceid]; } + + if (device == null) { + error = { error: "No device found with the name " + deviceid + "." }; } - api_config.host = opts.host || "127.0.0.1"; - api_config.port = opts.port || "3000"; - return api_config; - }; - // Public: Finds a particular robot by name - // - // name - name of the robot to find - // callback - optional callback to be executed - // - // Returns the found Robot or result of the callback if it's supplied - Master.prototype.findRobot = function(name, callback) { - var bot, error, robot, _i, _len; - robot = null; - for (_i = 0, _len = robots.length; _i < _len; _i++) { - bot = robots[_i]; - if (bot.name === name) { - robot = bot; - } + return callback ? callback(error, device) : device; + }); + }; + + // Public: Finds a particular Robot's connection by name + // + // robotid - name of the robot to find + // connid - name of the device to find + // callback - optional callback to be executed + // + // Returns the found Connection or result of the callback if it's supplied + Master.prototype.findRobotConnection = function(robotid, connid, callback) { + return this.findRobot(robotid, function(err, robot) { + var error, + connection = null; + + if (err) { return callback(err, robot); } + + if (robot.connections[connid]) { connection = robot.connections[connid]; } + + if (connection == null) { + error = { error: "No connection found with the name " + connid + "." }; } - if (robot == null) { - error = { - error: "No Robot found with the name " + name - }; - } - if (callback) { - return callback(error, robot); - } else { - return robot; - } - }; - // Public: Finds a particular Robot's device by name - // - // robotid - name of the robot to find - // deviceid - name of the device to find - // callback - optional callback to be executed - // - // Returns the found Device or result of the callback if it's supplied - Master.prototype.findRobotDevice = function(robotid, deviceid, callback) { - return this.findRobot(robotid, function(err, robot) { - var device, error; - if (err) { - callback(err, robot); - } - device = null; - if (robot.devices[deviceid]) { - device = robot.devices[deviceid]; - } - if (device == null) { - error = { - error: "No device found with the name " + deviceid + "." - }; - } - if (callback) { - return callback(error, device); - } else { - return device; - } - }); - }; + return callback ? callback(error, connection) : connection; + }); + }; - // Public: Finds a particular Robot's connection by name - // - // robotid - name of the robot to find - // connid - name of the device to find - // callback - optional callback to be executed - // - // Returns the found Connection or result of the callback if it's supplied - Master.prototype.findRobotConnection = function(robotid, connid, callback) { - return this.findRobot(robotid, function(err, robot) { - var connection, error; - if (err) { - callback(err, robot); - } - connection = null; - if (robot.connections[connid]) { - connection = robot.connections[connid]; - } - if (connection == null) { - error = { - error: "No connection found with the name " + connid + "." - }; - } - if (callback) { - return callback(error, connection); - } else { - return connection; - } - }); - }; + // Public: Starts up the API and the robots + // + // Returns nothing + Master.prototype.start = function() { + this.startAPI(); - // Public: Starts up the API and the robots - // - // Returns nothing - Master.prototype.start = function() { - var robot, _i, _len, _results; - this.startAPI(); - _results = []; - for (_i = 0, _len = robots.length; _i < _len; _i++) { - robot = robots[_i]; - _results.push(robot.start()); - } - return _results; - }; + for (var i = 0; i < robots.length; i++) { + var robot = robots[i]; + robot.start(); + } + }; - // Public: Stops the API and the robots - // - // Returns nothing - Master.prototype.stop = function() { - var robot, _i, _len, _results; - _results = []; - for (_i = 0, _len = robots.length; _i < _len; _i++) { - robot = robots[_i]; - _results.push(robot.stop()); - } - return _results; - }; + // Public: Stops the API and the robots + // + // Returns nothing + Master.prototype.stop = function() { + for (var i = 0; i < robots.length; i++) { + var robot = robots[i]; + robot.stop(); + } + }; - // Creates a new instance of the Cylon API server, or returns the - // already-existing one. - // - // Returns an Cylon.ApiServer instance - Master.prototype.startAPI = function() { - var server; - server = require('./api'); - api_config.master = this.self; - return api != null ? api : api = new server(api_config); - }; + // Creates a new instance of the Cylon API server, or returns the + // already-existing one. + // + // Returns an Cylon.ApiServer instance + Master.prototype.startAPI = function() { + var Server = require('./api'); + api_config.master = this.self; + return api != null ? api : api = new Server(api_config); + }; - return Master; + return Master; - })(); + })(); - return Cylon; - - }).call(this); - - module.exports = Cylon.getInstance(); + return Cylon; }).call(this); + +module.exports = Cylon.getInstance(); diff --git a/lib/logger.js b/lib/logger.js index 4fd726c..483e8a7 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -6,120 +6,126 @@ * Licensed under the Apache 2.0 license. */ +"use strict"; -(function() { - var BasicLogger, NullLogger, - __slice = [].slice; +var getArgs = function(args) { + return args.length >= 1 ? [].slice.call(args, 0) : []; +} - // The Logger is a global object to facilitate logging stuff to the console (or - // other output) easily and consistently. It's available anywhere in Cylon, as - // well as in external modules that are loaded into Cylon - global.Logger = { +// The Logger is a global object to facilitate logging stuff to the console (or +// other output) easily and consistently. It's available anywhere in Cylon, as +// well as in external modules that are loaded into Cylon +global.Logger = { - // Public: Creates a Logger instance and assigns it to @logger - // - // logger - logger object to use. Defaults to a BasicLogger, or a NullLogger if - // false is supplied - // - // Returns the new logger instance - setup: function(logger) { - if (logger == null) { - logger = new BasicLogger; - } - return this.logger = logger === false ? new NullLogger : logger; - }, - toString: function() { - return this.logger.toString(); - }, - debug: function() { - var args, _ref; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return (_ref = this.logger).debug.apply(_ref, args); - }, - info: function() { - var args, _ref; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return (_ref = this.logger).info.apply(_ref, args); - }, - warn: function() { - var args, _ref; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return (_ref = this.logger).warn.apply(_ref, args); - }, - error: function() { - var args, _ref; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return (_ref = this.logger).error.apply(_ref, args); - }, - fatal: function() { - var args, _ref; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return (_ref = this.logger).fatal.apply(_ref, args); + // Public: Creates a Logger instance and assigns it to @logger + // + // logger - logger object to use. Defaults to a BasicLogger, or a NullLogger if + // false is supplied + // + // Returns the new logger instance + setup: function(logger) { + if (logger == null) { logger = new BasicLogger; } + + if (logger === false) { + this.logger = new NullLogger(); + } else { + this.logger = logger; } + + return this.logger + }, + + toString: function() { return this.logger.toString(); }, + + debug: function() { + var args = getArgs(arguments); + return this.logger.debug.apply(this.logger, args); + }, + + info: function() { + var args = getArgs(arguments); + return this.logger.info.apply(this.logger, args); + }, + + warn: function() { + var args = getArgs(arguments); + return this.logger.warn.apply(this.logger, args); + }, + + error: function() { + var args = getArgs(arguments); + return this.logger.error.apply(this.logger, args); + }, + + fatal: function() { + var args = getArgs(arguments); + return this.logger.fatal.apply(this.logger, args); + } +}; + +// The BasicLogger pushes stuff to console.log. Nothing more, nothing less. +var BasicLogger = (function() { + function BasicLogger() {} + + BasicLogger.prototype.toString = function() { return "BasicLogger"; }; + + BasicLogger.prototype.debug = function() { + var args = getArgs(arguments), + string = ["D, [" + (new Date().toISOString()) + "] DEBUG -- :"], + data = string.concat(args.slice()); + + return console.log.apply(console, data); }; - // The BasicLogger pushes stuff to console.log. Nothing more, nothing less. - BasicLogger = (function() { - function BasicLogger() {} - BasicLogger.prototype.toString = function() { - return "BasicLogger"; - }; + BasicLogger.prototype.info = function() { + var args = getArgs(arguments), + string = ["I, [" + (new Date().toISOString()) + "] INFO -- :"], + data = string.concat(args.slice()); - BasicLogger.prototype.debug = function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return console.log.apply(console, ["D, [" + (new Date().toISOString()) + "] DEBUG -- :"].concat(__slice.call(args))); - }; + return console.log.apply(console, data); + }; - BasicLogger.prototype.info = function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return console.log.apply(console, ["I, [" + (new Date().toISOString()) + "] INFO -- :"].concat(__slice.call(args))); - }; + BasicLogger.prototype.warn = function() { + var args = getArgs(arguments), + string = ["W, [" + (new Date().toISOString()) + "] WARN -- :"], + data = string.concat(args.slice()); - BasicLogger.prototype.warn = function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return console.log.apply(console, ["W, [" + (new Date().toISOString()) + "] WARN -- :"].concat(__slice.call(args))); - }; + return console.log.apply(console, data); + }; - BasicLogger.prototype.error = function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return console.log.apply(console, ["E, [" + (new Date().toISOString()) + "] ERROR -- :"].concat(__slice.call(args))); - }; + BasicLogger.prototype.error = function() { + var args = getArgs(arguments), + string = ["E, [" + (new Date().toISOString()) + "] ERROR -- :"], + data = string.concat(args.slice()); - BasicLogger.prototype.fatal = function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return console.log.apply(console, ["F, [" + (new Date().toISOString()) + "] FATAL -- :"].concat(__slice.call(args))); - }; + return console.log.apply(console, data); + }; - return BasicLogger; + BasicLogger.prototype.fatal = function() { + var args = getArgs(arguments), + string = ["F, [" + (new Date().toISOString()) + "] FATAL -- :"], + data = string.concat(args.slice()); - })(); + return console.log.apply(console, data); + }; - // The NullLogger is designed for cases where you want absolutely nothing to - // print to anywhere. Every proxied method from the Logger returns a noop. - NullLogger = (function() { - function NullLogger() {} + return BasicLogger; - NullLogger.prototype.toString = function() { - return "NullLogger"; - }; +})(); - NullLogger.prototype.debug = function() {}; +// The NullLogger is designed for cases where you want absolutely nothing to +// print to anywhere. Every proxied method from the Logger returns a noop. +var NullLogger = (function() { + function NullLogger() {} - NullLogger.prototype.info = function() {}; + NullLogger.prototype.toString = function() { return "NullLogger"; }; - NullLogger.prototype.warn = function() {}; + NullLogger.prototype.debug = function() {}; + NullLogger.prototype.info = function() {}; + NullLogger.prototype.warn = function() {}; + NullLogger.prototype.error = function() {}; + NullLogger.prototype.fatal = function() {}; - NullLogger.prototype.error = function() {}; + return NullLogger; - NullLogger.prototype.fatal = function() {}; - - return NullLogger; - - })(); - -}).call(this); +})(); diff --git a/lib/utils.js b/lib/utils.js index 11492f9..0f82452 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -6,220 +6,201 @@ * Licensed under the Apache 2.0 license. */ +// Public: Alias to setInterval, combined with Number monkeypatches below to +// create an artoo-like syntax. +// +// interval - interval to run action on +// action - action to perform at interval +// +// Examples +// +// every 5.seconds(), -> console.log("hello world (and again in 5 seconds)!") +// +// Returns an interval +global.every = function(interval, action) { + return setInterval(action, interval); +}; -(function() { - var __slice = [].slice; +// Public: Alias to setTimeout, combined with Number monkeypatches below to +// create an artoo-like syntax. +// +// interval - interval to run action on +// action - action to perform at interval +// +// Examples +// +// after 10.seconds(), -> console.log("hello world from ten seconds ago!") +// +// Returns an interval +global.after = function(delay, action) { + return setTimeout(action, delay); +}; - // Public: Alias to setInterval, combined with Number monkeypatches below to - // create an artoo-like syntax. - // - // interval - interval to run action on - // action - action to perform at interval - // - // Examples - // - // every 5.seconds(), -> console.log("hello world (and again in 5 seconds)!") - // - // Returns an interval - global.every = function(interval, action) { - return setInterval(action, interval); - }; +// Public: Alias to the `every` function, but passing 0 +// Examples +// +// constantly -> console.log("hello world (and again and again)!") +// +// Returns an interval +global.constantly = function(action) { + return every(0, action); +}; - // Public: Alias to setTimeout, combined with Number monkeypatches below to - // create an artoo-like syntax. - // - // interval - interval to run action on - // action - action to perform at interval - // - // Examples - // - // after 10.seconds(), -> console.log("hello world from ten seconds ago!") - // - // Returns an interval - global.after = function(delay, action) { - return setTimeout(action, delay); - }; +// Public: Sleep - do nothing for some duration of time. +// +// ms - number of ms to sleep for +// +// Returns a function +// Examples: +// sleep 1.second() +global.sleep = function(ms) { + var start = Date.now(); - // Public: Alias to the `every` function, but passing 0 - // Examples - // - // constantly -> console.log("hello world (and again and again)!") - // - // Returns an interval - global.constantly = function(action) { - return every(0, action); - }; + while(Date.now() < start + ms) { + var i = 0; + } +}; - // Public: Sleep - do nothing for some duration of time. - // - // ms - number of ms to sleep for - // - // Returns a function - // Examples: - // sleep 1.second() - global.sleep = function(ms) { - var i, start, _results; - start = Date.now(); - _results = []; - while (Date.now() < start + ms) { - _results.push(i = 1); - } - return _results; - }; +// Copies +global.slice = [].slice; +global.hasProp = {}.hasOwnProperty; - global.slice = [].slice; +// 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 = function(child, parent) { + var ctor = function() { this.constructor = child; }; - global.hasProp = {}.hasOwnProperty; + for (var key in parent) { + if (hasProp.call(parent, key)) { child[key] = parent[key]; } + } - // 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 = function(child, parent) { - var ctor, key; - ctor = function() { - this.constructor = child; + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + child.__super__ = parent.prototype; + return child; +}; + +// Public: Proxies a list of methods from one object to another. It will not +// overwrite existing methods unless told to. +// +// methods - array of functions to proxy +// target - object to proxy the functions to +// base - (optional) object that proxied functions will be declared on. Defaults +// to this +// force - (optional) boolean - whether or not to force method assignment +// +// Returns base +global.proxyFunctionsToObject = function(methods, target, base, force) { + if (base == null) { base = this; } + if (force == null) { force = false; } + + var fn = function(method) { + return base[method] = function() { + var args = arguments.length >= 1 ? [].slice.call(arguments, 0) : []; + return target[method].apply(target, args); }; - for (key in parent) { - if (hasProp.call(parent, key)) { - child[key] = parent[key]; - } + }; + + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + if (!force) { + if (typeof base[method] === 'function') { continue; } } - ctor.prototype = parent.prototype; - child.prototype = new ctor(); - child.__super__ = parent.prototype; - return child; - }; - // Public: Proxies a list of methods from one object to another. It will not - // overwrite existing methods unless told to. - // - // methods - array of functions to proxy - // target - object to proxy the functions to - // base - (optional) object that proxied functions will be declared on. Defaults - // to this - // force - (optional) boolean - whether or not to force method assignment - // - // Returns base - global.proxyFunctionsToObject = function(methods, target, base, force) { - var method, _fn, _i, _len; - if (base == null) { - base = this; - } - if (force == null) { - force = false; - } - _fn = function(method) { - return base[method] = function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return target[method].apply(target, args); - }; - }; - for (_i = 0, _len = methods.length; _i < _len; _i++) { - method = methods[_i]; - if (!force) { - if (typeof base[method] === 'function') { - continue; - } - } - _fn(method); - } - return base; - }; + fn(method); + } + return base; +}; - // Public: Proxies a list of methods for test stubbing. - // - // methods - array of functions to proxy - // base - (optional) object that proxied functions will be declared on. Defaults - // to this - // - // Returns base - global.proxyTestStubs = function(methods, base) { - var method, _i, _len; - if (base == null) { - base = this; - } - for (_i = 0, _len = methods.length; _i < _len; _i++) { - method = methods[_i]; - base[method] = function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return true; - }; - base.commandList.push(method); - } - return base; - }; +// Public: Proxies a list of methods for test stubbing. +// +// methods - array of functions to proxy +// base - (optional) object that proxied functions will be declared on. Defaults +// to this +// +// Returns base +global.proxyTestStubs = function(methods, base) { + if (base == null) { base = this; } - // Public: Monkey-patches Number to have Rails-like #seconds() function. Warning, - // due to the way the Javascript parser works, applying functions on numbers is - // kind of weird. See examples for details. - // - // Examples - // - // 2.seconds() - // #=> SyntaxError: Unexpected token ILLEGAL - // - // 10..seconds() - // #=> 10000 - // - // (5).seconds() - // #=> 5000 - // - // Returns an integer representing time in milliseconds - Number.prototype.seconds = function() { - return this * 1000; - }; + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; - // Public: Alias for Number::seconds, see comments for that method - // - // Examples - // - // 1.second() - // #=> 1000 - // - // Returns an integer representing time in milliseconds - Number.prototype.second = function() { - return this.seconds(this); - }; + base[method] = function() { return true; }; + base.commandList.push(method); + } - // Public: Convert value from old scale (start, end) to (0..1) scale - // - // start - low point of scale to convert value from - // end - high point of scale to convert value from - // - // Examples - // - // 5..fromScale(0, 10) - // #=> 0.5 - // - // Returns an integer representing the scaled value - Number.prototype.fromScale = function(start, end) { - return (this - Math.min(start, end)) / (Math.max(start, end) - Math.min(start, end)); - }; + return base; +}; - // Public: Convert value from (0..1) scale to new (start, end) scale - // - // start - low point of scale to convert value to - // end - high point of scale to convert value to - // - // Examples - // - // 0.5.toScale(0, 10) - // #=> 5 - // - // Returns an integer representing the scaled value - Number.prototype.toScale = function(start, end) { - return Math.ceil(this * (Math.max(start, end) - Math.min(start, end)) + Math.min(start, end)); - }; +// Public: Monkey-patches Number to have Rails-like //seconds() function. Warning, +// due to the way the Javascript parser works, applying functions on numbers is +// kind of weird. See examples for details. +// +// Examples +// +// 2.seconds() +// //=> SyntaxError: Unexpected token ILLEGAL +// +// 10..seconds() +// //=> 10000 +// +// (5).seconds() +// //=> 5000 +// +// Returns an integer representing time in milliseconds +Number.prototype.seconds = function() { + return this * 1000; +}; -}).call(this); +// Public: Alias for Number::seconds, see comments for that method +// +// Examples +// +// 1.second() +// //=> 1000 +// +// Returns an integer representing time in milliseconds +Number.prototype.second = function() { + return this.seconds(this); +}; + +// Public: Convert value from old scale (start, end) to (0..1) scale +// +// start - low point of scale to convert value from +// end - high point of scale to convert value from +// +// Examples +// +// 5..fromScale(0, 10) +// //=> 0.5 +// +// Returns an integer representing the scaled value +Number.prototype.fromScale = function(start, end) { + return (this - Math.min(start, end)) / (Math.max(start, end) - Math.min(start, end)); +}; + +// Public: Convert value from (0..1) scale to new (start, end) scale +// +// start - low point of scale to convert value to +// end - high point of scale to convert value to +// +// Examples +// +// 0.5.toScale(0, 10) +// //=> 5 +// +// Returns an integer representing the scaled value +Number.prototype.toScale = function(start, end) { + + return Math.ceil(this * (Math.max(start, end) - Math.min(start, end)) + Math.min(start, end)); +};