diff --git a/README.md b/README.md index f9361d6b87..adcafced28 100755 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ List of Definitions * [SharePoint](http://sptypescript.codeplex.com) (by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru) and [Andrey Markeev](http://markeev.com)) * [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov)) * [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u)) +* [SlickGrid] (https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin)) * [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) * [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev)) * [SoundJS](http://www.createjs.com/#!/SoundJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) diff --git a/box2d/box2dweb-test.ts b/box2d/box2dweb-test.ts index 51dabf1789..5a5f44f24c 100644 --- a/box2d/box2dweb-test.ts +++ b/box2d/box2dweb-test.ts @@ -12,6 +12,5 @@ import b2Joints = Box2D.Dynamics.Joints; var w1 = new Box2D.Dynamics.b2World(new Box2D.Common.Math.b2Vec2(0, 10), true); var w2 = new b2Dynamics.b2World(new b2Math.b2Vec2(0, 10), true); -var debugDraw = new Box2D.Dynamics.b2DebugDraw(), - canvasElement = document.getElementsByTagName("canvas")[0]; -debugDraw.SetSprite(canvasElement.getContext("2d")); +var debugDraw = new Box2D.Dynamics.b2DebugDraw(); +debugDraw.SetSprite((document.getElementsByTagName("canvas")[0]).getContext("2d")); diff --git a/requirejs/require-tests.ts b/requirejs/require-tests.ts index 5788eabeb7..c66567e7b1 100644 --- a/requirejs/require-tests.ts +++ b/requirejs/require-tests.ts @@ -38,7 +38,6 @@ require(['main'], (main, $, _, Backbone) => { }); -// ISSUE: https://github.com/borisyankov/DefinitelyTyped/issues/764 -var recOne = requirejs.config({ baseUrl: 'js' }); +var recOne = require.config({ baseUrl: 'js' }); recOne(['core'], function (core) {/*some code*/}); diff --git a/requirejs/require.d.ts b/requirejs/require.d.ts index 109c0b1ae6..39b3d313c6 100644 --- a/requirejs/require.d.ts +++ b/requirejs/require.d.ts @@ -1,21 +1,67 @@ -// require-2.1.1.d.ts -// (c) 2012 Josh Baldwin -// require.d.ts may be freely distributed under the MIT license. -// For all details and documentation: -// https://github.com/jbaldwin/require.d.ts +/* +require-2.1.5.d.ts may be freely distributed under the MIT license. + +Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/require.d.ts + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*/ + +interface RequireError extends Error { + + /** + * Error Type + **/ + requireType: string; + + /** + * Required modules. + **/ + requireModules: string[]; + + /** + * Original error, might be null. + **/ + originalError: Error; +} interface RequireShim { - // List of dependencies. + /** + * List of dependencies. + **/ deps?: string[]; - // Name the module will be exported as. + /** + * Name the module will be exported as. + **/ exports?: string; - // Initialize function with all dependcies passed in, - // if the function returns a value then that value is used - // as the module export value instead of the object - // found via the 'exports' string. + /** + * Initialize function with all dependcies passed in, + * if the function returns a value then that value is used + * as the module export value instead of the object + * found via the 'exports' string. + * @param dependencies + * @return + **/ init?: (...dependencies: any[]) => any; } @@ -30,7 +76,7 @@ interface RequireConfig { // Dictionary of Shim's. // does not cover case of key->string[] - shim?: { [key: string]: RequireShim; }; + shim?: { [key: string]: RequireShim; }; /** * For the given module prefix, instead of loading the @@ -49,42 +95,59 @@ interface RequireConfig { * } * }); **/ - map?: { + map?: { [id: string]: { [id: string]: string; }; }; - // AMD configurations, use module.config() to access in - // define() functions - config?: { [id: string]: { }; }; + /** + * AMD configurations, use module.config() to access in + * define() functions + **/ + config?: { [id: string]: {}; }; - // Configures loading modules from CommonJS packages. - packages?: { }; + /** + * Configures loading modules from CommonJS packages. + **/ + packages?: {}; - // The number of seconds to wait before giving up on loading - // a script. The default is 7 seconds. + /** + * The number of seconds to wait before giving up on loading + * a script. The default is 7 seconds. + **/ waitSeconds?: number; - // A name to give to a loading context. This allows require.js - // to load multiple versions of modules in a page, as long as - // each top-level require call specifies a unique context string. + /** + * A name to give to a loading context. This allows require.js + * to load multiple versions of modules in a page, as long as + * each top-level require call specifies a unique context string. + **/ context?: string; - // An array of dependencies to load. + /** + * An array of dependencies to load. + **/ deps?: string[]; - // A function to pass to require that should be require after - // deps have been loaded. + /** + * A function to pass to require that should be require after + * deps have been loaded. + * @param modules + **/ callback?: (...modules: any[]) => void; - // If set to true, an error will be thrown if a script loads - // that does not call define() or have shim exports string - // value that can be checked. + /** + * If set to true, an error will be thrown if a script loads + * that does not call define() or have shim exports string + * value that can be checked. + **/ enforceDefine?: boolean; - // If set to true, document.createElementNS() will be used - // to create script elements. + /** + * If set to true, document.createElementNS() will be used + * to create script elements. + **/ xhtml?: boolean; /** @@ -107,11 +170,13 @@ interface RequireConfig { } -// not sure what to do with this guy +// todo: not sure what to do with this guy interface RequireModule { - - config(): { }; + /** + * + **/ + config(): {}; } @@ -124,92 +189,96 @@ interface RequireMap { fullName: string; } -interface Require { +interface Require { - // Configure require.js - config(config: RequireConfig): Require; + /** + * Configure require.js + **/ + config(config: RequireConfig): Require; - // Start the main app logic. - // Callback is optional. - // Can alternatively use deps and callback. - (module: string): any; - (modules: string[], ready?: (...modules: any[]) => void, errorCallback?: (err : RequireError) => void): void; + /** + * Start the main app logic. + * Callback is optional. + * Can alternatively use deps and callback. + * @param modules Required modules to load. + **/ + (modules: string[]): void; - // Generate URLs from require module + /** + * @see Require() + * @param ready Called when required modules are ready. + **/ + (modules: string[], ready: (...modules: any[]) => void ): void; + + /** + * Generate URLs from require module + * @param module Module to URL + * @return URL string + **/ toUrl(module: string): string; - // On Error override - onError(): void; + /** + * On Error override + * @param err + **/ + onError(err: RequireError): void; - // Undefine a module + /** + * Undefine a module + * @param module Module to undefine. + **/ undef(module: string): void; - // Semi-private function, overload in special instance of undef() + /** + * Semi-private function, overload in special instance of undef() + **/ onResourceLoad(context: Object, map: RequireMap, depArray: RequireMap[]): void; } -interface RequireError -{ - requireType: string; - requireModules: string[]; - originalError?: string; - contextName? : string; - requireMap?: any; -} - interface RequireDefine { /** * Define Simple Name/Value Pairs - * @config Dictionary of Named/Value pairs for the config. + * @param config Dictionary of Named/Value pairs for the config. **/ (config: { [key: string]: any; }): void; /** * Define function. - * @func: The function module. + * @param func: The function module. **/ (func: () => any): void; /** * Define function with dependencies. - * @deps List of dependencies module IDs. - * @ready Callback function when the dependencies are loaded. - * @deps module dependencies - * @return module definition + * @param deps List of dependencies module IDs. + * @param ready Callback function when the dependencies are loaded. + * callback param deps module dependencies + * callback return module definition **/ (deps: string[], ready: (...deps: any[]) => any): void; /** * Define module with simplified CommonJS wrapper. - * @ready - * @require requirejs instance - * @exports exports object - * @module module - * @return module definition + * @param ready + * callback require requirejs instance + * callback exports exports object + * callback module module + * callback return module definition **/ (ready: (require: Require, exports: { [key: string]: any; }, module: RequireModule) => any): void; /** * Define a module with a name and dependencies. - * @name The name of the module. - * @deps List of dependencies module IDs. - * @ready Callback function when the dependencies are loaded. - * @deps module dependencies - * @return module definition + * @param name The name of the module. + * @param deps List of dependencies module IDs. + * @param ready Callback function when the dependencies are loaded. + * callback deps module dependencies + * callback return module definition **/ (name: string, deps: string[], ready: (...deps: any[]) => any): void; - - /** - * Defines whether require js supports multiple versions of jQuery being loaded - **/ - amd: { - jQuery: boolean; - }; } // Ambient declarations for 'require' and 'define' declare var require: Require; -declare var requirejs: Require; -declare var req: Require; declare var define: RequireDefine; diff --git a/slickgrid/SlickGrid-tests.ts b/slickgrid/SlickGrid-tests.ts new file mode 100644 index 0000000000..c93a2704b4 --- /dev/null +++ b/slickgrid/SlickGrid-tests.ts @@ -0,0 +1,200 @@ +/// +/// + +declare var $: any; + +interface MyData extends Slick.SlickData { + title: string; + duration: string; + percentComplete: number; + start: string; + finish: string; + effortDriven: boolean; +} + +var grid: Slick.Grid; +var columns: Slick.Column[] = [ + { id: "title", name: "Title", field: "title" }, + { id: "duration", name: "Duration", field: "duration" }, + { id: "%", name: "% Complete", field: "percentComplete" }, + { id: "start", name: "Start", field: "start" }, + { id: "finish", name: "Finish", field: "finish" }, + { id: "effort-driven", name: "Effort Driven", field: "effortDriven" } +]; + +var options: Slick.GridOptions = { + enableCellNavigation: true, + enableColumnReorder: false +}; + +var data: MyData[] = []; +for (var i = 0; i < 500; i++) { + data[i] = { + title: "Task " + i, + duration: "5 days", + percentComplete: Math.round(Math.random() * 100), + start: "01/01/2009", + finish: "01/05/2009", + effortDriven: (i % 5 == 0) + }; +} + +grid = new Slick.Grid("#myGrid", data, columns, options); + +grid.init(); + +grid.getData(); + +grid.getDataItem(14).title; + +grid.setData([{ title: "task", duration: "5 days", percentComplete: 5, start: "01/01/2013", finish: "12/12/2013", effortDriven: false }], true); + +var ids = []; +for (i = 0; i < grid.getDataLength(); i++) { + ids.push(grid.getDataItem(i).title); +} + +var $selectedCells = $('.' + grid.getOptions().selectedCellCssClass); + +grid.getSelectedRows(); + +grid.getSelectionModel(); + +grid.setOptions({ selectedCellCssClass: "newSelection" }); +grid.setSelectedRows([0]); +$('.newSelection'); + +grid.setSelectedRows([0, 1, 2]); + +class SingleCellSelectionModel extends Slick.SelectionModel { + private self: SingleCellSelectionModel = null; + private _grid: Slick.Grid; + + constructor() { + super(); + this.self = this; + } + + public init(grid: Slick.Grid) { + this.self._grid = grid; + this.self._grid.onClick.subscribe(this.self.handleGridClick); + } + + public destroy() { + this.self._grid.onClick.unsubscribe(this.self.handleGridClick); + } + + public handleGridClick(e, args) { + var cell = this.self._grid.getCellFromEvent(e); + if (!cell || !this.self._grid.canCellBeSelected(cell.row, cell.cell)) { + return; + } + + this.onSelectedRangesChanged.notify([new Slick.Range(cell.row, cell.cell, cell.row, cell.cell)], new Slick.EventData(), this); + } +} + +var selectionModel = new SingleCellSelectionModel(); +selectionModel.init(grid); +grid.setSelectionModel(selectionModel); + +var column = grid.getColumns()[grid.getColumnIndex("title")]; + +var cols = grid.getColumns(); +var sortable = cols[0].sortable; +sortable ? console.log("It's sortable!") : console.log("It's not sortable!"); + +var data2 = grid.getColumns(); +data2[0].name = "First"; +grid.setColumns(data); + +grid.updateColumnHeader("FirstName", "A First Name"); + +grid.addCellCssStyles("test", { + 0: { + "number_column": "cell-bold", + "title_column": "cell-title cell-highlighted" + }, + 4: { + "percent_column": "cell-highlighted" + } +}); + +grid.canCellBeActive(5, 10); + +grid.canCellBeSelected(5, 10); + +grid.editActiveCell(new Slick.Editors.Date({ + column: cols, + container: undefined, + grid: grid +})); + +grid.setActiveCell(0, 0); +grid.editActiveCell(new Slick.Editors.Date({ + column: cols, + container: undefined, + grid: grid +})); + +grid.flashCell(5, 10); +grid.flashCell(5, 10, 500); + +grid.getActiveCell().row; +grid.getActiveCell().cell; + +grid.getActiveCellNode().innerHTML; + +grid.getActiveCellPosition().bottom; +grid.getActiveCellPosition().height; +grid.getActiveCellPosition().left; +grid.getActiveCellPosition().right; +grid.getActiveCellPosition().top; +grid.getActiveCellPosition().visible; +grid.getActiveCellPosition().width; + +grid.getCellCssStyles("test")[0]["number_column"]; + +grid.getCellEditor(); + +grid.getCellFromEvent(new Slick.SlickEvent()); + +grid.getCellFromPoint(5, 10); + +grid.getCellNode(5, 10); + +grid.getCellNodeBox(5, 10); +grid.getCellNodeBox(5, 10).bottom; +grid.getCellNodeBox(5, 10).height; +grid.getCellNodeBox(5, 10).left; +grid.getCellNodeBox(5, 10).right; +grid.getCellNodeBox(5, 10).top; +grid.getCellNodeBox(5, 10).visible; +grid.getCellNodeBox(5, 10).width; + +grid.gotoCell(5, 10); +grid.gotoCell(5, 10, true); + +grid.navigateDown(); +grid.navigateLeft(); +grid.navigateNext(); +grid.navigatePrev(); +grid.navigateRight(); +grid.navigateUp(); + +grid.removeCellCssStyles("test"); + +grid.resetActiveCell(); + +grid.setActiveCell(5, 10); + +grid.setCellCssStyles("test", { + 0: { + "number_column": "cell-bold", + "title_column": "cell-title cell-highlighted" + }, + 4: { + "percent_column": "cell-highlighted" + } +}); + diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts new file mode 100644 index 0000000000..35e37c2efc --- /dev/null +++ b/slickgrid/SlickGrid.d.ts @@ -0,0 +1,1700 @@ +/* +SlickGrid-2.1.d.ts may be freely distributed under the MIT license. + +Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/SlickGrid.d.ts + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*/ + +/// + +declare module Slick { + + /** + * slick.core.js + **/ + + /** + * An event object for passing data to event handlers and letting them control propagation. + *

This is pretty much identical to how W3C and jQuery implement events.

+ * @class EventData + * @constructor + **/ + export class EventData { + + constructor(); + + /*** + * Stops event from propagating up the DOM tree. + * @method stopPropagation + */ + public stopPropagation(): void; + + /*** + * Returns whether stopPropagation was called on this event object. + * @method isPropagationStopped + * @return {Boolean} + */ + public isPropagationStopped(): boolean; + + /*** + * Prevents the rest of the handlers from being executed. + * @method stopImmediatePropagation + */ + public stopImmediatePropagation(): void; + + /*** + * Returns whether stopImmediatePropagation was called on this event object.\ + * @method isImmediatePropagationStopped + * @return {Boolean} + */ + public isImmediatePropagationStopped(): boolean; + } + + /*** + * A simple publisher-subscriber implementation. + * todo: SlickEvent is named 'Event', but this clashes with the native DOM Event which is also used is various places. + * @class Event + * @constructor + */ + export class SlickEvent { + + constructor(); + + /*** + * Adds an event handler to be called when the event is fired. + *

Event handler will receive two arguments - an EventData and the data + * object the event was fired with.

+ * @method subscribe + * @param fn {Function} Event handler. + */ + public subscribe(fn: (eventData: EventData, data: T) => any ): void; + + /*** + * Removes an event handler added with subscribe(fn). + * @method unsubscribe + * @param fn {Function} Event handler to be removed. + */ + public unsubscribe(fn: (eventData: EventData, data: T) => any ): void; + + /*** + * Fires an event notifying all subscribers. + * @method notify + * @param args {Object} Additional data object to be passed to all handlers. + * @param e {EventData} + * Optional. + * An EventData object to be passed to all handlers. + * For DOM events, an existing W3C/jQuery event object can be passed in. + * @param scope {Object} + * Optional. + * The scope ("this") within which the handler will be executed. + * If not specified, the scope will be set to the Event instance. + * @return Last run callback result. + * @note slick.core.Event.notify shows this method as returning a value, type is unknown. + */ + public notify(args: T, e: EventData, scope: any): any; + public notify(args: T, e: Event, scope: any): any; + + } + + // todo: is this private? there are no comments in the code + export class EventHandler { + constructor(); + + public subscribe(event: EventData, handler: Function): EventHandler; + public unsubscribe(event: EventData, handler: Function): EventHandler; + public unsubscribeAll(): EventHandler; + } + + /*** + * A structure containing a range of cells. + * @class Range + **/ + export class Range { + + /** + * A structure containing a range of cells. + * @constructor + * @param fromRow {Integer} Starting row. + * @param fromCell {Integer} Starting cell. + * @param toRow {Integer} Optional. Ending row. Defaults to fromRow. + * @param toCell {Integer} Optional. Ending cell. Defaults to fromCell. + **/ + constructor(fromRow: number, fromCell: number, toRow?: number, toCell?: number); + + /*** + * @property fromRow + * @type {Integer} + */ + public fromRow: number; + + /*** + * @property fromCell + * @type {Integer} + */ + public fromCell: number; + + /*** + * @property toRow + * @type {Integer} + */ + public toRow: number; + + /*** + * @property toCell + * @type {Integer} + */ + public toCell: number; + + /*** + * Returns whether a range represents a single row. + * @method isSingleRow + * @return {Boolean} + */ + public isSingleRow(): boolean; + + /*** + * Returns whether a range represents a single cell. + * @method isSingleCell + * @return {Boolean} + */ + public isSingleCell(): boolean; + + /*** + * Returns whether a range contains a given cell. + * @method contains + * @param row {Integer} + * @param cell {Integer} + * @return {Boolean} + */ + public contains(row: number, cell: number): boolean; + + /*** + * Returns a readable representation of a range. + * @method toString + * @return {String} + */ + public toString(): string; + + } + + /*** + * A base class that all special / non-data rows (like Group and GroupTotals) derive from. + * @class NonDataItem + * @constructor + */ + export class NonDataRow { + + } + + /*** + * Information about a group of rows. + * @class Group + * @extends Slick.NonDataItem + * @constructor + */ + export class Group extends NonDataRow { + + constructor(); + + /** + * Grouping level, starting with 0. + * @property level + * @type {Number} + */ + public level: number; + + /*** + * Number of rows in the group. + * @property count + * @type {Integer} + */ + public count: number; + + /*** + * Grouping value. + * @property value + * @type {Object} + */ + public value: T; + + /*** + * Formatted display value of the group. + * @property title + * @type {String} + */ + public title: string; + + /*** + * Whether a group is collapsed. + * @property collapsed + * @type {Boolean} + */ + public collapsed: boolean; + + /*** + * GroupTotals, if any. + * @property totals + * @type {GroupTotals} + */ + public totals: GroupTotals; + + /** + * Rows that are part of the group. + * @property rows + * @type {Array} + */ + public rows: R[]; + + /** + * Sub-groups that are part of the group. + * @property groups + * @type {Array} + */ + public groups: Group[]; + + /** + * A unique key used to identify the group. This key can be used in calls to DataView + * collapseGroup() or expandGroup(). + * @property groupingKey + * @type {Object} + */ + public groupingKey: any; + + /*** + * Compares two Group instances. + * @method equals + * @return {Boolean} + * @param group {Group} Group instance to compare to. + * todo: this is on the prototype (NonDataRow()) instance, not Group, maybe doesn't matter? + */ + public equals(group: Group): boolean; + } + + /*** + * Information about group totals. + * An instance of GroupTotals will be created for each totals row and passed to the aggregators + * so that they can store arbitrary data in it. That data can later be accessed by group totals + * formatters during the display. + * @class GroupTotals + * @extends Slick.NonDataItem + * @constructor + */ + export class GroupTotals extends NonDataRow { + + constructor(); + + /*** + * Parent Group. + * @param group + * @type {Group} + */ + public group: Group; + + } + + /*** + * A locking helper to track the active edit controller and ensure that only a single controller + * can be active at a time. This prevents a whole class of state and validation synchronization + * issues. An edit controller (such as SlickGrid) can query if an active edit is in progress + * and attempt a commit or cancel before proceeding. + * @class EditorLock + * @constructor + */ + export class EditorLock { + + constructor(); + + /*** + * Returns true if a specified edit controller is active (has the edit lock). + * If the parameter is not specified, returns true if any edit controller is active. + * @method isActive + * @param editController {EditController} + * @return {Boolean} + */ + public isActive(editController: Editors.Editor): boolean; + + /*** + * Sets the specified edit controller as the active edit controller (acquire edit lock). + * If another edit controller is already active, and exception will be thrown. + * @method activate + * @param editController {EditController} edit controller acquiring the lock + */ + public activate(editController: Editors.Editor): void; + + /*** + * Unsets the specified edit controller as the active edit controller (release edit lock). + * If the specified edit controller is not the active one, an exception will be thrown. + * @method deactivate + * @param editController {EditController} edit controller releasing the lock + */ + public deactivate(editController: Editors.Editor): void; + + /*** + * Attempts to commit the current edit by calling "commitCurrentEdit" method on the active edit + * controller and returns whether the commit attempt was successful (commit may fail due to validation + * errors, etc.). Edit controller's "commitCurrentEdit" must return true if the commit has succeeded + * and false otherwise. If no edit controller is active, returns true. + * @method commitCurrentEdit + * @return {Boolean} + */ + public commitCurrentEdit(): boolean; + + /*** + * Attempts to cancel the current edit by calling "cancelCurrentEdit" method on the active edit + * controller and returns whether the edit was successfully cancelled. If no edit controller is + * active, returns true. + * @method cancelCurrentEdit + * @return {Boolean} + */ + public cancelCurrentEdit(): boolean; + } + + /** + * A global singleton editor lock. + * @class GlobalEditorLock + * @static + * @constructor + **/ + export var GlobalEditorLock: EditorLock; + + /** + * slick.grid.js + **/ + + /** + * Options which you can apply to the columns objects. + **/ + export interface Column { + + /** + * This accepts a function of the form function(cellNode, row, dataContext, colDef) and is used to post-process the cell's DOM node / nodes + * @param cellNode + * @param row + * @param dataContext + * @param colDef + * @return + **/ + asyncPostRender?: (cellNode, row, dataContext, colDef) => void; + + /** + * Used by the the slick.rowMoveManager.js plugin for moving rows. Has no effect without the plugin installed. + **/ + behavior?: any; + + /** + * In the "Add New" row, determines whether clicking cells in this column can trigger row addition. If true, clicking on the cell in this column in the "Add New" row will not trigger row addition. + **/ + cannotTriggerInsert?: boolean; + + /** + * Accepts a string as a class name, applies that class to every row cell in the column. + **/ + cssClass?: string; + + /** + * When set to true, the first user click on the header will do a descending sort. When set to false, the first user click on the header will do an ascending sort. + **/ + defaultSortAsc?: boolean; + + /** + * The editor for cell edits {TextEditor, IntegerEditor, DateEditor...} See slick.editors.js + **/ + editor?: Editors.Editor; + + /** + * The property name in the data object to pull content from. (This is assumed to be on the root of the data object.) + **/ + field?: string; + + /** + * When set to false, clicking on a cell in this column will not select the row for that cell. The cells in this column will also be skipped during tab navigation. + **/ + focusable?: boolean; + + /** + * This accepts a function of the form function(row, cell, value, columnDef, dataContext) and returns a formatted version of the data in each cell of this column. For example, setting formatter to function(r, c, v, cd, dc) { return "Hello!"; } would overwrite every value in the column with "Hello!" See defaultFormatter in slick.grid.js for an example formatter. + * @param row + * @param cell + * @param value + * @param columnDef + * @param dataContext + * @return + **/ + formatter?: Formatter; + + /** + * Accepts a string as a class name, applies that class to the cell for the column header. + **/ + headerCssClass?: string; + + /** + * A unique identifier for the column within the grid. + **/ + id?: string; + + /** + * Set the maximum allowable width of this column, in pixels. + **/ + maxWidth?: number; + + /** + * Set the minimum allowable width of this column, in pixels. + **/ + minWidth?: number; + + /** + * The text to display on the column heading. + **/ + name?: string; + + /** + * If set to true, whenever this column is resized, the entire table view will rerender. + **/ + rerenderOnReize?: boolean; + + /** + * If false, column can no longer be resized. + **/ + resizable?: boolean; + + /** + * If false, when a row is selected, the CSS class for selected cells ("selected" by default) is not applied to the cell in this column. + **/ + selectable?: boolean; + + /** + * If true, the column will be sortable by clicking on the header. + **/ + sortable?: boolean; + + /** + * If set to a non-empty string, a tooltip will appear on hover containing the string. + **/ + toolTip?: string; + + /** + * Width of the column in pixels. (May often be overridden by things like minWidth, maxWidth, forceFitColumns, etc.) + **/ + width?: number; + } + + export interface EditorFactory { + getEditor(column): Editors.Editor; + } + + export interface FormatterFactory { + getFormatter(column: Column): Formatter; + } + + export interface GridOptions { + + /** + * Makes cell editors load asynchronously after a small delay. This greatly increases keyboard navigation speed. + **/ + asyncEditorLoading?: boolean; + + /** + * Delay after which cell editor is loaded. Ignored unless asyncEditorLoading is true. + **/ + asyncEditorLoadDelay?: number; + + /** + * + **/ + asyncPostRenderDelay?: number; + + /** + * Cell will not automatically go into edit mode when selected. + **/ + autoEdit?: boolean; + + /** + * + **/ + autoHeight?: boolean; + + /** + * A CSS class to apply to flashing cells via flashCell(). + **/ + cellFlashingCssClass?: string; + + /** + * A CSS class to apply to cells highlighted via setHighlightedCells(). + **/ + cellHighlightCssClass?: string; + + /** + * + **/ + dataItemColumnValueExtractor?: any; + + /** + * + **/ + defaultColumnWidth?: number; + + /** + * + **/ + defaultFormatter?: Formatter; + + /** + * + **/ + editable?: boolean; + + /** + * Not listed as a default under options in slick.grid.js + **/ + editCommandHandler?: any; // queueAndExecuteCommand + + /** + * A factory object responsible to creating an editor for a given cell. Must implement getEditor(column). + **/ + editorFactory?: EditorFactory; + + /** + * A Slick.EditorLock instance to use for controlling concurrent data edits. + **/ + editorLock?: EditorLock; + + /** + * If true, a blank row will be displayed at the bottom - typing values in that row will add a new one. Must subscribe to onAddNewRow to save values. + **/ + enableAddRow?: boolean; + + /** + * If true, async post rendering will occur and asyncPostRender delegates on columns will be called. + **/ + enableAsyncPostRender?: boolean; + + /** + * *WARNING*: Not contained in SlickGrid 2.1, may be deprecated + **/ + enableCellRangeSelection?: any; + + /** + * Appears to enable cell virtualisation for optimised speed with large datasets + **/ + enableCellNavigation?: boolean; + + /** + * + **/ + enableColumnReorder?: boolean; + + /** + * *WARNING*: Not contained in SlickGrid 2.1, may be deprecated + **/ + enableRowReordering?: any; + + /** + * + **/ + enableTextSelectionOnCells?: boolean; + + /** + * @see Example: Explicit Initialization + **/ + explicitInitialization?: boolean; + + /** + * Force column sizes to fit into the container (preventing horizontal scrolling). Effectively sets column width to be 1/Number of Columns which on small containers may not be desirable + **/ + forceFitColumns?: boolean; + + /** + * + **/ + forceSyncScrolling?: boolean; + + /** + * A factory object responsible to creating a formatter for a given cell. Must implement getFormatter(column). + **/ + formatterFactory?: FormatterFactory; + + /** + * Will expand the table row divs to the full width of the container, table cell divs will remain aligned to the left + **/ + fullWidthRows?: boolean; + + /** + * + **/ + headerRowHeight?: number; + + /** + * + **/ + leaveSpaceForNewRows?: boolean; + + /** + * @see Example: Multi-Column Sort + **/ + multiColumnSort?: boolean; + + /** + * + **/ + multiSelect?: boolean; + + /** + * + **/ + rowHeight?: number; + + /** + * + **/ + selectedCellCssClass?: string; + + /** + * + **/ + showHeaderRow?: boolean; + + /** + * If true, the column being resized will change its width as the mouse is dragging the resize handle. If false, the column will resize after mouse drag ends. + **/ + syncColumnCellResize?: boolean; + + /** + * + **/ + topPanelHeight?: number; + } + + export interface DataProvider { + getItem(index: number): SlickData; + getLength(): number; + } + + export interface SlickData { + // todo ? might be able to leave as empty + } + + /** + * Selecting cells in SlickGrid is handled by a selection model. + * Selection models are controllers responsible for handling user interactions and notifying subscribers of the changes in the selection. Selection is represented as an array of Slick.Range objects. + * You can get the current selection model from the grid by calling getSelectionModel() and set a different one using setSelectionModel(selectionModel). By default, no selection model is set. + * The grid also provides two helper methods to simplify development - getSelectedRows() and setSelectedRows(rowsArray), as well as an onSelectedRowsChanged event. + * SlickGrid includes two pre-made selection models - Slick.CellSelectionModel and Slick.RowSelectionModel, but you can easily write a custom one. + **/ + export class SelectionModel { + /** + * An initializer function that will be called with an instance of the grid whenever a selection model is registered with setSelectionModel. The selection model can use this to initialize its state and subscribe to grid events. + **/ + init(grid: Grid): void; + + /** + * A destructor function that will be called whenever a selection model is unregistered from the grid by a call to setSelectionModel with another selection model or whenever a grid with this selection model is destroyed. The selection model can use this destructor to unsubscribe from grid events and release all resources (remove DOM nodes, event listeners, etc.). + **/ + destroy(): void; + + onSelectedRangesChanged: Slick.SlickEvent; + } + + export class Grid { + + /** + * Create an instance of the grid. + * @param container Container node to create the grid in. This can be a DOM Element, a jQuery node, or a jQuery selector. + * @param data Databinding source. This can either be a regular JavaScript array or a custom object exposing getItem(index) and getLength() functions. + * @param columns An array of column definition objects. See Column Options for a list of options that can be included on each column definition object. + * @param options Additional options. See Grid Options for a list of options that can be included. + **/ + constructor( + container: string, + data: T[], + columns: Column[], + options: GridOptions); + constructor( + container: HTMLElement, + data: T[], + columns: Column[], + options: GridOptions); + constructor( + container: string, + data: DataProvider, + columns: Column[], + options: GridOptions); + constructor( + container: HTMLElement, + data: DataProvider, + columns: Column[], + options: GridOptions); + + // #region Core + + /** + * Initializes the grid. Called after plugins are registered. Normally, this is called by the constructor, so you don't need to call it. However, in certain cases you may need to delay the initialization until some other process has finished. In that case, set the explicitInitialization option to true and call the grid.init() manually. + **/ + public init(): void; + + /** + * todo: no docs + **/ + public destroy(): void; + + /** + * Returns an array of every data object, unless you're using DataView in which case it returns a DataView object. + * @return + **/ + public getData(): any; + //public getData(): T[]; + // Issue: typescript limitation, cannot differentiate calls by return type only, so need to cast to DataView or T[]. + //public getData(): DataView; + + /** + * Returns the databinding item at a given position. + * @param index Item index. + * @return + **/ + public getDataItem(index: number): T; + + /** + * Sets a new source for databinding and removes all rendered rows. Note that this doesn't render the new rows - you can follow it with a call to render() to do that. + * @param newData New databinding source. This can either be a regular JavaScript array or a custom object exposing getItem(index) and getLength() functions. + * @param scrollToTop If true, the grid will reset the vertical scroll position to the top of the grid. + **/ + public setData(newData: T[], scrollToTop: boolean): void; + + /** + * Returns the size of the databinding source. + * @return + **/ + public getDataLength(): number; + + /** + * Returns an object containing all of the Grid options set on the grid. See a list of Grid Options here. + * @return + **/ + public getOptions(): GridOptions; + + /** + * Returns an array of row indices corresponding to the currently selected rows. + * @return + **/ + public getSelectedRows(): number[]; + + /** + * Returns the current SelectionModel. See here for more information about SelectionModels. + * @return + **/ + public getSelectionModel(): SelectionModel; + + /** + * Extends grid options with a given hash. If an there is an active edit, the grid will attempt to commit the changes and only continue if the attempt succeeds. + * @options An object with configuration options. + **/ + public setOptions(options: GridOptions): void; + + /** + * Accepts an array of row indices and applies the current selectedCellCssClass to the cells in the row, respecting whether cells have been flagged as selectable. + * @param rowsArray An array of row numbers. + **/ + public setSelectedRows(rowsArray: number[]): void; + + /** + * Unregisters a current selection model and registers a new one. See the definition of SelectionModel for more information. + * @selectionModel A SelectionModel. + **/ + public setSelectionModel(selectionModel: SelectionModel): void; // todo: don't know the type of the event data type + + // #endregion Core + + // #region Columns + + /** + * Proportionately resizes all columns to fill available horizontal space. This does not take the cell contents into consideration. + **/ + public autosizeColumns(): void; + + /** + * Returns the index of a column with a given id. Since columns can be reordered by the user, this can be used to get the column definition independent of the order: + * @param id A column id. + * @return + **/ + public getColumnIndex(id: string): number; + + /** + * Returns an array of column definitions, containing the option settings for each individual column. + * @return + **/ + public getColumns(): Column[]; + + /** + * Sets grid columns. Column headers will be recreated and all rendered rows will be removed. To rerender the grid (if necessary), call render(). + * @param columnDefinitions An array of column definitions. + **/ + public setColumns(columnDefinitions: Column[]): void; + + /** + * Accepts a columnId string and an ascending boolean. Applies a sort glyph in either ascending or descending form to the header of the column. Note that this does not actually sort the column. It only adds the sort glyph to the header. + * @param columnId + * @param ascending + **/ + public setSortColumn(columnId: string, ascending: boolean): void; + + /** + * Accepts an array of objects in the form [ { columnId: [string], sortAsc: [boolean] }, ... ]. When called, this will apply a sort glyph in either ascending or descending form to the header of each column specified in the array. Note that this does not actually sort the column. It only adds the sort glyph to the header + * @param cols + **/ + public setSortColumns(cols: { columnId: string; sortAsc: boolean }[]): void; + + /** + * todo: no docs or comments available + * @return + **/ + public getSortColumns(): Column[]; + + /** + * Updates an existing column definition and a corresponding header DOM element with the new title and tooltip. + * @param columnId Column id. + * @param title New column name. + * @param toolTip New column tooltip. + **/ + public updateColumnHeader(columnId: string, title: string, toolTip?: string): void; + + // #endregion Columns + + // #region Cells + + /** + * Adds an "overlay" of CSS classes to cell DOM elements. SlickGrid can have many such overlays associated with different keys and they are frequently used by plugins. For example, SlickGrid uses this method internally to decorate selected cells with selectedCellCssClass (see options). + * @param key A unique key you can use in calls to setCellCssStyles and removeCellCssStyles. If a hash with that key has already been set, an exception will be thrown. + * @param hash A hash of additional cell CSS classes keyed by row number and then by column id. Multiple CSS classes can be specified and separated by space. + * @example + * { + * 0: { + * "number_column": "cell-bold", + * "title_column": "cell-title cell-highlighted" + * }, + * 4: { + * "percent_column": "cell-highlighted" + * } + * } + **/ + public addCellCssStyles(key: string, hash: CellCssStylesHash): void; + + /** + * Returns true if you can click on a given cell and make it the active focus. + * @param row A row index. + * @param col A column index. + * @return + **/ + public canCellBeActive(row: number, col: number): boolean; + + /** + * Returns true if selecting the row causes this particular cell to have the selectedCellCssClass applied to it. A cell can be selected if it exists and if it isn't on an empty / "Add New" row and if it is not marked as "unselectable" in the column definition. + * @param row A row index. + * @param col A column index. + * @return + **/ + public canCellBeSelected(row: number, col: number): boolean; + + /** + * Attempts to switch the active cell into edit mode. Will throw an error if the cell is set to be not editable. Uses the specified editor, otherwise defaults to any default editor for that given cell. + * @param editor A SlickGrid editor (see examples in slick.editors.js). + **/ + public editActiveCell(editor: Editors.Editor): void; + + /** + * Flashes the cell twice by toggling the CSS class 4 times. + * @param row A row index. + * @param cell A column index. + * @param speed (optional) - The milliseconds delay between the toggling calls. Defaults to 100 ms. + **/ + public flashCell(row: number, cell: number, speed?: number): void; + + /** + * Returns an object representing the coordinates of the currently active cell: + * @example + * { + * row: activeRow, + * cell: activeCell + * } + * @return + **/ + public getActiveCell(): Cell; + + /** + * Returns the DOM element containing the currently active cell. If no cell is active, null is returned. + * @return + **/ + public getActiveCellNode(): HTMLElement; + + /** + * Returns an object representing information about the active cell's position. All coordinates are absolute and take into consideration the visibility and scrolling position of all ancestors. + * @return + **/ + public getActiveCellPosition(): CellPosition; + + /** + * Accepts a key name, returns the group of CSS styles defined under that name. See setCellCssStyles for more info. + * @param key A string. + * @return + **/ + public getCellCssStyles(key: string): CellCssStylesHash; + + /** + * Returns the active cell editor. If there is no actively edited cell, null is returned. + * @return + **/ + public getCellEditor(): Editors.Editor; + + /** + * Returns a hash containing row and cell indexes from a standard W3C/jQuery event. + * @param e A standard W3C/jQuery event. + * @return + **/ + public getCellFromEvent(e: SlickEvent): Cell; // todo: !! Unsure on return type !! + + /** + * Returns a hash containing row and cell indexes. Coordinates are relative to the top left corner of the grid beginning with the first row (not including the column headers). + * @param x An x coordinate. + * @param y A y coordinate. + * @return + **/ + public getCellFromPoint(x: number, y: number): Cell; // todo: !! Unsure on return type !! + + /** + * Returns a DOM element containing a cell at a given row and cell. + * @param row A row index. + * @param cell A column index. + * @return + **/ + public getCellNode(row: number, cell: number): HTMLElement; + + /** + * Returns an object representing information about a cell's position. All coordinates are absolute and take into consideration the visibility and scrolling position of all ancestors. + * @param row A row index. + * @param cell A column index. + * @return + **/ + public getCellNodeBox(row: number, cell: number): CellPosition; + + /** + * Accepts a row integer and a cell integer, scrolling the view to the row where row is its row index, and cell is its cell index. Optionally accepts a forceEdit boolean which, if true, will attempt to initiate the edit dialogue for the field in the specified cell. + * Unlike setActiveCell, this scrolls the row into the viewport and sets the keyboard focus. + * @param row A row index. + * @param cell A column index. + * @param forceEdit If true, will attempt to initiate the edit dialogue for the field in the specified cell. + * @return + **/ + public gotoCell(row: number, cell: number, forceEdit?: boolean): void; + + /** + * todo: no docs + * @return + **/ + public getTopPanel(): HTMLElement; + + /** + * todo: no docs + * @param visible + **/ + public setTopPanelVisibility(visible: boolean): void; + + /** + * todo: no docs + * @param visible + **/ + public setHeaderRowVisibility(visible: boolean): void; + + /** + * todo: no docs + * @return + **/ + public getHeaderRow(): HTMLElement; + + /** + * todo: no docs, return type is probably wrong -> "return $header && $header[0]" + * @param columnId + * @return + **/ + public getHeaderRowColumn(columnId: string): Column; + + /** + * todo: no docs + * @return + **/ + public getGridPosition(): CellPosition; + + /** + * Switches the active cell one row down skipping unselectable cells. Returns a boolean saying whether it was able to complete or not. + * @return + **/ + public navigateDown(): boolean; + + /** + * Switches the active cell one cell left skipping unselectable cells. Unline navigatePrev, navigateLeft stops at the first cell of the row. Returns a boolean saying whether it was able to complete or not. + * @return + **/ + public navigateLeft(): boolean; + + /** + * Tabs over active cell to the next selectable cell. Returns a boolean saying whether it was able to complete or not. + * @return + **/ + public navigateNext(): boolean; + + /** + * Tabs over active cell to the previous selectable cell. Returns a boolean saying whether it was able to complete or not. + * @return + **/ + public navigatePrev(): boolean; + + /** + * Switches the active cell one cell right skipping unselectable cells. Unline navigateNext, navigateRight stops at the last cell of the row. Returns a boolean saying whether it was able to complete or not. + * @return + **/ + public navigateRight(): boolean; + + /** + * Switches the active cell one row up skipping unselectable cells. Returns a boolean saying whether it was able to complete or not. + * @return + **/ + public navigateUp(): boolean; + + /** + * Removes an "overlay" of CSS classes from cell DOM elements. See setCellCssStyles for more. + * @param key A string key. + **/ + public removeCellCssStyles(key: string): void; + + /** + * Resets active cell. + **/ + public resetActiveCell(): void; + + /** + * Sets an active cell. + * @param row A row index. + * @param cell A column index. + **/ + public setActiveCell(row: number, cell: number): void; + + /** + * Sets CSS classes to specific grid cells by calling removeCellCssStyles(key) followed by addCellCssStyles(key, hash). key is name for this set of styles so you can reference it later - to modify it or remove it, for example. hash is a per-row-index, per-column-name nested hash of CSS classes to apply. + * Suppose you have a grid with columns: + * ["login", "name", "birthday", "age", "likes_icecream", "favorite_cake"] + * ...and you'd like to highlight the "birthday" and "age" columns for people whose birthday is today, in this case, rows at index 0 and 9. (The first and tenth row in the grid). + * @param key A string key. Will overwrite any data already associated with this key. + * @param hash A hash of additional cell CSS classes keyed by row number and then by column id. Multiple CSS classes can be specified and separated by space. + **/ + public setCellCssStyles(key: string, hash: CellCssStylesHash): void; + + // #endregion Cells + + // #region Events + + public onScroll: Slick.SlickEvent; + public onSort: Slick.SlickEvent>; + public onHeaderMouseEnter: Slick.SlickEvent>; + public onHeaderMouseLeave: Slick.SlickEvent>; + public onHeaderContextMenu: Slick.SlickEvent>; + public onHeaderClick: Slick.SlickEvent>; + public onHeaderCellRendered: Slick.SlickEvent>; + public onBeforeHeaderCellDestroy: Slick.SlickEvent>; + public onHeaderRowCellRendered: Slick.SlickEvent>; + public onBeforeHeaderRowCellDestroy: Slick.SlickEvent>; + public onMouseEnter: Slick.SlickEvent; + public onMouseLeave: Slick.SlickEvent; + public onClick: Slick.SlickEvent; + public onDblClick: Slick.SlickEvent; + public onContextMenu: Slick.SlickEvent; + public onKeyDown: Slick.SlickEvent; + public onAddNewRow: Slick.SlickEvent>; + public onValidationError: Slick.SlickEvent>; + public onColumnsReordered: Slick.SlickEvent; + public onColumnsResized: Slick.SlickEvent; + public onCellChange: Slick.SlickEvent>; + public onBeforeEditCell: Slick.SlickEvent>; + public onBeforeCellEditorDestroy: Slick.SlickEvent>; + public onBeforeDestroy: Slick.SlickEvent; + public onActiveCellChanged: Slick.SlickEvent; + public onActiveCellPositionChanged: Slick.SlickEvent; + public onDragInit: Slick.SlickEvent; + public onDragStart: Slick.SlickEvent; + public onDrag: Slick.SlickEvent; + public onDragEnd: Slick.SlickEvent; + public onSelectedRowsChanged: Slick.SlickEvent; + public onCellCssStylesChanged: Slick.SlickEvent; + // #endregion Events + + // #region Plugins + + public registerPlugin(plugin: Plugin): void; + public unregisterPlugin(plugin: Plugin): void; + + // #endregion Plugins + + // #region Rendering + + public render(): void; + public invalidate(): void; + public invalidateRow(row: number): void; + public invalidateRows(rows: number[]): void; + public updateCell(row: number, cell: number): void; + public updateRow(row: number): void; + public getViewport(viewportTop?: number, viewportLeft?: number): Viewport; + public getRenderedRange(viewportTop: number, viewportLeft: number): Viewport; + public resizeCanvas(): void; + public updateRowCount(): void; + public scrollRowIntoView(row: number, doPaging: boolean): void; + public scrollRowToTop(row: number): void; + public scrollCellIntoView(row: number, cell: number, doPaging: boolean): void; + public getCanvasNode(): HTMLCanvasElement; + public focus(): void; + + // #endregion Rendering + + // #region Editors + + public getEditorLock(): EditorLock; + public getEditController(): Editors.Editor; + + // #endregion Editors + } + + export interface OnCellCssStylesChangedEventData { + key: string; + hash: CellCssStylesHash; + } + + export interface OnSelectedRowsChangedEventData { + rows: number[]; + } + + export interface OnDragEndEventData { + // todo: need to understand $canvas drag event parameter's 'dd' object + // the documentation is not enlightening + } + + export interface OnDragEventData { + // todo: need to understand $canvas drag event parameter's 'dd' object + // the documentation is not enlightening + } + + export interface OnDragStartEventData { + // todo: need to understand $canvas drag event parameter's 'dd' object + // the documentation is not enlightening + } + + export interface OnDragInitEventData { + // todo: need to understand $canvas drag event parameter's 'dd' object + // the documentation is not enlightening + } + + export interface OnActiveCellPositionChangedEventData { + + } + + export interface OnActiveCellChangedEventData { + row: number; + cell: number; + } + + export interface OnBeforeDestroyEventData { + + } + + export interface OnBeforeCellEditorDestroyEventData { + editor: Editors.Editor; + } + + export interface OnBeforeEditCellEventData { + row: number; + cell: number; + item: T; + column: Column; + } + + export interface OnCellChangeEventData { + row: number; + cell: number; + item: T; + } + + export interface OnColumnsResizedEventData { + + } + + export interface OnColumnsReorderedEventData { + + } + + export interface OnValidationErrorEventData { + editor: Editors.Editor; + cellNode: HTMLElement; + validationResults: ValidateResults; + row: number; + cell: number; + column: Column; + } + + export interface OnAddNewRowEventData { + item: T; + column: Column; + } + + export interface OnKeyDownEventData { + row: number; + cell: number; + } + + export interface OnContextMenuEventData { + + } + + export interface OnDblClickEventData { + row: number; + cell: number; + } + + export interface OnClickEventData { + row: number; + cell: number; + } + + export interface OnMouseLeaveEventData { + + } + + export interface OnMouseEnterEventData { + + } + + export interface OnBeforeHeaderRowCellDestroyEventData { + node: HTMLElement; // todo: might be JQuery instance + column: Column; + } + + export interface OnHeaderRowCellRenderedEventData { + node: HTMLElement; // todo: might be JQuery instance + column: Column; + } + + export interface OnBeforeHeaderCellDestroyEventData { + node: HTMLElement; // todo: might be JQuery instance + column: Column; + } + + export interface OnHeaderCellRenderedEventData { + node: HTMLElement; // todo: might be JQuery instance + column: Column; + } + + export interface OnHeaderClickEventData { + column: Column; + } + + export interface OnHeaderContextMenuEventData { + column: Column; + } + + export interface OnHeaderMouseEventData { + column: Column; + } + + // todo: merge with existing column definition + export interface Column { + sortCol?: string; + sortAsc?: boolean; + } + + export interface OnSortEventData { + multiColumnSort: boolean; + sortCol?: Column; + sortCols: Column[]; + sortAsc?: boolean; + } + + export interface OnScrollEventData { + scrollLeft: number; + scrollTop: number; + } + + export interface Cell { + row: number; + cell: number; + } + + export interface CellPosition extends Position { + bottom: number; + height: number; + right: number; + visible: boolean; + width: number; + } + + export interface Position { + top: number; + left: number; + } + + export interface CellCssStylesHash { + [index: number]: { + [id: string]: string; + } + } + + export interface Viewport { + top: number; + bottom: number; + leftPx: number; + rightPx: number; + } + + export interface ValidateResults { + valid: boolean; + msg: string; + } + + export module Editors { + + export interface EditorOptions { + column: Column; + container: HTMLElement; + grid: Grid; + } + + export class Editor { + constructor(args: EditorOptions); + public init(): void; + public destroy(): void; + public focus(): void; + public loadValue(item): void; // todo: typeof(item) + public applyValue(item, state: string): void; // todo: typeof(item) + public isValueChanged(): boolean; + public serializeValue(): any; + public validate(): ValidateResults; + } + + export class Text extends Editor { + constructor(args: EditorOptions); + + public getValue(): string; + public setValue(val: string): void; + public serializeValue(): string; + } + + export class Integer extends Editor { + constructor(args: EditorOptions); + + public serializeValue(): number; + } + + export class Date extends Editor { + constructor(args: EditorOptions); + + public show(): void; + public hide(): void; + public position(position: Position): void; + public serializeValue(): string; + } + + export class YesNoSelect extends Editor { + constructor(args: EditorOptions); + + public serializeValue(): boolean; + } + + export class Checkbox extends Editor { + constructor(args: EditorOptions); + + public serializeValue(): boolean; + + } + export class PercentComplete extends Editor { + constructor(args: EditorOptions); + + public serializeValue(): number; + } + + export class LongText extends Editor { + constructor(args: EditorOptions); + + public handleKeyDown(e: Event): void; + public save(): void; + public cancel(): void; + public hide(): void; + public show(): void; + public position(position: Position): void; + public serializeValue(): string; + } + } + + export interface Formatter { + (row: number, cell: number, columnDef: Column, dataContext: SlickData): string; + } + + export module Formatters { + var PercentComplete: Formatter; + var PercentCompleteBar: Formatter; + var YesNo: Formatter; + var Checkmark: Formatter; + } + + export module Data { + + export interface DataViewOptions { + groupItemMetadataProvider: GroupItemMetadataProvider; + inlineFilters: boolean; + } + + /** + * Item -> Data by index + * Row -> Data by row + **/ + export class DataView { + + constructor(options: DataViewOptions); + + public beginUpdate(): void; + public endUpdate(): void; + public setPagingOptions(args: PagingOptions): void; + public getPagingInfo(): PagingOptions; + public getItems(): T[]; + public setItems(data: T[], objectIdProperty?: string): void; + public setFilter(filterFn: (item: T, args) => boolean): void; // todo: typeof(args) + public sort(comparer: Function, ascending: boolean): void; // todo: typeof(comparer), should be the same callback as Array.sort + public fastSort(field: string, ascending: boolean): void; + public fastSort(field: Function, ascending: boolean): void; // todo: typeof(field), should be the same callback as Array.sort + public reSort(): void; + public setGrouping(groupingInfo: GroupingOptions): void; + public getGrouping(): GroupingOptions; + + /** + * @deprecated + **/ + public groupBy(valueGetter, valueFormatter, sortComparer): void; + + /** + * @deprecated + **/ + public setAggregators(groupAggregators, includeCollapsed): void; + + /** + * @param level Optional level to collapse. If not specified, applies to all levels. + **/ + public collapseAllGroups(level?: number): void; + + /** + * @param level Optional level to collapse. If not specified, applies to all levels. + **/ + public expandAllGroups(level?: number): void; + + /** + * @param varArgs Either a Slick.Group's "groupingKey" property, or a + * variable argument list of grouping values denoting a unique path to the row. For + * example, calling collapseGroup('high', '10%') will collapse the '10%' subgroup of + * the 'high' setGrouping. + */ + public collapseGroup(...varArgs: string[]): void; + + /** + * @param varArgs Either a Slick.Group's "groupingKey" property, or a + * variable argument list of grouping values denoting a unique path to the row. For + * example, calling expandGroup('high', '10%') will expand the '10%' subgroup of + * the 'high' setGrouping. + */ + public expandGroup(...varArgs: string[]): void; + public getGroups(): Group[]; + public getIdxById(): string; + public getRowById(): T; + public getItemById(): T; + public getItemByIdx(): T; + public mapRowsToIds(rowArray: T[]): string[]; + public setRefreshHints(hints: RefreshHints): void; + public setFilterArgs(hints: RefreshHints): void; + public refresh(): void; + public updateItem(id: string, item: T): void; + public insertItem(insertBefore: number, item: T): void; + public addItem(item: T): void; + public deleteItem(id: string): void; + public syncGridSelection(grid: Grid, preserveHidden: boolean): void; + public syncGridCellCssStyles(grid: Grid, key: string): void; + + public getLength(): number; + public getItem(): void; + public getItemMetadata(): void; + + public onRowCountChanged: Slick.SlickEvent; + public onRowsChanged: Slick.SlickEvent; + public onPagingInfoChanged: Slick.SlickEvent; + } + + export interface GroupingOptions { + getter: Function; // todo + formatter: Formatter; + comparer: (a, b) => any; // todo + predefinedValues: any[]; // todo + aggregators: Aggregators.Aggregator[]; + aggregateEmpty: boolean; + aggregateCollapsed: boolean; + aggregateChildGroups: boolean; + collapsed: boolean; + displayTotalsRow: boolean; + } + + export interface PagingOptions { + pageSize?: number; + pageNum?: number; + totalRows?: number; + totalPages?: number; + } + + export interface RefreshHints { + isFilterNarrowing: boolean; + isFilterExpanding: boolean; + isFilterUnchanged: boolean; + ignoreDiffsBefore: boolean; + ignoreDiffsAfter: boolean; + } + + export interface OnRowCountChangedEventData { + // empty + } + export interface OnRowsChangedEventData { + // empty + } + export interface OnPagingInfoChangedEventData extends PagingOptions { + + } + + export module Aggregators { + export class Aggregator { + public field: string; + public init(): void; + public accumulate(item: T): void; + public storeResult(groupTotals: GroupTotals): void; // todo "R" + } + + export class Avg extends Aggregator { + + } + + export class Min extends Aggregator { + + } + + export class Max extends Aggregator { + + } + + export class Sum extends Aggregator { + + } + } + + /*** + * Provides item metadata for group (Slick.Group) and totals (Slick.Totals) rows produced by the DataView. + * This metadata overrides the default behavior and formatting of those rows so that they appear and function + * correctly when processed by the grid. + * + * This class also acts as a grid plugin providing event handlers to expand & collapse groups. + * If "grid.registerPlugin(...)" is not called, expand & collapse will not work. + * + * @class GroupItemMetadataProvider + * @module Data + * @namespace Slick.Data + * @constructor + * @param options + */ + export class GroupItemMetadataProvider { + public init(): void; + public destroy(): void; + public getGroupRowMetadata(): GroupRowMetadata; + public getTotalsRowMetadata(): TotalsRowMetadata; + } + + export interface GroupRowMetadata { + selectable: boolean; + focusable: boolean; + cssClasses: string; + columns: { + 0: { + colspan: string; + formatter: Formatter; + editor: Slick.Editors.Editor; + } + }; + } + + export interface TotalsRowMetadata { + selectable: boolean; + focusable: boolean; + cssClasses: string; + formatter: Formatter; + editor: Slick.Editors.Editor; + } + + export interface GroupItemMetadataProviderOptions { + groupCssClass?: string; + groupTitleCssClass?: string; + totalsCssClass?: string; + groupFocusable?: boolean; + totalsFocusable?: boolean; + toggleCssClass?: string; + toggleExpandedCssCass?: string; + toggleCollapsedCssClass?: string; + enableExpandCollapse?: boolean; + } + + //export class RemoteModel { + // public data: any; + + // public clear(): any; + // public isDataLoaded(): any; + // public ensureData(): any; + // public reloadData(): any; + // public setSort(): any; + // public setSearch(): any; + + // public onDataLoading: Slick.SlickEvent; + // public onDataLoaded: Slick.SlickEvent; + + //} + + //export interface OnDataLoadingEventData { + + //} + + //export interface OnDataLoadedEventData { + + //} + } + + export class Plugin { + + constructor(options: PluginOptions); + public init(grid: Grid): void; + public destroy(): void; + } + + export interface PluginOptions { + // extend your plugin options here + } +} + diff --git a/sugar/sugar-tests.ts b/sugar/sugar-tests.ts deleted file mode 100644 index 989fa53493..0000000000 --- a/sugar/sugar-tests.ts +++ /dev/null @@ -1,579 +0,0 @@ -/// - -'schfifty'.add(' five'); // - > schfifty five -'dopamine'.insert('e', 3); // - > dopeamine -'spelling eror'.insert('r', -3);// - > spelling error - -'Welcome, Mr. {name}.'.assign({ name: 'Franklin' }); // - > 'Welcome, Mr. Franklin.' -'You are {1} years old today.'.assign(14); // - > 'You are 14 years old today.' -'{n} and {r}'.assign({ n: 'Cheech' }, { r: 'Chong' }); // - > 'Cheech and Chong' - -'jumpy'.at(0); // - > 'j' -'jumpy'.at(2); //- > 'm' -'jumpy'.at(5); // - > 'j' -'jumpy'.at(5, false); // - > '' -'jumpy'.at(-1); // - > 'y' -'lucky charms'.at(2, 4, 6, 8); // - > ['u', 'k', 'y', c'] - -'caps_lock'.camelize(); // - > 'CapsLock' -'moz-border-radius'.camelize(); // - > 'MozBorderRadius' -'moz-border-radius'.camelize(false); // - > 'mozBorderRadius' - -'caps_lock'.camelize(); // - > 'CapsLock' -'moz-border-radius'.camelize(); // - > 'MozBorderRadius' -'moz-border-radius'.camelize(false); // - > 'mozBorderRadius' - -'jumpy'.chars(); // - > ['j', 'u', 'm', 'p', 'y'] -'jumpy'.chars(function (c) { - // Called 5 times: "j","u","m","p","y" -}); - -'jumpy'.codes(); // - > [106, 117, 109, 112, 121] -'jumpy'.codes(function (c) { - // Called 5 times: 106, 117, 109, 112, 121 -}); - -'too \n much \n space'.compact(); // - > 'too much space' -'enough \n '.compact(); // - > 'enough' - -'a_farewell_to_arms'.dasherize(); // - > 'a-farewell-to-arms' -'capsLock'.dasherize(); // - > 'caps-lock' - -'aHR0cDovL3R3aXR0ZXIuY29tLw=='.decodeBase64(); // - > 'http://twitter.com/' -'anVzdCBnb3QgZGVjb2RlZA=='.decodeBase64(); // - > 'just got decoded!' - -'jumpy'.each(); // - > ['j', 'u', 'm', 'p', 'y'] -'jumpy'.each(/[r-z]/); // - > ['u', 'y'] -'jumpy'.each(/[r-z]/, function (m) { - // Called twice: "u", "y" -}); - -'gonna get encoded!'.encodeBase64(); // - > 'Z29ubmEgZ2V0IGVuY29kZWQh' -'http://twitter.com/'.encodeBase64(); // - > 'aHR0cDovL3R3aXR0ZXIuY29tLw==' - -'jumpy'.endsWith('py'); // - > true -'jumpy'.endsWith(/[q-z]/); // - > true -'jumpy'.endsWith('MPY'); // - > false -'jumpy'.endsWith('MPY', false); // - > true - -'

some text

'.escapeHTML(); // - > '<p>some text</p>' -'one & two'.escapeHTML(); // - > 'one & two' - -'really?'.escapeRegExp(); // - > 'really\?' -'yes.'.escapeRegExp(); // - > 'yes\.' -'(not really)'.escapeRegExp(); // - > '\(not really\)' - -'http://foo.com/"bar"'.escapeURL(); // - > 'http://foo.com/%22bar%22' -'http://foo.com/"bar"'.escapeURL(true); // - > 'http%3A%2F%2Ffoo.com%2F%22bar%22' - -'lucky charms'.first(); // - > 'l' -'lucky charms'.first(3); // - > 'luc' - -'lucky charms'.from(); // - > 'lucky charms' -'lucky charms'.from(7); // - > 'harms' - -// visual studio is not liking these characters very much. -'??? YAMADA??!'.hankaku(); // - > '??? YAMADA??!' -'??? YAMADA??!'.hankaku('a'); // - > '??? YAMADA??!' -'??? YAMADA??!'.hankaku('alphabet'); // - > '??? YAMADA??!' -'?????! 25???!'.hankaku('katakana', 'numbers'); // - > '?????! 25???!' -'?????! 25???!'.hankaku('k', 'n'); // - > '?????! 25???!' -'?????! 25???!'.hankaku('kn'); // - > '?????! 25???!' -'?????! 25???!'.hankaku('sp'); // - > '?????! 25???!' - -'jumpy'.has('py'); // - > true -'broken'.has(/[a-n]/); // - > true -'broken'.has(/[s-z]/); // - > false - -// visual studio is not liking these characters very much. -'?????'.hasArabic(); // - > true -'?????'.hasCyrillic(); // - > true -'? ?????!'.hasHangul(); // - > true -'??????'.hasKatakana(); // - > true -"l'année".hasLatin(); // - > true - -// visual studio is not liking these characters very much. -'????'.hiragana(); // - > '????' -'?????'.hiragana(); // - > '?????' -'????'.hiragana(); // - > '????' -'????'.hiragana(false); // - > '????' - -'employee_salary'.humanize(); // - > 'Employee salary' -'author_id'.humanize(); // - > 'Author' - -''.isBlank(); // - > true -' '.isBlank(); // - > true -'noway'.isBlank(); // - > false - -// visual studio is not liking these characters very much. -'?????'.isArabic(); // - > true -'?????'.isCyrillic(); // - > true -'? ?????!'.isHangul(); // - > true -'??????'.isKatakana(); // - > false -"l'année".isLatin(); // - > true - -// visual studio is not liking these characters very much. -'????'.katakana(); // - > '????' -'?????'.katakana(); // - > '?????' - -'lucky charms'.last(); // - > 's' -'lucky charms'.last(3); // - > 'rms' - -'broken wear\nand\njumpy jump'.lines(); // - > ['broken wear', 'and', 'jumpy jump'] -'broken wear\nand\njumpy jump'.lines(function (l) { - // Called three times: "broken wear", "and", "jumpy jump" -}); - -'á'.normalize(); // - > 'a' -'Ménage à trois'.normalize(); // - > 'Menage a trois' -'Volkswagen'.normalize(); // - > 'Volkswagen' -'FULLWIDTH'.normalize(); // - > 'FULLWIDTH' - -'wasabi'.pad('-'); // - > '-wasabi-' -'wasabi'.pad('-', 2); // - > '--wasabi--' -'wasabi'.padLeft('-', 2); // - > '--wasabi' -'wasabi'.padRight('-', 2); // - > 'wasabi--' - -'Once upon a time.\n\nIn the land of oz...'.paragraphs(); // - > ['Once upon a time.', 'In the land of oz...'] -'Once upon a time.\n\nIn the land of oz...'.paragraphs(function (p) { - // Called twice: "Once upon a time.", "In teh land of oz..." -}); - -'hell, no!'.parameterize(); // - > 'hell-no' - -'post'.pluralize(); // - > 'posts' -'octopus'.pluralize(); // - > 'octopi' -'sheep'.pluralize(); // - > 'sheep' -'words'.pluralize(); // - > 'words' -'CamelOctopus'.pluralize(); // - > 'CamelOctopi' - -'schfifty five'.remove('f'); // - > 'schity ive' -'schfifty five'.remove(/[a-f]/g); // - > 'shity iv' - -'

just some text

'.removeTags(); // - > '' -'

just some text

'.removeTags('b'); // - > '

just text

' - -'jumpy'.repeat(2); // - > 'jumpyjumpy' -'a'.repeat(5); // - > 'aaaaa' -'a'.repeat(0); // - > '' - -'jumpy'.reverse(); // - > 'ypmuj' -'lucky charms'.reverse(); // - > 'smrahc ykcul' - -'a'.shift(1); // - > 'b' -'?'.shift(1); //- > '?' - -'posts'.singularize(); // -> 'post' -'octopi'.singularize(); // -> 'octopus' -'sheep'.singularize(); // -> 'sheep' -'word'.singularize(); // -> 'word' -'CamelOctopi'.singularize(); // -> 'CamelOctopus' - -'camelCase'.spacify(); // - > 'camel case' -'an-ugly-string'.spacify(); // - > 'an ugly string' -'oh-no_youDid-not'.spacify().capitalize(true); // - > 'something else' - -'hello'.startsWith('hell'); // - > true -'hello'.startsWith(/[a-h]/); // - > true -'hello'.startsWith('HELL'); // - > false -'hello'.startsWith('HELL', false); // - > true - -'

just some text

'.stripTags(); // - > 'just some text' -'

just some text

'.stripTags('p'); // - > 'just some text' - -'man from the boondocks'.titleize(); // - > 'Man from the Boondocks' -'x-men: the last stand'.titleize(); // - > 'X Men: The Last Stand' -'TheManWithoutAPast'.titleize(); // - > 'The Man Without a Past' -'raiders_of_the_lost_ark'.titleize(); // - > 'Raiders of the Lost Ark' - -'lucky charms'.to(); // - > 'lucky charms' -'lucky charms'.to(7); // - > 'lucky ch' - -'153'.toNumber(); // - > 153 -'12,000'.toNumber(); // - > 12000 -'10px'.toNumber(); // - > 10 -'ff'.toNumber(16); // - > 255 - -' wasabi '.trim(); // - > 'wasabi' -' wasabi '.trimLeft(); // - > 'wasabi ' -' wasabi '.trimRight(); // - > ' wasabi' - -'just sittin on the dock of the bay'.truncate(20); // - > 'just sittin on the do...' -'just sittin on the dock of the bay'.truncate(20, false); // - > 'just sittin on the...' -'just sittin on the dock of the bay'.truncate(20, true, 'middle'); // - > 'just sitt...of the bay' -'just sittin on the dock of the bay'.truncate(20, true, 'left'); // - > '...the dock of the bay' - -'a-farewell-to-arms'.underscore(); // - > 'a_farewell_to_arms' -'capsLock'.underscore(); // - > 'caps_lock' - -'<p>some text</p>'.unescapeHTML(); // - > '

some text

' -'one & two'.unescapeHTML(); // - > 'one & two' - -'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL(); // - > 'http://foo.com/the bar' -'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL(true); // - > 'http%3A%2F%2Ffoo.com%2Fthe bar' - -'broken wear'.words(); // - > ['broken', 'wear'] -'broken wear'.words(function (w) { - // Called twice: "broken", "wear" -}); - -'??? YAMADA??!'.zenkaku(); // - > '??? YAMADA??!' -'??? YAMADA??!'.zenkaku('a'); // - > '??? YAMADA??!' -'??? YAMADA??!'.zenkaku('alphabet'); // - > '??? YAMADA??!' -'?????! 25???!'.zenkaku('katakana', 'numbers'); // - > '?????! 25???!' -'?????! 25???!'.zenkaku('k', 'n'); // - > '?????! 25???!' -'?????! 25???!'.zenkaku('kn'); // - > '?????! 25???!' -'?????! 25???!'.zenkaku('sp'); // - > '?????! 25???!' - -// static -//Number.random(50, 100); // - > ex.85 -//Number.random(50); // - > ex.27 -//Number.random(); // - > ex.0 - -(1000).abbr(); // - > "1k" -(1000000).abbr(); // - > "1m" -(1280).abbr(1); // - > "1.3k" - -(1000).bytes(); // - > "1kB" -(1000).bytes(2); // - > "0.98kB" -((10).pow(20)).bytes(); // - > "90,949,470TB" -((10).pow(20)).bytes(0, false); // - > "87EB" - -(1000).bytes(); // - > "1kB" -(1000).bytes(2); // - > "0.98kB" -((10).pow(20)).bytes(); // - > "90,949,470TB" -((10).pow(20)).bytes(0, false); // - > "87EB" - -(3.241).ceil(); // - > 4 -(-3.241).ceil(); // - > -3 -(3.241).ceil(2); // - > 3.25 -(3748).ceil(-2); // - > 3800 - -(65).chr(); // - > "A" -(75).chr(); // - > "K" - -(8).downto(3); // - > [8, 7, 6, 5, 4, 3] -(8).downto(3, function (n) { - // This function is called 6 times receiving n as the value. -}); -(8).downto(2, null, 2); // - > [8, 6, 4, 2] - -(500).duration(); // - > '500 milliseconds' -(1200).duration(); // - > '1 second' -(75).minutes().duration(); // - > '1 hour' -(75).minutes().duration('es'); // - > '1 hora' - -(3.241).floor(); // - > 3 -(-3.841).floor(); // - > -4 -(3.241).floor(2); // - > 3.24 -(3748).floor(-2); // - > 3700 - -(56782).format(); //- > '56,782' -(56782).format(2); // - > '56,782.00' -(4388.43).format(2, ' '); // - > '4 388.43' -(4388.43).format(2, '.', ','); // - > '4.388,43' - -(255).hex(); // - > 'ff'; -(255).hex(4); // - > '00ff'; -(23654).hex(); // - > '5c66'; - -(6).isEven(); // - > true -(17).isEven(); // - > false - -(420).isInteger(); // - > true -(4.5).isInteger(); // - > false - -(6).isMultipleOf(2); // - > true -(17).isMultipleOf(2); // - > false -(32).isMultipleOf(4); // - > true -(34).isMultipleOf(4); // - > false - -(3).isOdd(); // - > true -(18).isOdd(); // - > false - -(64).log(2); // - > 6 -(9).log(3); // - > 2 -(5).log(); // - > 1.6094379124341003 - -(3).pow(3); // - > 27 -(-3).abs(); // - > 3 -(1024).sqrt(); // - > 32 - -(1000).metric(); // - > "1k" -(1000000).metric(); // - > "1,000k" -(1000000).metric(0, false); // - > "1M" -(1249).metric(2) + 'g'; // - > "1.25kg" -(0.025).metric() + 'm'; // - > "25mm" - -(1).ordinalize(); // - > '1st' -(2).ordinalize(); // - > '2nd' -(8).ordinalize(); // - > '8th' - -(5).pad(2); // - > '05' -(-5).pad(4); // - > '-0005' -(82).pad(3, true); // - > '+082' - -(3.241).round(); // - > 3 -(-3.841).round(); // - > -4 -(3.241).round(2); // - > 3.24 -(3748).round(-2); // - > 3800 - -(8).times(function (i) { - // This function is called 8 times. -}); - -(420).toNumber(); // - > 420 - -(5).milliseconds(); // - > 5 -(10).hours(); // - > 36000000 -(1).day(); // - > 86400000 - -(5).daysAfter('tuesday'); // - > 5 days after tuesday of this week -(1).yearAfter('January 23, 1997'); // - > January 23, 1998 - -(5).weeksAgo(); // - > 5 weeks ago -(1).yearAgo(); // - > January 23, 1996 - -(5).daysBefore('tuesday'); // - > 5 days before tuesday of this week -(1).yearBefore('January 23, 1997'); // - > January 23, 1996 - -(5).weeksFromNow(); // - > 5 weeks ago -(1).yearFromNow(); // - > January 23, 1998 - -(2).upto(6); // - > [2, 3, 4, 5, 6] -(2).upto(6, function (n) { - // This function is called 5 times receiving n as the value. -}); -(2).upto(8, null, 2); // - > [2, 4, 6, 8] - - -//#region Arrays - -[1, 2, 3, 4].add(5); -[1, 2, 3, 4].add([5, 6, 7]); -[1, 2, 3, 4].insert(8, 1); - -[1, 2, 3].at(0); -[1, 2, 3].at(2); -[1, 2, 3].at(4); -[1, 2, 3].at(4, false); -[1, 2, 3].at(-1); -[1, 2, 3].at(0, 1); - -[1, 2, 3].average(); -[{age:35},{age:11},{age:11}].average(function(n) { - return n.age; -}); -[{ age: 35 }, { age: 11 }, { age: 11 }].average('age'); - -[1, 2, 3].clone(); - -[1, null, 2, undefined, 3].compact(); -[1, '', 2, false, 3].compact(); -[1, '', 2, false, 3].compact(true); - -[1, 2, 3, 1].count(1); -['a', 'b', 'c'].count(/b/); -[{a:1},{b:2}].count(function(n) { - return n['a'] > 1; -}); - -[1,2,3,4].each(function(n) { - // Called 4 times: 1, 2, 3, 4 -}); -[1,2,3,4].each(function(n) { - // Called 4 times: 3, 4, 1, 2 -}, 2, true); -[1,2,3,4].each(n => false); - -['a','a','a'].every(function(n) { - return n == 'a'; -}); -['a', 'a', 'a'].every('a'); -[{ a: 2 }, { a: 2 }].every({ a: 2 }); - -[1, 2, 3].exclude(3); -['a', 'b', 'c'].exclude(/b/); -[{a:1},{b:2}].exclude(function(n) { - return n['a'] == 1; -}); -["a", "bbb", "ccc"].exclude((e,i,a) => e.length > 2, (e,i,a) => e.length < 0); - -[1,2,3].filter(function(n) { - return n > 1; -}); -[1, 2, 2, 4].filter(2); - -[{a:1,b:2},{a:1,b:3},{a:1,b:4}].find(function(n) { - return n['a'] == 1; -}); -['cuba', 'japan', 'canada'].find(/^c/, 2); - -[{a:1,b:2},{a:1,b:3},{a:2,b:4}].findAll(function(n) { - return n['a'] == 1; -}); -['cuba', 'japan', 'canada'].findAll(/^c/); -['cuba', 'japan', 'canada'].findAll(/^c/, 2); - -[1,2,3,4].findIndex(3); -[1,2,3,4].findIndex(function(n) { - return n % 2 == 0; -}); -['one','two','three'].findIndex(/th/); - -[1, 2, 3].first(); -[1, 2, 3].first(2); - -[[1], 2, [3]].flatten(); -[['a'], [], 'b', 'c'].flatten(); - -['a','b','c'].forEach(function(a) { - // Called 3 times: 'a','b','c' -}); - -[1, 2, 3].from(1); -[1, 2, 3].from(2); - -['fee', 'fi', 'fum'].groupBy('length'); -[{age:35,name:'ken'},{age:15,name:'bob'}].groupBy(function(n) { - return n.age; -}); - -[1, 2, 3, 4, 5, 6, 7].inGroups(3); -[1, 2, 3, 4, 5, 6, 7].inGroups(3, 'none'); - -[1, 2, 3, 4, 5, 6, 7].inGroupsOf(4); -[1, 2, 3, 4, 5, 6, 7].inGroupsOf(4, 'none'); - -[1, 2, 3, 4].include(5); -[1, 2, 3, 4].include(8, 1); -[1, 2, 3, 4].include([5, 6, 7]); - -[1, 2, 3].indexOf(3); -[1, 2, 3].indexOf(7); - -[1, 3, 5].intersect([5, 7, 9]); -['a', 'b'].intersect('b', 'c'); - -[1, 2, 3].last(); -[1, 2, 3].last(2); - -[1, 2, 1].lastIndexOf(1); -[1, 2, 1].lastIndexOf(7); - -[3, 2, 2].least(); -['fe', 'fo', 'fum'].least('length'); -[{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].least(function(n) { - return n.age; -}); - -[1,2,3].map(function(n) { - return n * 3; -}); -['one','two','three'].map(function(n) { - return n.length; -}); -['one', 'two', 'three'].map('length'); - -[1, 2, 3].max(); -['fee', 'fo', 'fum'].max('length'); -['fee', 'fo', 'fum'].max('length', true); -[{a:3,a:2}].max(function(n) { - return n['a']; -}); - -[1, 2, 3].min(); -['fee', 'fo', 'fum'].min('length'); -['fee', 'fo', 'fum'].min('length', true); -['fee','fo','fum'].min(function(n) { - return n.length; -}); -[{a:3,a:2}].min(function(n) { - return n['a']; -}); - -[3, 2, 2].most(); -['fe', 'fo', 'fum'].most('length'); -[{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].most(function(n) { - return n.age; -}); - -[1, 2, 3].none(5); -['a', 'b', 'c'].none(/b/); -[{a:1},{b:2}].none(function(n) { - return n['a'] > 1; -}); - -[1, 2, 3, 4].randomize(); - -[1,2,3,4].reduce(function(a, b) { - return a - b; -}); -[1,2,3,4].reduce(function(a, b) { - return a - b; -}, 100); - -[1,2,3,4].reduceRight(function(a, b) { - return a - b; -}); - -[1, 2, 3].remove(3); -['a', 'b', 'c'].remove(/b/); -[{a:1},{b:2}].remove(function(n) { - return n['a'] == 1; -}); - -[1, 2, 3].remove(3); -['a', 'b', 'c'].remove(/b/); -[{a:1},{b:2}].remove(function(n) { - return n['a'] == 1; -}); - -['a', 'b', 'c'].removeAt(0); -[1, 2, 3, 4].removeAt(1, 3); - -[1, 2, 3, 4, 5].sample(); -[1, 2, 3, 4, 5].sample(3); - -['a','b','c'].some(function(n) { - return n == 'a'; -}); -['a','b','c'].some(function(n) { - return n == 'd'; -}); -['a', 'b', 'c'].some('a'); -[{ a: 2 }, { b: 5 }].some({ a: 2 }); - -['world', 'a', 'new'].sortBy('length'); -['world', 'a', 'new'].sortBy('length', true); -[{age:72},{age:13},{age:18}].sortBy(function(n) { - return n.age; -}); - -[1, 3, 5].subtract([5, 7, 9]); -[1, 3, 5].subtract([3], [5]); -['a', 'b'].subtract('b', 'c'); - -[1, 2, 2].sum(); -[{age:35},{age:12},{age:12}].sum(function(n) { - return n.age; -}); -[{ age: 35 }, { age: 12 }, { age: 12 }].sum('age'); - -[1, 2, 3].to(1); -[1, 2, 3].to(2); - -[1, 3, 5].union([5, 7, 9]); -['a', 'b'].union(['b', 'c']); - -[1, 2, 2, 3].unique(); -[{ foo: 'bar' }, { foo: 'bar' }].unique(); -[{foo:'bar'},{foo:'bar'}].unique(function(obj){ - return obj.foo; -}); -[{ foo: 'bar' }, { foo: 'bar' }].unique('foo'); - -[1, 2, 3].zip([4, 5, 6]); -['Martin', 'John'].zip(['Luther', 'F.'], ['King', 'Kennedy']); - -//#endregion \ No newline at end of file diff --git a/sugar/sugar.d.ts b/sugar/sugar.d.ts index 5e884de129..e376400b63 100644 --- a/sugar/sugar.d.ts +++ b/sugar/sugar.d.ts @@ -77,12 +77,11 @@ interface String { * 'jumpy'.at(-1) -> 'y' * 'lucky charms'.at(2,4,6,8) -> ['u','k','y',c'] ***/ - at(index: number, loop?: boolean): string; + at(index: number, loop?: bool): string; /** * @see at - * @limitation Typescript does not allow for arguments - * after a variable argument list. + * @limitation Typescript does not allow for arguments after a variable argument list. **/ at(...indicies: number[]): string[]; @@ -97,7 +96,7 @@ interface String { * 'moz-border-radius'.camelize() -> 'MozBorderRadius' * 'moz-border-radius'.camelize(false) -> 'mozBorderRadius' **/ - camelize(first?: boolean): string; + camelize(first?: bool): string; /** * Capitalizes the first character in the string. @@ -112,7 +111,7 @@ interface String { * 'hello kitty'.capitalize(true) -> 'Hello Kitty' * **/ - capitalize(all: boolean): string; + capitalize(all: bool): string; /** * Runs callback [fn] against each character in the string. @@ -186,12 +185,12 @@ interface String { * // Called twice: "u", "y" * }); **/ - each(search: string, fn?: (m: string) => void ): string[]; + each(search: string, fn?: (m: string) => void): string[]; /** * @see each **/ - each(search: RegExp, fn?: (m: string) => void ): string[]; + each(search: RegExp, fn?: (m: string) => void): string[]; /** * @see each @@ -221,22 +220,22 @@ interface String { * 'jumpy'.endsWith('MPY') -> false * 'jumpy'.endsWith('MPY', false) -> true **/ - endsWith(find: string, pos?: number, case_?: boolean): boolean; + endsWith(find: string, pos?: number, case_?: bool): bool; /** * @see endsWith **/ - endsWith(find: string, case_?: boolean): boolean; + endsWith(find: string, case_?: bool): bool; /** * @see endsWith **/ - endsWith(find: RegExp, pos?: number, case_?: boolean): boolean; + endsWith(find: RegExp, pos?: number, case_?: bool): bool; /** * @see endsWith **/ - endsWith(find: RegExp, case_?: boolean): boolean; + endsWith(find: RegExp, case_?: bool): bool; /** * Converts HTML characters to their entity equivalents. @@ -266,7 +265,7 @@ interface String { * 'http://foo.com/"bar"'.escapeURL() -> 'http://foo.com/%22bar%22' * 'http://foo.com/"bar"'.escapeURL(true) -> 'http%3A%2F%2Ffoo.com%2F%22bar%22' **/ - escapeURL(param?: boolean): string; + escapeURL(param?: bool): string; /** * Returns the first [n] characters of the string. @@ -322,12 +321,12 @@ interface String { * 'broken'.has(/[a-n]/) -> true * 'broken'.has(/[s-z]/) -> false **/ - has(find: string): boolean; + has(find: string): bool; /** * @see has **/ - has(find: RegExp): boolean; + has(find: RegExp): bool; /** * Returns true if the string contains any characters in Arabic. @@ -339,79 +338,79 @@ interface String { * '??????'.hasKatakana() -> true * "l'année".hasLatin() -> true **/ - hasArabic(): boolean; + hasArabic(): bool; /** * Returns true if the string contains any characters in Cyrillic. * @returns True if the string contains Cyrillic. **/ - hasCyrillic(): boolean; + hasCyrillic(): bool; /** * Returns true if the string contains any characters in Greek. * @returns True if the string contains Greek. **/ - hasGreek(): boolean; + hasGreek(): bool; /** * Returns true if the string contains any characters in Hangul. * @returns True if the string contains Hangul. **/ - hasHangul(): boolean; + hasHangul(): bool; /** * Returns true if the string contains any characters in Han. * @returns True if the string contains Han. **/ - hasHan(): boolean; + hasHan(): bool; /** * Returns true if the string contains any characters in Kanji. * @returns True if the string contains Kanji. **/ - hasKanji(): boolean; + hasKanji(): bool; /** * Returns true if the string contains any characters in Hebrew. * @returns True if the string contains Hebrew. **/ - hasHebrew(): boolean; + hasHebrew(): bool; /** * Returns true if the string contains any characters in Hiragana. * @returns True if the string contains Hiragana. **/ - hasHiragana(): boolean; + hasHiragana(): bool; /** * Returns true if the string contains any characters in Kana. * @returns True if the string contains Kana. **/ - hasKana(): boolean; + hasKana(): bool; /** * Returns true if the string contains any characters in Katakana. * @returns True if the string contains Katakana. **/ - hasKatakana(): boolean; + hasKatakana(): bool; /** * Returns true if the string contains any characters in Latin. * @returns True if the string contains Latin. **/ - hasLatin(): boolean; + hasLatin(): bool; /** * Returns true if the string contains any characters in Thai. * @returns True if the string contains Thai. **/ - hasThai(): boolean; + hasThai(): bool; /** * Returns true if the string contains any characters in Devanagari. * @returns True if the string contains Devanagari. **/ - hasDevanagari(): boolean; + hasDevanagari(): bool; /** * Converts katakana into hiragana. @@ -423,7 +422,7 @@ interface String { * '????'.hiragana() -> '????' * '????'.hiragana(false) -> '????' **/ - hiragana(all?: boolean): string; + hiragana(all?: bool): string; /** * Creates a human readable string. @@ -444,7 +443,7 @@ interface String { * ' '.isBlank() -> true * 'noway'.isBlank() -> false **/ - isBlank(): boolean; + isBlank(): bool; /** * Returns true if the string contains only characters in Arabic. Whitespace is ignored. @@ -456,79 +455,79 @@ interface String { * '??????'.isKatakana() -> false * "l'année".isLatin() -> true **/ - isArabic(): boolean; + isArabic(): bool; /** * Returns true if the string contains only characters in Cyrillic. Whitespace is ignored. * @returns True if the string containsly only characters in Cyrillic. **/ - isCyrillic(): boolean; + isCyrillic(): bool; /** * Returns true if the string contains only characters in Greek. Whitespace is ignored. * @returns True if the string containsly only characters in Greek. **/ - isGreek(): boolean; + isGreek(): bool; /** * Returns true if the string contains only characters in Hangul. Whitespace is ignored. * @returns True if the string containsly only characters in Hangul. **/ - isHangul(): boolean; + isHangul(): bool; /** * Returns true if the string contains only characters in Han. Whitespace is ignored. * @returns True if the string containsly only characters in Han. **/ - isHan(): boolean; + isHan(): bool; /** * Returns true if the string contains only characters in Kanji. Whitespace is ignored. * @returns True if the string containsly only characters in Kanji. **/ - isKanji(): boolean; + isKanji(): bool; /** * Returns true if the string contains only characters in Hebrew. Whitespace is ignored. * @returns True if the string containsly only characters in Hebrew. **/ - isHebrew(): boolean; + isHebrew(): bool; /** * Returns true if the string contains only characters in Hiragana. Whitespace is ignored. * @returns True if the string containsly only characters in Hiragana. **/ - isHiragana(): boolean; + isHiragana(): bool; /** * Returns true if the string contains only characters in Kana. Whitespace is ignored. * @returns True if the string containsly only characters in Kana. **/ - isKana(): boolean; + isKana(): bool; /** * Returns true if the string contains only characters in Katakana. Whitespace is ignored. * @returns True if the string containsly only characters in Katakana. **/ - isKatakana(): boolean; + isKatakana(): bool; /** * Returns true if the string contains only characters in Latin. Whitespace is ignored. * @returns True if the string containsly only characters in Latin. **/ - isLatin(): boolean; + isLatin(): bool; /** * Returns true if the string contains only characters in Thai. Whitespace is ignored. * @returns True if the string containsly only characters in Thai. **/ - isThai(): boolean; + isThai(): bool; /** * Returns true if the string contains only characters in Devanagari. Whitespace is ignored. * @returns True if the string containsly only characters in Devanagari. **/ - isDevanagari(): boolean; + isDevanagari(): bool; /** * Converts hiragana into katakana. @@ -651,24 +650,13 @@ interface String { /** * Removes all HTML tags and their contents from the string + * @param tags Remove these HTML tags. * @returns String with HTML tags removed. * @extra Tags to remove may be enumerated in the parameters, otherwise will remove all. * @example * '

just some text

'.removeTags() -> '' * '

just some text

'.removeTags('b') -> '

just text

' **/ - removeTags(): string; - - /** - * @see removeTags - * @param tag Remove only this HTML tag. - **/ - removeTags(tag: string): string; - - /** - * @see removeTags - * @param tags Remove these HTML tags. - **/ removeTags(...tags: string[]): string; /** @@ -735,44 +723,32 @@ interface String { * 'hello'.startsWith('HELL') -> false * 'hello'.startsWith('HELL', false) -> true **/ - startsWith(find: string, pos?: number, case_?: boolean): boolean; + startsWith(find: string, pos?: number, case_?: bool): bool; /** * @see startsWith **/ - startsWith(find: string, case_?: boolean): boolean; + startsWith(find: string, case_?: bool): bool; /** * @see startsWith **/ - startsWith(find: RegExp, pos?: number, case_?: boolean): boolean; + startsWith(find: RegExp, pos?: number, case_?: bool): bool; /** * @see startsWith **/ - startsWith(find: RegExp, case_?: boolean): boolean; + startsWith(find: RegExp, case_?: bool): bool; /** * Strips all HTML tags from the string. - + * @param tags HTML tags to strip from the string. * @returns Returns the string with all HTML removed. * @extra Tags to strip may be enumerated in the parameters, otherwise will strip all. * @example * '

just some text

'.stripTags() -> 'just some text' * '

just some text

'.stripTags('p') -> 'just some text' **/ - stripTags(): string; - - /** - * @see stripTags - * @param tags HTML tag to strip from the string. - **/ - stripTags(tag: string): string; - - /** - * @see stripTags - * @param tags HTML tags to strip from the string. - **/ stripTags(...tags: string[]): string; /** @@ -825,6 +801,7 @@ interface String { * ' wasabi '.trimLeft() -> 'wasabi ' * ' wasabi '.trimRight() -> ' wasabi' **/ + // Trim is already available on lib.d.ts interface definition. //trim(): string; /** @@ -857,7 +834,7 @@ interface String { * 'just sittin on the dock of the bay'.truncate(20, true, 'middle') -> 'just sitt...of the bay' * 'just sittin on the dock of the bay'.truncate(20, true, 'left') -> '...the dock of the bay' **/ - truncate(length: number, split?: boolean, from?: string, ellipsis?: string): string; + truncate(length: number, split?: bool, from?: string, ellipsis?: string): string; /** * Converts hyphens and camel casing to underscores. @@ -887,7 +864,7 @@ interface String { * 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL() -> 'http://foo.com/the bar' * 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL(true) -> 'http%3A%2F%2Ffoo.com%2Fthe bar' **/ - unescapeURL(partial?: boolean): string; + unescapeURL(partial?: bool): string; /** * Runs callback [fn] against each word in the string. @@ -925,6 +902,7 @@ interface String { zenkaku(...modes: string[]): string; } +// Todo: fix when TypeScript supports adding static functions to native types. interface NumberStatic { /** @@ -976,7 +954,7 @@ interface Number { * @see bytes * @limit If false upper limit for units is 'exa'. **/ - bytes(precision?: number, limit?: boolean): string; + bytes(precision?: number, limit?: bool): string; /** * Shortcut for %Math.ceil% that also allows a . @@ -1083,7 +1061,7 @@ interface Number { * (6).isEven() -> true * (17).isEven() -> false **/ - isEven(): boolean; + isEven(): bool; /** * Returns true if the number has no trailing decimal. @@ -1092,10 +1070,11 @@ interface Number { * (420).isInteger() -> true * (4.5).isInteger() -> false **/ - isInteger(): boolean; + isInteger(): bool; /** * Returns true if the number is a multiple of . + * @param num Number to check for multiple of. * @returns True if the number is a multiple of . * @example * (6).isMultipleOf(2) -> true @@ -1103,7 +1082,7 @@ interface Number { * (32).isMultipleOf(4) -> true * (34).isMultipleOf(4) -> false **/ - isMultipleOf(num: number): boolean; + isMultipleOf(num: number): bool; /** * Returns true if the number is odd. @@ -1112,7 +1091,7 @@ interface Number { * (3).isOdd() -> true * (18).isOdd() -> false **/ - isOdd(): boolean; + isOdd(): bool; /** * Returns the logarithm of the number with base , @@ -1207,7 +1186,7 @@ interface Number { * @see metric * @limit If false the upper limit for the metric units will be 'exa'. **/ - metric(precision?: number, limit?: boolean): string; + metric(precision?: number, limit?: bool): string; /** * Returns an ordinalized (English) string, i.e. "1st", "2nd", etc. @@ -1232,7 +1211,7 @@ interface Number { * (-5).pad(4) -> '-0005' * (82).pad(3, true) -> '+082' **/ - pad(place?: number, sign?: boolean, base?: number): string; + pad(place?: number, sign?: bool, base?: number): string; /** * Shortcut for %Math.round% that also allows a [precision]. @@ -1980,12 +1959,13 @@ interface Number { upto(num: number, fn?: Function, step?: number): number[]; } -interface Array { +// Todo: Fix when TypeScript supports static members on native types. +interface ArrayStatic { - /*** + /** * Alternate array constructor. - * @method Array.create(, , ...) - * @returns Array + * @param args Elements to create the array from. + * @returns Array containing the elements in . * @extra This method will create a single array by calling %concat% * on all arguments passed. In addition to ensuring that an unknown * variable is in a single, flat array (the standard constructor will @@ -1993,35 +1973,35 @@ interface Array { * shorthand to convert a function's arguments object into a standard * array. * @example - * * Array.create('one', true, 3) -> ['one', true, 3] * Array.create(['one', true, 3]) -> ['one', true, 3] - + Array.create(function(n) { + * Array.create(function(n) { * return arguments; * }('howdy', 'doody')); - * - ***/ - create(...args: any[]): any[]; + **/ + create(...args: T[]): T[]; - /*** + /** * Returns true if is an Array. - * @method Array.isArray() - * @returns Boolean + * @param obj Object to check if it is an Array. + * @returns True if is of type Array. * @extra This method is provided for browsers that don't support it internally. * @example - * * Array.isArray(3) -> false * Array.isArray(true) -> false * Array.isArray('wasabi') -> false * Array.isArray([1,2,3]) -> true - * - ***/ - isArray(obj: any): boolean; + **/ + isArray(obj: any): bool; +} - /*** +interface Array { + + /** * Adds to the array. - * @method add(, [index]) - * @returns Array + * @param el Elements to add to the array. + * @param index Specifies the index where to insert/add into the array, default = Array.length + * @returns Array containing the added elements at position . * @extra If [index] is specified, it will add at [index], otherwise * adds to the end of the array. %add% behaves like %concat% * in that if is an array it will be joined, not inserted. @@ -2029,103 +2009,108 @@ interface Array { * non-destructive alias. Also, %insert% is provided as an * alias that reads better when using an index. * @example - * * [1,2,3,4].add(5) -> [1,2,3,4,5] * [1,2,3,4].add([5,6,7]) -> [1,2,3,4,5,6,7] * [1,2,3,4].insert(8, 1) -> [1,8,2,3,4] - * - ***/ + **/ add(el: T, index?: number): T[]; + + /** + * @see add + **/ add(el: T[], index?: number): T[]; - insert(el: any, index?: number): T[]; - insert(el: any[], index?: number): T[]; + + /** + * @see add + **/ + insert(el: T, index?: number): T[]; + + /** + * @see add + **/ + insert(el: T[], index?: number): T[]; /*** * Gets the element(s) at a given index. - * @method at(, [loop] = true) - * @returns Mixed - * @extra When [loop] is true, overshooting the end of the array (or the beginning) will begin counting from the other end. As an alternate syntax, passing multiple indexes will get the elements at those indexes. + * @param index Element's index to retrieve. + * @param loop Continue counting if the index overshoots the Array.length + * @returns The element at . + * @extra When [loop] is true, overshooting the end of the array (or the beginning) + * will begin counting from the other end. As an alternate syntax, passing + * multiple indexes will get the elements at those indexes. * @example - * * [1,2,3].at(0) -> 1 * [1,2,3].at(2) -> 3 * [1,2,3].at(4) -> 2 * [1,2,3].at(4, false) -> null * [1,2,3].at(-1) -> 3 * [1,2,3].at(0,1) -> [1,2] - * - ***/ - at(index: number, loop?: boolean): T; + **/ + at(index: number, loop?: bool): T; + + /** + * @see at + * @param start Start index. + * @param end End index. + * @return Elements between and + **/ at(start: number, stop: number): T[]; - /*** + /** * Averages all values in the array. - * @method average([map]) - * @returns Number + * @param map Maps each element to a number. + * @returns The average of the entire array. * @extra [map] may be a function mapping the value to be averaged or * a string acting as a shortcut. * @example - * * [1,2,3].average() -> 2 - + [{age:35},{age:11},{age:11}].average(function(n) { + * [{age:35},{age:11},{age:11}].average(function(n) { * return n.age; * }); -> 19 * [{age:35},{age:11},{age:11}].average('age') -> 19 - * - ***/ - average(map?: (n: T) => number): number; - average(mapShortcut: string): number; + **/ + average(map?: (e: T) => number): number; - /*** + /** * Clones the array. - * @method clone() - * @returns Array + * @returns Cloned array. * @example - * * [1,2,3].clone() -> [1,2,3] - * - ***/ + **/ clone(): T[]; - /*** + /** * Removes all instances of %undefined%, %null%, and %NaN% from the array. - * @method compact([all] = false) - * @returns Array + * @param all Remove false elements, default = false. + * @returns The same array with the special values removed. * @extra If [all] is %true%, all "falsy" elements will be removed. This includes empty strings, 0, and false. * @example - * * [1,null,2,undefined,3].compact() -> [1,2,3] * [1,'',2,false,3].compact() -> [1,'',2,false,3] * [1,'',2,false,3].compact(true) -> [1,2,3] - * - ***/ - compact(all?: boolean): T[]; + **/ + compact(all?: bool): T[]; - /*** + /** * Counts all elements in the array that match . - * @method count() - * @returns Number + * @param f object to match against in the array. + * @returns Number of elements in the array that match . * @extra will match a string, number, array, object, or alternately test against a function or regex. This method implements @array_matching. * @example - * * [1,2,3,1].count(1) -> 2 * ['a','b','c'].count(/b/) -> 1 - + [{a:1},{b:2}].count(function(n) { + * [{a:1},{b:2}].count(function(n) { * return n['a'] > 1; * }); -> 0 - * - ***/ - count(f: number): number; - count(f: string): number; - count(f: any[]): number; - count(f: Object): number; - count(f: (n: T) => boolean): number; - count(f: RegExp): number; + **/ + count(f: T): number; - /*** + /** * Runs against each element in the array. Enhanced version of %Array#forEach%. - * @method each(, [index] = 0, [loop] = false) - * @returns Array + * @param fn Callback function for applied to each element in the array. + * @param index Starting index, default = 0. + * @param loop Continue from the beginning if the end of the array is reached, default = false. + * @returns Original array. * @extra Parameters passed to are identical to %forEach%, * ie. the first parameter is the current element, second * parameter is the current index, and third parameter is @@ -2136,134 +2121,147 @@ interface Array { * is true, it will then start over from the beginning of the * array and continue until it reaches [index] - 1. * @example - * * [1,2,3,4].each(function(n) { * // Called 4 times: 1, 2, 3, 4 * }); * [1,2,3,4].each(function(n) { * // Called 4 times: 3, 4, 1, 2 * }, 2, true); - * - ***/ - each(fn: (el: T, i?: number, array?: T[]) => any, + **/ + each( + fn: (element: T, index: number, array: T[]) => bool, index?: number, - loop?: boolean): T[]; + loop?: bool): T[]; - /*** + /** * Returns true if all elements in the array match . - * @method every(, [scope]) + * @param f Match all elements to this. + * @param scope [this] object. * @returns Boolean * @extra [scope] is the %this% object. %all% is provided an alias. * In addition to providing this method for browsers that don't * support it natively, this method also implements @array_matching. * @example - * - + ['a','a','a'].every(function(n) { + * ['a','a','a'].every(function(n) { * return n == 'a'; * }); * ['a','a','a'].every('a') -> true * [{a:2},{a:2}].every({a:2}) -> true - ***/ - every(f: number, scope?: any): boolean; - every(f: string, scope?: any): boolean; - every(f: Object, scope?: any): boolean; - every(f: (el: T, i?: number, array?: T[]) => boolean, scope?: any): boolean; - all(f: number, scope?: any): boolean; - all(f: string, scope?: any): boolean; - all(f: Object, scope?: any): boolean; - all(f: (el: T, i?: number, array?: T[]) => boolean, scope?: any): boolean; + **/ + every(f: T, scope?: any): bool; - /*** + /** + * @see every + * @note Already defined in lib.d.ts. + **/ + //every(f: (element: T, index: number, array: T[]) => bool, scope?: any): bool; + + /** + * @see every + **/ + all(f: T, scope?: any): bool; + + /** + * @see every + **/ + all(f: (element: T, index: number, array: T[]) => bool, scope?: any): bool; + + /** * Removes any element in the array that matches [f1], [f2], etc. - * @method exclude([f1], [f2], ...) - * @returns Array + * @param f Elements to find in the array and remove. + * @returns A copy of the original array with all instances of removed. * @extra This is a non-destructive alias for %remove%. It will not change the original array. This method implements @array_matching. * @example - * * [1,2,3].exclude(3) -> [1,2] * ['a','b','c'].exclude(/b/) -> ['a','c'] * [{a:1},{b:2}].exclude(function(n) { * return n['a'] == 1; * }); -> [{b:2}] - * - ***/ - exclude(...f: number[]): T[]; - exclude(...f: string[]): T[]; - exclude(...f: RegExp[]): T[]; - exclude(...f: Object[]): T[]; - exclude(fn: (n: T) => boolean): T[]; + **/ + exclude(...f: T[]): T[]; - /*** + /** + * @see exclude + **/ + exclude(f: (element: T, index: number, array: T[]) => bool): T[]; + + /** * Returns any elements in the array that match . - * @method filter(, [scope]) - * @returns Array + * @param f Find these elements in the array. + * @param scope %this% object while filtering. + * @returns Array containing th items found in the array. * @extra [scope] is the %this% object. In addition to providing this * method for browsers that don't support it natively, this method * also implements @array_matching. * @example - * * [1,2,3].filter(function(n) { * return n > 1; * }); * [1,2,2,4].filter(2) -> 2 - * - ***/ - filter(f: number, scope?: any): T[]; - filter(f: string, scope?: any): T[]; - filter(f: RegExp, scope?: any): T[]; - filter(f: Object, scope?: any): T[]; - filter(f: (el: T, i?: number, array?: T[]) => boolean, scope?: any): T[]; + **/ + filter(f: T, scope?: any): T[]; - /*** + /** + * @see filter + * @note Already defined in lib.d.ts. + **/ + //filter(f: (element: T, index: number, array: T[]) => bool, scope?: any): T[]; + + /** * Returns the first element that matches . - * @method find(, [index] = 0, [loop] = false) - * @returns Mixed + * @param f Elements to match against. + * @param index Index to start searching from, default = 0. + * @param loop Loop around the end of the array, default = false. + * @returns First element matching . * @extra will match a string, number, array, object, or alternately * test against a function or regex. Starts at [index], and will * continue once from index = 0 if [loop] is true. This method * implements @array_matching. * @example - * * [{a:1,b:2},{a:1,b:3},{a:1,b:4}].find(function(n) { * return n['a'] == 1; * }); -> {a:1,b:3} * ['cuba','japan','canada'].find(/^c/, 2) -> 'canada' - * - ***/ - find(f: number, index?: number, loop?: boolean): T; - find(f: string, index?: number, loop?: boolean): T; - find(f: RegExp, index?: number, loop?: boolean): T; - find(f: Object, index?: number, loop?: boolean): T; - find(f: (el: T, i?: number, array?: T[]) => boolean, index?: number, loop?: boolean): T; + **/ + find(f: T, index?: number, loop?: bool): T; - /*** + /** + * @see find + **/ + find(f: (element: T, index: number, array: T[]) => bool, index?: number, loop?: bool): T; + + /** * Returns all elements that match . - * @method findAll(, [index] = 0, [loop] = false) - * @returns Array + * @param f Element to match against. + * @param index Index to start searching from, default = 0. + * @param loop Loop around the end of the array, default = false. + * @returns Elements matching . * @extra will match a string, number, array, object, or alternately * test against a function or regex. Starts at [index], and will * continue once from index = 0 if [loop] is true. This method * implements @array_matching. * @example - * * [{a:1,b:2},{a:1,b:3},{a:2,b:4}].findAll(function(n) { * return n['a'] == 1; * }); -> [{a:1,b:3},{a:1,b:4}] * ['cuba','japan','canada'].findAll(/^c/) -> 'cuba','canada' * ['cuba','japan','canada'].findAll(/^c/, 2) -> 'canada' - * - ***/ - findAll(f: number, index?: number, loop?: boolean): T[]; - findAll(f: string, index?: number, loop?: boolean): T[]; - findAll(f: RegExp, index?: number, loop?: boolean): T[]; - findAll(f: Object, index?: number, loop?: boolean): T[]; - findAll(f: (el: T, i?: number, array?: T[]) => boolean, index?: number, loop?: boolean): T[]; + **/ + findAll(f: T, index?: number, loop?: bool): T[]; - /*** + /** + * @see findAll + **/ + findAll(f: (element: T, index: number, array: T[]) => bool, index?: number, loop?: bool): T[]; + + /** * Returns the index of the first element that matches * or -1 if not found. * @method findIndex(, [startIndex] = 0, [loop] = false) - * @returns Number + * @param f Element to match against. + * @param startIndex Index to start searching from, default = 0. + * @param loop Loop around the end of th array, default = false. + * @returns Index at which is found. * @extra This method has a few notable differences to native %indexOf%. * Although will similarly match a primitive such as a string * or number, it will also match deep objects and arrays that are @@ -2274,209 +2272,248 @@ interface Array { * and will continue once from index = 0 if [loop] is true. * This method implements @array_matching. * @example - * * [1,2,3,4].findIndex(3); -> 2 * [1,2,3,4].findIndex(function(n) { * return n % 2 == 0; * }); -> 1 * ['one','two','three'].findIndex(/th/); -> 2 - * - ***/ - findIndex(f: number, startIndex?: number, loop?: boolean): number; - findIndex(f: any, startIndex?: number, loop?: boolean): number; - findIndex(f: RegExp, startIndex?: number, loop?: boolean): number; - findIndex(f: (el: T, i?: number, array?: T[]) => boolean, startIndex?: number, loop?: boolean): number; + **/ + findIndex(f: T, startIndex?: number, loop?: bool): number; - /*** + /** + * @see findIndex + **/ + findIndex(f: (element: T, index: number, array: T[]) => bool, startIndex?: number, loop?: bool): number; + + /** * Returns the first element(s) in the array. - * @method first([num] = 1) - * @returns Mixed + * @param num Retrieve this many elements in the array, default = 1. + * @returns first elements in the array. * @extra When is passed, returns the first elements in the array. + * @note If is omitted then the return type is the element itself, not an array of the element, + * For example 1 instead of [1], however if is present the result is always wrapped in an + * array like first(1) -> [1], not 1. * @example - * * [1,2,3].first() -> 1 * [1,2,3].first(2) -> [1,2] - * - ***/ - first(num?: number): T[]; + **/ + first(): T; - /*** + /** + * @see first + **/ + first(num: number): T[]; + + /** * Returns a flattened, one-dimensional copy of the array. - * @method flatten([limit] = Infinity) - * @returns Array + * @param limit Limit the flattening to this depth, default = Infinity. + * @returns Flattened array. * @extra You can optionally specify a [limit], which will only flatten * that depth. * @example - * * [[1], 2, [3]].flatten() -> [1,2,3] * [['a'],[],'b','c'].flatten() -> ['a','b','c'] - * - ***/ + **/ flatten(limit?: number): T[]; - /*** + /** * Iterates over the array, calling [fn] on each loop. - * @method forEach([fn], [scope]) + * @param fn Callback function for each element in the array. + * @param scope Scope during [fn] callbacks, default = this. * @returns Nothing * @extra This method is only provided for those browsers that do not support * it natively. [scope] becomes the %this% object. * @example - * * ['a','b','c'].forEach(function(a) { * // Called 3 times: 'a','b','c' * }); - * - ***/ - forEach(fn: (el: T, i?: number, array?: T[]) => void, scope?: any): void; + * @note Already defined in lib.d.ts. + **/ + //forEach(fn: (element: T, index: number, array: T[]) => void, scope?: any): void; - /*** + /** * Returns a slice of the array from . - * @method from() - * @returns Array + * @param index Index to start the slice from. + * @returns Subarray starting from [index] to the end of the original array. * @example - * * [1,2,3].from(1) -> [2,3] * [1,2,3].from(2) -> [3] - * - ***/ + **/ from(index: number): T[]; - /*** + /** * Groups the array by . - * @method groupBy(, [fn]) - * @returns Object + * @param map Property on the elements in the array. + * @param fn Optional callback for each group, default = No callback. + * @returns * @extra Will return an object with keys equal to the grouped values. * may be a mapping function, or a string acting as a shortcut. * Optionally calls [fn] for each group. * @example - * * ['fee','fi','fum'].groupBy('length') -> { 2: ['fi'], 3: ['fee','fum'] } - + [{age:35,name:'ken'},{age:15,name:'bob'}].groupBy(function(n) { + * [{age:35,name:'ken'},{age:15,name:'bob'}].groupBy(function(n) { * return n.age; * }); -> { 35: [{age:35,name:'ken'}], 15: [{age:15,name:'bob'}] } - * - ***/ - groupBy(map: string, fn?: (n: any) => void ): any; - groupBy(fn: (n: T) => any ): any; + * todo: return should be : { [key: U]: any } + **/ + groupBy(map: string, fn?: (group: T) => void ): { [key: string]: any }; - /*** + /** + * @see groupBy + * @param map Callback function for each element, returns the key for the group the element should be in. + * todo: return should be : { [key: U]: any } + **/ + groupBy(map: (element: T) => U, fn?: (group: T) => void ): { [key: string]: any }; + + /** * Groups the array into arrays. - * @method inGroups(, [padding]) - * @returns Array + * @param num The number of sub-arrays to create. + * @param padding Padding element if the groups do not make whole amounts. + * @returns Array with sub-arrays. * @extra [padding] specifies a value with which to pad the last array * so that they are all equal length. * @example - * * [1,2,3,4,5,6,7].inGroups(3) -> [ [1,2,3], [4,5,6], [7] ] * [1,2,3,4,5,6,7].inGroups(3, 'none') -> [ [1,2,3], [4,5,6], [7,'none','none'] ] - * - ***/ - inGroups(num: number, padding?: any): any[][]; + **/ + inGroups(num: number, padding?: T): T[][]; - /*** + /** * Groups the array into arrays of elements each. - * @method inGroupsOf(, [padding] = null) - * @returns Array + * @param num The number of elements to put into each sub-array. + * @param padding Padding element if the groups do not make whole amounts. + * @returns Array with sub-arrays each containing elements. * @extra [padding] specifies a value with which to pad the last array so that they are all equal length. * @example - * * [1,2,3,4,5,6,7].inGroupsOf(4) -> [ [1,2,3,4], [5,6,7] ] * [1,2,3,4,5,6,7].inGroupsOf(4, 'none') -> [ [1,2,3,4], [5,6,7,'none'] ] - * - ***/ - inGroupsOf(num: number, padding?: any): any[][]; + **/ + inGroupsOf(num: number, padding?: T): T[][]; - /*** - * Adds to the array. - * @method include(, [index]) - * @returns Array + /** + * Adds to the array. + * @param element Element to add to the array. + * @param index , default = Array.length. + * @returns Array with included at [index]. * @extra This is a non-destructive alias for %add%. It will not change * the original array. * @example - * * [1,2,3,4].include(5) -> [1,2,3,4,5] * [1,2,3,4].include(8, 1) -> [1,8,2,3,4] * [1,2,3,4].include([5,6,7]) -> [1,2,3,4,5,6,7] - * - ***/ - include(el: T, index?: number): T[]; - include(els: T[], index?: number): T[]; + **/ + include(element: T, index?: number): T[]; - /*** + /** + * @see include + * @param elements Elements to include into the array at [index]. + **/ + include(elements: T[], index?: number): T[]; + + /** + * Searches the array and returns the first index where occurs, or -1 if the element is not found. + * @method indexOf(, [fromIndex]) + * @param search Element to search for in the array. + * @param fromIndex Index to start searching from, default = 0. + * @returns Index of or -1 if is not found. + * @extra [fromIndex] is the index from which to begin the search. + * This method performs a simple strict equality comparison on . + * It does not support enhanced functionality such as searching + * the contents against a regex, callback, or deep comparison of objects. + * For such functionality, use the %findIndex% method instead. + * @example + * [1,2,3].indexOf(3) -> 1 + * [1,2,3].indexOf(7) -> -1 + **/ + indexOf(search: T, fromIndex?: number): number; + + /** * Returns an array containing the elements all arrays have in common. - * @method intersect([a1], [a2], ...) - * @returns Array + * @param args Elements to intersect with. + * @returns An array containing the intersecting elements. * @extra This method will also correctly operate on arrays of objects. * @example - * * [1,3,5].intersect([5,7,9]) -> [5] * ['a','b'].intersect('b','c') -> ['b'] - * - ***/ + **/ intersect(...args: T[]): T[]; - intersect(args: T[]): T[]; - intersect(...args: any[]): any[]; - intersect(args: any[]): any[]; /*** * Returns true if the array is empty. - * @method isEmpty() - * @returns Boolean + * @returns True if the array is empty, otherwise false. * @extra This is true if the array has a length of zero, or contains * only %undefined%, %null%, or %NaN%. * @example - * * [].isEmpty() -> true * [null,undefined].isEmpty() -> true - * ***/ - isEmpty(): boolean; + isEmpty(): bool; - /*** + /** * Returns the last element(s) in the array. * @method last([num] = 1) - * @returns Mixed + * @returns The last element in the array, if [num] is present then it returns an array of the last [num] elements. * @extra When is passed, returns the last elements in the array. * @example - * * [1,2,3].last() -> 3 * [1,2,3].last(2) -> [2,3] - * - ***/ + **/ last(): T; + + /** + * @see last + * @param num The number of elements to return. + **/ last(num: number): T[]; - /*** + /** + * Searches the array and returns the last index where occurs, + * or -1 if the element is not found. + * @param search The element to search for. + * @param fromIndex Start the search from this index, default = Array.length. + * @returns The last index of or -1 if is not found. + * @extra [fromIndex] is the index from which to begin the search. + * This method performs a simple strict equality comparison on . + * @example + * [1,2,1].lastIndexOf(1) -> 2 + * [1,2,1].lastIndexOf(7) -> -1 + **/ + lastIndexOf(search: any, fromIndex?: number): number; + + /** * Returns the elements in the array with the least * commonly occuring value. * @method least([map]) + * @param map Property on elements in the array. * @returns Array * @extra [map] may be a function mapping the value to be checked or a * string acting as a shortcut. * @example - * * [3,2,2].least() -> [3] * ['fe','fo','fum'].least('length') -> ['fum'] * [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].least(function(n) { * return n.age; * }); -> [{age:35,name:'ken'}] - * - ***/ - least(): T[]; + **/ least(map: string): T[]; - least(map: (n: T) => any): any[]; - /*** + /** + * @see least + * @param map Callback to retrieve the 'least' property to compare elements against. + **/ + least(map: (n: T) => U): T[]; + + /** * Maps the array to another array containing the values that * are the result of calling on each element. - * @method map(, [scope]) - * @returns Array + * @param map Property on each element in the array or callback function. + * @param scope This pointer in callback. + * @returns Mapped array. * @extra [scope] is the %this% object. In addition to providing this method * for browsers that don't support it natively, this enhanced method * also directly accepts a string, which is a shortcut for a function * that gets that property (or invokes a function) on each element. * @example - * * [1,2,3].map(function(n) { * return n * 3; * }); -> [3,6,9] @@ -2484,172 +2521,243 @@ interface Array { * return n.length; * }); -> [3,3,5] * ['one','two','three'].map('length') -> [3,3,5] - ***/ + **/ map(map: string, scope?: any): U[]; + + /** + * @see map + * @param map Callback function to map each element in the array. + **/ map(map: (n: T) => U, scope?: any): U[]; - /*** + /** * Returns the element in the array with the greatest value. * @method max([map], [all] = false) - * @returns Mixed + * @param map Property on each element in the array or callback function. + * @returns Maximum element in the array. * @extra [map] may be a function mapping the value to be checked or a string * acting as a shortcut. If [all] is true, will return all max values * in an array. * @example - * * [1,2,3].max() -> 3 * ['fee','fo','fum'].max('length') -> 'fee' * ['fee','fo','fum'].max('length', true) -> ['fee'] - + [{a:3,a:2}].max(function(n) { + * [{a:3,a:2}].max(function(n) { * return n['a']; * }); -> {a:3} - * - ***/ - max(): T; + **/ max(map: string): T; - max(map: string, all: boolean): any; - max(map: (n: T) => any): T; - max(map: (n: T) => any, all: boolean): any; + + /** + * @see max + * @param If true return all max values in the array, default = false. + * @return All max values in the array. + **/ + max(map: string, all: boolean): T[]; + + /** + * @see max + * @param map Callback function to determine the max value of each element in the array. + **/ + max(map: (n: T) => U): T; + + /** + * @see max + **/ + max(map: (n: T) => U): T[]; /*** * Returns the element in the array with the lowest value. - * @method min([map], [all] = false) - * @returns Mixed + * @param map Property on each element in the array or callback. + * @returns Minimum element in the array. * @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut. If [all] is true, will return all min values in an array. * @example - * * [1,2,3].min() -> 1 * ['fee','fo','fum'].min('length') -> 'fo' * ['fee','fo','fum'].min('length', true) -> ['fo'] - + ['fee','fo','fum'].min(function(n) { + * ['fee','fo','fum'].min(function(n) { * return n.length; * }); -> ['fo'] - + [{a:3,a:2}].min(function(n) { + * [{a:3,a:2}].min(function(n) { * return n['a']; * }); -> [{a:2}] - * - ***/ - min(): T; + **/ min(map: string): T; - min(map: string, all: boolean): any; - min(map: (n: T) => any): T; - min(map: (n: T) => any, all: boolean): any; - /*** - * Returns the elements in the array with the most - * commonly occuring value. - * @method most([map]) - * @returns Array + /** + * @see min If true return all min values in the array, default = false. + * @param all + **/ + min(map: string, all: boolean): T[]; + + /** + * @see min + * @param map Callback function to determine the min value of each element in the array. + **/ + min(map: (n: T) => U): T; + + /** + * @see min + **/ + min(map: (n: T) => U, all: boolean): T[]; + + /** + * Returns the elements in the array with the most commonly occuring value. + * @param map Property on each element in the array or + * @returns Array of elements that have the most common property. * @extra [map] may be a function mapping the value to be checked or a string * acting as a shortcut. * @example - * * [3,2,2].most() -> [2] * ['fe','fo','fum'].most('length') -> ['fe','fo'] - + [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].most(function(n) { + * [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].most(function(n) { * return n.age; * }); -> [{age:12,name:'bob'},{age:12,name:'ted'}] - * - ***/ - most(): T[]; + **/ most(map: string): T[]; - most(map: (T: any) => any): T[]; - /*** + /** + * @see most + * @param map Callback function to determine the element that contains the most commonly occuring value. + **/ + most(map: (n: T) => U): T[]; + + /** * Returns true if none of the elements in the array match . - * @method none() - * @returns Boolean + * @param f Value to see if it exists in the array. + * @returns True if none of the values match , false if one or more match . * @extra will match a string, number, array, object, or alternately test * against a function or regex. This method implements @array_matching. * @example * * [1,2,3].none(5) -> true * ['a','b','c'].none(/b/) -> false - + [{a:1},{b:2}].none(function(n) { + * [{a:1},{b:2}].none(function(n) { * return n['a'] > 1; * }); -> true - * - ***/ - none(f: number): boolean; - none(f: string): boolean; - none(f: RegExp): boolean; - none(f: Object): boolean; - none(f: any[]): boolean; - none(f: (n: T) => boolean): boolean; + **/ + none(f: T): bool; + + /** + * @see none + * @param f Callback function to determine if none of the elements in the array contain a certain value. + **/ + none(f: (n: T) => bool): bool; /*** * Returns a copy of the array with the elements randomized. - * @method randomize() - * @returns Array + * @returns Copy of the array with the elements in a random order. * @extra Uses Fisher-Yates algorithm. * @example - * * [1,2,3,4].randomize() -> [?,?,?,?] - * ***/ randomize(): T[]; - - /*** + /** + * Reduces the array to a single result. + * @param fn Reduce function callback. + * @param init First argument to the callback if present. + * @returns Reduced value of the entire array. + * @extra If [init] is passed as a starting value, that value will be passed + * as the first argument to the callback. The second argument will be + * the first element in the array. From that point, the result of the + * callback will then be used as the first argument of the next + * iteration. This is often refered to as "accumulation", and [init] + * is often called an "accumulator". If [init] is not passed, then + * will be called n - 1 times, where n is the length of the array. + * In this case, on the first iteration only, the first argument will + * be the first element of the array, and the second argument will be + * the second. After that callbacks work as normal, using the result + * of the previous callback as the first argument of the next. This + * method is only provided for those browsers that do not support it + * natively. + * @example + * [1,2,3,4].reduce(function(a, b) { + * return a - b; + * }); + * [1,2,3,4].reduce(function(a, b) { + * return a - b; + * }, 100); + **/ + reduce(fn: (a: T, b: T) => T, init: T): T; + + /** + * Identical to %Array#reduce%, but operates on the elements in reverse order. + * @param fn Reduce function callback. + * @param init First argument to the callback if present. + * @returns Reduced right value of the entire array. + * @extra This method is only provided for those browsers that do not support + * it natively. + * @example + * [1,2,3,4].reduceRight(function(a, b) { + * return a - b; + * }); + **/ + reduceRight(fn: (a: T, b: T) => T, init: T): T; + + /** * Removes any element in the array that matches [f1], [f2], etc. - * @method remove([f1], [f2], ...) - * @returns Array + * @param args Elements that should be removed from the array. + * @returns The array with elements removed. * @extra Will match a string, number, array, object, or alternately test * against a function or regex. This method will change the array! * Use %exclude% for a non-destructive alias. This method implements * @array_matching. * @example - * * [1,2,3].remove(3) -> [1,2] * ['a','b','c'].remove(/b/) -> ['a','c'] - + [{a:1},{b:2}].remove(function(n) { + * [{a:1},{b:2}].remove(function(n) { * return n['a'] == 1; * }); -> [{b:2}] - * - ***/ - remove(...args: number[]): T[]; - remove(...args: string[]): T[]; - remove(...args: Object[]): T[]; - remove(...args: any[]): any[]; - remove(...args: {(n: T): boolean}[]): T[]; + **/ + remove(...args: T[]): T[]; - /*** + /** + * @see remove + * @param fn Callback function to check if elements should be removed. + **/ + remove(fn: (n: T) => bool): T[]; + + /** * Removes element at . If [end] is specified, removes the range * between and [end]. This method will change the array! * If you don't intend the array to be changed use %clone% first. - * @method removeAt(, [end]) - * @returns Array + * @param start Starting index. + * @param end Stop index, default = Array.length. + * @returns Subarray with elements to [end] removed. * @example - * * ['a','b','c'].removeAt(0) -> ['b','c'] * [1,2,3,4].removeAt(1, 3) -> [1] - * - ***/ + **/ removeAt(start: number, end?: number): T[]; - /*** + /** * Returns a random element from the array. - * @method sample([num]) - * @returns Mixed + * @returns Single random element in the array. * @extra If [num] is passed, will return [num] samples from the array. * @example - * * [1,2,3,4,5].sample() -> // Random element * [1,2,3,4,5].sample(3) -> // Array of 3 random elements - * - ***/ + **/ sample(): T; + + /** + * @see sample + * @param num Grab this many random elements in the array. + * @return random elements in the array. + **/ sample(num: number): T[]; /*** * Returns true if any element in the array matches . * @method some(, [scope]) - * @returns Boolean + * @param f Element to match or callback function. + * @param scope this object in the callback. + * @returns Returns true if any element in the array matchs . * @extra [scope] is the %this% object. %any% is provided as an alias. * In addition to providing this method for browsers that don't * support it natively, this method also implements @array_matching. * @example - * * ['a','b','c'].some(function(n) { * return n == 'a'; * }); @@ -2658,16 +2766,19 @@ interface Array { * }); * ['a','b','c'].some('a') -> true * [{a:2},{b:5}].some({a:2}) -> true - ***/ - some(f: number, scope?: any): boolean; - some(f: string, scope?: any): boolean; - some(f: any, scope?: any): boolean; - some(f: (n: T) => boolean, scope?: any): boolean; + **/ + some(f: T, scope?: any): bool; - /*** + /** + * @see some + **/ + some(f: (n: T) => bool, scope?: any): bool; + + /** * Sorts the array by . - * @method sortBy(, [desc] = false) - * @returns Array + * @param map Property on each element in the array or map callback function. + * @param desc True to sort the array in descending order, default = false. + * @returns Sorted array. * @extra may be a function, a string acting as a shortcut, or blank * (direct comparison of array values). [desc] will sort the array in * descending order. When the field being sorted on is a string, the @@ -2675,103 +2786,109 @@ interface Array { * that is optimized for major Western languages, but can be customized. * For more information see @array_sorting. * @example - * * ['world','a','new'].sortBy('length') -> ['a','new','world'] * ['world','a','new'].sortBy('length', true) -> ['world','new','a'] * [{age:72},{age:13},{age:18}].sortBy(function(n) { * return n.age; * }); -> [{age:13},{age:18},{age:72}] - * - ***/ - sortBy(map: string, desc?: boolean): T[]; - sortBy(fn: (n: T) => any, desc?: boolean): T[]; + **/ + sortBy(map: string, desc?: bool): T[]; - /*** + /** + * @see sortBy + **/ + sortBy(fn: (n: T) => U, desc?: bool): T[]; + + /** * Subtracts from the array all elements in [a1], [a2], etc. - * @method subtract([a1], [a2], ...) - * @returns Array + * @param args Elements to remove from the array. + * @returns Array with removed. * @extra This method will also correctly operate on arrays of objects. * @example - * * [1,3,5].subtract([5,7,9]) -> [1,3] * [1,3,5].subtract([3],[5]) -> [1] * ['a','b'].subtract('b','c') -> ['a'] - * - ***/ - subtract(...args: any[]): T[]; + **/ + subtract(...args: T[]): T[]; - /*** - * @method sum([map]) - * @returns Number + /** * Sums all values in the array. + * @param map Property on each element in the array or callback function to sum up the elements. + * @returns The sum of all elements in the array. * @extra [map] may be a function mapping the value to be summed or a string * acting as a shortcut. * @example - * * [1,2,2].sum() -> 5 * [{age:35},{age:12},{age:12}].sum(function(n) { * return n.age; * }); -> 59 * [{age:35},{age:12},{age:12}].sum('age') -> 59 - * - ***/ - sum(): number; + **/ sum(map: string): number; - sum(fn: (n: T) => number): number; - /*** + /** + * @see sum + **/ + sum(map: (n: T) => number): number; + + /** * Returns a slice of the array up to . - * @method to() - * @returns Array + * @param index Slick the array up to this index. + * @returns Slice of the array from 0 to . * @example - * * [1,2,3].to(1) -> [1] * [1,2,3].to(2) -> [1,2] - * - ***/ - to(index: number): T[]; + **/ + to(index: number): any[]; - /*** - * Returns an array containing all elements in all arrays with - * duplicates removed. + /** + * Returns an array containing all elements in all arrays with duplicates removed. * @method union([a1], [a2], ...) - * @returns Array + * @param array + * @returns Union between the original array and . * @extra This method will also correctly operate on arrays of objects. * @example - * * [1,3,5].union([5,7,9]) -> [1,3,5,7,9] * ['a','b'].union(['b','c']) -> ['a','b','c'] - * - ***/ - union(array: any[]): any[]; - union(...args: any[]): any[]; + **/ + union(array: T[]): T[]; - /*** + /** + * @see union + * @param args Elements to create a union with. + * @return Union between the original array and + **/ + union(...args: T[]): T[]; + + /** * Removes all duplicate elements in the array. - * @method unique([map] = null) - * @returns Array + * @param map Property on each element in the array or callback function to pick a property on the element. + * @returns Array with only unique elements. * @extra [map] may be a function mapping the value to be uniqued on or a * string acting as a shortcut. This is most commonly used when you * have a key that ensures the object's uniqueness, and don't need to * check all fields. This method will also correctly operate on arrays * of objects. * @example - * * [1,2,2,3].unique() -> [1,2,3] * [{foo:'bar'},{foo:'bar'}].unique() -> [{foo:'bar'}] - + [{foo:'bar'},{foo:'bar'}].unique(function(obj){ + * [{foo:'bar'},{foo:'bar'}].unique(function(obj){ * return obj.foo; * }); -> [{foo:'bar'}] * [{foo:'bar'},{foo:'bar'}].unique('foo') -> [{foo:'bar'}] - * - ***/ + **/ unique(map?: string): T[]; - unique(fn?: (obj: T) => any): T[]; - /*** + /** + * @see unique + * @param fn Callback to pluck the property to check for uniqueness. + **/ + unique(fn: (obj: T) => U): T[]; + + /** * Merges multiple arrays together. - * @method zip([arr1], [arr2], ...) - * @returns Array + * @param arrays Arrays to zip together. + * @returns Zipped arrays. * @extra This method "zips up" smaller arrays into one large whose elements * are "all elements at index 0", "all elements at index 1", etc. * Useful when you have associated data that is split over separated @@ -2779,54 +2896,49 @@ interface Array { * array, they will be discarded. If they have fewer elements, the * missing elements will filled with %null%. * @example - * * [1,2,3].zip([4,5,6]) -> [[1,2], [3,4], [5,6]] * ['Martin','John'].zip(['Luther','F.'], ['King','Kennedy']) -> [['Martin','Luther','King'], ['John','F.','Kennedy']] - * - ***/ - zip(...arrays: any[]): any[][]; + **/ + zip(...arrays: T[]): T[][]; } -interface Object { +interface ObjectStatic { - /*** - * Creates a new object, equivalent to %new Object()% or %{}%, - * but with extended methods. - * @method Object.extended( = {}) - * @returns Extended object + /** + * Creates a new object, equivalent to %new Object()% or %{}%, but with extended methods. + * @param obj , default = {}. + * @returns Extended object. * @extra See extended objects for more. * @example - * * Object.extended() * Object.extended({ happy:true, pappy:false }).keys() -> ['happy','pappy'] * Object.extended({ happy:true, pappy:false }).values() -> [true, false] - * - ***/ - extended(obj?: Object): Object; + **/ + extended(obj?: any): any; - /*** + /** * Converts the query string of a URL into an object. * @method Object.fromQueryString(, [deep] = true) - * @returns Object + * @param str Query string to convert into an object. + * @param deep If false the conversion will only accept shallow params, default = true. + * @returns Object generated from the . * @extra If [deep] is %false%, conversion will only accept shallow params (ie. no object or arrays with %[]% syntax) as these are not universally supported. * @example - * * Object.fromQueryString('foo=bar&broken=wear') -> { foo: 'bar', broken: 'wear' } * Object.fromQueryString('foo[]=1&foo[]=2') -> { foo: [1,2] } - * - ***/ - fromQueryString(str: string, deep?: boolean): Object; - - /*** + **/ + fromQueryString(str: string, deep?: bool): T; + + /** * Returns true if is an object of that type. * @method Object.is[Type]() - * @returns Boolean + * @param obj Object to check if it is of type [Type]. + * @returns True if is of type [Type]. * @extra %isObject% will return false on anything that is not an object * literal, including instances of inherited classes. Note also * that %isNaN% will ONLY return true if the object IS %NaN%. * It does not mean the same as browser native %isNaN%, which returns * true for anything that is "not a number". - * * @set * isArray * isObject @@ -2837,33 +2949,53 @@ interface Object { * isNumber * isString * isRegExp - * * @example - * * Object.isArray([1,2,3]) -> true * Object.isDate(3) -> false * Object.isRegExp(/wasabi/) -> true * Object.isObject({ broken:'wear' }) -> true - * - ***/ - isArray(): boolean; - isArray(obj: any): boolean; - isObject(): boolean; - isObject(obj: any): boolean; - isBoolean(): boolean; - isBoolean(obj: any): boolean; - isDate(): boolean; - isDate(obj: any): boolean; - isFunction(): boolean; - isFunction(obj: any): boolean; - isNaN(): boolean; - isNaN(obj: any): boolean; - isNumber(): boolean; - isNumber(obj: any): boolean; - isString(): boolean; - isString(obj: any): boolean; - isRegExp(): boolean; - isRegExp(obj: any): boolean; + **/ + isArray(obj: any): bool; + + /** + * @see isArray + **/ + isObject(obj: any): bool; + + /** + * @see isArray + **/ + isBoolean(obj: any): bool; + + /** + * @see isArray + **/ + isDate(obj: any): bool; + + /** + * @see isArray + **/ + isFunction(obj: any): bool; + + /** + * @see isArray + **/ + isNaN(obj: any): bool; + + /** + * @see isArray + **/ + isNumber(obj: any): bool; + + /** + * @see isArray + **/ + isString(obj: any): bool; + + /** + * @see isArray + **/ + isRegExp(obj: any): bool; /** * Converts the object into a query string. Accepts deep nested objects and arrays. @@ -2874,22 +3006,22 @@ interface Object { **/ toQueryString(obj: any, namespace?: string): string; - /*** + /** * Creates a clone (copy) of . * @method clone( = {}, [deep] = false) - * @returns Cloned object + * @param obj Object to clone. + * @param deep If true then deep clone, default = false. + * @returns Cloned object. * @extra Default is a shallow clone, unless [deep] is true. %clone% * is available as an instance method on extended objects. * @example - * * Object.clone({foo:'bar'}) -> { foo: 'bar' } * Object.clone() -> {} * Object.extended({foo:'bar'}).clone() -> { foo: 'bar' } - * - ***/ - clone(obj?: Object, deep?: boolean): Object; + **/ + clone(obj?: T, deep?: bool): T; - /*** + /** * Enumerable methods in the Array package are also available to * the Object class. They will perform their normal operations for * every property in . @@ -2898,7 +3030,6 @@ interface Object { * @extra In cases where a callback is used, instead of %element, index%, * the callback will instead be passed %key, value%. Enumerable methods * are also available to extended objects as instance methods. - * * @set * each * map @@ -2916,146 +3047,209 @@ interface Object { * max * least * most - * * @example - * * Object.any({foo:'bar'}, 'bar') -> true * Object.extended({foo:'bar'}).any('bar') -> true * Object.isEmpty({}) -> true * Object.map({ fred: { age: 52 } }, 'age'); -> { fred: 52 } - * - ***/ - map(map: string): Object; - map(obj: Object, map: string): Object; - map(map: (key: string, value: any) => any): Object; - map(obj: Object, map: (key: string, value: any) => any): Object; + **/ + map(obj: T, map: string): U; - any(map: string): boolean; - any(obj: Object, map: string): boolean; - any(map: (key: string, value: any) => boolean): boolean; - any(obj: Object, map: (key: string, value: any) => boolean): boolean; + /** + * @see map + **/ + map(obj: T, map: (key: string, value: any) => any): U; - all(map: string): boolean; - all(obj: Object, map: string): boolean; - all(map: (key: string, value: any) => boolean): boolean; - all(obj: Object, map: (key: string, value: any) => boolean): boolean; + /** + * @see map + **/ + any(obj: any, map: string): bool; - none(map: string): boolean; - none(obj: Object, map: string): boolean; - none(map: (key: string, value: any) => boolean): boolean; - none(obj: Object, map: (key: string, value: any) => boolean): boolean; + /** + * @see map + **/ + any(obj: any, map: (key: string, value: any) => bool): bool; - count(map: string): number; - count(obj: Object, map: string): number; - count(map: (key: string, value: any) => boolean): number; - count(obj: Object, map: (key: string, value: any) => boolean): number; + /** + * @see map + **/ + all(obj: any, map: string): bool; - find(map: string): any; - find(obj: Object, map: string): any; - find(map: (key: string, value: any) => boolean): any; - find(obj: Object, map: (key: string, value: any) => boolean): any; + /** + * @see map + **/ + all(obj: any, map: (key: string, value: any) => bool): bool; - findAll(map: string): any[]; - findAll(obj: Object, map: string): any[]; - findAll(map: (key: string, value: any) => boolean): any[]; - findAll(obj: Object, map: (key: string, value: any) => boolean): any[]; + /** + * @see map + **/ + none(obj: any, map: string): bool; - reduce(map: string, init?: any): any; - reduce(obj: Object, map: string, init?: any): any; - reduce(map: (key: string, value: any) => any, init?: any): any; - reduce(obj: Object, map: (key: string, value: any) => any, init?: any): any; + /** + * @see map + **/ + none(obj: any, map: (key: string, value: any) => bool): bool; - isEmpty(): boolean; - isEmpty(obj: Object): boolean; + /** + * @see map + **/ + count(obj: any, map: string): number; - sum(map: string): number; - sum(obj: Object, map: string): number; - sum(map: (key: string, value: any) => number): number; - sum(obj: Object, map: (key: string, value: any) => number): number; + /** + * @see map + **/ + count(obj: any, map: (key: string, value: any) => bool): number; - average(map: string): number; - average(obj: Object, map: string): number; - average(map: (key: string, value: any) => number): number; - average(obj: Object, map: (key: string, value: any) => number): number; + /** + * @see map + **/ + find(obj: any, map: string): any; - min(map: string): Object; - min(obj: Object, map: string): Object; - min(map: (key: string, value: any) => any): Object; - min(obj: Object, map: (key: string, value: any) => any): Object; + /** + * @see map + **/ + find(obj: any, map: (key: string, value: any) => bool): any; - max(map: string): Object; - max(obj: Object, map: string): Object; - max(map: (key: string, value: any) => any): Object; - max(obj: Object, map: (key: string, value: any) => any): Object; + /** + * @see map + **/ + findAll(obj: any, map: string): any[]; - least(map: string): Object; - least(obj: Object, map: string): Object; - least(map: (key: string, value: any) => any): Object; - least(obj: Object, map: (key: string, value: any) => any): Object; + /** + * @see map + **/ + findAll(obj: any, map: (key: string, value: any) => bool): any[]; - most(map: string): Object; - most(obj: Object, map: string): Object; - most(map: (key: string, value: any) => any): Object; - most(obj: Object, map: (key: string, value: any) => any): Object; + /** + * @see map + **/ + reduce(obj: any, map: string, init?: any): any; - /*** + /** + * @see map + **/ + reduce(obj: any, map: (key: string, value: any) => any, init?: any): any; + + /** + * @see map + **/ + isEmpty(obj: any): bool; + + /** + * @see map + **/ + sum(obj: any, map: string): number; + + /** + * @see map + **/ + sum(obj: any, map: (key: string, value: any) => number): number; + + /** + * @see map + **/ + average(obj: any, map: string): number; + + /** + * @see map + **/ + average(obj: any, map: (key: string, value: any) => number): number; + + /** + * @see map + **/ + min(obj: any, map: string): any; + + /** + * @see map + **/ + min(obj: any, map: (key: string, value: any) => any): any; + + /** + * @see map + **/ + max(obj: any, map: string): any; + + /** + * @see map + **/ + max(obj: any, map: (key: string, value: any) => any): any; + + /** + * @see map + **/ + least(obj: any, map: string): any; + + /** + * @see map + **/ + least(obj: any, map: (key: string, value: any) => any): any; + + /** + * @see map + **/ + most(obj: any, map: string): any; + + /** + * @see map + **/ + most(obj: any, map: (key: string, value: any) => any): any; + + /** * Returns true if and are equal. - * @method equal(, ) - * @returns Boolean + * @param a First object to compare. + * @param b Second object to compare. + * @returns True if the objects are equal, otherwise false. * @extra %equal% in Sugar is "egal", meaning the values are equal * if they are "not observably distinguishable". Note that on * extended objects the name is %equals% for readability. * @example - * * Object.equal({a:2}, {a:2}) -> true * Object.equal({a:2}, {a:3}) -> false * Object.extended({a:2}).equals({a:3}) -> false - * - ***/ - equal(a: Object, b: Object): boolean; + **/ + equal(a: any, b: any): bool; - /*** + /** * Checks if has using hasOwnProperty from Object.prototype. - * @method has(, ) - * @returns Boolean + * @param obj Object to check for the property . + * @param key Property to check to see if it exists on . + * @returns True if exists on , otherwise false. * @extra This method is considered safer than %Object#hasOwnProperty% when * using objects as hashes. See * http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ * for more. * @example - * * Object.has({ foo: 'bar' }, 'foo') -> true * Object.has({ foo: 'bar' }, 'baz') -> false * Object.has({ hasOwnProperty: true }, 'foo') -> false - * - ***/ - has(key: string): boolean; - has(obj: Object, key: string): boolean; + **/ + has(obj: any, key: string): bool; - /*** - * Returns an array containing the keys in . Optionally calls - * [fn] for each key. - * @method keys(, [fn]) - * @returns Array + /** + * Returns an array containing the keys in . Optionally calls [fn] for each key. + * @param obj Retreive all keys/properties from this object. + * @param fn Optional callback for each key/value pair. + * @returns Array of each property on . * @extra This method is provided for browsers that don't support it natively, * and additionally is enhanced to accept the callback [fn]. Returned * keys are in no particular order. %keys% is available as an instance * method on extended objects. * @example - * * Object.keys({ broken: 'wear' }) -> ['broken'] * Object.keys({ broken: 'wear' }, function(key, value) { * // Called once for each key. * }); * Object.extended({ broken: 'wear' }).keys() -> ['broken'] - * - ***/ - keys(): string[]; - keys(obj: Object, fn?: (key: string, value: any) => void ): string[]; + **/ + keys(obj: any, fn?: (key: string, value: any) => void ): string[]; - /*** + /** * Merges all the properties of into . - * @method merge(, , [deep] = false, [resolve] = true) + * @param target + * @param source + * @param deep If true then deep merge, default = false. + * @param resolve If false then properties of source are used in the merge, default = true. * @returns Merged object * @extra Merges are shallow unless [deep] is %true%. Properties of * will win in the case of conflicts, unless [resolve] is %false%. @@ -3066,17 +3260,20 @@ interface Object { * together, etc. %merge% is available as an instance method on * extended objects. * @example - * * Object.merge({a:1},{b:2}) -> { a:1, b:2 } * Object.merge({a:1},{a:2}, false, false) -> { a:1 } + Object.merge({a:1},{a:2}, false, function(key, a, b) { * return a + b; * }); -> { a:3 } * Object.extended({a:1}).merge({b:2}) -> { a:1, b:2 } - * - ***/ - merge(target: Object, source: Object, deep?: boolean, resolve?: boolean): Object; - merge(target: Object, source: Object, deep?: boolean, resolve?: (key: string, targetVal: any, sourceVal: any) => any): Object; + **/ + merge(target: any, source: any, deep?: bool, resolve?: bool): any; + + /** + * @see merge + * @param resolve Callback to resolve conflicts in the merge. + **/ + merge(target: any, source: any, deep?: bool, resolve?: (key: string, targetVal: any, sourceVal: any) => any): any; /** * Builds a new object containing all values except those specified in find. @@ -3105,67 +3302,61 @@ interface Object { select(obj: any, ...find: any[]): any; - /*** + /** * Returns the number of properties in . - * @method size() - * @returns Number + * @param obj Object to determine the number of properties on. + * @returns The number of properties on . * @extra %size% is available as an instance method on extended objects. * @example - * * Object.size({ foo: 'bar' }) -> 1 - * - ***/ - size(): number; + **/ size(obj: Object): number; - /*** + /** * Runs and returns . - * @method tap(, ) - * @returns Object + * @param obj Object to tap. + * @param fn Function to tap on . + * @returns * @extra A string can also be used as a shortcut to a method. This method * is used to run an intermediary function in the middle of method * chaining. As a standalone method on the Object class it doesn't * have too much use. The power of %tap% comes when using extended * objects or modifying the Object prototype with Object.extend(). * @example - * * Object.extend(); * [2,4,6].map(Math.exp).tap(function(arr) { * arr.pop() * }); * [2,4,6].map(Math.exp).tap('pop').map(Math.round); -> [7,55] - * - ***/ - tap(fn: string): Object; - tap(fn: (...args: any[]) => any): Object; - tap(obj: Object, fn: string): Object; - tap(obj: Object, fn: (...args: any[]) => any): Object; + **/ + tap(obj: any, fn: string): any; - /*** - * Returns an array containing the values in . - * Optionally calls [fn] for each value. - * @method values(, [fn]) + /** + * @see tap + **/ + tap(obj: any, fn: (...args: any[]) => any): any; + + /** + * Returns an array containing the values in . Optionally calls [fn] for each value. + * @param obj Object to retrieve all values from. + * @param fn Optional callback for each value on . * @returns Array * @extra Returned values are in no particular order. %values% is available * as an instance method on extended objects. * @example - * * Object.values({ broken: 'wear' }) -> ['wear'] * Object.values({ broken: 'wear' }, function(value) { * // Called once for each value. * }); * Object.extended({ broken: 'wear' }).values() -> ['wear'] - * - ***/ - values(): any[]; - values(fn: (value: any) => any): any[]; - values(obj: Object): any[]; - values(obj: Object, fn: (value: any) => any): any[]; + **/ + values(obj: any, fn?: (value: any) => any): any[]; - /*** + /** * Watches a property of and runs when it changes. - * @method watch(, , ) - * @returns Nothing + * @param obj Object to watch. + * @param prop Property to watch on + * @param fn Callback function when changes on . * @extra is passed three arguments: the property , the old value, * and the new value. The return value of [fn] will be set as the new * value. This method is useful for things such as validating or cleaning @@ -3183,34 +3374,482 @@ interface Object { * // Will be run when the property 'foo' is set on the object. * }); * - ***/ + **/ + watch(obj: any, prop: string, fn: (prop: string, oldVal: any, newVal: any) => any): void; +} + +interface Object { + + /** + * Creates a new object, equivalent to %new Object()% or %{}%, but with extended methods. + * @returns Extended object. + * @extra See extended objects for more. + * @example + * Object.extended() + * Object.extended({ happy:true, pappy:false }).keys() -> ['happy','pappy'] + * Object.extended({ happy:true, pappy:false }).values() -> [true, false] + **/ + extended(): Object; + + /** + * Returns true if is an object of that type. + * @method Object.is[Type]() + * @returns True if is of type [Type]. + * @extra %isObject% will return false on anything that is not an object + * literal, including instances of inherited classes. Note also + * that %isNaN% will ONLY return true if the object IS %NaN%. + * It does not mean the same as browser native %isNaN%, which returns + * true for anything that is "not a number". + * @set + * isArray + * isObject + * isBoolean + * isDate + * isFunction + * isNaN + * isNumber + * isString + * isRegExp + * @example + * Object.isArray([1,2,3]) -> true + * Object.isDate(3) -> false + * Object.isRegExp(/wasabi/) -> true + * Object.isObject({ broken:'wear' }) -> true + **/ + isArray(): bool; + + /** + * @see isArray + **/ + isObject(): bool; + + /** + * @see isArray + **/ + isBoolean(): bool; + + /** + * @see isArray + **/ + isDate(): bool; + + /** + * @see isArray + **/ + isFunction(): bool; + + /** + * @see isArray + **/ + isNaN(): bool; + + /** + * @see isArray + **/ + isNumber(): bool; + + /** + * @see isArray + **/ + isString(): bool; + + /** + * @see isArray + **/ + isRegExp(): bool; + + /** + * Converts the object into a query string. Accepts deep nested objects and arrays. + * If namespace is passed, it will be prefixed to all param names. + * @param obj Object to convert to a query string. + * @param namespace Namespace to prefix properties with in the query string. + * @return A query string generated from `obj` and `namespace`. + **/ + toQueryString(namespace?: string): string; + + /** + * Creates a clone (copy) of . + * @param deep If true then deep clone, default = false. + * @returns Cloned object. + * @extra Default is a shallow clone, unless [deep] is true. %clone% + * is available as an instance method on extended objects. + * @example + * Object.clone({foo:'bar'}) -> { foo: 'bar' } + * Object.clone() -> {} + * Object.extended({foo:'bar'}).clone() -> { foo: 'bar' } + **/ + clone(deep?: bool): any; + + /** + * Enumerable methods in the Array package are also available to + * the Object class. They will perform their normal operations for + * every property in . + * @method [enumerable]() + * @returns Boolean + * @extra In cases where a callback is used, instead of %element, index%, + * the callback will instead be passed %key, value%. Enumerable methods + * are also available to extended objects as instance methods. + * @set + * each + * map + * any + * all + * none + * count + * find + * findAll + * reduce + * isEmpty + * sum + * average + * min + * max + * least + * most + * @example + * Object.any({foo:'bar'}, 'bar') -> true + * Object.extended({foo:'bar'}).any('bar') -> true + * Object.isEmpty({}) -> true + * Object.map({ fred: { age: 52 } }, 'age'); -> { fred: 52 } + **/ + map(map: string): U; + + /** + * @see map + **/ + map(map: (key: string, value: any) => any): U; + + /** + * @see map + **/ + any(map: string): bool; + + /** + * @see map + **/ + any(map: (key: string, value: any) => bool): bool; + + /** + * @see map + **/ + all(map: string): bool; + + /** + * @see map + **/ + all(map: (key: string, value: any) => bool): bool; + + /** + * @see map + **/ + none(map: string): bool; + + /** + * @see map + **/ + none(map: (key: string, value: any) => bool): bool; + + /** + * @see map + **/ + count(map: string): number; + + /** + * @see map + **/ + count(map: (key: string, value: any) => bool): number; + + /** + * @see map + **/ + find(map: string): any; + + /** + * @see map + **/ + find(map: (key: string, value: any) => bool): any; + + /** + * @see map + **/ + findAll(map: string): any[]; + + /** + * @see map + **/ + findAll(map: (key: string, value: any) => bool): any[]; + + /** + * @see map + **/ + reduce(map: string, init?: any): any; + + /** + * @see map + **/ + reduce(map: (key: string, value: any) => any, init?: any): any; + + /** + * @see map + **/ + isEmpty(): bool; + + /** + * @see map + **/ + sum(map: string): number; + + /** + * @see map + **/ + sum(map: (key: string, value: any) => number): number; + + /** + * @see map + **/ + average(map: string): number; + + /** + * @see map + **/ + average(map: (key: string, value: any) => number): number; + + /** + * @see map + **/ + min(map: string): any; + + /** + * @see map + **/ + min(map: (key: string, value: any) => any): any; + + /** + * @see map + **/ + max(map: string): any; + + /** + * @see map + **/ + max(map: (key: string, value: any) => any): any; + + /** + * @see map + **/ + least(map: string): any; + + /** + * @see map + **/ + least(map: (key: string, value: any) => any): any; + + /** + * @see map + **/ + most(map: string): any; + + /** + * @see map + **/ + most(map: (key: string, value: any) => any): any; + + /** + * Returns true if and are equal. + * @param b Compare to this object + * @returns True if the objects are equal, otherwise false. + * @extra %equal% in Sugar is "egal", meaning the values are equal + * if they are "not observably distinguishable". Note that on + * extended objects the name is %equals% for readability. + * @example + * Object.equal({a:2}, {a:2}) -> true + * Object.equal({a:2}, {a:3}) -> false + * Object.extended({a:2}).equals({a:3}) -> false + **/ + equal(b: any): bool; + + /** + * Checks if has using hasOwnProperty from Object.prototype. + * @param key Property to check to see if it exists on . + * @returns True if exists on , otherwise false. + * @extra This method is considered safer than %Object#hasOwnProperty% when + * using objects as hashes. See + * http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ + * for more. + * @example + * Object.has({ foo: 'bar' }, 'foo') -> true + * Object.has({ foo: 'bar' }, 'baz') -> false + * Object.has({ hasOwnProperty: true }, 'foo') -> false + **/ + has(key: string): bool; + + /** + * Returns an array containing the keys in . Optionally calls [fn] for each key. + * @param fn Optional callback for each key/value pair. + * @returns Array of each property on . + * @extra This method is provided for browsers that don't support it natively, + * and additionally is enhanced to accept the callback [fn]. Returned + * keys are in no particular order. %keys% is available as an instance + * method on extended objects. + * @example + * Object.keys({ broken: 'wear' }) -> ['broken'] + * Object.keys({ broken: 'wear' }, function(key, value) { + * // Called once for each key. + * }); + * Object.extended({ broken: 'wear' }).keys() -> ['broken'] + **/ + keys(fn?: (key: string, value: any) => void ): string[]; + + /** + * Merges all the properties of into . + * @param source + * @param deep If true then deep merge, default = false. + * @param resolve If false then properties of source are used in the merge, default = true. + * @returns Merged object + * @extra Merges are shallow unless [deep] is %true%. Properties of + * will win in the case of conflicts, unless [resolve] is %false%. + * [resolve] can also be a function that resolves the conflict. + * In this case it will be passed 3 arguments, %key%, %targetVal%, + * and %sourceVal%, with the context set to . This will allow + * you to solve conflict any way you want, ie. adding two numbers + * together, etc. %merge% is available as an instance method on + * extended objects. + * @example + * Object.merge({a:1},{b:2}) -> { a:1, b:2 } + * Object.merge({a:1},{a:2}, false, false) -> { a:1 } + + Object.merge({a:1},{a:2}, false, function(key, a, b) { + * return a + b; + * }); -> { a:3 } + * Object.extended({a:1}).merge({b:2}) -> { a:1, b:2 } + **/ + merge(source: any, deep?: bool, resolve?: bool): any; + + /** + * @see merge + * @param resolve Callback to resolve conflicts in the merge. + **/ + merge(source: any, deep?: bool, resolve?: (key: string, targetVal: any, sourceVal: any) => any): any; + + /** + * Builds a new object containing all values except those specified in find. + * When find is a string, that single key will be rejected. It can also be a regex, + * rejecting any key that matches, or an object which will match if the key also + * exists in that object, effectively "subtracting" that object. Multiple selections + * may also be passed as an array or directly as enumerated arguments. reject is + * available as an instance method on extended objects. + * @param find The property (string), properties (object) or RegExp to remove from `obj`. + * @return Modified `obj` with `find` properties removed. + **/ + reject(...find: any[]): any; + + /** + * Builds a new object containing the values specified in find. When find is a string, + * that single key will be selected. It can also be a regex, selecting any key that + * matches, or an object which will match if the key also exists in that object, + * effectively doing an "intersect" operation on that object. Multiple selections + * may also be passed as an array or directly as enumerated arguments. select is + * available as an instance method on extended objects. + * @param find The property (string), properties (object) or RegExp to keep on `obj`. + * @return Modified `obj` with only the `find` properties remaining. + **/ + select(...find: any[]): any; + + + /** + * Returns the number of properties in . + * @returns The number of properties on . + * @extra %size% is available as an instance method on extended objects. + * @example + * Object.size({ foo: 'bar' }) -> 1 + **/ + size(): number; + + /** + * Runs and returns . + * @param fn Function to tap on . + * @returns + * @extra A string can also be used as a shortcut to a method. This method + * is used to run an intermediary function in the middle of method + * chaining. As a standalone method on the Object class it doesn't + * have too much use. The power of %tap% comes when using extended + * objects or modifying the Object prototype with Object.extend(). + * @example + * Object.extend(); + * [2,4,6].map(Math.exp).tap(function(arr) { + * arr.pop() + * }); + * [2,4,6].map(Math.exp).tap('pop').map(Math.round); -> [7,55] + **/ + tap(fn: string): any; + + /** + * @see tap + **/ + tap(fn: (...args: any[]) => any): any; + + /** + * Returns an array containing the values in . Optionally calls [fn] for each value. + * @param fn Optional callback for each value on . + * @returns Array + * @extra Returned values are in no particular order. %values% is available + * as an instance method on extended objects. + * @example + * Object.values({ broken: 'wear' }) -> ['wear'] + * Object.values({ broken: 'wear' }, function(value) { + * // Called once for each value. + * }); + * Object.extended({ broken: 'wear' }).values() -> ['wear'] + **/ + values(fn?: (value: any) => any): any[]; + + /** + * Watches a property of and runs when it changes. + * @param obj Object to watch. + * @param prop Property to watch on + * @param fn Callback function when changes on . + * @extra is passed three arguments: the property , the old value, + * and the new value. The return value of [fn] will be set as the new + * value. This method is useful for things such as validating or cleaning + * the value when it is set. Warning: this method WILL NOT work in + * browsers that don't support %Object.defineProperty%. This notably + * includes IE 8 and below, and Opera. This is the only method in Sugar + * that is not fully compatible with all browsers. %watch% is available + * as an instance method on extended objects. + * @example + * + * Object.watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) { + * // Will be run when the property 'foo' is set on the object. + * }); + * Object.extended().watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) { + * // Will be run when the property 'foo' is set on the object. + * }); + * + **/ watch(prop: string, fn: (prop: string, oldVal: any, newVal: any) => any): void; - watch(obj: Object, prop: string, fn: (prop: string, oldVal: any, newVal: any) => any): void; } interface Function { - /*** + /** * Creates a function that will execute after [num] calls. - * @method after([num] = 1) - * @returns Function + * @param num Execute the function after this many calls, default = 1. + * @returns Function that can only execute after it has been called times. * @extra %after% is useful for running a final callback after a series of * asynchronous operations, when the order in which the operations will * complete is unknown. * @example - * * var fn = (function() { * // Will be executed once only * }).after(3); fn(); fn(); fn(); - * - ***/ + **/ after(num?: number): Function; - /*** + /** * Binds as the %this% object for the function when it is called. * Also allows currying an unlimited number of parameters. - * @method bind(, [arg1], ...) - * @returns Function + * @param scope this object during the function call. + * @param args Curried parameters. + * @returns Function with bound 'this' and curried parameters. * @extra "currying" means setting parameters ([arg1], [arg2], etc.) ahead of * time so that they are passed when the function is called later. * If you pass additional parameters when the function is actually @@ -3218,8 +3857,7 @@ interface Function { * parameters. This method is provided for browsers that don't support * it internally. * @example - * - + (function() { + * (function() { * return this; * }).bind('woof')(); -> returns 'woof'; function is bound with 'woof' as the this object. * (function(a) { @@ -3228,64 +3866,56 @@ interface Function { * (function(a, b) { * return a + b; * }).bind(1, 2)(3); -> returns 5; function is bound with 1 as the this object, 2 curied as the first parameter and 3 passed as the second when calling the function - * - ***/ - bind(scope?: Object, ...args: any[]): Function; + **/ + bind(scope?: any, ...args: any[]): Function; - /*** + /** * Cancels a delayed function scheduled to be run. - * @method cancel() * @returns Function * @extra %delay%, %lazy%, %throttle%, and %debounce% can all set delays. * @example - * * (function() { * alert('hay'); // Never called * }).delay(500).cancel(); - * - ***/ + **/ cancel(): Function; - /*** - * Creates a "debounced" function that postpones its execution until - * after milliseconds have passed. - * @method debounce() - * @returns Function + /** + * Creates a "debounced" function that postpones its execution until after milliseconds have passed. + * @param ms Number of milliseconds to debounce the function. + * @returns Deboucned function by ms . * @extra This method is useful to execute a function after things have * "settled down". A good example of this is when a user tabs quickly * through form fields, execution of a heavy operation should happen * after a few milliseconds when they have "settled" on a field. * @example - * * var fn = (function(arg1) { * // called once 50ms later * }).debounce(50); fn() fn() fn(); - * - ***/ + **/ debounce(ms: number): Function; - /*** + /** * Executes the function after milliseconds. - * @method delay([ms] = 0, [arg1], ...) - * @returns Function + * @param ms Milliseconds to delay execution, default = 0. + * @param args Additional arguments. + * @returns Reference to itself. * @extra Returns a reference to itself. %delay% is also a way to execute * non-blocking operations that will wait until the CPU is free. * Delayed functions can be canceled using the %cancel% method. * Can also curry arguments passed in after . * @example - * * (function(arg1) { * // called 1s later * }).delay(1000, 'arg1'); - * - ***/ + **/ delay(ms?: number, ...args: any[]): Function; - /*** + /** * Returns a new version of the function which when called will have * some of its arguments pre-emptively filled in, also known as "currying". - * @method fill(, , ...) - * @returns Function + * @param args Pre-filled arguments. + * @returns Function with pre-filled arguments. * @extra Arguments passed to a "filled" function are generally appended to * the curried arguments. However, if %undefined% is passed as any of * the arguments to %fill%, it will be replaced, when the "filled" @@ -3293,19 +3923,18 @@ interface Function { * they occur toward the end of an argument list (the example * demonstrates this much more clearly). * @example - * * var delayOneSecond = setTimeout.fill(undefined, 1000); * delayOneSecond(function() { * // Will be executed 1s later * }); - * - ***/ + **/ fill(...args: any[]): Function; - /*** - * Creates a lazy function that, when called repeatedly, will queue - * execution and wait [ms] milliseconds to execute again. + /** + * Creates a lazy function that, when called repeatedly, will queue execution and wait [ms] milliseconds to execute again. * @method lazy([ms] = 1, [limit] = Infinity) + * @param ms Wait this long between successive calls, default = 1. + * @param limit Maximum number of times the function can execute, default = Infinity. * @returns Function * @extra Lazy functions will always execute as many times as they are called * up to [limit], after which point subsequent calls will be ignored @@ -3315,7 +3944,6 @@ interface Function { * in a non-blocking manner. Calling %cancel% on a lazy function will * clear the entire queue. Note that [ms] can also be a fraction. * @example - * * (function() { * // Executes immediately. * }).lazy()(); @@ -3325,31 +3953,26 @@ interface Function { * (100).times(function() { * // Executes 50 times, with each execution 20ms later than the last. * }.lazy(20, 50)); - * - ***/ + **/ lazy(ms?: number, limit?: number): Function; - /*** + /** * Creates a function that will execute only once and store the result. - * @method once() * @returns Function * @extra %once% is useful for creating functions that will cache the result of * an expensive operation and use it on subsequent calls. Also it can be * useful for creating initialization functions that only need to be run * once. * @example - * * var fn = (function() { * // Will be executed once only * }).once(); fn(); fn(); fn(); - * - ***/ + **/ once(): Function; - /*** - * Creates a "throttled" version of the function that will only be - * executed once per milliseconds. - * @method throttle() + /** + * Creates a "throttled" version of the function that will only be executed once per milliseconds. + * @param ms Execute only once in this time span. * @returns Function * @extra This is functionally equivalent to calling %lazy% with a [limit] * of %1%. %throttle% is appropriate when you want to make sure a @@ -3357,77 +3980,67 @@ interface Function { * Compare this to %lazy%, which will queue rapid calls and execute * them later. * @example - * * (3).times(function() { * // called only once. will wait 50ms until it responds again * }.throttle(50)); - * - ***/ + **/ throttle(ms: number): Function; } +interface RegExpStatic { + + /** + * Escapes all RegExp tokens in a string. + * @param str Escape RegExp tokens in this string. + * @returns Escaped RegExp tokens in . + * @example + * RegExp.escape('really?') -> 'really\?' + * RegExp.escape('yes.') -> 'yes\.' + * RegExp.escape('(not really)') -> '\(not really\)' + **/ + escape(str: string): string; +} + interface RegExp { - /*** - * Escapes all RegExp tokens in a string. - * @method RegExp.escape( = '') - * @returns String - * @example - * - * RegExp.escape('really?') -> 'really\?' - * RegExp.escape('yes.') -> 'yes\.' - * RegExp.escape('(not really)') -> '\(not really\)' - * - ***/ - escape(str: string): string; - - /*** + /** * Adds to the regex. - * @method addFlag() - * @returns RegExp + * @param flag RegExp flag to add. + * @returns RegExp with added. * @example - * * /texty/.addFlag('g') -> now has global flag set - * - ***/ + **/ addFlag(flag: string): RegExp; - /*** + /** * Returns the flags of the regex as a string. - * @method getFlags() - * @returns String + * @returns RegExp flags. * @example - * * /texty/gim.getFlags('testy') -> 'gim' - * - ***/ + **/ getFlags(): string; - /*** + /** * Removes from the regex. - * @method removeFlag() - * @returns RegExp + * @param flag RegExp flag to remove. + * @returns RegExp with flag removed. * @example - * * /texty/g.removeFlag('g') -> now has global flag removed - * - ***/ + **/ removeFlag(flag: string): RegExp; - /*** + /** * Sets the flags on a regex and retuns a copy. - * @method setFlags() - * @returns RegExp + * @param flags Set the RegExp to have these flags. + * @returns Copy of RegExp with . * @example - * * /texty/.setFlags('gim') -> now has global, ignoreCase, and multiline set - * - ***/ + **/ setFlags(flags: string): RegExp; } interface Locale { - plural: boolean; + plural: bool; months: string; weekdays: string; units: string; @@ -3451,20 +4064,23 @@ interface Locale { timeParse: string[]; } -interface Date { +interface DateStatic { - /*** + /** * Adds a locale to the locales understood by Sugar. * @method Date.addLocale(, ) + * @param code Locale code. + * @param set Locale definition. * @returns Locale * @extra For more see @date_format. - ***/ + **/ addLocale(code: string, set: Locale): Locale; - /*** + /** * Alternate Date constructor which understands many different text formats, * a timestamp, or another date. * @method Date.create(, [locale] = currentLocale) + * @param locale Locale to create the date in, default = currentLocale. * @returns Date * @extra If no argument is given, date is assumed to be now. %Date.create% additionally * can accept enumerated parameters as with the standard date constructor. [locale] @@ -3473,9 +4089,7 @@ interface Date { * through the %utc% object. For more see @date_format. * @set * Date.utc.create - * * @example - * * Date.create('July') -> July of this year * Date.create('1776') -> 1776 * Date.create('today') -> today @@ -3486,15 +4100,28 @@ interface Date { * Date.create(1776, 6, 4) -> July 4, 1776 * Date.create('1776?07?04?', 'ja') -> July 4, 1776 * Date.utc.create('July 4, 1776', 'en') -> July 4, 1776 - * - ***/ + **/ create(locale?: string): Date; + + /** + * @see create + * @param d Human readable date to convert to a Date object. + **/ create(d: string, locale?: string): Date; + + /** + * @see create + * @param year Year YYYY + * @param month Month MM + * @param day Day DD + **/ create(year: number, month: number, day: number, locale?: string): Date; - /*** + /** * Alternate form of %Date.create% with any ambiguity assumed to be the future. * @method Date.future(, [locale] = currentLocale) + * @param d Future human redable date to convert to a Date object. + * @param locale Locale to create the date in, default = currentLocale. * @returns Date * @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" * depending on context. Note that dates explicitly in the past ("last Sunday") will @@ -3502,39 +4129,37 @@ interface Date { * -based dates can be created through the %utc% object. For more, see @date_format. * @set * Date.utc.future - * * @example - * * Date.future('July') -> July of this year or next depending on the current month * Date.future('Wednesday') -> This wednesday or next depending on the current weekday - * - ***/ + **/ future(d: string, locale?: string): Date; - /*** + /** * Gets the locale for the given code, or the current locale. * @method Date.getLocale([code] = current) + * @param code Locale code to retrieve. * @returns Locale * @extra The resulting locale object can be manipulated to provide more control over date localizations. * For more about locales, see @date_format. - ***/ + **/ getLocale(code?: string): Locale; - /*** + /** * Returns the number of milliseconds since January 1st, 1970 00:00:00 (UTC time). * @method Date.now() * @returns String * @extra Provided for browsers that do not support this method. * @example - * * Date.now() -> ex. 1311938296231 - * - ***/ + **/ now(): string; - /*** + /** * Alternate form of %Date.create% with any ambiguity assumed to be the past. * @method Date.past(, [locale] = currentLocale) + * @param d Past human readable date to convert to a Date object. + * @param locale , default = currentLocale. * @returns Date * @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" depending * on context. Note that dates explicitly in the future ("next Sunday") will remain in the future. @@ -3543,42 +4168,51 @@ interface Date { * @set * Date.utc.past * @example - * * Date.past('July') -> July of this year or last depending on the current month * Date.past('Wednesday') -> This wednesday or last depending on the current weekday - * - ***/ + **/ past(d: string, local?: string): Date; - /*** + /** * Creates a new date range. * @method Date.range([start], [end]) + * @param start Beginning date. + * @param end Ending date. * @returns DateRange * @extra If either [start] or [end] are null, they will default to the current date. - ***/ + **/ range(start: Date, end: Date): DateRange; - /*** + /** * Sets the current locale to be used with dates. * @method Date.setLocale() + * @param code Locale code. * @returns Locale * @extra Sugar has support for 13 locales that are available through the - & "Date Locales" package. In addition you can define a new locale with + * "Date Locales" package. In addition you can define a new locale with * %Date.addLocale%. For more see @date_format. - * - ***/ + **/ setLocale(code: string): Locale; +} - /*** - * Adds of the unit to the date. If [reset] is true, all lower - * units will be reset. +interface DateFields { + year?: number; + month?: number; + day?: number; +} + +interface Date { + + /** + * Adds of the unit to the date. If [reset] is true, all lower units will be reset. * @method add[Units](, [reset] = false) + * @param num Add this many [Units] to the date. + * @param reset If true lower units will be reset. * @returns Date * @extra Note that "months" is ambiguous as a unit of time. If the target * date falls on a day that does not exist (ie. August 31 -> February 31), * the date will be shifted to the last day of the month. Don't use * %addMonths% if you need precision. - * * @set * addMilliseconds * addSeconds @@ -3588,26 +4222,53 @@ interface Date { * addWeeks * addMonths * addYears - * * @example - * * Date.create().addMilliseconds(5) -> current time + 5 milliseconds * Date.create().addDays(5) -> current time + 5 days * Date.create().addYears(5) -> current time + 5 years - * - ***/ - addMilliseconds(num: number, reset?: boolean): Date; - addSeconds(num: number, reset?: boolean): Date; - addMinutes(num: number, reset?: boolean): Date; - addHours(num: number, reset?: boolean): Date; - addDays(num: number, reset?: boolean): Date; - addWeeks(num: number, reset?: boolean): Date; - addMonths(num: number, reset?: boolean): Date; - addYears(num: number, reset?: boolean): Date; + **/ + addMilliseconds(num: number, reset?: bool): Date; - /*** + /** + * @see addMilliseconds + **/ + addSeconds(num: number, reset?: bool): Date; + + /** + * @see addMilliseconds + **/ + addMinutes(num: number, reset?: bool): Date; + + /** + * @see addMilliseconds + **/ + addHours(num: number, reset?: bool): Date; + + /** + * @see addMilliseconds + **/ + addDays(num: number, reset?: bool): Date; + + /** + * @see addMilliseconds + **/ + addWeeks(num: number, reset?: bool): Date; + + /** + * @see addMilliseconds + **/ + addMonths(num: number, reset?: bool): Date; + + /** + * @see addMilliseconds + **/ + addYears(num: number, reset?: bool): Date; + + /** * Sets the date forward. * @method advance(, [reset] = false) + * @param set Human readable amount of time to advance the date. + * @param reset If true resets the lower date fields to zero. * @returns Date * @extra This method can accept multiple formats including an object, a string * in the format %3 days%, a single number as milliseconds, or enumerated @@ -3615,90 +4276,93 @@ interface Date { * units more specific than those passed will be reset. For more see * @date_format. * @example - * * new Date().advance({ year: 2 }) -> 2 years in the future * new Date().advance('2 days') -> 2 days in the future * new Date().advance(0, 2, 3) -> 2 months 3 days in the future * new Date().advance(86400000) -> 1 day in the future - * - ***/ - advance(set: string, reset?: boolean): Date; - advance(year: number, month: number, day: number, reset?: boolean): Date; - advance(milliseconds: number, reset?: boolean): Date; - advance(set: Object, reset?: boolean): Date; + **/ + advance(set: string, reset?: bool): Date; - /*** + /** + * @see advance + * @param year YYYY to advance. + * @param month MM to advance. + * @param day DD to advance. + **/ + advance(year: number, month: number, day: number, reset?: bool): Date; + + /** + * @see advance + * @param milliseconds Milliseconds to advance the date. + **/ + advance(milliseconds: number, reset?: bool): Date; + + /** + * @see advance + * @param set Advance the year/month/day of the date from a single object. + **/ + advance(set: DateFields, reset?: bool): Date; + + /** * Sets the date to the beginning of the appropriate unit. * @method beginningOf[Unit]() * @returns Date - * * @set * beginningOfDay * beginningOfWeek * beginningOfMonth * beginningOfYear - * * @example - * * Date.create().beginningOfDay() -> the beginning of today (resets the time) * Date.create().beginningOfWeek() -> the beginning of the week * Date.create().beginningOfMonth() -> the beginning of the month * Date.create().beginningOfYear() -> the beginning of the year - * - ***/ + **/ beginningOfDay(): Date; beginningOfWeek(): Date; beginningOfMonth(): Date; beginningOfYear(): Date; - /*** + /** * Clones the date. * @method clone() * @returns Date * @example - * * Date.create().clone() -> Copy of now - * - ***/ + **/ clone(): Date; - /*** + /** * Returns the number of days in the date's month. * @method daysInMonth() * @returns Number * @example - * * Date.create('May').daysInMonth() -> 31 * Date.create('February, 2000').daysInMonth() -> 29 - * - ***/ + **/ daysInMonth(): number; - /*** + /** * Sets the date to the end of the appropriate unit. * @method endOf[Unit]() * @returns Date - * * @set * endOfDay * endOfWeek * endOfMonth * endOfYear - * * @example - * * Date.create().endOfDay() -> the end of today (sets the time to 23:59:59.999) * Date.create().endOfWeek() -> the end of the week * Date.create().endOfMonth() -> the end of the month * Date.create().endOfYear() -> the end of the year - * - ***/ + **/ endOfDay(): Date; endOfWeek(): Date; endOfMonth(): Date; endOfYear(): Date; - /*** + /** * Formats and outputs the date. * @method format(, [locale] = currentLocale) * @returns String @@ -3708,14 +4372,11 @@ interface Date { * If is not specified the %long% format is assumed. [locale] * specifies a locale code to use (if not specified the current locale * is used). See @date_format for more details. - * * @set * short * long * full - * * @example - * * Date.create().format() -> ex. July 4, 2003 * Date.create().format('{Weekday} {d} {Month}, {yyyy}') -> ex. Monday July 4, 2003 * Date.create().format('{hh}:{mm}') -> ex. 15:57 @@ -3725,57 +4386,48 @@ interface Date { * Date.create('yesterday').format(function(value,unit,ms,loc) { * // value = 1, unit = 3, ms = -86400000, loc = [current locale object] * }); -> ex. 1 day ago - * - ***/ + **/ format(format: string, locale?: string): string; short(): string; long(): string; full(): string; - /*** + /** * Returns a string representation of the offset from UTC time. If [iso] * is true the offset will be in ISO8601 format. * @method getUTCOffset([iso]) * @returns String * @example - * * new Date().getUTCOffset() -> "+0900" * new Date().getUTCOffset(true) -> "+09:00" - * - ***/ - getUTCOffset(iso?: boolean): string; + **/ + getUTCOffset(iso?: bool): string; - /*** + /** * Gets the date's week (of the year). * @returns The date's week of the year as defined by the ISO-8601 standard. * @extra If %utc% is set on the date, the week will be according to UTC time. - * * @example - * * new Date().getWeek() -> today's week of the year - * - ***/ + **/ getISOWeek(): number; - /*** + /** * Alias for %getDay%. * @method getWeekday() * @returns Number * @set * getUTCWeekday - * * @example - * * Date.create().getWeekday(); -> (ex.) 3 * Date.create().getUTCWeekday(); -> (ex.) 3 - * - ***/ + **/ getWeekday(): number; getUTCWeekday(): number; //getDay(): number; //getUTCDay(): number; - /*** + /** * Returns true if the date is . * @method is(, [margin] = 0) * @returns Boolean @@ -3785,7 +4437,6 @@ interface Date { * implied in . [margin] allows an extra margin of error in * milliseconds. For more, see @date_format. * @example - * * Date.create().is('July') -> true or false? * Date.create().is('1776') -> false * Date.create().is('today') -> true @@ -3793,13 +4444,12 @@ interface Date { * Date.create().is('July 4, 1776') -> false * Date.create().is(-6106093200000) -> false * Date.create().is(new Date(1776, 6, 4)) -> false - * - ***/ - is(d: string, margin?: number): boolean; - is(milliseconds: number, margin?: number): boolean; - is(d: Date, margin?: number): boolean; + **/ + is(d: string, margin?: number): bool; + is(milliseconds: number, margin?: number): bool; + is(d: Date, margin?: number): bool; - /*** + /** * Returns true if the date is after the . * @method isAfter(, [margin] = 0) * @returns Boolean @@ -3807,16 +4457,14 @@ interface Date { * a date object, timestamp, or text format. If not specified, is * assumed to be now. See @date_format for more. * @example - * * new Date().isAfter('tomorrow') -> false * new Date().isAfter('yesterday') -> true - * - ***/ - isAfter(d: string, margin?: number): boolean; - isAfter(milliseconds: number, margin?: number): boolean; - isAfter(d: Date, margin?: number): boolean; + **/ + isAfter(d: string, margin?: number): bool; + isAfter(milliseconds: number, margin?: number): bool; + isAfter(d: Date, margin?: number): bool; - /*** + /** * Returns true if the date is before . * @method isBefore(, [margin] = 0) * @returns Boolean @@ -3824,16 +4472,14 @@ interface Date { * a date object, timestamp, or text format. If not specified, is * assumed to be now. See @date_format for more. * @example - * * new Date().isBefore('tomorrow') -> true * new Date().isBefore('yesterday') -> false - * - ***/ - isBefore(d: string, margin?: number): boolean; - isBefore(milliseconds: number, margin?: number): boolean; - isBefore(d: Date, margin?: number): boolean; + **/ + isBefore(d: string, margin?: number): bool; + isBefore(milliseconds: number, margin?: number): bool; + isBefore(d: Date, margin?: number): bool; - /*** + /** * Returns true if the date falls between and . * @method isBetween(, , [margin] = 0) * @returns Boolean @@ -3841,22 +4487,19 @@ interface Date { * will accept a date object, timestamp, or text format. If not specified, * they are assumed to be now. See @date_format for more. * @example - * * new Date().isBetween('yesterday', 'tomorrow') -> true * new Date().isBetween('last year', '2 years ago') -> false - * - ***/ - isBefore(start: string, end: string, margin?: number): boolean; - isBefore(start: number, end: string, margin?: number): boolean; - isBefore(start: Date, end: Date, margin?: number): boolean; + **/ + isBefore(start: string, end: string, margin?: number): bool; + isBefore(start: number, end: string, margin?: number): bool; + isBefore(start: Date, end: Date, margin?: number): bool; - /*** + /** * Returns true if the date falls on that day. * @method is[Day]() * @returns Boolean * @extra Also available: %isYesterday%, %isToday%, %isTomorrow%, %isWeekday%, * and %isWeekend%. - * * @set * isToday * isYesterday @@ -3870,152 +4513,127 @@ interface Date { * isThursday * isFriday * isSaturday - * * @example - * * Date.create('tomorrow').isToday() -> false * Date.create('thursday').isTomorrow() -> ? * Date.create('yesterday').isWednesday() -> ? * Date.create('today').isWeekend() -> ? - * - ***/ - isToday(): boolean; - isYesterday(): boolean; - isTomorrow(): boolean; - isWeekday(): boolean; - isWeekend(): boolean; - isSunday(): boolean; - isMonday(): boolean; - isTuesday(): boolean; - isWednesday(): boolean; - isThursday(): boolean; - isFriday(): boolean; - isSaturday(): boolean; + **/ + isToday(): bool; + isYesterday(): bool; + isTomorrow(): bool; + isWeekday(): bool; + isWeekend(): bool; + isSunday(): bool; + isMonday(): bool; + isTuesday(): bool; + isWednesday(): bool; + isThursday(): bool; + isFriday(): bool; + isSaturday(): bool; - /*** + /** * Returns true if the date is in the future. * @method isFuture() * @returns Boolean * @example - * * Date.create('next week').isFuture() -> true * Date.create('last week').isFuture() -> false - * - ***/ - isFuture(): boolean; + **/ + isFuture(): bool; - /*** + /** * Returns true if the date is last week/month/year. * @method isLast[Unit]() * @returns Boolean - * * @set * isLastWeek * isLastMonth * isLastYear - * * @example - * * Date.create('yesterday').isLastWeek() -> true or false? * Date.create('yesterday').isLastMonth() -> probably not... * Date.create('yesterday').isLastYear() -> even less likely... - * - ***/ - isLastWeek(): boolean; - isLastMonth(): boolean; - isLastYear(): boolean; + **/ + isLastWeek(): bool; + isLastMonth(): bool; + isLastYear(): bool; - /*** + /** * Returns true if the date is a leap year. * @method isLeapYear() * @returns Boolean * @example - * * Date.create('2000').isLeapYear() -> true - * - ***/ - isLeapYear(): boolean; + **/ + isLeapYear(): bool; - /*** + /** * Returns true if the date is next week/month/year. * @method isNext[Unit]() * @returns Boolean - * * @set * isNextWeek * isNextMonth * isNextYear - * * @example - * * Date.create('tomorrow').isNextWeek() -> true or false? * Date.create('tomorrow').isNextMonth() -> probably not... * Date.create('tomorrow').isNextYear() -> even less likely... - * - ***/ - isNextWeek(): boolean; - isNextMonth(): boolean; - isNextYear(): boolean; + **/ + isNextWeek(): bool; + isNextMonth(): bool; + isNextYear(): bool; - /*** + /** * Returns true if the date is in the past. * @method isPast() * @returns Boolean * @example - * * Date.create('last week').isPast() -> true * Date.create('next week').isPast() -> false - * - ***/ - isPast(): boolean; + **/ + isPast(): bool; - /*** + /** * Returns true if the date is this week/month/year. * @method isThis[Unit]() * @returns Boolean - * * @set * isThisWeek * isThisMonth * isThisYear - * * @example - * * Date.create('tomorrow').isThisWeek() -> true or false? * Date.create('tomorrow').isThisMonth() -> probably... * Date.create('tomorrow').isThisYear() -> signs point to yes... - * - ***/ - isThisWeek(): boolean; - isThisMonth(): boolean; - isThisYear(): boolean; + **/ + isThisWeek(): bool; + isThisMonth(): bool; + isThisYear(): bool; - /*** + /** * Returns true if the date has no timezone offset. * @method isUTC() * @returns Boolean * @extra This will also return true for a date that has had %toUTC% called on it. This is intended to help approximate shifting timezones which is not possible in client-side Javascript. Note that the native method %getTimezoneOffset% will always report the same thing, even if %isUTC% becomes true. * @example - * * new Date().isUTC() -> true or false? * new Date().toUTC().isUTC() -> true - * - ***/ - isUTC(): boolean; + **/ + isUTC(): bool; - /*** + /** * Returns true if the date is valid. * @method isValid() * @returns Boolean * @example - * * new Date().isValid() -> true * new Date('flexor').isValid() -> false - * - ***/ - isValid(): boolean; + **/ + isValid(): bool; - /*** + /** * @method iso() * @method toISOString() * @returns String @@ -4023,14 +4641,12 @@ interface Date { * @extra This will always format as UTC time. Provided for browsers that do not * support this method. * @example - * * Date.create().toISOString() -> ex. 2011-07-05 12:24:55.528Z - * - ***/ + **/ iso(): string; //toISOString(): string; - /*** + /** * Returns a relative date string offset to the current time. * @method relative([fn], [locale] = currentLocale) * @returns String @@ -4040,32 +4656,28 @@ interface Date { * alternate syntax, [locale] can also be passed as the first (and only) * parameter. For more, see @date_format. * @example - * * Date.create('90 seconds ago').relative() -> 1 minute ago * Date.create('January').relative() -> ex. 5 months ago * Date.create('January').relative('ja') -> 3??? * Date.create('120 minutes ago').relative(function(val,unit,ms,loc) { * // value = 2, unit = 3, ms = -7200, loc = [current locale object] * }); -> ex. 5 months ago - * - ***/ + **/ relative(locale: string): string; relative(fn?: (value: number, unit: string, ms: number, loc: Locale) => string, locale?: string): string; - /*** + /** * Resets the unit passed and all smaller units. Default is "hours", * effectively resetting the time. * @method reset([unit] = 'hours') * @returns Date * @example - * * Date.create().reset('day') -> Beginning of today * Date.create().reset('month') -> 1st of the month - * - ***/ + **/ reset(unit?: string): Date; - /*** + /** * Sets the date back. * @method rewind(, [reset] = false) * @returns Date @@ -4074,17 +4686,15 @@ interface Date { * constructor). If [reset] is %true%, any units more specific than * those passed will be reset. For more see @date_format. * @example - * * new Date().rewind({ year: 2 }) -> 2 years in the past * new Date().rewind(0, 2, 3) -> 2 months 3 days in the past * new Date().rewind(86400000) -> 1 day in the past - * - ***/ - rewind(ms: number, reset?: boolean): Date; - rewind(year: number, month: number, day: number, reset?: boolean): Date; - //rewind(d: Object, reset?: boolean): Date; // Do not like this, is not typesafe + **/ + rewind(ms: number, reset?: bool): Date; + rewind(year: number, month: number, day: number, reset?: bool): Date; + rewind(d: DateFields, reset?: bool): Date; - /*** + /** * Sets the date object. * @method set(, [reset] = false) * @returns Date @@ -4092,43 +4702,34 @@ interface Date { * timestamp, an object, or enumerated parameters (as with the Date * constructor). If [reset] is %true%, any units more specific than those * passed will be reset. - * * @example - * * new Date().set({ year: 2011, month: 11, day: 31 }) -> December 31, 2011 * new Date().set(2011, 11, 31) -> December 31, 2011 * new Date().set(86400000) -> 1 day after Jan 1, 1970 * new Date().set({ year: 2004, month: 6 }, true) -> June 1, 2004, 00:00:00.000 - * - ***/ - set (ms: number): Date; - set (year: number, month: number, day: number): Date; - //set(d: Object, reset?: boolean): Date; // Do not like this, is not typesafe + **/ + set(ms: number): Date; + set(year: number, month: number, day: number): Date; + set(d: DateFields, reset?: bool): Date; - - /*** + /** * Sets the week (of the year). * @example - * * d = new Date(); d.setWeek(15); d; -> 15th week of the year - * - ***/ + **/ setISOWeek(week: number): void; - /*** + /** * Sets the weekday of the date. * @method setWeekday() * @returns Nothing - * * @example - * * d = new Date(); d.setWeekday(1); d; -> Monday of this week * d = new Date(); d.setWeekday(6); d; -> Saturday of this week - * - ***/ + **/ setWeekday(day: number): void; - /*** + /** * Returns a JSON representation of the date. * @method toJSON() * @returns String @@ -4136,17 +4737,14 @@ interface Date { * the date in UTC time. Provided for browsers that do not support this * method. * @example - * * Date.create().toJSON() -> ex. 2011-07-05 12:24:55.528Z - * - ***/ + **/ toJSON(): string; - /*** + /** * Returns the time ago in the appropriate unit. * @method [units]Ago() * @returns Number - * * @set * millisecondsAgo * secondsAgo @@ -4156,14 +4754,11 @@ interface Date { * weeksAgo * monthsAgo * yearsAgo - * * @example - * * Date.create('last year').millisecondsAgo() -> 3,600,000 * Date.create('last year').daysAgo() -> 7 * Date.create('last year').yearsAgo() -> 15 - * - ***/ + **/ millisecondsAgo(): number; secondsAgo(): number; minutesAgo(): number; @@ -4173,11 +4768,10 @@ interface Date { monthsAgo(): number; yearsAgo(): number; - /*** + /** * Returns the time from now in the appropriate unit. * @method [units]FromNow() * @returns Number - * * @set * millisecondsFromNow * secondsFromNow @@ -4187,14 +4781,11 @@ interface Date { * weeksFromNow * monthsFromNow * yearsFromNow - * * @example - * * Date.create('next year').millisecondsFromNow() -> 3,600,000 * Date.create('next year').daysFromNow() -> 7 * Date.create('next year').yearsFromNow() -> 15 - * - ***/ + **/ millisecondsFromNow(): number; secondsFromNow(): number; minutesFromNow(): number; @@ -4204,7 +4795,7 @@ interface Date { monthsFromNow(): number; yearsFromNow(): number; - /*** + /** * Returns the time since [d] in the appropriate unit. * @method [units]Since([d], [locale] = currentLocale) * @returns Number @@ -4213,7 +4804,6 @@ interface Date { * the locale that the date is in. %[unit]Ago% is provided as an alias to * make this more readable when [d] is assumed to be the current date. * For more see @date_format. - * * @set * millisecondsSince * secondsSince @@ -4223,15 +4813,12 @@ interface Date { * weeksSince * monthsSince * yearsSince - * * @example - * * Date.create().millisecondsSince('1 hour ago') -> 3,600,000 * Date.create().daysSince('1 week ago') -> 7 * Date.create().yearsSince('15 years ago') -> 15 * Date.create('15 years ago').yearsAgo() -> 15 - * - ***/ + **/ millisecondsSince(date?: Date, locale?: string): number; millisecondsSince(date: string, locale?: string): number; secondsSince(date?: Date, locale?: string): number; @@ -4249,7 +4836,7 @@ interface Date { yearsSince(date?: Date, locale?: string): number; yearsSince(date: string, locale?: string): number; - /*** + /** * Returns the time until [d] in the appropriate unit. * @method [units]Until([d], [locale] = currentLocale) * @returns Number @@ -4258,7 +4845,6 @@ interface Date { * the locale that the date is in. %[unit]FromNow% is provided as an * alias to make this more readable when [d] is assumed to be the current * date. For more see @date_format. - * * @set * millisecondsUntil * secondsUntil @@ -4268,15 +4854,12 @@ interface Date { * weeksUntil * monthsUntil * yearsUntil - * * @example - * * Date.create().millisecondsUntil('1 hour from now') -> 3,600,000 * Date.create().daysUntil('1 week from now') -> 7 * Date.create().yearsUntil('15 years from now') -> 15 * Date.create('15 years from now').yearsFromNow() -> 15 - * - ***/ + **/ millisecondsUntil(date?: Date, locale?: string): number; millisecondsUntil(date: string, locale?: string): number; secondsUntil(date?: Date, locale?: string): number; @@ -4294,62 +4877,58 @@ interface Date { yearsUntil(date?: Date, locale?: string): number; yearsUntil(date: string, locale?: string): number; - /*** + /** * Sets the internal utc flag for the date. When on, UTC-based methods * will be called internally. * @method utc([on] = true) * @returns Date * @extra For more see @date_format. * @example - * * new Date().utc(true) * new Date().utc(false) - * - ***/ - utc(on?: boolean): Date; + **/ + utc(on?: bool): Date; } -/*** +/** * @package DateRange * @dependency date * @description Date Ranges define a range of time. They can enumerate over specific points * within that range, and be manipulated and compared. -* -***/ +**/ interface DateRange { start: Date; end: Date; - /*** + /** * Returns true if is contained inside the DateRange. * may be a date or another DateRange. - * @method contains() - * @returns Boolean + * @param d Date to check if it is contained within this DateRange. + * @returns True if is contained within the DateRange, false otherwise. * @example - * * Date.range('2003', '2005').contains(Date.create('2004')) -> true - * - ***/ - contains(d: Date): boolean; - contains(d: DateRange): boolean; + **/ + contains(d: Date): bool; - /*** + /** + * @see contains + **/ + contains(d: DateRange): bool; + + /** * Return the duration of the DateRange in milliseconds. - * @method duration() - * @returns Number + * @returns Duration of the DateRange in milliseconds. * @example - * * Date.range('2003', '2005').duration() -> 94694400000 - * - ***/ + **/ duration(): number; - /*** + /** * Increments through the date range for each [unit], calling [fn] if it is passed. * Returns an array of each increment visited. * @method each[Unit]([fn]) - * @returns Date - * + * @param fn Callback function for each date in the requested increments. + * @returns Array of Dates for each increment. * @set * eachMillisecond * eachSecond @@ -4359,27 +4938,54 @@ interface DateRange { * eachWeek * eachMonth * eachYear - * * @example - * * Date.range('2003-01', '2003-02').eachMonth() -> [...] * Date.range('2003-01-15', '2003-01-16').eachDay() -> [...] - * - ***/ - eachMillisecond(fn?: (d: Date) => void ): Date[]; - eachSecond(fn?: (d: Date) => void ): Date[]; - eachMinute(fn?: (d: Date) => void ): Date[]; - eachHour(fn?: (d: Date) => void ): Date[]; - eachDay(fn?: (d: Date) => void ): Date[]; - eachWeek(fn?: (d: Date) => void ): Date[]; - eachMonth(fn?: (d: Date) => void ): Date[]; - eachYear(fn?: (d: Date) => void ): Date[]; + **/ + eachMillisecond(fn?: (d: Date) => void): Date[]; - /*** + /** + * @see eachMillisecond + **/ + eachSecond(fn?: (d: Date) => void): Date[]; + + /** + * @see eachMillisecond + **/ + eachMinute(fn?: (d: Date) => void): Date[]; + + /** + * @see eachMillisecond + **/ + eachHour(fn?: (d: Date) => void): Date[]; + + /** + * @see eachMillisecond + **/ + eachDay(fn?: (d: Date) => void): Date[]; + + /** + * @see eachMillisecond + **/ + eachWeek(fn?: (d: Date) => void): Date[]; + + /** + * @see eachMillisecond + **/ + eachMonth(fn?: (d: Date) => void): Date[]; + + /** + * @see eachMillisecond + **/ + eachYear(fn?: (d: Date) => void): Date[]; + + /** * Iterates through the DateRange for every , * calling [fn] if it is passed. Returns an array of each increment visited. * @method every(, [fn]) - * @returns Array + * @param ms Time span to increment by. + * @param fn Callback for each incremented date. + * @returns An array of each incremented date visited. * @extra When is a number, increments will be to the exact millisecond. * can also be a string in the format %{number} {unit}s%, in which * case it will increment in the unit specified. Note that a discrepancy exists @@ -4387,59 +4993,52 @@ interface DateRange { * through the actual months by passing %"2 months"% is usually preferable in * this case. * @example - * * Date.range('2003-01', '2003-03').every("2 months") -> [...] - * - ***/ + **/ every(ms: number, fn?: (d: Date) => void ): Date[]; + + /** + * @see every + * @param increment Time span to increment by. + **/ every(increment: string, fn?: (d: Date) => void ): Date[]; - /*** + /** * Returns a new DateRange with the latest starting point as its start, and the * earliest ending point as its end. If the two ranges do not intersect this will * effectively produce an invalid range. - * @method intersect() + * @param range DateRange to intersect with. * @returns DateRange * @example - * * Date.range('2003-01', '2005-01').intersect(Date.range('2004-01', '2006-01')) -> Jan 1, 2004..Jan 1, 2005 - * - ***/ + **/ intersect(range: DateRange): DateRange; - /*** + /** * Returns true if the DateRange is valid, false otherwise. - * @method isValid() - * @returns Boolean + * @returns True if the date range is valid, false otherwise. * @example - * * Date.range('2003', '2005').isValid() -> true * Date.range('2005', '2003').isValid() -> false - * - ***/ - isValid(): boolean; + **/ + isValid(): bool; - /*** + /** * Returns a string representation of the DateRange. - * @method toString() - * @returns String + * @returns String representation of the DateRange. * @example - * * Date.range('2003', '2005').toString() -> January 1, 2003..January 1, 2005 - * - ***/ + **/ toString(): string; - /*** + /** * Returns a new DateRange with the earliest starting point as its start, * and the latest ending point as its end. If the two ranges do not intersect * this will effectively remove the "gap" between them. - * @method union() + * @param range DateRange to create a union with. * @returns DateRange * @example - * * Date.range('2003=01', '2005-01').union(Date.range('2004-01', '2006-01')) -> Jan 1, 2003..Jan 1, 2006 - * - ***/ + **/ union(range: DateRange): DateRange; } diff --git a/zepto/zepto.d.ts b/zepto/zepto.d.ts index 5b59634b6d..50184d7c46 100644 --- a/zepto/zepto.d.ts +++ b/zepto/zepto.d.ts @@ -262,13 +262,13 @@ interface ZeptoStatic { * @param fn Callback function when the HTTP GET request is completed. * @return The XMLHttpRequest object. **/ - get (url: string, fn: (data: any, status?: string, xhr?: XMLHttpRequest) => void ): XMLHttpRequest; + get (url: string, fn: (data: any, status: string, xhr: XMLHttpRequest) => void ): XMLHttpRequest; /** * @see ZeptoStatic.get * @param data See ZeptoAjaxSettings.data **/ - get (url: string, data: any, fn: (data: any, status?: string, xhr?: XMLHttpRequest) => void ): XMLHttpRequest; + get (url: string, data: any, fn: (data: any, status: string, xhr: XMLHttpRequest) => void ): XMLHttpRequest; /** * Get JSON data via Ajax GET request. This is a shortcut for the $.ajax method. @@ -1009,7 +1009,7 @@ interface ZeptoCollection { * @param fn * @return **/ - reduce(fn: (memo: any, item: any, index: number, array: any[], initial?: any) => any): any; + reduce(fn: (memo: any, item: any, index: number, array: any[], initial: any) => any): any; /** * Remove elements in the current collection from their parent nodes, effectively detaching them from the DOM. @@ -1391,7 +1391,7 @@ interface ZeptoCollection { * @example * $('#some_element').load('/foo.html #bar') **/ - load(url: string, fn?: (data: any, status?: string, xhr?: XMLHttpRequest) => void ): ZeptoCollection; + load(url: string, fn?: (data: any, status: string, xhr: XMLHttpRequest) => void ): ZeptoCollection; /** * Form