Merge remote-tracking branch 'upstream/master'

This commit is contained in:
AdaskoTheBeAsT
2014-05-08 20:49:06 +02:00
36 changed files with 10632 additions and 5218 deletions
+5
View File
@@ -63,6 +63,7 @@ All definitions files include a header with the author and editors, so at some p
* [emissary](https://github.com/atom/emissary) (by [vvakame](https://github.com/vvakame))
* [EpicEditor](http://epiceditor.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [ES6-Promises](https://github.com/jakearchibald/ES6-Promises) (by [François de Campredon](https://github.com/fdecampredon/))
* [Esprima](http://esprima.org/) (by [Teppei Sato](https://github.com/teppeis))
* [expect.js](https://github.com/LearnBoost/expect.js) (by [Teppei Sato](https://github.com/teppeis))
* [expectations](https://github.com/spmason/expectations) (by [vvakame](https://github.com/vvakame))
* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
@@ -87,6 +88,7 @@ All definitions files include a header with the author and editors, so at some p
* [GoJS](http://gojs.net/) (by [Barbara Duckworth](https://github.com/barbara42))
* [Greasemonkey](http://www.greasespot.net/) (by [Kota Saito](https://github.com/kotas))
* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt))
* [gridfs-stream](https://github.com/aheckmann/gridfs-stream) (by [Lior Mualem](https://github.com/liorm))
* [Grunt JS](http://gruntjs.com/) (by [Jeff May](https://github.com/jeffmay), [Basarat Ali Syed](https://github.com/basarat) and [San Chen](https://github.com/bigsan))
* [Google API Client](https://code.google.com/p/google-api-javascript-client/) (by [Frank M](https://github.com/sgtfrankieboy))
* [Google App Engine Channel API](https://developers.google.com/appengine/docs/java/channel/javascript) (by [vvakame](https://github.com/vvakame))
@@ -116,6 +118,7 @@ All definitions files include a header with the author and editors, so at some p
* [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/))
* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov))
* [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac))
* [jDataView](https://github.com/jDataView/jDataView) (by [Ingvar Stepanyan](https://github.com/RReverser))
* [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel))
* [jQRangeSlider](http://ghusse.github.com/jQRangeSlider) (by [Dániel Tar](https://github.com/qcz))
* [jQuery](http://jquery.com/) (from TypeScript samples)
@@ -156,6 +159,7 @@ All definitions files include a header with the author and editors, so at some p
* [jQuery.TinyCarousel](http://baijs.nl/tinycarousel/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.TinyScrollbar](http://baijs.nl/tinyscrollbar/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.tooltipster](https://github.com/iamceege/tooltipster) (by [Patrick Magee](https://github.com/pjmagee))
* [jQuery.total-storage](https://github.com/Upstatement/jquery-total-storage) (by [Jeremy Brooks](https://github.com/JeremyCBrooks/))
* [jQuery.Transit](http://ricostacruz.com/jquery.transit/) (by [MrBigDog2U](https://github.com/MrBigDog2U))
* [jQuery.Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.Watermark](http://jquery-watermark.googlecode.com) (by [Anwar Javed](https://github.com/anwarjaved))
@@ -205,6 +209,7 @@ All definitions files include a header with the author and editors, so at some p
* [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov) and [Theodore Brown](https://github.com/theodorejb/))
* [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield))
* [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee))
* [mongoose](http://mongoosejs.com/) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz))
* [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki))
* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov))
+1 -1
View File
@@ -22,7 +22,7 @@ declare module ng.translate {
}
interface ITranslateService {
(key: string, ...params: string[]): string;
(key: string, ...params: string[]): ng.IPromise<string>;
fallbackLanguage(): string;
preferredLanguage(): string;
proposedLanguage(): string;
+52 -1
View File
@@ -19,7 +19,7 @@ actionDescriptor.params = { key: 'value' };
///////////////////////////////////////
var resourceClass: IMyResourceClass;
var resource: IMyResource;
var resourceArray: IMyResource[];
var resourceArray: ng.resource.IResourceArray<IMyResource>;
resource = resourceClass.delete();
resource = resourceClass.delete({ key: 'value' });
@@ -29,6 +29,7 @@ resource = resourceClass.delete(function () { }, function () { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function () { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function () { }, function () { });
resource.$promise.then(function(data: IMyResource) {});
resource = resourceClass.get();
resource = resourceClass.get({ key: 'value' });
@@ -47,6 +48,8 @@ resourceArray = resourceClass.query(function () { }, function () { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { }, function () { });
resourceArray.push(resource);
resourceArray.$promise.then(function(data: ng.resource.IResourceArray<IMyResource>) {});
resource = resourceClass.remove();
resource = resourceClass.remove({ key: 'value' });
@@ -66,6 +69,50 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { }, function () { });
///////////////////////////////////////
// IResource
///////////////////////////////////////
var promise : ng.IPromise<IMyResource>;
var arrayPromise : ng.IPromise<IMyResource[]>;
promise = resource.$delete();
promise = resource.$delete({ key: 'value' });
promise = resource.$delete({ key: 'value' }, function () { });
promise = resource.$delete(function () { });
promise = resource.$delete(function () { }, function () { });
promise = resource.$delete({ key: 'value' }, function () { }, function () { });
promise.then(function(data: IMyResource) {});
promise = resource.$get();
promise = resource.$get({ key: 'value' });
promise = resource.$get({ key: 'value' }, function () { });
promise = resource.$get(function () { });
promise = resource.$get(function () { }, function () { });
promise = resource.$get({ key: 'value' }, function () { }, function () { });
arrayPromise = resourceArray[0].$query();
arrayPromise = resourceArray[0].$query({ key: 'value' });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { });
arrayPromise = resourceArray[0].$query(function () { });
arrayPromise = resourceArray[0].$query(function () { }, function () { });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { }, function () { });
arrayPromise.then(function(data: ng.resource.IResourceArray<IMyResource>) {});
promise = resource.$remove();
promise = resource.$remove({ key: 'value' });
promise = resource.$remove({ key: 'value' }, function () { });
promise = resource.$remove(function () { });
promise = resource.$remove(function () { }, function () { });
promise = resource.$remove({ key: 'value' }, function () { }, function () { });
promise = resource.$save();
promise = resource.$save({ key: 'value' });
promise = resource.$save({ key: 'value' }, function () { });
promise = resource.$save(function () { });
promise = resource.$save(function () { }, function () { });
promise = resource.$save({ key: 'value' }, function () { }, function () { });
///////////////////////////////////////
// IResourceService
///////////////////////////////////////
@@ -85,3 +132,7 @@ resourceClass = resourceServiceFactoryFunction<IMyResourceClass>(resourceService
resourceServiceFactoryFunction = function (resourceService: ng.resource.IResourceService) { return <any>resourceClass; };
mod = mod.factory('factory name', resourceServiceFactoryFunction);
///////////////////////////////////////
// IResource
///////////////////////////////////////
+61 -44
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.2 (ngResource module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Michael Jess <http://github.com/miffels> (minor enhancements)
// Definitions: https://github.com/daptiv/DefinitelyTyped
/// <reference path="angular.d.ts" />
@@ -50,67 +50,84 @@ declare module ng.resource {
// PATCH (in other words, methods with body). Otherwise, it's going
// to be considered as parameters to the request.
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465
//
// Only those methods with an HTTP body do have 'data' as first parameter:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L463
// More specifically, those methods are POST, PUT and PATCH:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L432
//
// Also, static calls always return the IResource (or IResourceArray) retrieved
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549
interface IResourceClass<T> {
new(dataOrParams? : any) : T;
get(): T;
get(dataOrParams: any): T;
get(dataOrParams: any, success: Function): T;
get(params: Object): T;
get(success: Function, error?: Function): T;
get(params: any, data: any, success?: Function, error?: Function): T;
get(params: Object, success: Function, error?: Function): T;
get(params: Object, data: Object, success?: Function, error?: Function): T;
query(): IResourceArray<T>;
query(params: Object): IResourceArray<T>;
query(success: Function, error?: Function): IResourceArray<T>;
query(params: Object, success: Function, error?: Function): IResourceArray<T>;
query(params: Object, data: Object, success?: Function, error?: Function): IResourceArray<T>;
save(): T;
save(dataOrParams: any): T;
save(dataOrParams: any, success: Function): T;
save(data: Object): T;
save(success: Function, error?: Function): T;
save(params: any, data: any, success?: Function, error?: Function): T;
query(): T[];
query(dataOrParams: any): T[];
query(dataOrParams: any, success: Function): T[];
query(success: Function, error?: Function): T[];
query(params: any, data: any, success?: Function, error?: Function): T[];
save(data: Object, success: Function, error?: Function): T;
save(params: Object, data: Object, success?: Function, error?: Function): T;
remove(): T;
remove(dataOrParams: any): T;
remove(dataOrParams: any, success: Function): T;
remove(params: Object): T;
remove(success: Function, error?: Function): T;
remove(params: any, data: any, success?: Function, error?: Function): T;
remove(params: Object, success: Function, error?: Function): T;
remove(params: Object, data: Object, success?: Function, error?: Function): T;
delete(): T;
delete(dataOrParams: any): T;
delete(dataOrParams: any, success: Function): T;
delete(params: Object): T;
delete(success: Function, error?: Function): T;
delete(params: any, data: any, success?: Function, error?: Function): T;
delete(params: Object, success: Function, error?: Function): T;
delete(params: Object, data: Object, success?: Function, error?: Function): T;
}
// Instance calls always return the the promise of the request which retrieved the object
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L546
interface IResource<T> {
$get(): T;
$get(dataOrParams: any): T;
$get(dataOrParams: any, success: Function): T;
$get(success: Function, error?: Function): T;
$get(params: any, data: any, success?: Function, error?: Function): T;
$save(): T;
$save(dataOrParams: any): T;
$save(dataOrParams: any, success: Function): T;
$save(success: Function, error?: Function): T;
$save(params: any, data: any, success?: Function, error?: Function): T;
$query(): T[];
$query(dataOrParams: any): T[];
$query(dataOrParams: any, success: Function): T[];
$query(success: Function, error?: Function): T[];
$query(params: any, data: any, success?: Function, error?: Function): T[];
$remove(): T;
$remove(dataOrParams: any): T;
$remove(dataOrParams: any, success: Function): T;
$remove(success: Function, error?: Function): T;
$remove(params: any, data: any, success?: Function, error?: Function): T;
$delete(): T;
$delete(dataOrParams: any): T;
$delete(dataOrParams: any, success: Function): T;
$delete(success: Function, error?: Function): T;
$delete(params: any, data: any, success?: Function, error?: Function): T;
$get(): ng.IPromise<T>;
$get(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$get(success: Function, error?: Function): ng.IPromise<T>;
$query(): ng.IPromise<IResourceArray<T>>;
$query(params?: Object, success?: Function, error?: Function): ng.IPromise<IResourceArray<T>>;
$query(success: Function, error?: Function): ng.IPromise<IResourceArray<T>>;
$save(): ng.IPromise<T>;
$save(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$save(success: Function, error?: Function): ng.IPromise<T>;
$remove(): ng.IPromise<T>;
$remove(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$remove(success: Function, error?: Function): ng.IPromise<T>;
$delete(): ng.IPromise<T>;
$delete(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$delete(success: Function, error?: Function): ng.IPromise<T>;
/** the promise of the original server interaction that created this instance. **/
$promise : ng.IPromise<T>;
$resolved : boolean;
}
/**
* Really just a regular Array object with $promise and $resolve attached to it
*/
interface IResourceArray<T> extends Array<T> {
/** the promise of the original server interaction that created this collection. **/
$promise : ng.IPromise<IResourceArray<T>>;
$resolved : boolean;
}
/** when creating a resource factory via IModule.factory */
interface IResourceServiceFactoryFunction<T> {
($resource: ng.resource.IResourceService): IResourceClass<T>;
+6
View File
@@ -351,6 +351,7 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
// LogService
// see http://docs.angularjs.org/api/ng.$log
// see http://docs.angularjs.org/api/ng.$logProvider
///////////////////////////////////////////////////////////////////////////
interface ILogService {
debug: ILogCall;
@@ -360,6 +361,11 @@ declare module ng {
warn: ILogCall;
}
interface ILogProvider {
debugEnabled(enabled: boolean): ILogProvider;
debugEnabled(): boolean;
}
// We define this as separete interface so we can reopen it later for
// the ngMock module.
interface ILogCall {
+958 -174
View File
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
/// <reference path="../chai/chai.d.ts" />
/// <reference path="../chai/chai-assert.d.ts" />
/// <reference path="chai-datetime.d.ts" />
var expect = chai.expect;
function test_equalTime(){
var date: Date = new Date(2014, 1, 1);
expect(date).to.be.equalTime(date);
date.should.be.equalTime(date);
assert.equalTime(date, date);
}
function test_beforeTime(){
var date: Date = new Date(2014, 1, 1);
expect(date).to.be.beforeTime(date);
date.should.be.beforeTime(date);
assert.beforeTime(date, date);
}
function test_afterTime(){
var date: Date = new Date(2014, 1, 1);
expect(date).to.be.afterTime(date);
date.should.be.afterTime(date);
assert.afterTime(date, date);
}
function test_equalDate(){
var date: Date = new Date(2014, 1, 1);
expect(date).to.equalDate(date);
date.should.equalDate(date);
assert.equalDate(date, date);
}
function test_beforeDate(){
var date: Date = new Date(2014, 1, 1);
expect(date).to.beforeDate(date);
date.should.beforeDate(date);
assert.beforeDate(date, date);
}
function test_afterDate(){
var date: Date = new Date(2014, 1, 1);
expect(date).to.afterDate(date);
date.should.afterDate(date);
assert.afterDate(date, date);
}
+39
View File
@@ -0,0 +1,39 @@
// Type definitions for chai-datetime
// Project: https://github.com/gaslight/chai-datetime.git
// Definitions by: Cliff Burger <https://github.com/cliffburger/>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../chai/chai.d.ts" />
declare module chai {
interface Expect {
afterDate(date: Date): boolean;
beforeDate(date: Date): boolean;
equalDate(date: Date): boolean;
afterTime(date: Date): boolean;
beforeTime(date: Date): boolean;
equalTime(date: Date): boolean;
}
interface Assert {
equalTime(val: Date, exp: Date, msg?: string): boolean;
notEqualTime(val: Date, exp: Date, msg?: string): boolean;
beforeTime(val: Date, exp: Date, msg?: string): boolean;
notBeforeTime(val: Date, exp: Date, msg?: string): boolean;
afterTime(val: Date, exp: Date, msg?: string): boolean;
notAfterTime(val: Date, exp: Date, msg?: string): boolean;
equalDate(val: Date, exp: Date, msg?: string): boolean;
notEqualDate(val: Date, exp: Date, msg?: string): boolean;
beforeDate(val: Date, exp: Date, msg?: string): boolean;
notBeforeDate(val: Date, exp: Date, msg?: string): boolean;
afterDate(val: Date, exp: Date, msg?: string): boolean;
notAfterDate(val: Date, exp: Date, msg?: string): boolean;
}
}
interface Date {
should: chai.Expect;
}
+16 -16
View File
@@ -9,28 +9,28 @@ declare module chai {
function expect(target: any, message?: string): Expect;
// Provides a way to extend the internals of Chai
function use(fn: (chai: any, utils: any) => void);
function use(fn: (chai: any, utils: any) => void): any;
interface ExpectStatic {
(target: any): Expect;
}
interface Assertions {
attr(name, value?);
css(name, value?);
data(name, value?);
class(className);
id(id);
html(html);
text(text);
value(value);
visible;
hidden;
selected;
checked;
disabled;
empty;
exist;
attr(name: string, value?: string): any;
css(name: string, value?: string): any;
data(name: string, value?: string): any;
class(className: string): any;
id(id: string): any;
html(html: string): any;
text(text: string): any;
value(value: string): any;
visible: any;
hidden: any;
selected: any;
checked: any;
disabled: any;
empty: any;
exist: any;
}
interface Expect extends LanguageChains, NumericComparison, TypeComparison, Assertions {
+163
View File
@@ -0,0 +1,163 @@
/// <reference path="esprima.d.ts" />
import esprima = require('esprima');
import Syntax = esprima.Syntax;
var token: esprima.Token;
var options: esprima.Options;
var comment: Syntax.Comment;
var program: Syntax.Program;
var statement: Syntax.SomeStatement;
var blockStatement: Syntax.BlockStatement;
var expression: Syntax.SomeExpression;
var property: Syntax.Property;
var identifier: Syntax.Identifier;
var literal: Syntax.Literal;
var switchCase: Syntax.SwitchCase;
var catchClause: Syntax.CatchClause;
var variableDeclaratorOrExpression: Syntax.VariableDeclaratorOrExpression;
var literalOrIdentifier: Syntax.LiteralOrIdentifier;
var blockStatementOrExpression: Syntax.BlockStatementOrExpression;
var identifierOrExpression: Syntax.IdentifierOrExpression;
var any: any;
var string: string;
var boolean: boolean;
var number: number;
// esprima
string = esprima.version;
program = esprima.parse('code');
program = esprima.parse('code', {range: true});
token = esprima.tokenize('code')[0];
token = esprima.tokenize('code', {range: true})[0];
// Token
string = token.type;
string = token.value;
// Program
string = program.type;
statement = program.body[0];
comment = program.comments[0]
// Location
number = program.loc.start.line;
number = program.loc.start.column;
number = program.loc.end.line;
number = program.loc.end.column;
number = program.range[0];
// Comment
string = comment.value;
// Statement
// BlockStatement
string = statement.type;
statement = statement.body[0];
comment = statement.leadingComments[0]
comment = statement.trailingComments[0]
// ExpressionStatement
expression = statement.expression;
// IfStatement
expression = statement.test;
statement = statement.consequent;
statement = statement.alternate;
// LabeledStatement
identifier = statement.label;
statement = statement.body;
// WithStatement
expression = statement.object;
// SwitchStatement
expression = statement.discriminant;
switchCase = statement.cases[0];
boolean = statement.lexical;
// ReturnStatement
expression = statement.argument;
// TryStatement
blockStatement = statement.block;
catchClause = statement.handler;
catchClause = statement.guardedHandlers[0];
blockStatement = statement.finalizer;
// ForStatement
variableDeclaratorOrExpression = statement.init;
expression = statement.update;
// ForInStatement
variableDeclaratorOrExpression = statement.left;
expression = statement.right;
boolean = statement.each;
// Expression
// ArrayExpression
string = expression.type;
expression = expression.elements[0];
// ObjectExpression
property = expression.properties[0];
string = property.type;
literalOrIdentifier = property.key;
expression = property.value;
string = property.kind;
// FunctionExpression
identifier = expression.id;
identifier = expression.params[0];
expression = expression.defaults[0];
identifier = expression.rest;
blockStatementOrExpression = expression.body;
boolean = expression.generator;
boolean = expression.expression;
// SequenceExpression
expression = expression.expressions[0]
// UnaryExpression
string = expression.operator;
boolean = expression.prefix;
// BinaryExpression
expression = expression.left;
expression = expression.right;
// ConditionalExpression
expression = expression.test;
expression = expression.alternate;
expression = expression.consequent;
// ConditionalExpression
expression = expression.callee;
expression = expression.arguments[0];
// MemberExpression
expression = expression.object;
identifierOrExpression = expression.property;
boolean = expression.computed;
// Clauses
// SwitchCase
string = switchCase.type;
expression = switchCase.test;
statement = switchCase.consequent[0];
// CatchClause
string = catchClause.type;
identifier = catchClause.param;
expression = catchClause.guard;
blockStatement = catchClause.body;
// Misc
// Identifier
string = identifier.type;
string = identifier.name;
// Literal
string = literal.type;
any = literal.value;
+276
View File
@@ -0,0 +1,276 @@
// Type definitions for Esprima v1.2.0
// Project: http://esprima.org
// Definitions by: teppeis <https://github.com/teppeis/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module esprima {
var version: string;
function parse(code: string, options?: Options): Syntax.Program;
function tokenize(code: string, options?: Options): Array<Token>;
interface Token {
type: string
value: string
}
interface Options {
loc?: boolean
range?: boolean
raw?: boolean
tokens?: boolean
comment?: boolean
attachComment?: boolean
tolerant?: boolean
source?: boolean
}
module Syntax {
// Node
interface Node {
type: string
loc?: LineLocation
range?: number[]
leadingComments?: Comment[]
trailingComments?: Comment[]
}
interface LineLocation {
start: Position
end: Position
}
interface Position {
line: number
column: number
}
// Comment
interface Comment extends Node {
value: string
}
// Program
interface Program extends Node {
body: SomeStatement[]
comments?: Comment[]
}
// Function
interface Function extends Node {
id: Identifier // | null
params: Identifier[]
defaults: SomeExpression[]
rest: Identifier // | null
body: BlockStatementOrExpression
generator: boolean
expression: boolean
}
interface BlockStatementOrExpression extends Array<SomeStatement>, BlockStatement, SomeExpression {
body: BlockStatementOrExpression
}
// Statement
interface Statement extends Node {
}
interface EmptyStatement extends Statement {
}
interface BlockStatement extends Statement {
body: SomeStatement[]
}
interface ExpressionStatement extends Statement {
expression: SomeExpression
}
interface IfStatement extends Statement {
test: SomeExpression
consequent: SomeStatement
alternate: SomeStatement
}
interface LabeledStatement extends Statement {
label: Identifier
body: SomeStatement
}
interface BreakStatement extends Statement {
label: Identifier // | null
}
interface ContinueStatement extends Statement {
label: Identifier // | null
}
interface WithStatement extends Statement {
object: SomeExpression
body: SomeStatement
}
interface SwitchStatement extends Statement {
discriminant: SomeExpression
cases: SwitchCase[]
lexical: boolean
}
interface ReturnStatement extends Statement {
argument: SomeExpression // | null
}
interface ThrowStatement extends Statement {
argument: SomeExpression
}
interface TryStatement extends Statement {
block: BlockStatement
handler: CatchClause // | null
guardedHandlers: CatchClause[]
finalizer: BlockStatement // | null
}
interface WhileStatement extends Statement {
test: SomeExpression
body: SomeStatement
}
interface DoWhileStatement extends Statement {
body: SomeStatement
test: SomeExpression
}
interface ForStatement extends Statement {
init: VariableDeclaratorOrExpression // | null
test: SomeExpression // | null
update: SomeExpression // | null
body: SomeStatement
}
interface ForInStatement extends Statement {
left: VariableDeclaratorOrExpression
right: SomeExpression
body: SomeStatement
each: boolean
}
interface VariableDeclaratorOrExpression extends VariableDeclarator, SomeExpression {
}
interface DebuggerStatement extends Statement {
}
interface SomeStatement extends
EmptyStatement, ExpressionStatement, BlockStatement, IfStatement,
LabeledStatement, BreakStatement, ContinueStatement, WithStatement,
SwitchStatement, ReturnStatement, ThrowStatement, TryStatement,
WhileStatement, DoWhileStatement, ForStatement, ForInStatement, DebuggerStatement {
body: SomeStatementOrList
}
interface SomeStatementOrList extends Array<SomeStatement>, SomeStatement {
}
// Declration
interface Declration extends Statement {
}
interface FunctionDeclration extends Declration {
id: Identifier
params: Identifier[] // Pattern
defaults: SomeExpression[]
rest: Identifier
body: BlockStatementOrExpression
generator: boolean
expression: boolean
}
interface VariableDeclaration extends Declration {
declarations: VariableDeclarator[]
kind: string // "var" | "let" | "const"
}
interface VariableDeclarator extends Node {
id: Identifier // Pattern
init: SomeExpression
}
// Expression
interface Expression extends Node { // | Pattern
}
interface SomeExpression extends
ThisExpression, ArrayExpression, ObjectExpression, FunctionExpression,
ArrowFunctionExpression, SequenceExpression, UnaryExpression, BinaryExpression,
AssignmentExpression, UpdateExpression, LogicalExpression, ConditionalExpression,
NewExpression, CallExpression, MemberExpression {
}
interface ThisExpression extends Expression {
}
interface ArrayExpression extends Expression {
elements: SomeExpression[] // [ Expression | null ]
}
interface ObjectExpression extends Expression {
properties: Property[]
}
interface Property extends Node {
key: LiteralOrIdentifier // Literal | Identifier
value: SomeExpression
kind: string // "init" | "get" | "set"
}
interface LiteralOrIdentifier extends Literal, Identifier {
}
interface FunctionExpression extends Function, Expression {
}
interface ArrowFunctionExpression extends Function, Expression {
}
interface SequenceExpression extends Expression {
expressions: SomeExpression[]
}
interface UnaryExpression extends Expression {
operator: string // UnaryOperator
prefix: boolean
argument: SomeExpression
}
interface BinaryExpression extends Expression {
operator: string // BinaryOperator
left: SomeExpression
right: SomeExpression
}
interface AssignmentExpression extends Expression {
operator: string // AssignmentOperator
left: SomeExpression
right: SomeExpression
}
interface UpdateExpression extends Expression {
operator: string // UpdateOperator
argument: SomeExpression
prefix: boolean
}
interface LogicalExpression extends Expression {
operator: string // LogicalOperator
left: SomeExpression
right: SomeExpression
}
interface ConditionalExpression extends Expression {
test: SomeExpression
alternate: SomeExpression
consequent: SomeExpression
}
interface NewExpression extends Expression {
callee: SomeExpression
arguments: SomeExpression[]
}
interface CallExpression extends Expression {
callee: SomeExpression
arguments: SomeExpression[]
}
interface MemberExpression extends Expression {
object: SomeExpression
property: IdentifierOrExpression // Identifier | Expression
computed: boolean
}
interface IdentifierOrExpression extends Identifier, SomeExpression {
}
// Pattern
// interface Pattern extends Node {
// }
// Clauses
interface SwitchCase extends Node {
test: SomeExpression
consequent: SomeStatement[]
}
interface CatchClause extends Node {
param: Identifier // Pattern
guard: SomeExpression
body: BlockStatement
}
// Misc
interface Identifier extends Node, Expression { // | Pattern
name: string
}
interface Literal extends Node, Expression {
value: any // string | boolean | null | number | RegExp
}
}
}
declare module "esprima" {
export = esprima
}
+1 -1
View File
@@ -240,7 +240,7 @@ declare module "express" {
count: number;
}
interface Request extends Express.Request {
interface Request extends http.ServerRequest, Express.Request {
session: Session;
+29
View File
@@ -0,0 +1,29 @@
/// <reference path="fbsdk.d.ts" />
window.fbAsyncInit = function() {
FB.init(
{
appId : '{your-app-id}',
xfbml : true,
version : 'v2.0'
}
);
FB.ui(
{
method: 'share',
href: 'https://developers.facebook.com/docs/dialogs/'
},
function(response) {
console.log(response);
}
);
FB.api(
"/me",
"POST",
function (fbResponse){
console.log(fbResponse);
}
);
};
+135
View File
@@ -0,0 +1,135 @@
// Type definitions for Facebook Javascript SDK
// Project: https://developers.facebook.com/docs/javascript
// Definitions by: Joshua Strobl <https://github.com/JoshStrobl>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface FBInitParams{
appId ?: string;
authResponse ?: string;
cookie ?: boolean;
frictionlessRequests ?: boolean;
hideFlashCallback ?: Function;
logging ?: boolean;
status ?: boolean;
version ?: string;
xfbml ?: boolean;
}
interface FBUIParams{
method : string;
}
interface FBLoginOptions{
auth_type ?: string;
scopes ?: string;
return_scopes ?: boolean;
enable_profile_selector ?: boolean;
profile_selector_ids ?: string;
}
interface FBSDKEvents{
/* This method allows you to subscribe to a range of events, and define callback functions for when they fire. */
subscribe(event : string, callback : (fbResponseObject : Object) => any) : void;
/* This method allows you to un-subscribe a callback from any events previously subscribed to using .Event.subscribe(). */
unsubscribe(event : string, callback : (fbResponseObject : Object) => any) : void;
}
interface FBSDKXFBML{
/* This function parses and renders XFBML markup in a document on the fly. */
parse(ParseElement ?: Element) : void;
parse(ParseElement ?: HTMLElement) : void;
}
interface FBSDKCanvasPrefetcher{
/* Tells Facebook that the current page uses a specified resource. */
addStaticResource(res : string) : void;
/* Controls how statistics are collected on resources used by your application. */
setCollectionMode(option : string) : void;
}
interface FBSDKCanvasSize{
height ?: Number;
width ?: Number;
}
interface FBSDKCanvasDoneLoading{
time_delta_ms : Number;
}
interface FBSDKCanvas{
Prefetcher : FBSDKCanvasPrefetcher;
/* Hides the HTML element passed in via the elem param from view. */
hideFlashElement(element : Element) : void;
hideFlashElement(element : HTMLElement) : void;
/* Displays the HTML element passed in via the elem param, after it has been hidden via FB.Canvas.hideFlashElement. */
showFlashElement(element : Element) : void;
showFlashElement(element : HTMLElement) : void;
/* Tells Facebook to scroll to a specific location of your canvas page. */
scrollTo(x : Number, y : Number) : void;
/* Starts or stops a timer which will grow your iframe to fit the content every few milliseconds. */
setAutoGrow(stopTimer : boolean) : void;
setAutoGrow(diffInterval : Number) : void;
setAutoGrow(stopTimer : boolean, diffInterval : Number) : void
/* Tells Facebook to resize your iframe. */
setSize(canvasSizeOptions : FBSDKCanvasSize) : void;
/* Registers the callback for inline processing (i.e. without page reload) of user actions when they click on any link to the current app from Canvas */
setUrlHandler(handler ?: Function) : string;
/* Calls you back with an integer, in milliseconds, of the timing of the page load, beginning from the time when the first bytes arrive on
the client, and ending from the point at which you call this function.
*/
setDoneLoading(handler ?: Function) : FBSDKCanvasDoneLoading;
/* Call startTimer to resume the timer after a period of time for the page load that you didn't wish to measure, which you began by calling stopTimer. */
startTimer() : void;
/* Call stopTimer when you wish to stop timing the page load for a period of time */
stopTimer(handler ?: (fbResponseObject : Object) => any) : void;
}
interface FBSDK{
/* This method is used to initialize and setup the SDK. */
init(fbInitObject : FBInitParams) : void;
/* This method lets you make calls to the Graph API. */
api(path : string, method : string, callback : (fbResponseObject : Object) => any) : Object;
api(path : string, params : Object, callback : (fbResponseObject : Object) => any) : Object;
api(path : string, method : string, params : Object, callback : (fbResponseObject : Object) => any) : Object;
/* This method is used to trigger different forms of Facebook created UI dialogs. */
ui(params : FBUIParams, handler : (fbResponseObject : Object) => any) : void;
/* Allows you to determine if a user is logged in to Facebook and has authenticated your app */
getLoginStatus(handler : Function, force ?: Boolean) : void;
/* Calling FB.login prompts the user to authenticate your application using the Login Dialog. */
login(handler : (fbResponseObject : Object) => any, params ?: FBLoginOptions): void;
/* Log the user out of your site and Facebook */
logout(handler : (fbResponseObject : Object) => any) : void;
/* Synchronous accessor for the current authResponse. */
getAuthResponse() : Object;
Event : FBSDKEvents;
XFBML : FBSDKXFBML;
Canvas : FBSDKCanvas;
}
interface Window{
fbAsyncInit() : any;
}
declare module "FB" {
export = FB;
}
declare var FB : FBSDK;
+173 -86
View File
@@ -7,29 +7,37 @@
declare module FullCalendar {
export interface Calendar {
/**
* Formats a Date object into a string.
*/
* Formats a Date object into a string.
*/
formatDate(date: Date, format: string, options?: Options): string;
/**
* Formats a date range (two Date objects) into a string.
*/
* Formats a date range (two Date objects) into a string.
*/
formatDates(date1: Date, date2: Date, format: string, options?: Options): string;
/**
* Parses a string into a Date object.
*/
* Parses a string into a Date object.
*/
parseDate(dateString: string, ignoreTimezone?: boolean): Date;
/**
* Parses an ISO8601 string into a Date object.
*/
* Parses an ISO8601 string into a Date object.
*/
parseISO8601(dateString: string, ignoreTimezone?: boolean): Date;
/**
* Gets the version of Fullcalendar
*/
* Gets the version of Fullcalendar
*/
version: string;
}
export interface Options {
// General display - http://arshaw.com/fullcalendar/docs/display/
header?: {
left: string;
center: string;
@@ -43,22 +51,31 @@ declare module FullCalendar {
firstDay?: number;
isRTL?: boolean;
weekends?: boolean;
hiddenDays?: number[];
weekMode?: string;
weekNumbers?: boolean;
weekNumberCalculation?: any; // String/Function
height?: number;
contentHeight?: number;
aspectRation?: number;
viewDisplay?: (view: View) => void;
windowResize?: (view: View) => void;
aspectRatio?: number;
handleWindowResize?: boolean;
viewRender?: (view: View, element: JQuery) => void;
viewDestroy?: (view: View, element: JQuery) => void;
dayRender?: (date: Date, cell: HTMLTableDataCellElement) => void;
windowResize?: (view: View) => void;
// Views - http://arshaw.com/fullcalendar/docs/views/
defaultView?: string;
// Current Date - http://arshaw.com/fullcalendar/docs/current_date/
year?: number;
month?: number;
date?: number;
// Text/Time Customization - http://arshaw.com/fullcalendar/docs/text/
timeFormat?: any; // String/ViewOptionHash
columnFormat?: any; // String/ViewOptionHash
titleFormat?: any; // String/ViewOptionHash
@@ -67,13 +84,17 @@ declare module FullCalendar {
monthNamesShort?: Array<string>;
dayNames?: Array<string>;
dayNamesShort?: Array<string>;
weekNumberTitle?: number;
weekNumberTitle?: string;
// Clicking & Hovering - http://arshaw.com/fullcalendar/docs/mouse/
dayClick?: (date: Date, allDay: boolean, jsEvent: MouseEvent, view: View) => void;
eventClick?: (event: EventObject, jsEvent: MouseEvent, view: View) => any; // return type boolean or void
eventMouseover?: (event: EventObject, jsEvent: MouseEvent, view: View) => void;
eventMouseout?: (event: EventObject, jsEvent: MouseEvent, view: View) => void;
// Selection - http://arshaw.com/fullcalendar/docs/selection/
selectable?: any; // Boolean/ViewOptionHash
selectHelper?: any; // Boolean/Function
unselectAuto?: boolean;
@@ -81,26 +102,51 @@ declare module FullCalendar {
select?: (startDate: Date, endDate: Date, allDay: boolean, jsEvent: MouseEvent, view: View) => void;
unselect?: (view: View, jsEvent: Event) => void;
eventSources?: Array<EventSource>;
// Event Data - http://arshaw.com/fullcalendar/docs/event_data/
/**
* This has one of the following types:
*
* - EventObject[]
* - string (JSON feed)
* - (start: Date, end: Date, callback: {(events: EventObject[]) => void;}) => void;
*/
events?: any;
/**
* An array, each element being one of the following types:
*
* - EventSource
* - EventObject[]
* - string (JSON feed)
* - (start: Date, end: Date, callback: {(events: EventObject[]) => void;}) => void;
*/
eventSources?: any[];
allDayDefault?: boolean;
ignoreTimezone?: boolean;
eventDataTransform?: (eventData: any) => EventObject;
startParam?: string;
endParam?: string
lazyFetching?: boolean;
eventDataTransform?: (eventData: any) => EventObject;
loading?: (isLoading: boolean, view: View) => void;
// Event Rendering - http://arshaw.com/fullcalendar/docs/event_rendering/
eventColor?: string;
eventBackgroundColor?: string;
eventBorderColor?: string;
eventTextColor?: string;
eventRender?: (event: EventObject, element: HTMLDivElement, view: View) => void;
eventAfterRender?: (event: EventObject, element: HTMLDivElement, view: View) => void;
eventAllAfterRender?: (view: View) => void;
eventAfterAllRender?: (view: View) => void;
eventDestroy?: (event: EventObject, element: JQuery, view: View) => void;
// Event Dragging & Resizing
editable?: boolean;
disableDragging?: boolean;
disableResizing?: boolean;
eventStartEditable?: boolean;
eventDurationEditable?: boolean;
dragRevertDuration?: number;
dragOpacity?: any; // Float/ViewOptionHash
eventDragStart?: (event: EventObject, jsEvent: MouseEvent, ui: any, view: View) => void;
@@ -119,7 +165,7 @@ declare module FullCalendar {
name: string;
title: string;
start: Date;
End: Date;
end: Date;
visStart: Date;
visEnd: Date;
}
@@ -137,6 +183,9 @@ declare module FullCalendar {
''?: any;
}
/**
* Agenda Options - http://arshaw.com/fullcalendar/docs/agenda/
*/
export interface AgendaOptions {
allDaySlot?: boolean;
allDayText?: string;
@@ -147,6 +196,7 @@ declare module FullCalendar {
firstHour?: number;
minTime?: any; // Integer/String
maxTime?: any; // Integer/String
slotEventOverlap?: boolean;
}
export interface ButtonTextObject {
@@ -177,7 +227,16 @@ declare module FullCalendar {
}
export interface EventSource extends JQueryAjaxSettings {
/**
* This has one of the following types:
*
* - EventObject[]
* - string (JSON feed)
* - (start: Date, end: Date, callback: {(events: EventObject[]) => void;}) => void;
*/
events?: any;
color?: string;
backgroundColor?: string;
borderColor?: string;
@@ -194,117 +253,145 @@ declare module FullCalendar {
}
interface JQuery {
/**
* Get/Set option value
*/
* Get/Set option value
*/
fullCalendar(method: 'option', option: string, value?: any): void;
/**
* Immediately forces the calendar to render and/or readjusts its size.
*/
* Immediately forces the calendar to render and/or readjusts its size.
*/
fullCalendar(method: 'render'): void;
/**
* Restores the element to the state before FullCalendar was initialized.
*/
* Restores the element to the state before FullCalendar was initialized.
*/
fullCalendar(method: 'destroy'): void;
/**
* Moves the calendar one step back (either by a month, week, or day).
*/
fullCalendar(method: 'prev'): void;
/**
* Moves the calendar one step forward (either by a month, week, or day).
*/
fullCalendar(method: 'next'): void;
/**
* Moves the calendar back one year.
*/
fullCalendar(method: 'prevYear'): void;
/**
* Moves the calendar forward one year.
*/
fullCalendar(method: 'nextYear'): void;
/**
* Moves the calendar to the current date.
*/
fullCalendar(method: 'today'): void;
/**
* Returns the View Object for the current view.
*/
* Returns the View Object for the current view.
*/
fullCalendar(method: 'getView'): FullCalendar.View;
/**
* Immediately switches to a different view.
*/
* Immediately switches to a different view.
*/
fullCalendar(method: 'changeView', viewName: string): void;
/**
* Moves the calendar to an arbitrary year/month/date.
*/
* Moves the calendar one step back (either by a month, week, or day).
*/
fullCalendar(method: 'prev'): void;
/**
* Moves the calendar one step forward (either by a month, week, or day).
*/
fullCalendar(method: 'next'): void;
/**
* Moves the calendar back one year.
*/
fullCalendar(method: 'prevYear'): void;
/**
* Moves the calendar forward one year.
*/
fullCalendar(method: 'nextYear'): void;
/**
* Moves the calendar to the current date.
*/
fullCalendar(method: 'today'): void;
/**
* Moves the calendar to an arbitrary year/month/date.
*/
fullCalendar(method: 'gotoDate', year: number, month?: number, date?: number): void;
/**
* Moves the calendar to an arbitrary date.
*/
* Moves the calendar to an arbitrary date.
*/
fullCalendar(method: 'gotoDate', date: Date): void;
/**
* Moves the calendar forward/backward an arbitrary amount of time.
*/
* Moves the calendar forward/backward an arbitrary amount of time.
*/
fullCalendar(method: 'incrementDate', year: number, month?: number, date?: number): void;
/**
* Returns a Date object for the current date of the calendar.
*/
* Returns a Date object for the current date of the calendar.
*/
fullCalendar(method: 'getDate'): Date;
/**
* A method for programmatically selecting a period of time.
*/
* A method for programmatically selecting a period of time.
*/
fullCalendar(method: 'select', startDate: Date, endDate: Date, allDay: boolean): void;
/**
* A method for programmatically clearing the current selection.
*/
* A method for programmatically clearing the current selection.
*/
fullCalendar(method: 'unselect'): void;
/**
* Reports changes to an event and renders them on the calendar.
*/
* Reports changes to an event and renders them on the calendar.
*/
fullCalendar(method: 'updateEvent', event: FullCalendar.EventObject): void;
/**
* Retrieves events that FullCalendar has in memory.
*/
* Retrieves events that FullCalendar has in memory.
*/
fullCalendar(method: 'clientEvents', idOrfilter?: any): Array<FullCalendar.EventObject>;
/**
* Retrieves events that FullCalendar has in memory.
*/
* Retrieves events that FullCalendar has in memory.
*/
fullCalendar(method: 'clientEvents', idOrfilter?: (e: FullCalendar.EventObject) => boolean): Array<FullCalendar.EventObject>;
/**
* Removes events from the calendar.
*/
* Removes events from the calendar.
*/
fullCalendar(method: 'removeEvents', idOrfilter?: any): void;
/**
* Removes events from the calendar.
*/
* Removes events from the calendar.
*/
fullCalendar(method: 'removeEvents', idOrfilter?: (e: FullCalendar.EventObject) => boolean): void;
/**
* Refetches events from all sources and rerenders them on the screen.
*/
* Refetches events from all sources and rerenders them on the screen.
*/
fullCalendar(method: 'refetchEvents'): void;
/**
* Dynamically adds an event source.
*/
* Dynamically adds an event source.
*/
fullCalendar(method: 'addEventSource', source: any): void;
/**
* Dynamically removes an event source.
*/
* Dynamically removes an event source.
*/
fullCalendar(method: 'removeEventSource', source: any): void;
/**
* Renders a new event on the calendar.
*/
* Renders a new event on the calendar.
*/
fullCalendar(method: 'renderEvent', event: FullCalendar.EventObject, stick?: boolean): void;
/**
* Rerenders all events on the calendar.
*/
* Rerenders all events on the calendar.
*/
fullCalendar(method: 'rerenderEvents'): void;
/**
* Create calendar object
*/
* Create calendar object
*/
fullCalendar(options: FullCalendar.Options): JQuery;
/**
* Generic method function
*/
* Generic method function
*/
fullCalendar(method: string, arg1: any, arg2: any, arg3: any): void;
}
+37
View File
@@ -0,0 +1,37 @@
/// <reference path="gridfs-stream.d.ts" />
/// <reference path="../mongodb/mongodb.d.ts" />
/// <reference path="../node/node.d.ts" />
// Samples from:
// https://github.com/aheckmann/gridfs-stream
import fs = require('fs');
import mongo = require('mongodb');
import Grid = require('gridfs-stream');
// create or use an existing mongodb-native db instance
var db = new mongo.Db('gridfs-stream-test', new mongo.Server("127.0.0.1", 27017));
var gfs = Grid(db, mongo);
// streaming to gridfs
var writestream = gfs.createWriteStream({
filename: 'my_file.txt'
});
fs.createReadStream('blob.txt').pipe(writestream);
// streaming from gridfs
var readstream = gfs.createReadStream({
filename: 'my_file.txt'
});
//error handling, e.g. file does not exist
readstream.on('error', function (err: any) {
console.log('An error occurred!', err);
throw err;
});
var bufs: Array<any> = [];
readstream.on('data', function(d: any){ bufs.push(d); });
readstream.on('end', function() {
var buf = Buffer.concat(bufs);
});
+68
View File
@@ -0,0 +1,68 @@
// Type definitions for gridfs-stream 0.5.0
// Project: https://github.com/aheckmann/gridfs-stream
// Definitions by: Lior Mualem <https://github.com/liorm/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../mongodb/mongodb.d.ts" />
declare module GridFSStream {
export interface Range {
startPos: number;
endPos: number;
}
export interface Options {
_id?: string;
filename?: string;
mode?: string;
range?: Range;
// any other options from the GridStore may be passed too, e.g.
chunkSize?: number;
content_type?: string;
root?: string;
metadata?: any;
}
export interface WriteStream extends NodeJS.WritableStream {
writable: boolean;
name: string;
id: string;
options: Options;
mode: string;
}
export interface ReadStream extends NodeJS.ReadableStream {
readable: boolean;
paused: boolean;
}
}
declare module "gridfs-stream" {
import mongo = require('mongodb');
// Merged declaration, g is both a callable function and a namespace
function g(db: any, mongo: any): g.Grid;
module g {
export class Grid {
files: mongo.Collection;
collection(name?: string): mongo.Collection;
createWriteStream(options?: GridFSStream.Options): GridFSStream.WriteStream;
createReadStream(options?: GridFSStream.Options): GridFSStream.ReadStream;
createWriteStream(options?: string): GridFSStream.WriteStream;
createReadStream(options?: string): GridFSStream.ReadStream;
remove(options: GridFSStream.Options, callback: (err: Error) => void): void;
exist(options: GridFSStream.Options, callback: (err: Error, found: boolean) => void): void;
}
}
export = g;
}
+74
View File
@@ -0,0 +1,74 @@
/// <reference path="jdataview.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
interface TARMetaData {
name: string;
mode: number;
owner: number;
group: number;
size: number;
modtime: number;
checksum: number;
link: string;
name_linked: string;
ustar: string;
ustar_version: number;
owner_name: string;
group_name: string;
device: number[];
name_prefix: string;
}
// Download the file
$.get('jquery.tar', function (data) {
// Make a view on the data
var view = new jDataView(data);
// console.log(view.getUint32(0, true));
// console.log(view.getUint32(0, false));
// view.seek(0);
while (view.tell() < view.byteLength) {
// Parse the file meta data
var metadata: TARMetaData = {
name: view.getString(100).replace(/\0+$/, ''),
mode: parseInt(view.getString(8), 8),
owner: parseInt(view.getString(8), 8),
group: parseInt(view.getString(8), 8),
size: parseInt(view.getString(12), 8),
modtime: parseInt(view.getString(12), 8),
checksum: parseInt(view.getString(8), 8),
link: view.getChar(),
name_linked: view.getString(100).replace(/\0+$/, ''),
ustar: view.getString(6),
ustar_version: parseInt(view.getString(2), 8),
owner_name: view.getString(32).replace(/\0+$/, ''),
group_name: view.getString(32).replace(/\0+$/, ''),
device: [parseInt(view.getString(8), 8), parseInt(view.getString(8), 8)],
name_prefix: view.getString(155).replace(/\0+$/, '')
};
// Padding
if (view.tell() % 512 !== 0) {
view.seek(view.tell() + 512 - (view.tell() % 512));
}
// Get the file
if (isNaN(metadata.size)) {
break;
}
var content = view.getString(metadata.size);
// Padding
if (view.tell() % 512 != 0) {
view.seek(view.tell() + 512 - (view.tell() % 512));
}
// Print the file
$(document.body).append($('<pre></pre>').html(JSON.stringify(metadata, null, ' ')));
if (metadata.size) {
$('body').append($('<textarea></textarea>').val(content));
}
}
});
+105
View File
@@ -0,0 +1,105 @@
// Type definitions for jDataView
// Project: https://github.com/jDataView/jDataView
// Definitions by: Ingvar Stepanyan <https://github.com/RReverser>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare class jDataView implements DataView {
constructor(byteCount: number, offset?: number, length?: number, littleEndian?: boolean)
constructor(buffer: string, offset?: number, length?: number, littleEndian?: boolean)
constructor(buffer: jDataView.Bytes, offset?: number, length?: number, littleEndian?: boolean)
buffer: any
byteOffset: number
byteLength: number
// 64 bit integers
getInt64(byteOffset?: number, littleEndian?: boolean): jDataView.Int64
setInt64(byteOffset: number, value: jDataView.Int64, littleEndian?: boolean): void
writeInt64(value: jDataView.Int64, littleEndian?: boolean): void
getUint64(byteOffset?: number, littleEndian?: boolean): jDataView.Uint64
setUint64(byteOffset: number, value: jDataView.Uint64, littleEndian?: boolean): void
writeUint64(value: jDataView.Uint64, littleEndian?: boolean): void
// Bitfields
getSigned(bitLength: number, byteOffset?: number): number
setSigned(byteOffset: number, value: number, bitLength: number): void
writeSigned(value: number, bitLength: number): void
getUnsigned(bitLength: number, byteOffset?: number): number
setUnsigned(byteOffset: number, value: number, bitLength: number): void
writeUnsigned(value: number, bitLength: number): void
// Internal utilities
wrapBuffer(string: string): jDataView.Buffer
wrapBuffer(bytes: jDataView.Bytes): jDataView.Buffer
wrapBuffer(byteCount: number): jDataView.Buffer
createBuffer(...bytes: number[]): jDataView.Buffer
// Operation control
seek(byteOffset: number): number
tell(): number
skip(byteLength: number): number
slice(start: number, end?: number, forceCopy?: boolean): jDataView
// Specification getters
getInt8(byteOffset?: number): number
getUint8(byteOffset?: number): number
getInt16(byteOffset?: number, littleEndian?: boolean): number
getUint16(byteOffset?: number, littleEndian?: boolean): number
getInt32(byteOffset?: number, littleEndian?: boolean): number
getUint32(byteOffset?: number, littleEndian?: boolean): number
getFloat32(byteOffset?: number, littleEndian?: boolean): number
getFloat64(byteOffset?: number, littleEndian?: boolean): number
// Specification setters
setInt8(byteOffset: number, value: number): void
setUint8(byteOffset: number, value: number): void
setInt16(byteOffset: number, value: number, littleEndian?: boolean): void
setUint16(byteOffset: number, value: number, littleEndian?: boolean): void
setInt32(byteOffset: number, value: number, littleEndian?: boolean): void
setUint32(byteOffset: number, value: number, littleEndian?: boolean): void
setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void
setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void
// Strings and Blobs
getChar(byteOffset?: number): string
setChar(byteOffset: number, char: string): void
writeChar(char: string): void
getString(byteLength: number, byteOffset?: number, encoding?: string): string
setString(byteOffset: number, chars: string, encoding?: string): void
writeString(chars: string, encoding?: string): void
getBytes(length: number, byteOffset?: number, littleEndian?: boolean, toArray?: boolean): number[]
setBytes(byteOffset: number, bytes: number[], littleEndian?: boolean): void
writeBytes(bytes: number[], littleEndian?: boolean): void
// writeXXX methods
writeInt8(value: number): void
writeUint8(value: number): void
writeInt16(value: number, littleEndian?: boolean): void
writeUint16(value: number, littleEndian?: boolean): void
writeInt32(value: number, littleEndian?: boolean): void
writeUint32(value: number, littleEndian?: boolean): void
writeFloat32(value: number, littleEndian?: boolean): void
writeFloat64(value: number, littleEndian?: boolean): void
}
declare module jDataView {
interface Bytes {
length: number;
[index: number]: number;
}
interface Buffer extends Bytes {
byteLength: number;
}
class Uint64 {
lo: number
hi: number
constructor(lo: number, hi: number)
valueOf(): number
static fromNumber(number: number): Uint64
}
class Int64 extends Uint64 {
static fromNumber(number: number): Int64
}
}
@@ -0,0 +1,21 @@
// Type definitions for jQueryTotalStorage 1.1.2
// Project: https://github.com/Upstatement/jquery-total-storage
// Definitions by: Jeremy Brooks <https://github.com/JeremyCBrooks/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="jquery.total-storage.d.ts"/>
//direct call
$.totalStorage("test_key1", "test_value");
var val1:string = $.totalStorage("test_key");
//set/get
$.totalStorage.setItem("test_key2", 123);
var val2:number = $.totalStorage.getItem("test_key2");
//get all items
var list = $.totalStorage.getAll();
//delete item
var deleted = $.totalStorage.deleteItem("test_key1");
+64
View File
@@ -0,0 +1,64 @@
// Type definitions for jQueryTotalStorage 1.1.2
// Project: https://github.com/Upstatement/jquery-total-storage
// Definitions by: Jeremy Brooks <https://github.com/JeremyCBrooks/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
/**
* @desc Set the value of a key to a string
* @example $.totalStorage('the_key', 'the_value');
* @desc Set the value of a key to a number
* @example $.totalStorage('the_key', 800.2);
* @desc Set the value of a key to a complex Array
* @example var myArray = new Array();
* myArray.push({name:'Jared', company:'Upstatement', zip:63124});
* myArray.push({name:'McGruff', company:'Police', zip:60652};
* $.totalStorage('people', myArray);
* //to return:
* $.totalStorage('people');
*
*/
interface JQueryTotalStorage {
/**
* @desc Set or get a key's value
* @param key Key to set.
* @param value Value to set for key. If ommited, current value for key is returned.
* @param options Not implemented.
*/
(key: string, value?: any, options?: JQueryTotalStorageOptions): any;
/**
* @desc Set a key's value
* @param key Key to set.
* @param value Value to set for key.
*/
setItem(key: string, value: any): any;
/**
* @desc Get a key's value
* @param key Key to get.
*/
getItem(key: string): any;
/**
* @desc Get all set values
*/
getAll(): any[];
/**
* @desc Delete item by key
* @param key Key of item to delete
*/
deleteItem(key: string): boolean;
}
interface JQueryTotalStorageOptions {
//not implemented...
}
interface JQueryStatic {
totalStorage: JQueryTotalStorage;
}
+1
View File
@@ -142,6 +142,7 @@ interface KnockoutSubscribableFunctions<T> {
isValid: KnockoutComputed<boolean>;
isValidating: KnockoutObservable<boolean>;
rules: KnockoutObservableArray<KnockoutValidationRule>;
isModified(val: boolean): void;
}
declare module "knockout.validation" {
-979
View File
@@ -1,979 +0,0 @@
/// <reference path="lodash.d.ts" />
declare var $: any, jQuery: any;
interface IFoodOrganic {
name: string;
organic: boolean;
}
interface IFoodType {
name: string;
type: string;
}
interface IFoodCombined {
name: string;
organic: boolean;
type: string;
}
interface IStoogesQuote {
name: string;
quotes: string[];
}
interface IStoogesAge {
name: string;
age: number;
}
interface IStoogesCombined {
name: string;
age: number;
quotes: string[];
}
interface IKey {
dir: string;
code: number;
}
var foodsOrganic: IFoodOrganic[] = [
{ name: 'banana', organic: true },
{ name: 'beet', organic: false },
];
var foodsType: IFoodType[] = [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'beet', type: 'vegetable' }
];
var foodsCombined: IFoodCombined[] = [
{ 'name': 'apple', 'organic': false, 'type': 'fruit' },
{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
];
var stoogesQuotes: IStoogesQuote[] = [
{ 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
{ 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] }
];
var stoogesAges: IStoogesAge[] = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
var stoogesCombined: IStoogesCombined[] = [
{ 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
{ 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] }
];
var keys: IKey[] = [
{ 'dir': 'left', 'code': 97 },
{ 'dir': 'right', 'code': 100 }
];
class Dog {
constructor(public name: string) {}
public bark() {
console.log('Woof, woof!');
}
}
var result : any;
/*************
* Chaining *
*************/
result = <_.LoDashWrapper<string>>_('test');
result = <_.LoDashWrapper<number>>_(1);
result = <_.LoDashWrapper<boolean>>_(true);
result = <_.LoDashArrayWrapper<string>>_(['test1', 'test2']);
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_({'key1': 'test1', 'key2': 'test2'});
result = <_.LoDashWrapper<string>>_.chain('test');
result = <_.LoDashWrapper<string>>_('test').chain();
result = <_.LoDashWrapper<number>>_.chain(1);
result = <_.LoDashWrapper<number>>_(1).chain();
result = <_.LoDashWrapper<boolean>>_.chain(true);
result = <_.LoDashWrapper<boolean>>_(true).chain();
result = <_.LoDashArrayWrapper<string>>_.chain(['test1', 'test2']);
result = <_.LoDashArrayWrapper<string>>_(['test1', 'test2']).chain();
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_.chain({'key1': 'test1', 'key2': 'test2'});
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_({'key1': 'test1', 'key2': 'test2'}).chain();
//Wrapped array shortcut methods
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).concat(5, 6);
result = <_.LoDashWrapper<string>>_([1, 2, 3, 4]).join(',');
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).pop();
_([1, 2, 3, 4]).push(5, 6, 7);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).reverse();
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).shift();
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).slice(1, 2);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).slice(2);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).sort((a, b) => 1);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).splice(1);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).splice(1, 2, 5, 6);
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).unshift(5, 6);
result = <number[]>_.tap([1, 2, 3, 4], function(array) { console.log(array); });
result = <_.LoDashWrapper<string>>_('test').tap(function(value) { console.log(value); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).tap(function(array) { console.log(array); });
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_({'key1': 'test1', 'key2': 'test2'}).tap(function(array) { console.log(array); });
result = <string>_('test').toString();
result = <string>_([1, 2, 3]).toString();
result = <string>_({'key1': 'test1', 'key2': 'test2'}).toString();
result = <string>_('test').valueOf();
result = <number[]>_([1, 2, 3]).valueOf();
result = <_.Dictionary<string>>_({'key1': 'test1', 'key2': 'test2'}).valueOf();
result = <string>_('test').value();
result = <number[]>_([1, 2, 3]).value();
result = <_.Dictionary<string>>_({'key1': 'test1', 'key2': 'test2'}).value();
// /*************
// * Arrays *
// *************/
result = <any[]>_.compact([0, 1, false, 2, '', 3]);
result = <_.LoDashArrayWrapper<any>>_([0, 1, false, 2, '', 3]).compact();
result = <number[]>_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4, 5]).difference([5, 2, 10]);
result = <number[]>_.rest([1, 2, 3]);
result = <number[]>_.rest([1, 2, 3], 2);
result = <number[]>_.rest([1, 2, 3], (num) => num < 3)
result = <IFoodOrganic[]>_.rest(foodsOrganic, 'test');
result = <IFoodType[]>_.rest(foodsType, { 'type': 'value' });
result = <number[]>_.drop([1, 2, 3]);
result = <number[]>_.drop([1, 2, 3], 2);
result = <number[]>_.drop([1, 2, 3], (num) => num < 3)
result = <IFoodOrganic[]>_.drop(foodsOrganic, 'test');
result = <IFoodType[]>_.drop(foodsType, { 'type': 'value' });
result = <number[]>_.tail([1, 2, 3])
result = <number[]>_.tail([1, 2, 3], 2)
result = <number[]>_.tail([1, 2, 3], (num) => num < 3)
result = <IFoodOrganic[]>_.tail(foodsOrganic, 'test')
result = <IFoodType[]> _.tail(foodsType, { 'type': 'value' })
result = <number>_.findIndex(['apple', 'banana', 'beet'], function(f) {
return /^b/.test(f);
});
result = <number>_.findIndex(['apple', 'banana', 'beet'], 'apple');
result = <number>_.findIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple'});
result = <number>_.findLastIndex(['apple', 'banana', 'beet'], function(f: string) {
return /^b/.test(f);
});
result = <number>_.findLastIndex(['apple', 'banana', 'beet'], 'apple');
result = <number>_.findLastIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple'});
result = <number>_.first([1, 2, 3]);
result = <number[]>_.first([1, 2, 3], 2);
result = <number[]>_.first([1, 2, 3], function(num) {
return num < 3;
});
result = <IFoodOrganic[]>_.first(foodsOrganic, 'organic');
result = <IFoodType[]>_.first(foodsType, { 'type': 'fruit' });
result = <number>_.head([1, 2, 3]);
result = <number[]>_.head([1, 2, 3], 2);
result = <number[]>_.head([1, 2, 3], function(num) {
return num < 3;
});
result = <IFoodOrganic[]>_.head(foodsOrganic, 'organic');
result = <IFoodType[]>_.head(foodsType, { 'type': 'fruit' });
result = <number>_.take([1, 2, 3]);
result = <number[]>_.take([1, 2, 3], 2);
result = <number[]>_.take([1, 2, 3], (num) => num < 3);
result = <IFoodOrganic[]>_.take(foodsOrganic, 'organic');
result = <IFoodType[]>_.take(foodsType, { 'type': 'fruit' });
result = <number[]>_.flatten([1, [2], [3, [[4]]]]);
result = <any[]>_.flatten([1, [2], [3, [[4]]]], true);
var result: any
result = <string[]>_.flatten(stoogesQuotes, 'quotes');
result = <_.LoDashArrayWrapper<number>>_([1, [2], [3, [[4]]]]).flatten();
result = <_.LoDashArrayWrapper<number>>_([1, [2], [3, [[4]]]]).flatten(true);
result = <_.LoDashArrayWrapper<string>>_(stoogesQuotes).flatten('quotes');
result = <number>_.indexOf([1, 2, 3, 1, 2, 3], 2);
result = <number>_.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
result = <number>_.indexOf([1, 1, 2, 2, 3, 3], 2, true);
result = <number[]>_.initial([1, 2, 3]);
result = <number[]>_.initial([1, 2, 3], 2);
result = <number[]>_.initial([1, 2, 3], function(num) {
return num > 1;
});
result = <IFoodOrganic[]>_.initial(foodsOrganic, 'organic');
result = <IFoodType[]>_.initial(foodsType, { 'type': 'vegetable' });
result = <number[]>_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
result = <number>_.last([1, 2, 3]);
result = <number[]>_.last([1, 2, 3], 2);
result = <number[]>_.last([1, 2, 3], function(num) {
return num > 1;
});
result = <IFoodOrganic[]>_.last(foodsOrganic, 'organic');
result = <IFoodType[]>_.last(foodsType, { 'type': 'vegetable' });
result = <number>_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
result = <number>_.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
result = <{[key: string]: any}>_.zipObject(['moe', 'larry'], [30, 40]);
result = <{[key: string]: any}>_.object(['moe', 'larry'], [30, 40]);
result = <number[]>_.pull([1, 2, 3, 1, 2, 3], 2, 3);
result = <number[]>_.range(10);
result = <number[]>_.range(1, 11);
result = <number[]>_.range(0, 30, 5);
result = <number[]>_.range(0, -10, -1);
result = <number[]>_.range(1, 4, 0);
result = <number[]>_.range(0);
result = <number[]>_.remove([1, 2, 3, 4, 5, 6], function(num: number) { return num % 2 == 0; });
result = <IFoodOrganic[]>_.remove(foodsOrganic, 'organic');
result = <IFoodType[]>_.remove(foodsType, { 'type': 'vegetable'});
result = <number>_.sortedIndex([20, 30, 50], 40);
result = <number>_.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
var sortedIndexDict = {
'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
};
result = <number>_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return sortedIndexDict.wordToNumber[word];
});
result = <number>_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return this.wordToNumber[word];
}, sortedIndexDict);
result = <number[]>_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
result = <number[]>_.uniq([1, 2, 1, 3, 1]);
result = <number[]>_.uniq([1, 1, 2, 2, 3], true);
result = <string[]>_.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) {
return letter.toLowerCase();
});
result = <number[]>_.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
result = <{x: number;}[]>_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
result = <number[]>_.unique([1, 2, 1, 3, 1]);
result = <number[]>_.unique([1, 1, 2, 2, 3], true);
result = <string[]>_.unique(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) {
return letter.toLowerCase();
});
result = <number[]>_.unique([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
result = <{x: number;}[]>_.unique([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
result = <number[]>_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
result = <any[][]>_.zip(['moe', 'larry'], [30, 40], [true, false]);
result = <any[][]>_.unzip(['moe', 'larry'], [30, 40], [true, false]);
// /* *************
// * Collections *
// ************* */
result = <string[]>_.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
result = <string[]>_.at(['moe', 'larry', 'curly'], 0, 2);
result = <boolean>_.contains([1, 2, 3], 1);
result = <boolean>_.contains([1, 2, 3], 1, 2);
result = <boolean>_.contains({ 'name': 'moe', 'age': 40 }, 'moe');
result = <boolean>_.contains('curly', 'ur');
result = <boolean>_.include([1, 2, 3], 1);
result = <boolean>_.include([1, 2, 3], 1, 2);
result = <boolean>_.include({ 'name': 'moe', 'age': 40 }, 'moe');
result = <boolean>_.include('curly', 'ur');
result = <_.Dictionary<number>>_.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
result = <_.Dictionary<number>>_.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
result = <_.Dictionary<number>>_.countBy(['one', 'two', 'three'], 'length');
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_([4.3, 6.1, 6.4]).countBy(function(num) { return Math.floor(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_([4.3, 6.1, 6.4]).countBy(function(num) { return this.floor(num); }, Math);
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_(['one', 'two', 'three']).countBy('length');
result = <boolean>_.every([true, 1, null, 'yes'], Boolean);
result = <boolean>_.every(stoogesAges, 'age');
result = <boolean>_.every(stoogesAges, { 'age': 50 });
result = <boolean>_.all([true, 1, null, 'yes'], Boolean);
result = <boolean>_.all(stoogesAges, 'age');
result = <boolean>_.all(stoogesAges, { 'age': 50 });
result = <number[]>_.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
result = <IFoodCombined[]>_.filter(foodsCombined, 'organic');
result = <IFoodCombined[]>_.filter(foodsCombined, { 'type': 'fruit' });
result = <number[]>_([1, 2, 3, 4, 5, 6]).filter(function(num) { return num % 2 == 0; }).value();
result = <IFoodCombined[]>_(foodsCombined).filter('organic').value();
result = <IFoodCombined[]>_(foodsCombined).filter({ 'type': 'fruit' }).value();
result = <number[]>_.select([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
result = <IFoodCombined[]>_.select(foodsCombined, 'organic');
result = <IFoodCombined[]>_.select(foodsCombined, { 'type': 'fruit' });
result = <number[]>_([1, 2, 3, 4, 5, 6]).select(function(num) { return num % 2 == 0; }).value();
result = <IFoodCombined[]>_(foodsCombined).select('organic').value();
result = <IFoodCombined[]>_(foodsCombined).select({ 'type': 'fruit' }).value();
result = <number>_.find([1, 2, 3, 4], function(num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.find(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.find(foodsCombined, 'organic');
result = <number>_.detect([1, 2, 3, 4], function(num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.detect(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.detect(foodsCombined, 'organic');
result = <number>_.findWhere([1, 2, 3, 4], function(num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.findWhere(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.findWhere(foodsCombined, 'organic');
result = <number>_.findLast([1, 2, 3, 4], function(num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.findLast(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.findLast(foodsCombined, 'organic');
result = <number[]>_.forEach([1, 2, 3], function(num) { console.log(num); });
result = <_.Dictionary<number>>_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
result = <number[]>_.each([1, 2, 3], function(num) { console.log(num); });
result = <_.Dictionary<number>>_.each({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).forEach(function(num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_({ 'one': 1, 'two': 2, 'three': 3 }).forEach(function(num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).each(function(num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_({ 'one': 1, 'two': 2, 'three': 3 }).each(function(num) { console.log(num); });
result = <number[]>_.forEachRight([1, 2, 3], function(num) { console.log(num); });
result = <_.Dictionary<number>>_.forEachRight({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
result = <number[]>_.eachRight([1, 2, 3], function(num) { console.log(num); });
result = <_.Dictionary<number>>_.eachRight({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).forEachRight(function(num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_({ 'one': 1, 'two': 2, 'three': 3 }).forEachRight(function(num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).eachRight(function(num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_({ 'one': 1, 'two': 2, 'three': 3 }).eachRight(function(num) { console.log(num); });
result = <_.Dictionary<number[]>>_.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
result = <_.Dictionary<number[]>>_.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
result = <_.Dictionary<string[]>>_.groupBy(['one', 'two', 'three'], 'length');
result = <_.LoDashObjectWrapper<_.Dictionary<number[]>>>_([4.2, 6.1, 6.4]).groupBy(function(num) { return Math.floor(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number[]>>>_([4.2, 6.1, 6.4]).groupBy(function(num) { return this.floor(num); }, Math);
result = <_.LoDashObjectWrapper<_.Dictionary<string[]>>>_(['one', 'two', 'three']).groupBy('length');
result = <_.Dictionary<IKey>>_.indexBy(keys, 'dir');
result = <_.Dictionary<IKey>>_.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
result = <_.Dictionary<IKey>>_.indexBy(keys, function(key) { this.fromCharCode(key.code); }, String);
result = <number[][]>_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
result = <string[][]>_.invoke([123, 456], String.prototype.split, '');
result = <number[]>_.map([1, 2, 3], function(num) { return num * 3; });
result = <number[]>_.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
result = <IStoogesAge[]>_.map(stoogesAges, 'name');
result = <number[]>_([1, 2, 3]).map(function(num) { return num * 3; }).value();
result = <number[]>_({ 'one': 1, 'two': 2, 'three': 3 }).map(function(num) { return num * 3; }).value();
result = <IStoogesAge[]>_(stoogesAges).map('name').value();
result = <number[]>_.collect([1, 2, 3], function(num) { return num * 3; });
result = <number[]>_.collect({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
result = <IStoogesAge[]>_.collect(stoogesAges, 'name');
result = <number[]>_([1, 2, 3]).collect(function(num) { return num * 3; }).value();
result = <number[]>_({ 'one': 1, 'two': 2, 'three': 3 }).collect(function(num) { return num * 3; }).value();
result = <IStoogesAge[]>_(stoogesAges).collect('name').value();
result = <number>_.max([4, 2, 8, 6]);
result = <IStoogesAge>_.max(stoogesAges, function(stooge) { return stooge.age; });
result = <IStoogesAge>_.max(stoogesAges, 'age');
result = <number>_.min([4, 2, 8, 6]);
result = <IStoogesAge>_.min(stoogesAges, function(stooge) { return stooge.age; });
result = <IStoogesAge>_.min(stoogesAges, 'age');
result = <string[]>_.pluck(stoogesAges, 'name');
result = <number>_.reduce<number, number>([1, 2, 3], function(sum: number, num: number) {
return sum + num;
});
interface ABC {
a: number;
b: number;
c: number;
}
result = <ABC>_.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(r: ABC, num, key) {
r[key] = num * 3;
return r;
}, {});
result = <number>_.foldl([1, 2, 3], function(sum, num) {
return sum + num;
});
result = <ABC>_.foldl({ 'a': 1, 'b': 2, 'c': 3 }, function(r: ABC, num, key) {
r[key] = num * 3;
return r;
}, {});
result = <number>_.inject([1, 2, 3], function(sum, num) {
return sum + num;
});
result = <ABC>_.inject({ 'a': 1, 'b': 2, 'c': 3 }, function(r: ABC, num, key) {
r[key] = num * 3;
return r;
}, {});
result = <number[]>_.reduceRight([[0, 1], [2, 3], [4, 5]], function(a: number[], b: number[]) { return a.concat(b); }, <number[]>[]);
result = <number[]>_.foldr([[0, 1], [2, 3], [4, 5]], function(a: number[], b: number[]) { return a.concat(b); }, <number[]>[]);
result = <number[]>_.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
result = <IFoodCombined[]>_.reject(foodsCombined, 'organic');
result = <IFoodCombined[]>_.reject(foodsCombined, { 'type': 'fruit' });
result = <number>_.sample([1, 2, 3, 4]);
result = <number[]>_.sample([1, 2, 3, 4], 2);
result = <number[]>_.shuffle([1, 2, 3, 4, 5, 6]);
result = <number>_.size([1, 2]);
result = <number>_.size({ 'one': 1, 'two': 2, 'three': 3 });
result = <number>_.size('curly');
result = <boolean>_.some([null, 0, 'yes', false], Boolean);
result = <boolean>_.some(foodsCombined, 'organic');
result = <boolean>_.some(foodsCombined, { 'type': 'meat' });
result = <boolean>_.any([null, 0, 'yes', false], Boolean);
result = <boolean>_.any(foodsCombined, 'organic');
result = <boolean>_.any(foodsCombined, { 'type': 'meat' });
result = <number[]>_.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
result = <number[]>_.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
result = <string[]>_.sortBy(['banana', 'strawberry', 'apple'], 'length');
(function(a: number, b: number, c: number, d: number){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
result = <IStoogesCombined[]>_.where(stoogesCombined, { 'age': 40 });
result = <IStoogesCombined[]>_.where(stoogesCombined, { 'quotes': ['Poifect!'] });
/*************
* Functions *
*************/
var saves = ['profile', 'settings'];
var asyncSave = (obj: any) => obj.done();
var done: Function;
done = _.after(saves.length, function() {
console.log('Done saving!');
});
_.forEach(saves, function(type) {
asyncSave({ 'type': type, 'complete': done });
});
done = _(saves.length).after(function() {
console.log('Done saving!');
}).value();
_.forEach(saves, function(type) {
asyncSave({ 'type': type, 'complete': done });
});
var funcBind = function (greeting: string) { return greeting + ' ' + this.name };
var funcBind2: () => any = _.bind(funcBind, { 'name': 'moe' }, 'hi');
funcBind2();
var funcBind3: () => any = _(funcBind).bind({ 'name': 'moe' }, 'hi').value();
funcBind3();
var view = {
'label': 'docs',
'onClick': function() { console.log('clicked ' + this.label); }
};
view = _.bindAll(view);
jQuery('#docs').on('click', view.onClick);
view = _(view).bindAll().value();
jQuery('#docs').on('click', view.onClick);
var objectBindKey = {
'name': 'moe',
'greet': function(greeting: string) {
return greeting + ' ' + this.name;
}
};
var funcBindKey: Function = _.bindKey(objectBindKey, 'greet', 'hi');
funcBindKey();
objectBindKey.greet = function(greeting) {
return greeting + ', ' + this.name + '!';
};
funcBindKey();
funcBindKey = _(objectBindKey).bindKey('greet', 'hi').value();
funcBindKey();
var realNameMap = {
'curly': 'jerome'
};
var format = function(name: string) {
name = realNameMap[name.toLowerCase()] || name;
return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
};
var greet = function(formatted: string) {
return 'Hiya ' + formatted + '!';
};
result = <Function>_.compose(greet, format);
result = <_.LoDashObjectWrapper<Function>>_(greet).compose(format);
var createCallbackObj = { name: 'Joe' };
result = <() => any>_.createCallback('name');
result = <() => boolean>_.createCallback(createCallbackObj);
result = <_.LoDashObjectWrapper<() => any>>_('name').createCallback();
result = <_.LoDashObjectWrapper<() => boolean>>_(createCallbackObj).createCallback();
result = <Function>_.curry(function(a, b, c) {
console.log(a + b + c);
});
result = <_.LoDashObjectWrapper<Function>>_(function(a, b, c) {
console.log(a + b + c);
}).curry();
declare var source: any;
result = <Function>_.debounce(function() {}, 150);
jQuery('#postbox').on('click', <Function>_.debounce(function() {}, 300, {
'leading': true,
'trailing': false
}));
source.addEventListener('message', <Function>_.debounce(function() {}, 250, {
'maxWait': 1000
}), false);
result = <_.LoDashObjectWrapper<Function>>_(function() {}).debounce(150);
jQuery('#postbox').on('click', <_.LoDashObjectWrapper<Function>>_(function() {}).debounce(300, {
'leading': true,
'trailing': false
}));
source.addEventListener('message', <_.LoDashObjectWrapper<Function>>_(function() {}).debounce(250, {
'maxWait': 1000
}), false);
var returnedDebounce = _.throttle(function (a) { return a * 5; }, 5);
returnedThrottled(4);
result = <number>_.defer(function() { console.log('deferred'); });
result = <_.LoDashWrapper<number>>_(function() { console.log('deferred'); }).defer();
var log = _.bind(console.log, console);
result = <number>_.delay(log, 1000, 'logged later');
result = <_.LoDashWrapper<number>>_(log).delay(1000, 'logged later');
var fibonacci = <Function>_.memoize(function(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
var data = {
'moe': { 'name': 'moe', 'age': 40 },
'curly': { 'name': 'curly', 'age': 60 }
};
var stooge = _.memoize(function(name: string) { return data[name]; }, _.identity);
stooge('curly');
stooge['cache']['curly'].name = 'jerome';
stooge('curly');
var returnedMemoize = _.throttle(function (a) { return a * 5; }, 5);
returnedMemoize(4);
var initialize = _.once(function(){ });
initialize();
initialize();''
var returnedOnce = _.throttle(function (a) { return a * 5; }, 5);
returnedOnce(4);
var greetPartial = function(greeting: string, name: string) { return greeting + ' ' + name; };
var hi = <Function>_.partial(greetPartial, 'hi');
hi('moe');
var defaultsDeep = <Function>_.partialRight(_.merge, _.defaults);
var optionsPartialRight = {
'variable': 'data',
'imports': { 'jq': $ }
};
defaultsDeep(optionsPartialRight, _.templateSettings);
var throttled = _.throttle(function () { }, 100);
jQuery(window).on('scroll', throttled);
jQuery('.interactive').on('click', _.throttle(function() { }, 300000, {
'trailing': false
}));
var returnedThrottled = _.throttle(function (a) { return a*5; }, 5);
returnedThrottled(4);
var helloWrap = function(name: string) { return 'hello ' + name; };
var helloWrap2 = _.wrap(helloWrap, function(func) {
return 'before, ' + func('moe') + ', after';
});
helloWrap2();
/**********
* Objects *
***********/
interface NameAge {
name: string;
age: number;
}
result = <NameAge>_.assign({ 'name': 'moe' }, { 'age': 40 });
result = <NameAge>_.assign({ 'name': 'moe' }, { 'age': 40 }, function(a, b) {
return typeof a == 'undefined' ? b : a;
});
result = <_.LoDashObjectWrapper<NameAge>>_({ 'name': 'moe' }).assign({ 'age': 40 });
result = <_.LoDashObjectWrapper<NameAge>>_({ 'name': 'moe' }).assign({ 'age': 40 }, function(a, b) {
return typeof a == 'undefined' ? b : a;
});
result = <NameAge>_.extend({ 'name': 'moe' }, { 'age': 40 });
result = <NameAge>_.extend({ 'name': 'moe' }, { 'age': 40 }, function(a, b) {
return typeof a == 'undefined' ? b : a;
});
result = <_.LoDashObjectWrapper<NameAge>>_({ 'name': 'moe' }).extend({ 'age': 40 });
result = <_.LoDashObjectWrapper<NameAge>>_({ 'name': 'moe' }).extend({ 'age': 40 }, function(a, b) {
return typeof a == 'undefined' ? b : a;
});
result = <IStoogesAge[]>_.clone(stoogesAges);
result = <IStoogesAge[]>_.clone(stoogesAges, true);
result = <any>_.clone(stoogesAges, true, function(value) {
return _.isElement(value) ? value.cloneNode(false) : undefined;
});
result = <IStoogesAge[]>_.cloneDeep(stoogesAges);
result = <IStoogesAge[]>_.cloneDeep(stoogesAges, function(value) {
return _.isElement(value) ? value.cloneNode(false) : undefined;
});
interface Food {
name: string;
type: string;
}
var foodDefaults = { 'name': 'apple' };
result = <Food>_.defaults(foodDefaults, { 'name': 'banana', 'type': 'fruit' });
result = <_.LoDashObjectWrapper<Food>>_(foodDefaults).defaults({ 'name': 'banana', 'type': 'fruit' });
result = <string>_.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
return num % 2 == 0;
});
result = <string>_.findLastKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
return num % 2 == 1;
});
result = <Dog>_.forIn(new Dog('Dagny'), function(value, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<Dog>>_(new Dog('Dagny')).forIn(function(value, key) {
console.log(key);
});
result = <Dog>_.forInRight(new Dog('Dagny'), function(value, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<Dog>>_(new Dog('Dagny')).forInRight(function(value, key) {
console.log(key);
});
interface ZeroOne {
0: string;
1: string;
one: string;
}
result = <ZeroOne>_.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<ZeroOne>>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwn(function(num, key) {
console.log(key);
});
result = <any>_.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<ZeroOne>>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwnRight(function(num, key) {
console.log(key);
});
result = <string[]>_.functions(_);
result = <string[]>_.methods(_);
result = <_.LoDashArrayWrapper<string>>_(_).functions();
result = <_.LoDashArrayWrapper<string>>_(_).methods();
result = <boolean>_.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
interface FirstSecond {
first: string;
second: string;
}
result = <FirstSecond>_.invert({ 'first': 'moe', 'second': 'larry' });
(function(...args: any[]) { return <boolean>_.isArguments(arguments); })(1, 2, 3);
(function () { return <boolean>_.isArray(arguments); })();
result = <boolean>_.isArray([1, 2, 3]);
result = <boolean>_.isBoolean(null);
result = <boolean>_.isDate(new Date());
result = <boolean>_.isElement(document.body);
result = <boolean>_.isEmpty([1, 2, 3]);
result = <boolean>_.isEmpty({});
result = <boolean>_.isEmpty('');
var moe = { 'name': 'moe', 'age': 40 };
var copy = { 'name': 'moe', 'age': 40 };
result = <boolean>_.isEqual(moe, copy);
var words = ['hello', 'goodbye'];
var otherWords = ['hi', 'goodbye'];
result = <boolean>_.isEqual(words, otherWords, function(a, b) {
var reGreet = /^(?:hello|hi)$/i,
aGreet = _.isString(a) && reGreet.test(a),
bGreet = _.isString(b) && reGreet.test(b);
return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
});
result = <boolean>_.isFinite(-101);
result = <boolean>_.isFinite('10');
result = <boolean>_.isFinite(true);
result = <boolean>_.isFinite('');
result = <boolean>_.isFinite(Infinity);
result = <boolean>_.isFunction(_);
result = <boolean>_.isNaN(NaN);
result = <boolean>_.isNaN(new Number(NaN));
result = <boolean>_.isNaN(undefined);
result = <boolean>_.isNull(null);
result = <boolean>_.isNull(undefined);
result = <boolean>_.isNumber(8.4 * 5);
result = <boolean>_.isObject({});
result = <boolean>_.isObject([1, 2, 3]);
result = <boolean>_.isObject(1);
class Stooge {
constructor(
public name: string,
public age: number
) {}
}
result = <boolean>_.isPlainObject(new Stooge('moe', 40));
result = <boolean>_.isPlainObject([1, 2, 3]);
result = <boolean>_.isPlainObject({ 'name': 'moe', 'age': 40 });
result = <boolean>_.isRegExp(/moe/);
result = <boolean>_.isString('moe');
result = <boolean>_.isUndefined(void 0);
result = <string[]>_.keys({ 'one': 1, 'two': 2, 'three': 3 });
var mergeNames = {
'stooges': [
{ 'name': 'moe' },
{ 'name': 'larry' }
]
};
var mergeAges = {
'stooges': [
{ 'age': 40 },
{ 'age': 50 }
]
};
result = <NameAge>_.merge(mergeNames, mergeAges);
var mergeFood = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var mergeOtherFood = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
interface FruitVeg {
fruits: string[];
vegetables: string[]
};
result = <FruitVeg[]>_.merge(mergeFood, mergeOtherFood, function(a, b) {
return _.isArray(a) ? a.concat(b) : undefined;
});
interface HasName {
name: string;
}
result = <HasName>_.omit({ 'name': 'moe', 'age': 40 }, 'age');
result = <HasName>_.omit({ 'name': 'moe', 'age': 40 }, ['age']);
result = <HasName>_.omit({ 'name': 'moe', 'age': 40 }, function(value) {
return typeof value == 'number';
});
result = <any[][]>_.pairs({ 'moe': 30, 'larry': 40 });
result = <HasName>_.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
result = <HasName>_.pick({ 'name': 'moe', '_userid': 'moe1' }, ['name']);
result = <HasName>_.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) {
return key.charAt(0) != '_';
});
result = <number[]>_.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(r, num) {
num *= num;
if (num % 2) {
return r.push(num) < 3;
}
});
// → [1, 9, 25]
result = <{a:number;b:number;c:number;}>_.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(r, num, key) {
r[key] = num * 3;
});
result = <number[]>_.values({ 'one': 1, 'two': 2, 'three': 3 });
/**********
* Utilities *
***********/
result = <string>_.escape('Moe, Larry & Curly');
result = <{ name: string }>_.identity({ 'name': 'moe' });
_.mixin({
'capitalize': function(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
});
var lodash = <typeof _>_.noConflict();
result = <number>_.parseInt('08');
result = <number>_.random(0, 5);
result = <number>_.random(5);
result = <number>_.random(5, true);
result = <number>_.random(1.2, 5.2);
result = <number>_.random(0, 5, true);
var object = {
'cheese': 'crumpets',
'stuff': function() {
return 'nonsense';
}
};
result = <string>_.result(object, 'cheese');
result = <string>_.result(object, 'stuff');
var tempObject = {};
result = <typeof _>_.runInContext(tempObject);
result = <_.TemplateExecutor>_.template('hello <%= name %>');
result = <string>_.template('<b><%- value %></b>', { 'value': '<script>' });
var listTemplate = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
result = <string>_.template(listTemplate, { 'people': ['moe', 'larry'] });
result = <string>_.template('hello ${ name }', { 'name': 'curly' });
result = <string>_.template('<% print("hello " + name); %>!', { 'name': 'larry' });
var listTemplate = '<% $.each(people, function(name) { %><li><%- name %></li><% }); %>';
result = <string>_.template(listTemplate, { 'people': ['moe', 'larry'] }, { 'imports': { '$': jQuery } });
result = <_.TemplateExecutor>_.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
result = <_.TemplateExecutor>_.template('hi <%= data.name %>!', null, { 'variable': 'data' });
result = <string>(<_.TemplateExecutor>result).source;
class Mage {
public castSpell(n: number) {
return n;
}
public cast(n: number) {
return n;
}
}
var mage = new Mage();
result = _.times(3, <() => number>_.partial(_.random, 1, 6));
result = _.times(3, function(n: number) { mage.castSpell(n); });
result = _.times(3, function(n: number) { this.cast(n); }, mage);
result = <string>_.unescape('Moe, Larry &amp; Curly');
result = <string>_.uniqueId('contact_');
result = <string>_.uniqueId();
/**********
* Utilities *
***********/
result = <string>_.VERSION;
result = <_.Support>_.support;
result = <_.TemplateSettings>_.templateSettings;
+981
View File
@@ -0,0 +1,981 @@
/// <reference path="lodash.d.ts" />
declare var $: any, jQuery: any;
interface IFoodOrganic {
name: string;
organic: boolean;
}
interface IFoodType {
name: string;
type: string;
}
interface IFoodCombined {
name: string;
organic: boolean;
type: string;
}
interface IStoogesQuote {
name: string;
quotes: string[];
}
interface IStoogesAge {
name: string;
age: number;
}
interface IStoogesCombined {
name: string;
age: number;
quotes: string[];
}
interface IKey {
dir: string;
code: number;
}
var foodsOrganic: IFoodOrganic[] = [
{ name: 'banana', organic: true },
{ name: 'beet', organic: false },
];
var foodsType: IFoodType[] = [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'beet', type: 'vegetable' }
];
var foodsCombined: IFoodCombined[] = [
{ 'name': 'apple', 'organic': false, 'type': 'fruit' },
{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
];
var stoogesQuotes: IStoogesQuote[] = [
{ 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
{ 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] }
];
var stoogesAges: IStoogesAge[] = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
var stoogesCombined: IStoogesCombined[] = [
{ 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
{ 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] }
];
var keys: IKey[] = [
{ 'dir': 'left', 'code': 97 },
{ 'dir': 'right', 'code': 100 }
];
class Dog {
constructor(public name: string) { }
public bark() {
console.log('Woof, woof!');
}
}
var result: any;
/*************
* Chaining *
*************/
result = <_.LoDashWrapper<string>>_('test');
result = <_.LoDashWrapper<number>>_(1);
result = <_.LoDashWrapper<boolean>>_(true);
result = <_.LoDashArrayWrapper<string>>_(['test1', 'test2']);
// Appears to be a change in the compiler, if the type explicity implements the object indexer.
// Looking at: https://typescript.codeplex.com/wikipage?title=Known%20breaking%20changes%20between%200.8%20and%200.9&referringTitle=Documentation
// "The noimplicitany option now warns on the use of the hidden default indexer"
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' });
result = <_.LoDashWrapper<string>>_.chain('test');
result = <_.LoDashWrapper<string>>_('test').chain();
result = <_.LoDashWrapper<number>>_.chain(1);
result = <_.LoDashWrapper<number>>_(1).chain();
result = <_.LoDashWrapper<boolean>>_.chain(true);
result = <_.LoDashWrapper<boolean>>_(true).chain();
result = <_.LoDashArrayWrapper<string>>_.chain(['test1', 'test2']);
result = <_.LoDashArrayWrapper<string>>_(['test1', 'test2']).chain();
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_.chain(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' });
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).chain();
//Wrapped array shortcut methods
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).concat(5, 6);
result = <_.LoDashWrapper<string>>_([1, 2, 3, 4]).join(',');
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).pop();
_([1, 2, 3, 4]).push(5, 6, 7);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).reverse();
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).shift();
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).slice(1, 2);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).slice(2);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).sort((a, b) => 1);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).splice(1);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).splice(1, 2, 5, 6);
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).unshift(5, 6);
result = <number[]>_.tap([1, 2, 3, 4], function (array) { console.log(array); });
result = <_.LoDashWrapper<string>>_('test').tap(function (value) { console.log(value); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).tap(function (array) { console.log(array); });
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).tap(function (array) { console.log(array); });
result = <string>_('test').toString();
result = <string>_([1, 2, 3]).toString();
result = <string>_({ 'key1': 'test1', 'key2': 'test2' }).toString();
result = <string>_('test').valueOf();
result = <number[]>_([1, 2, 3]).valueOf();
result = <_.Dictionary<string>>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).valueOf();
result = <string>_('test').value();
result = <number[]>_([1, 2, 3]).value();
result = <_.Dictionary<string>>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).value();
// /*************
// * Arrays *
// *************/
result = <any[]>_.compact([0, 1, false, 2, '', 3]);
result = <_.LoDashArrayWrapper<any>>_([0, 1, false, 2, '', 3]).compact();
result = <number[]>_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4, 5]).difference([5, 2, 10]);
result = <number[]>_.rest([1, 2, 3]);
result = <number[]>_.rest([1, 2, 3], 2);
result = <number[]>_.rest([1, 2, 3], (num) => num < 3)
result = <IFoodOrganic[]>_.rest(foodsOrganic, 'test');
result = <IFoodType[]>_.rest(foodsType, { 'type': 'value' });
result = <number[]>_.drop([1, 2, 3]);
result = <number[]>_.drop([1, 2, 3], 2);
result = <number[]>_.drop([1, 2, 3], (num) => num < 3)
result = <IFoodOrganic[]>_.drop(foodsOrganic, 'test');
result = <IFoodType[]>_.drop(foodsType, { 'type': 'value' });
result = <number[]>_.tail([1, 2, 3])
result = <number[]>_.tail([1, 2, 3], 2)
result = <number[]>_.tail([1, 2, 3], (num) => num < 3)
result = <IFoodOrganic[]>_.tail(foodsOrganic, 'test')
result = <IFoodType[]> _.tail(foodsType, { 'type': 'value' })
result = <number>_.findIndex(['apple', 'banana', 'beet'], function (f) {
return /^b/.test(f);
});
result = <number>_.findIndex(['apple', 'banana', 'beet'], 'apple');
result = <number>_.findIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple' });
result = <number>_.findLastIndex(['apple', 'banana', 'beet'], function (f: string) {
return /^b/.test(f);
});
result = <number>_.findLastIndex(['apple', 'banana', 'beet'], 'apple');
result = <number>_.findLastIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple' });
result = <number>_.first([1, 2, 3]);
result = <number[]>_.first([1, 2, 3], 2);
result = <number[]>_.first([1, 2, 3], function (num) {
return num < 3;
});
result = <IFoodOrganic[]>_.first(foodsOrganic, 'organic');
result = <IFoodType[]>_.first(foodsType, { 'type': 'fruit' });
result = <number>_.head([1, 2, 3]);
result = <number[]>_.head([1, 2, 3], 2);
result = <number[]>_.head([1, 2, 3], function (num) {
return num < 3;
});
result = <IFoodOrganic[]>_.head(foodsOrganic, 'organic');
result = <IFoodType[]>_.head(foodsType, { 'type': 'fruit' });
result = <number>_.take([1, 2, 3]);
result = <number[]>_.take([1, 2, 3], 2);
result = <number[]>_.take([1, 2, 3], (num) => num < 3);
result = <IFoodOrganic[]>_.take(foodsOrganic, 'organic');
result = <IFoodType[]>_.take(foodsType, { 'type': 'fruit' });
result = <number[]>_.flatten([1, [2], [3, [[4]]]]);
result = <any[]>_.flatten([1, [2], [3, [[4]]]], true);
var result: any
result = <string[]>_.flatten(stoogesQuotes, 'quotes');
result = <_.LoDashArrayWrapper<number>>_([1, [2], [3, [[4]]]]).flatten();
result = <_.LoDashArrayWrapper<number>>_([1, [2], [3, [[4]]]]).flatten(true);
result = <_.LoDashArrayWrapper<string>>_(stoogesQuotes).flatten('quotes');
result = <number>_.indexOf([1, 2, 3, 1, 2, 3], 2);
result = <number>_.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
result = <number>_.indexOf([1, 1, 2, 2, 3, 3], 2, true);
result = <number[]>_.initial([1, 2, 3]);
result = <number[]>_.initial([1, 2, 3], 2);
result = <number[]>_.initial([1, 2, 3], function (num) {
return num > 1;
});
result = <IFoodOrganic[]>_.initial(foodsOrganic, 'organic');
result = <IFoodType[]>_.initial(foodsType, { 'type': 'vegetable' });
result = <number[]>_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
result = <number>_.last([1, 2, 3]);
result = <number[]>_.last([1, 2, 3], 2);
result = <number[]>_.last([1, 2, 3], function (num) {
return num > 1;
});
result = <IFoodOrganic[]>_.last(foodsOrganic, 'organic');
result = <IFoodType[]>_.last(foodsType, { 'type': 'vegetable' });
result = <number>_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
result = <number>_.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
result = <{ [key: string]: any }>_.zipObject(['moe', 'larry'], [30, 40]);
result = <{ [key: string]: any }>_.object(['moe', 'larry'], [30, 40]);
result = <number[]>_.pull([1, 2, 3, 1, 2, 3], 2, 3);
result = <number[]>_.range(10);
result = <number[]>_.range(1, 11);
result = <number[]>_.range(0, 30, 5);
result = <number[]>_.range(0, -10, -1);
result = <number[]>_.range(1, 4, 0);
result = <number[]>_.range(0);
result = <number[]>_.remove([1, 2, 3, 4, 5, 6], function (num: number) { return num % 2 == 0; });
result = <IFoodOrganic[]>_.remove(foodsOrganic, 'organic');
result = <IFoodType[]>_.remove(foodsType, { 'type': 'vegetable' });
result = <number>_.sortedIndex([20, 30, 50], 40);
result = <number>_.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
var sortedIndexDict: { wordToNumber: { [idx: string]: number } } = {
'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
};
result = <number>_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function (word: string) {
return sortedIndexDict.wordToNumber[word];
});
result = <number>_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function (word: string) {
return this.wordToNumber[word];
}, sortedIndexDict);
result = <number[]>_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
result = <number[]>_.uniq([1, 2, 1, 3, 1]);
result = <number[]>_.uniq([1, 1, 2, 2, 3], true);
result = <string[]>_.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function (letter) {
return letter.toLowerCase();
});
result = <number[]>_.uniq([1, 2.5, 3, 1.5, 2, 3.5], function (num) { return this.floor(num); }, Math);
result = <{ x: number; }[]>_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
result = <number[]>_.unique([1, 2, 1, 3, 1]);
result = <number[]>_.unique([1, 1, 2, 2, 3], true);
result = <string[]>_.unique(['A', 'b', 'C', 'a', 'B', 'c'], function (letter) {
return letter.toLowerCase();
});
result = <number[]>_.unique([1, 2.5, 3, 1.5, 2, 3.5], function (num) { return this.floor(num); }, Math);
result = <{ x: number; }[]>_.unique([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
result = <number[]>_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
result = <any[][]>_.zip(['moe', 'larry'], [30, 40], [true, false]);
result = <any[][]>_.unzip(['moe', 'larry'], [30, 40], [true, false]);
// /* *************
// * Collections *
// ************* */
result = <string[]>_.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
result = <string[]>_.at(['moe', 'larry', 'curly'], 0, 2);
result = <boolean>_.contains([1, 2, 3], 1);
result = <boolean>_.contains([1, 2, 3], 1, 2);
result = <boolean>_.contains({ 'name': 'moe', 'age': 40 }, 'moe');
result = <boolean>_.contains('curly', 'ur');
result = <boolean>_.include([1, 2, 3], 1);
result = <boolean>_.include([1, 2, 3], 1, 2);
result = <boolean>_.include({ 'name': 'moe', 'age': 40 }, 'moe');
result = <boolean>_.include('curly', 'ur');
result = <_.Dictionary<number>>_.countBy([4.3, 6.1, 6.4], function (num) { return Math.floor(num); });
result = <_.Dictionary<number>>_.countBy([4.3, 6.1, 6.4], function (num) { return this.floor(num); }, Math);
result = <_.Dictionary<number>>_.countBy(['one', 'two', 'three'], 'length');
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_([4.3, 6.1, 6.4]).countBy(function (num) { return Math.floor(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_([4.3, 6.1, 6.4]).countBy(function (num) { return this.floor(num); }, Math);
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_(['one', 'two', 'three']).countBy('length');
result = <boolean>_.every([true, 1, null, 'yes'], Boolean);
result = <boolean>_.every(stoogesAges, 'age');
result = <boolean>_.every(stoogesAges, { 'age': 50 });
result = <boolean>_.all([true, 1, null, 'yes'], Boolean);
result = <boolean>_.all(stoogesAges, 'age');
result = <boolean>_.all(stoogesAges, { 'age': 50 });
result = <number[]>_.filter([1, 2, 3, 4, 5, 6], function (num) { return num % 2 == 0; });
result = <IFoodCombined[]>_.filter(foodsCombined, 'organic');
result = <IFoodCombined[]>_.filter(foodsCombined, { 'type': 'fruit' });
result = <number[]>_([1, 2, 3, 4, 5, 6]).filter(function (num) { return num % 2 == 0; }).value();
result = <IFoodCombined[]>_(foodsCombined).filter('organic').value();
result = <IFoodCombined[]>_(foodsCombined).filter({ 'type': 'fruit' }).value();
result = <number[]>_.select([1, 2, 3, 4, 5, 6], function (num) { return num % 2 == 0; });
result = <IFoodCombined[]>_.select(foodsCombined, 'organic');
result = <IFoodCombined[]>_.select(foodsCombined, { 'type': 'fruit' });
result = <number[]>_([1, 2, 3, 4, 5, 6]).select(function (num) { return num % 2 == 0; }).value();
result = <IFoodCombined[]>_(foodsCombined).select('organic').value();
result = <IFoodCombined[]>_(foodsCombined).select({ 'type': 'fruit' }).value();
result = <number>_.find([1, 2, 3, 4], function (num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.find(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.find(foodsCombined, 'organic');
result = <number>_.detect([1, 2, 3, 4], function (num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.detect(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.detect(foodsCombined, 'organic');
result = <number>_.findWhere([1, 2, 3, 4], function (num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.findWhere(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.findWhere(foodsCombined, 'organic');
result = <number>_.findLast([1, 2, 3, 4], function (num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.findLast(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.findLast(foodsCombined, 'organic');
result = <number[]>_.forEach([1, 2, 3], function (num) { console.log(num); });
result = <_.Dictionary<number>>_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function (num) { console.log(num); });
result = <number[]>_.each([1, 2, 3], function (num) { console.log(num); });
result = <_.Dictionary<number>>_.each({ 'one': 1, 'two': 2, 'three': 3 }, function (num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).forEach(function (num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_(<{ [index: string]: number; }>{ 'one': 1, 'two': 2, 'three': 3 }).forEach(function (num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).each(function (num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_(<{ [index: string]: number; }>{ 'one': 1, 'two': 2, 'three': 3 }).each(function (num) { console.log(num); });
result = <number[]>_.forEachRight([1, 2, 3], function (num) { console.log(num); });
result = <_.Dictionary<number>>_.forEachRight({ 'one': 1, 'two': 2, 'three': 3 }, function (num) { console.log(num); });
result = <number[]>_.eachRight([1, 2, 3], function (num) { console.log(num); });
result = <_.Dictionary<number>>_.eachRight({ 'one': 1, 'two': 2, 'three': 3 }, function (num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).forEachRight(function (num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_(<{ [index: string]: number; }>{ 'one': 1, 'two': 2, 'three': 3 }).forEachRight(function (num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).eachRight(function (num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_(<{ [index: string]: number; }>{ 'one': 1, 'two': 2, 'three': 3 }).eachRight(function (num) { console.log(num); });
result = <_.Dictionary<number[]>>_.groupBy([4.2, 6.1, 6.4], function (num) { return Math.floor(num); });
result = <_.Dictionary<number[]>>_.groupBy([4.2, 6.1, 6.4], function (num) { return this.floor(num); }, Math);
result = <_.Dictionary<string[]>>_.groupBy(['one', 'two', 'three'], 'length');
result = <_.LoDashObjectWrapper<_.Dictionary<number[]>>>_([4.2, 6.1, 6.4]).groupBy(function (num) { return Math.floor(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number[]>>>_([4.2, 6.1, 6.4]).groupBy(function (num) { return this.floor(num); }, Math);
result = <_.LoDashObjectWrapper<_.Dictionary<string[]>>>_(['one', 'two', 'three']).groupBy('length');
result = <_.Dictionary<IKey>>_.indexBy(keys, 'dir');
result = <_.Dictionary<IKey>>_.indexBy(keys, function (key) { return String.fromCharCode(key.code); });
result = <_.Dictionary<IKey>>_.indexBy(keys, function (key) { this.fromCharCode(key.code); }, String);
result = <number[][]>_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
result = <string[][]>_.invoke([123, 456], String.prototype.split, '');
result = <number[]>_.map([1, 2, 3], function (num) { return num * 3; });
result = <number[]>_.map({ 'one': 1, 'two': 2, 'three': 3 }, function (num) { return num * 3; });
result = <IStoogesAge[]>_.map(stoogesAges, 'name');
result = <number[]>_([1, 2, 3]).map(function (num) { return num * 3; }).value();
result = <number[]>_({ 'one': 1, 'two': 2, 'three': 3 }).map(function (num: number) { return num * 3; }).value();
result = <IStoogesAge[]>_(stoogesAges).map('name').value();
result = <number[]>_.collect([1, 2, 3], function (num) { return num * 3; });
result = <number[]>_.collect({ 'one': 1, 'two': 2, 'three': 3 }, function (num) { return num * 3; });
result = <IStoogesAge[]>_.collect(stoogesAges, 'name');
result = <number[]>_([1, 2, 3]).collect(function (num) { return num * 3; }).value();
result = <number[]>_({ 'one': 1, 'two': 2, 'three': 3 }).collect(function (num: number) { return num * 3; }).value();
result = <IStoogesAge[]>_(stoogesAges).collect('name').value();
result = <number>_.max([4, 2, 8, 6]);
result = <IStoogesAge>_.max(stoogesAges, function (stooge) { return stooge.age; });
result = <IStoogesAge>_.max(stoogesAges, 'age');
result = <number>_.min([4, 2, 8, 6]);
result = <IStoogesAge>_.min(stoogesAges, function (stooge) { return stooge.age; });
result = <IStoogesAge>_.min(stoogesAges, 'age');
result = <string[]>_.pluck(stoogesAges, 'name');
result = <number>_.reduce<number, number>([1, 2, 3], function (sum: number, num: number) {
return sum + num;
});
interface ABC {
[index: string]: number;
a: number;
b: number;
c: number;
}
result = <ABC>_.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) {
r[key] = num * 3;
return r;
}, {});
result = <number>_.foldl([1, 2, 3], function (sum: number, num: number) {
return sum + num;
});
result = <ABC>_.foldl({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) {
r[key] = num * 3;
return r;
}, {});
result = <number>_.inject([1, 2, 3], function (sum: number, num: number) {
return sum + num;
});
result = <ABC>_.inject({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) {
r[key] = num * 3;
return r;
}, {});
result = <number[]>_.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, <number[]>[]);
result = <number[]>_.foldr([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, <number[]>[]);
result = <number[]>_.reject([1, 2, 3, 4, 5, 6], function (num) { return num % 2 == 0; });
result = <IFoodCombined[]>_.reject(foodsCombined, 'organic');
result = <IFoodCombined[]>_.reject(foodsCombined, { 'type': 'fruit' });
result = <number>_.sample([1, 2, 3, 4]);
result = <number[]>_.sample([1, 2, 3, 4], 2);
result = <number[]>_.shuffle([1, 2, 3, 4, 5, 6]);
result = <number>_.size([1, 2]);
result = <number>_.size({ 'one': 1, 'two': 2, 'three': 3 });
result = <number>_.size('curly');
result = <boolean>_.some([null, 0, 'yes', false], Boolean);
result = <boolean>_.some(foodsCombined, 'organic');
result = <boolean>_.some(foodsCombined, { 'type': 'meat' });
result = <boolean>_.any([null, 0, 'yes', false], Boolean);
result = <boolean>_.any(foodsCombined, 'organic');
result = <boolean>_.any(foodsCombined, { 'type': 'meat' });
result = <number[]>_.sortBy([1, 2, 3], function (num) { return Math.sin(num); });
result = <number[]>_.sortBy([1, 2, 3], function (num) { return this.sin(num); }, Math);
result = <string[]>_.sortBy(['banana', 'strawberry', 'apple'], 'length');
(function (a: number, b: number, c: number, d: number) { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
result = <IStoogesCombined[]>_.where(stoogesCombined, { 'age': 40 });
result = <IStoogesCombined[]>_.where(stoogesCombined, { 'quotes': ['Poifect!'] });
/*************
* Functions *
*************/
var saves = ['profile', 'settings'];
var asyncSave = (obj: any) => obj.done();
var done: Function;
done = _.after(saves.length, function () {
console.log('Done saving!');
});
_.forEach(saves, function (type) {
asyncSave({ 'type': type, 'complete': done });
});
done = _(saves.length).after(function () {
console.log('Done saving!');
}).value();
_.forEach(saves, function (type) {
asyncSave({ 'type': type, 'complete': done });
});
var funcBind = function (greeting: string) { return greeting + ' ' + this.name };
var funcBind2: () => any = _.bind(funcBind, { 'name': 'moe' }, 'hi');
funcBind2();
var funcBind3: () => any = _(funcBind).bind({ 'name': 'moe' }, 'hi').value();
funcBind3();
var view = {
'label': 'docs',
'onClick': function () { console.log('clicked ' + this.label); }
};
view = _.bindAll(view);
jQuery('#docs').on('click', view.onClick);
view = _(view).bindAll().value();
jQuery('#docs').on('click', view.onClick);
var objectBindKey = {
'name': 'moe',
'greet': function (greeting: string) {
return greeting + ' ' + this.name;
}
};
var funcBindKey: Function = _.bindKey(objectBindKey, 'greet', 'hi');
funcBindKey();
objectBindKey.greet = function (greeting) {
return greeting + ', ' + this.name + '!';
};
funcBindKey();
funcBindKey = _(objectBindKey).bindKey('greet', 'hi').value();
funcBindKey();
var realNameMap: { [index: string]: string; } = {
'curly': 'jerome'
};
var format = function (name: string) {
name = realNameMap[name.toLowerCase()] || name;
return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
};
var greet = function (formatted: string) {
return 'Hiya ' + formatted + '!';
};
result = <Function>_.compose(greet, format);
result = <_.LoDashObjectWrapper<Function>>_(greet).compose(format);
var createCallbackObj: { [index: string]: string; } = { name: 'Joe' };
result = <() => any>_.createCallback('name');
result = <() => boolean>_.createCallback(createCallbackObj);
result = <_.LoDashObjectWrapper<() => any>>_('name').createCallback();
result = <_.LoDashObjectWrapper<() => boolean>>_(createCallbackObj).createCallback();
result = <Function>_.curry(function (a: any, b: any, c: any) {
console.log(a + b + c);
});
result = <_.LoDashObjectWrapper<Function>>_(function (a, b, c) {
console.log(a + b + c);
}).curry();
declare var source: any;
result = <Function>_.debounce(function () { }, 150);
jQuery('#postbox').on('click', <Function>_.debounce(function () { }, 300, {
'leading': true,
'trailing': false
}));
source.addEventListener('message', <Function>_.debounce(function () { }, 250, {
'maxWait': 1000
}), false);
result = <_.LoDashObjectWrapper<Function>>_(function () { }).debounce(150);
jQuery('#postbox').on('click', <_.LoDashObjectWrapper<Function>>_(function () { }).debounce(300, {
'leading': true,
'trailing': false
}));
source.addEventListener('message', <_.LoDashObjectWrapper<Function>>_(function () { }).debounce(250, {
'maxWait': 1000
}), false);
var returnedDebounce = _.throttle(function (a) { return a * 5; }, 5);
returnedThrottled(4);
result = <number>_.defer(function () { console.log('deferred'); });
result = <_.LoDashWrapper<number>>_(function () { console.log('deferred'); }).defer();
var log = _.bind(console.log, console);
result = <number>_.delay(log, 1000, 'logged later');
result = <_.LoDashWrapper<number>>_(log).delay(1000, 'logged later');
var fibonacci = <Function>_.memoize(function (n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
var data: { [index: string]: { name: string; age: number; } } = {
'moe': { 'name': 'moe', 'age': 40 },
'curly': { 'name': 'curly', 'age': 60 }
};
var stooge = _.memoize(function (name: string) { return data[name]; }, _.identity);
stooge('curly');
var returnedMemoize = _.throttle(function (a) { return a * 5; }, 5);
returnedMemoize(4);
var initialize = _.once(function () { });
initialize();
initialize();''
var returnedOnce = _.throttle(function (a) { return a * 5; }, 5);
returnedOnce(4);
var greetPartial = function (greeting: string, name: string) { return greeting + ' ' + name; };
var hi = <Function>_.partial(greetPartial, 'hi');
hi('moe');
var defaultsDeep = <Function>_.partialRight(_.merge, _.defaults);
var optionsPartialRight = {
'variable': 'data',
'imports': { 'jq': $ }
};
defaultsDeep(optionsPartialRight, _.templateSettings);
var throttled = _.throttle(function () { }, 100);
jQuery(window).on('scroll', throttled);
jQuery('.interactive').on('click', _.throttle(function () { }, 300000, {
'trailing': false
}));
var returnedThrottled = _.throttle(function (a) { return a * 5; }, 5);
returnedThrottled(4);
var helloWrap = function (name: string) { return 'hello ' + name; };
var helloWrap2 = _.wrap(helloWrap, function (func) {
return 'before, ' + func('moe') + ', after';
});
helloWrap2();
/**********
* Objects *
***********/
interface NameAge {
name: string;
age: number;
}
result = <NameAge>_.assign({ 'name': 'moe' }, { 'age': 40 });
result = <NameAge>_.assign({ 'name': 'moe' }, { 'age': 40 }, function (a, b) {
return typeof a == 'undefined' ? b : a;
});
result = <_.LoDashObjectWrapper<NameAge>>_({ 'name': 'moe' }).assign({ 'age': 40 });
result = <_.LoDashObjectWrapper<NameAge>>_({ 'name': 'moe' }).assign({ 'age': 40 }, function (a, b) {
return typeof a == 'undefined' ? b : a;
});
result = <NameAge>_.extend({ 'name': 'moe' }, { 'age': 40 });
result = <NameAge>_.extend({ 'name': 'moe' }, { 'age': 40 }, function (a, b) {
return typeof a == 'undefined' ? b : a;
});
result = <_.LoDashObjectWrapper<NameAge>>_({ 'name': 'moe' }).extend({ 'age': 40 });
result = <_.LoDashObjectWrapper<NameAge>>_({ 'name': 'moe' }).extend({ 'age': 40 }, function (a, b) {
return typeof a == 'undefined' ? b : a;
});
result = <IStoogesAge[]>_.clone(stoogesAges);
result = <IStoogesAge[]>_.clone(stoogesAges, true);
result = <any>_.clone(stoogesAges, true, function (value) {
return _.isElement(value) ? value.cloneNode(false) : undefined;
});
result = <IStoogesAge[]>_.cloneDeep(stoogesAges);
result = <IStoogesAge[]>_.cloneDeep(stoogesAges, function (value) {
return _.isElement(value) ? value.cloneNode(false) : undefined;
});
interface Food {
name: string;
type: string;
}
var foodDefaults = { 'name': 'apple' };
result = <Food>_.defaults(foodDefaults, { 'name': 'banana', 'type': 'fruit' });
result = <_.LoDashObjectWrapper<Food>>_(foodDefaults).defaults({ 'name': 'banana', 'type': 'fruit' });
result = <string>_.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function (num) {
return num % 2 == 0;
});
result = <string>_.findLastKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function (num) {
return num % 2 == 1;
});
result = <Dog>_.forIn(new Dog('Dagny'), function (value, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<Dog>>_(new Dog('Dagny')).forIn(function (value, key) {
console.log(key);
});
result = <Dog>_.forInRight(new Dog('Dagny'), function (value, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<Dog>>_(new Dog('Dagny')).forInRight(function (value, key) {
console.log(key);
});
interface ZeroOne {
0: string;
1: string;
one: string;
}
result = <ZeroOne>_.forOwn(<ZeroOne>{ '0': 'zero', '1': 'one', 'one': '2' }, function (num, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<ZeroOne>>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwn(function (num, key) {
console.log(key);
});
result = <any>_.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function (num, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<ZeroOne>>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwnRight(function (num, key) {
console.log(key);
});
result = <string[]>_.functions(_);
result = <string[]>_.methods(_);
result = <_.LoDashArrayWrapper<string>>_(_).functions();
result = <_.LoDashArrayWrapper<string>>_(_).methods();
result = <boolean>_.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
interface FirstSecond {
first: string;
second: string;
}
result = <FirstSecond>_.invert({ 'first': 'moe', 'second': 'larry' });
(function (...args: any[]) { return <boolean>_.isArguments(arguments); })(1, 2, 3);
(function () { return <boolean>_.isArray(arguments); })();
result = <boolean>_.isArray([1, 2, 3]);
result = <boolean>_.isBoolean(null);
result = <boolean>_.isDate(new Date());
result = <boolean>_.isElement(document.body);
result = <boolean>_.isEmpty([1, 2, 3]);
result = <boolean>_.isEmpty({});
result = <boolean>_.isEmpty('');
var moe = { 'name': 'moe', 'age': 40 };
var copy = { 'name': 'moe', 'age': 40 };
result = <boolean>_.isEqual(moe, copy);
var words = ['hello', 'goodbye'];
var otherWords = ['hi', 'goodbye'];
result = <boolean>_.isEqual(words, otherWords, function (a, b) {
var reGreet = /^(?:hello|hi)$/i,
aGreet = _.isString(a) && reGreet.test(a),
bGreet = _.isString(b) && reGreet.test(b);
return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
});
result = <boolean>_.isFinite(-101);
result = <boolean>_.isFinite('10');
result = <boolean>_.isFinite(true);
result = <boolean>_.isFinite('');
result = <boolean>_.isFinite(Infinity);
result = <boolean>_.isFunction(_);
result = <boolean>_.isNaN(NaN);
result = <boolean>_.isNaN(new Number(NaN));
result = <boolean>_.isNaN(undefined);
result = <boolean>_.isNull(null);
result = <boolean>_.isNull(undefined);
result = <boolean>_.isNumber(8.4 * 5);
result = <boolean>_.isObject({});
result = <boolean>_.isObject([1, 2, 3]);
result = <boolean>_.isObject(1);
class Stooge {
constructor(
public name: string,
public age: number
) { }
}
result = <boolean>_.isPlainObject(new Stooge('moe', 40));
result = <boolean>_.isPlainObject([1, 2, 3]);
result = <boolean>_.isPlainObject({ 'name': 'moe', 'age': 40 });
result = <boolean>_.isRegExp(/moe/);
result = <boolean>_.isString('moe');
result = <boolean>_.isUndefined(void 0);
result = <string[]>_.keys({ 'one': 1, 'two': 2, 'three': 3 });
var mergeNames = {
'stooges': [
{ 'name': 'moe' },
{ 'name': 'larry' }
]
};
var mergeAges = {
'stooges': [
{ 'age': 40 },
{ 'age': 50 }
]
};
result = <NameAge>_.merge(mergeNames, mergeAges);
var mergeFood = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var mergeOtherFood: { [index: string]: string[] } = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
interface FruitVeg {
[index: string]: string[];
fruits: string[];
vegetables: string[]
};
result = <FruitVeg[]>_.merge(<FruitVeg>mergeFood, <FruitVeg>mergeOtherFood, function (a: any, b: any) {
return _.isArray(a) ? a.concat(b) : undefined;
});
interface HasName {
name: string;
}
result = <HasName>_.omit({ 'name': 'moe', 'age': 40 }, 'age');
result = <HasName>_.omit({ 'name': 'moe', 'age': 40 }, ['age']);
result = <HasName>_.omit({ 'name': 'moe', 'age': 40 }, function (value) {
return typeof value == 'number';
});
result = <any[][]>_.pairs({ 'moe': 30, 'larry': 40 });
result = <HasName>_.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
result = <HasName>_.pick({ 'name': 'moe', '_userid': 'moe1' }, ['name']);
result = <HasName>_.pick({ 'name': 'moe', '_userid': 'moe1' }, function (value, key) {
return key.charAt(0) != '_';
});
result = <number[]>_.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function (r: number[], num: number) {
num *= num;
if (num % 2) {
return r.push(num) < 3;
}
});
// → [1, 9, 25]
result = <{ a: number; b: number; c: number; }>_.transform(<{ [index: string]: number; }>{ 'a': 1, 'b': 2, 'c': 3 }, function (r: any, num: number, key: string) {
r[key] = num * 3;
});
result = <number[]>_.values({ 'one': 1, 'two': 2, 'three': 3 });
/**********
* Utilities *
***********/
result = <string>_.escape('Moe, Larry & Curly');
result = <{ name: string }>_.identity({ 'name': 'moe' });
_.mixin({
'capitalize': function (string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
});
var lodash = <typeof _>_.noConflict();
result = <number>_.parseInt('08');
result = <number>_.random(0, 5);
result = <number>_.random(5);
result = <number>_.random(5, true);
result = <number>_.random(1.2, 5.2);
result = <number>_.random(0, 5, true);
var object = {
'cheese': 'crumpets',
'stuff': function () {
return 'nonsense';
}
};
result = <string>_.result(object, 'cheese');
result = <string>_.result(object, 'stuff');
var tempObject = {};
result = <typeof _>_.runInContext(tempObject);
result = <_.TemplateExecutor>_.template('hello <%= name %>');
result = <string>_.template('<b><%- value %></b>', { 'value': '<script>' });
var listTemplate = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
result = <string>_.template(listTemplate, { 'people': ['moe', 'larry'] });
result = <string>_.template('hello ${ name }', { 'name': 'curly' });
result = <string>_.template('<% print("hello " + name); %>!', { 'name': 'larry' });
var listTemplate = '<% $.each(people, function(name) { %><li><%- name %></li><% }); %>';
result = <string>_.template(listTemplate, { 'people': ['moe', 'larry'] }, { 'imports': { '$': jQuery } });
result = <_.TemplateExecutor>_.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
result = <_.TemplateExecutor>_.template('hi <%= data.name %>!', null, { 'variable': 'data' });
result = <string>(<_.TemplateExecutor>result).source;
class Mage {
public castSpell(n: number) {
return n;
}
public cast(n: number) {
return n;
}
}
var mage = new Mage();
result = _.times(3, <() => number>_.partial(_.random, 1, 6));
result = _.times(3, function (n: number) { mage.castSpell(n); });
result = _.times(3, function (n: number) { this.cast(n); }, mage);
result = <string>_.unescape('Moe, Larry &amp; Curly');
result = <string>_.uniqueId('contact_');
result = <string>_.uniqueId();
/**********
* Utilities *
***********/
result = <string>_.VERSION;
result = <_.Support>_.support;
result = <_.TemplateSettings>_.templateSettings;
+5448 -3591
View File
File diff suppressed because it is too large Load Diff
+366
View File
@@ -0,0 +1,366 @@
/// <reference path="mongoose.d.ts" />
var fs = require('fs');
import mongoose = require('mongoose');
var createInstance = new mongoose.Mongoose();
var Schema = mongoose.Schema;
var CreateSchema = new Schema({});
mongoose.connect('mongodb://user:pass@localhost:port/database');
mongoose.connect('mongodb://hostA:27501,hostB:27501', { mongos: true });
var conn: mongoose.Connection = mongoose.createConnection('mongodb://user:pass@localhost:port/database');
conn = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', { replset: { strategy: 'ping', rs_name: 'testSet' }});
conn = mongoose.createConnection('localhost', 'database', 27014);
conn = mongoose.createConnection('localhost', 'database', 27014, { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' });
conn = mongoose.createConnection();
conn.open('localhost', 'database', 27014, {});
var db = mongoose.createConnection();
db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019");
db.openSet('mongodb://mongosA:27501,mongosB:27501', 'db', { mongos: true }, (err: any) => {});
db.close();
var collection = db.collection('collection1');
mongoose.connection.on('error', (err: any) => {});
mongoose.disconnect();
mongoose.set('test', 1234567890);
var value = mongoose.get('test');
mongoose.set('debug', true);
interface IActor extends mongoose.Document {
name: string;
}
mongoose.model<IActor>('Actor', new Schema({ name: String }));
db.model<IActor>('Actor', new Schema({ name: String }));
var schema: mongoose.Schema = new Schema({ name: String }, { collection: 'actor' });
schema.set('collection', 'actor');
var Model = mongoose.model<IActor>('Actor', schema, 'actor');
var names: string[] = mongoose.modelNames();
var names: string[] = db.modelNames();
mongoose.plugin((schema: mongoose.Schema) => {
}, { index: true });
var aggregate = new mongoose.Aggregate();
var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } });
var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 });
var aggregate = new mongoose.Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]);
aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]);
aggregate.group({ _id: "$department" });
aggregate.skip(10);
aggregate.limit(10);
aggregate.match({ department: { $in: [ "sales", "engineering" ] } });
aggregate.near({
near: [40.724, -73.997],
distanceField: "dist.calculated", // required
maxDistance: 0.008,
query: { type: "public" },
includeLocs: "dist.location",
uniqueDocs: true,
num: 5
});
aggregate.project("a b -_id");
aggregate.project({a: 1, b: 1, _id: 0});
aggregate.project({
newField: '$b.nested',
plusTen: { $add: ['$val', 10]},
sub: {
name: '$a'
}
});
aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });
aggregate.sort({ field: 'asc', test: -1 });
aggregate.sort('field -test');
aggregate.unwind("tags");
aggregate.unwind("a", "b", "c");
var p = aggregate.exec();
aggregate.read('primaryPreferred').exec((err: any, result: {}) => {});
var p = new mongoose.Promise;
var p2 = p.then(function() { throw new Error('shucks') }).end();
setTimeout(function() {
p.fulfill({});
}, 10);
var promise = new mongoose.Promise<number>();
promise.then(function (meetups: number) {
return new mongoose.Promise<string[]>();
}).then(function (people: string[]) {
if (people.length < 10000) {
throw new Error('Too few people!!!');
} else {
throw new Error('Still need more people!!!');
}
}).then(null, function (err: Error) {
}).end();
Model.findOne({ name: 'john' }, (err: any, doc: mongoose.Document) => {
doc.invalidate('size', 'must be less than 20', 14);
doc.validate((err: any) => { });
doc.set('documents.0.title', 'changed');
doc.get('documents.0');
doc.set({
'path' : 1,
'path2' : {
'path' : 2
}
});
doc.set('path', 'value', { strict: false });
doc.set('path3', '1', Number);
doc.get('path3', Number);
doc.id;
doc._id;
doc.isModified();
doc.isModified('documents');
doc.isModified('documents.0.title');
doc.isDirectModified('documents.0.title');
doc.isDirectModified('documents');
doc.isSelected('name');
doc.markModified('mixed.type');
doc.populate('user');
doc.populate('other', (err: any, doc: mongoose.Document) => {});
doc.populated('author');
doc.save();
doc.toJSON({ getters: true, virtuals: false });
var data: any = doc.toObject();
delete data['age'];
delete data['weight'];
data['isAwesome'] = true;
});
Model.model('User').findById('id', (err: any, res: IActor) => {});
Model.count({ type: 'jungle' }, (err: any, count: number) => {});
Model.remove((err: any, res: IActor[]) => {});
Model.save((err: any, res: IActor, numberAffected: number) => {});
Model.create({ type: 'jelly bean' }, { type: 'snickers' }, (err: any, res1: IActor, res2: IActor) => {});
Model.create({ type: 'jawbreaker' });
Model.distinct('url', { clicks: {$gt: 100}}, (err: any, result: IActor[]) => {});
Model.distinct('url');
Model.aggregate(
{ $group: { _id: null, maxBalance: { $max: '$balance' }}},
{ $project: { _id: 0, maxBalance: 1 }},
(err: any, res: IActor[]) => {});
Model.aggregate()
.group({ _id: null, maxBalance: { $max: '$balance' } })
.select('-id maxBalance')
.exec((err: any, res: IActor[]) => {});
Model.ensureIndexes((err) => {});
Model.find({ name: 'john', age: { $gte: 18 }});
Model.find({ name: 'john', age: { $gte: 18 }}, (err: any, docs: IActor[]) => {});
Model.find({ name: /john/i }, 'name friends', (err: any, docs: IActor[]) => {});
Model.find({ name: /john/i }, null, { skip: 10 });
Model.find({ name: /john/i }, null, { skip: 10 }, (err: any, docs: IActor[]) => {});
Model.find({ name: /john/i }, null, { skip: 10 }).exec((err: any, docs: IActor[]) => {});
var query = Model.find({ name: /john/i }, null, { skip: 10 });
var promise1 = query.exec();
promise1.addBack((err: any, docs: IActor[]) => {});
Model.findById('id', (err: any, res: IActor) => {});
Model.findById('id').exec((err: any, res: IActor) => {});
Model.findById('id', 'name length', (err: any, res: IActor) => {});
Model.findById('id', '-length').exec((err: any, res: IActor) => {});
Model.findById('id', 'name', { lean: true }, (err: any, res: IActor) => {});
Model.findById('id', 'name').lean().exec((err: any, res: IActor) => {});
Model.findByIdAndRemove('id1', { select: 'name' }, (err: any, res: IActor) => {});
Model.findByIdAndRemove('id1', { select: 'name' }).exec((err: any, res: IActor) => {});
Model.findByIdAndRemove('id1', (err: any, res: IActor) => {});
Model.findByIdAndRemove('id1').exec((err: any, res: IActor) => {});
Model.findByIdAndUpdate('id2', { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {});
Model.findOne({ type: 'iphone' }, (err: any, res: IActor) => {});
Model.findOne({ type: 'iphone' }).exec((err: any, res: IActor) => {});
Model.findOne({ type: 'iphone' }, 'name', (err: any, res: IActor) => {});
Model.findOne({ type: 'iphone' }, 'name').exec((err: any, res: IActor) => {});
Model.findOne({ type: 'iphone' }, 'name', { lean: true }, (err: any, res: IActor) => {});
Model.findOne({ type: 'iphone' }, 'name', { lean: true }).exec((err: any, res: IActor) => {});
Model.findOne({ type: 'iphone' }).select('name').lean().exec((err: any, res: IActor) => {});
Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }, (err: any, res: IActor) => {});
Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }).exec((err: any, res: IActor) => {});
Model.findOneAndUpdate({ type: 'iphone' }, { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {});
Model.geoNear([1, 3], { maxDistance : 5, spherical : true }, (err: any, res: IActor[]) => {});
Model.geoNear({ type : "Point", coordinates : [9,9] }, { maxDistance : 5, spherical : true }, (err: any, res: IActor[]) => {});
Model.geoSearch({ type : "house" }, { near: [10, 10], maxDistance: 5 }, (err: any, res: IActor[]) => {});
var o = {
map: function () { this.emit(this.name, 1) },
reduce: function (k: string, vals: IActor[]) { return vals.length },
};
Model.mapReduce(o, (err: any, res: any[]) => {});
Model.findById('id', (err: any, res: IActor) => {
var opts = [
{ path: 'company', match: { x: 1 }, select: 'name' },
{ path: 'notes', options: { limit: 10 }, model: 'override' }
];
Model.populate(res, opts, (err: any, res: IActor) => {});
});
Model.find({ type: 'iphone' }, (err: any, res: IActor[]) => {
var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }];
var promise = Model.populate(res, opts);
promise.then(console.log).end();
});
Model.populate({ name: 'Test A' }, { path: 'weapon', model: 'Weapon' }, (err: any, user: IActor) => {});
Model.populate([
{ name: 'User hoge' },
{ name: 'User fuga' },
], { path: 'weapon' }, (err: any, users: IActor[]) => {});
Model.remove({ title: 'baby born from alien father' }, (err: any) => {});
var query2 = Model.remove({ _id: 'id' });
query2.exec();
Model.update({ age: { $gt: 18 } }, { oldEnough: true }, (err: any, numberAffected: number, raw: any) => {});
Model.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, (err: any, numberAffected: number, raw: any) => {});
Model.update({ _id: 'id' }, { $set: { text: 'changed' }}).exec();
Model.where('age').gte(21).lte(65).exec((err: any, res: IActor[]) => {});
var query3 =Model
.where('age').gt(21).lt(65)
.where('name', /^b/i).all('type', 1);
query3.all(25);
query3.and([{ color: 'green' }, { status: 'ok' }]);
query3.batchSize(100);
query3.where('loc').within().box([40.73083, -73.99756], [40.741404, -73.988135]);
query3.where('loc').within().circle({ center: [50, 50], radius: 10, unique: true });
query3.circle('loc', { center: [50, 50], radius: 10, unique: true });
query3.comment('login query');
query3.where({ 'color': 'black' }).count();
query3.count({ color: 'black' }).count((err: any, count: number) => {});
query3.count({ color: 'black' }, (err: any, count: number) => {});
query3.where({ color: 'black' }).count((err: any, count: number) => {});
query3.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}});
query3.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}});
query.elemMatch('comment', (elem: mongoose.Query<IActor>) => {
elem.where('author').equals('autobot');
elem.where('votes').gte(5);
});
query3.where('age').equals(49);
query3.where('age', 49);
query3.exec();
query3.exec('update');
query3.where('name').exists();
query3.where('name').exists(true);
query3.find().exists('name');
query3.where('name').exists(false);
query3.find().exists('name', false);
query3.find({ name: 'Los Pollos Hermanos' }).find((err: any, res: IActor[]) => {});
query3.where('loc').within().geometry({ type: 'Polygon', coordinates: [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] });
query3.find().where('age').gt(21);
query3.find().gt('age', 21);
query3.hint({ indexA: 1, indexB: -1});
query3.where('path').intersects().geometry({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] });
query3.where('path').intersects({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] });
query3.maxScan(100);
query3.where('loc').near({ center: [10, 10] });
query3.where('loc').near({ center: [10, 10], maxDistance: 5 });
query3.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
query3.near('loc', { center: [10, 10], maxDistance: 5 });
query3.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
query3.nor([{ color: 'green' }, { status: 'ok' }]);
query3.or([{ color: 'red' }, { status: 'emergency' }]);
query3.where('loc').within().polygon([10,20], [13, 25], [7,15]);
query3.polygon('loc', [10,20], [13, 25], [7,15]);
query3.findOne().populate('owner').exec((err: any, res: IActor[]) => {});
query3.find().populate({
path: 'owner',
select: 'name',
match: { color: 'black' },
options: { sort: { name: -1 }}
}).exec((err: any, res: IActor[]) => {});
query3.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec((err: any, res: IActor[]) => {});
query3.read('primary');
query3.read('p');
query3.read('primaryPreferred');
query3.read('pp');
query3.read('secondary');
query3.read('s');
query3.read('secondaryPreferred');
query3.read('sp');
query3.read('nearest');
query3.read('n');
query3.read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]);
query3.remove({ artist: 'Anne Murray' }, (err: any, res: IActor[]) => {});
query3.select('a b -c');
query3.select({a: 1, b: 1, c: 0});
query3.select('+path');
query3.where('tags').size(0);
query3.skip(100).limit(20);
query3.slaveOk();
query3.slaveOk(true);
query3.slaveOk(false);
query3.slice('comments', -5);
query3.slice('comments', [10, 5])
query3.where('comments').slice(5);
query3.where('comments').slice([-10, 5]);
query3.snapshot();
query3.snapshot(true);
query3.snapshot(false);
query3.sort({ field: 'asc', test: -1 });
query3.sort('field -test');
Model.find({ name: /^hello/ }).stream({ transform: JSON.stringify }).pipe(fs.createWriteStream('./test.json'));
var stream = Model.find({ name: /^hello/ }).stream();
stream
.on('data', (doc: IActor) => {})
.on('error', (err: any) => {})
.on('close', () => {});
query3.tailable();
query3.tailable(false);
var AdvQuery = query3.toConstructor();
query3.update({ title: 'words' });
query3.update({ $set: { title: 'words' }});
query3.update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, (err: any, row: number, raw: any) => {});
query3.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
query3.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
query3.where('loc').within({ polygon: [[],[],[],[]] });
query3.where('loc').within([], [], []); // polygon
query3.where('loc').within([], []); // box
query3.where('loc').within({ type: 'LineString', coordinates: [] }); // geometry
mongoose.Query.use$geoWithin = false;
var ToySchema = new Schema({});
ToySchema.add({ name: 'string', color: 'string', price: 'number' });
schema.eachPath(function(path: string, value: any) {});
schema.index({ first: 1, last: -1 });
schema.indexes();
schema.method('meow', function() {
console.log('meeeeeoooooooooooow');
});
var Kitty = mongoose.model<IActor>('Kitty', schema);
var fizz: any = new Kitty({ name: 'kitty' });
fizz.meow();
schema.method({
purr: function() {},
scratch: function() {},
});
schema.path('name');
schema.path('name', Number);
schema.pathType('name');
schema.plugin(function() {});
schema.post('save', function(doc: IActor) {});
schema.pre('save', function(next: () => void) {});
schema.requiredPaths();
schema.static('findByName', function(name: string, callback: () => void) {});
schema.virtual('display_name')
.get(function(): string { return this.name; })
.set((value: string): void => {});
+453
View File
@@ -0,0 +1,453 @@
// Type definitions for Mongoose 3.8.5
// Project: http://mongoosejs.com/
// Definitions by: horiuchi <https://github.com/horiuchi/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../node/node.d.ts" />
declare module "mongoose" {
function connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose;
function createConnection(): Connection;
function createConnection(uri: string, options?: ConnectionOption): Connection;
function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection;
function disconnect(callback?: (err?: any) => void): Mongoose;
function model<T extends Document>(name: string, schema: Schema, collection?: string, skipInit?: boolean): Model<T>;
function modelNames(): string[];
function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose;
function get(key: string): any;
function set(key: string, value: any): void;
var mongo: any;
var mquery: any;
var version: string;
var connection: Connection;
export class Mongoose {
connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose;
createConnection(): Connection;
createConnection(uri: string, options?: Object): Connection;
createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection;
disconnect(callback?: (err?: any) => void): Mongoose;
get(key: string): any;
model<T extends Document>(name: string, schema: Schema, collection?: string, skipInit?: boolean): Model<T>;
modelNames(): string[];
plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose;
set(key: string, value: any): void;
mongo: any;
mquery: any;
version: string;
connection: Connection;
}
export interface Connection extends NodeJS.EventEmitter {
constructor(base: Mongoose): Connection;
close(callback?: (err: any) => void): Connection;
collection(name: string, options?: Object): Collection;
model<T extends Document>(name: string, schema: Schema, collection?: string): Model<T>;
modelNames(): string[];
open(host: string, database?: string, port?: number, options?: ConnectionOption, callback?: (err: any) => void): Connection;
openSet(uris: string, database?: string, options?: ConnectionSetOption, callback?: (err: any) => void): Connection;
db: any;
collections: {[index: string]: Collection};
readyState: number;
}
export interface ConnectionOption {
db?: any;
server?: any;
replset?: any;
user?: string;
pass?: string;
auth?: any;
}
export interface ConnectionSetOption extends ConnectionOption {
mongos?: boolean;
}
export interface Collection {
}
export class SchemaType { }
export class VirtualType {
get(fn: Function): VirtualType;
set(fn: Function): VirtualType;
}
export module Types {
export class ObjectId {}
}
export class Schema {
static Types: {
String: String;
ObjectId: Types.ObjectId;
OId: Types.ObjectId;
Mixed: any;
};
constructor(schema?: Object, options?: Object);
add(obj: Object, prefix?: string): void;
eachPath(fn: (path: string, type: any) => void): Schema;
get(key: string): any;
index(fields: Object, options?: Object): Schema;
indexes(): void;
method(name: string, fn: Function): Schema;
method(method: Object): Schema;
path(path: string): any;
path(path: string, constructor: any): Schema;
pathType(path: string): string;
plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema;
post(method: string, fn: Function): Schema;
pre(method: string, callback: Function): Schema;
requiredPaths(): string[];
set(key: string, value: any): void;
static(name: string, fn: Function): Schema;
virtual(name: string, options?: Object): VirtualType;
virtualpath(name: string): VirtualType;
}
export interface SchemaOption {
autoIndex?: boolean;
bufferCommands?: boolean;
capped?: boolean;
collection?: string;
id?: boolean;
_id?: boolean;
minimize?: boolean;
read?: string;
safe?: boolean;
shardKey?: boolean;
strict?: boolean;
toJSON?: Object;
toObject?: Object;
versionKey?: boolean;
}
export interface Model<T extends Document> {
new(doc: Object): T;
aggregate(...aggregations: Object[]): Aggregate<T[]>;
aggregate(aggregation: Object, callback: (err: any, res: T[]) => void): Promise<T[]>;
aggregate(aggregation1: Object, aggregation2: Object, callback: (err: any, res: T[]) => void): Promise<T[]>;
aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise<T[]>;
count(conditions: Object, callback?: (err: any, count: number) => void): Query<number>;
create(doc: Object, fn?: (err: any, res: T) => void): Promise<T[]>;
create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise<T[]>;
create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise<T[]>;
discriminator<U extends Document>(name: string, schema: Schema): Model<U>;
distinct(field: string, callback?: (err: any, res: T[]) => void): Query<T[]>;
distinct(field: string, conditions: Object, callback?: (err: any, res: T[]) => void): Query<T[]>;
ensureIndexes(callback: (err: any) => void): Promise<T>;
find(cond: Object, callback?: (err: any, res: T[]) => void): Query<T[]>;
find(cond: Object, fields: Object, callback?: (err: any, res: T[]) => void): Query<T[]>;
find(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T[]) => void): Query<T[]>;
findById(id: string, callback?: (err: any, res: T) => void): Query<T>;
findById(id: string, fields: Object, callback?: (err: any, res: T) => void): Query<T>;
findById(id: string, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query<T>;
findByIdAndRemove(id: string, callback?: (err: any, res: T) => void): Query<T>;
findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query<T>;
findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query<T>;
findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query<T>;
findOne(cond: Object, callback?: (err: any, res: T) => void): Query<T>;
findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query<T>;
findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query<T>;
findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query<T>;
findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query<T>;
findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query<T>;
findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query<T>;
geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[]) => void): Query<T[]>;
geoNear(point: number[], options: Object, callback?: (err: any, res: T[]) => void): Query<T[]>;
geoSearch(cond: Object, options: GeoSearchOption, callback?: (err: any, res: T[]) => void): Query<T[]>;
increment(): T;
mapReduce<K, V>(options: MapReduceOption<T, K, V>, callback?: (err: any, res: MapReduceResult<K, V>[]) => void): Promise<MapReduceResult<K, V>[]>;
mapReduce<K, V>(options: MapReduceOption2<T, K, V>, callback?: (err: any, res: MapReduceResult<K, V>[]) => void): Promise<MapReduceResult<K, V>[]>;
model<U extends Document>(name: string): Model<U>;
populate<U>(doc: U, options: Object, callback?: (err: any, res: U) => void): Promise<U>;
populate<U>(doc: U[], options: Object, callback?: (err: any, res: U[]) => void): Promise<U[]>;
update(cond: Object, update: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query<T>;
update(cond: Object, update: Object, options: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query<T>;
remove(cond: Object, callback?: (err: any) => void): Query<{}>;
save(callback?: (err: any, result: T, numberAffected: number) => void): Query<T>;
where(path: string, val?: Object): Query<T[]>;
$where(argument: string): Query<T>;
$where(argument: Function): Query<T>;
base: Mongoose;
collection: Collection;
db: any;
discriminators: any;
modelName: string;
schema: Schema;
}
export interface FindAndUpdateOption {
new?: boolean;
upsert?: boolean;
sort?: Object;
select?: Object;
}
export interface GeoSearchOption {
near: number[];
maxDistance: number;
limit?: number;
lean?: boolean;
}
export interface MapReduceOption<T extends Document, Key, Val> {
map: () => void;
reduce: (key: Key, vals: T[]) => Val;
query?: Object;
limit?: number;
keeptemp?: boolean;
finalize?: (key: Key, val: Val) => Val;
scope?: Object;
jsMode?: boolean;
verbose?: boolean;
out?: {
inline?: number;
replace?: string;
reduce?: string;
merge?: string;
};
}
export interface MapReduceOption2<T extends Document, Key, Val> {
map: string;
reduce: (key: Key, vals: T[]) => Val;
query?: Object;
limit?: number;
keeptemp?: boolean;
finalize?: (key: Key, val: Val) => Val;
scope?: Object;
jsMode?: boolean;
verbose?: boolean;
out?: {
inline?: number;
replace?: string;
reduce?: string;
merge?: string;
};
}
export interface MapReduceResult<Key, Val> {
_id: Key;
value: Val;
}
export class Query<T> {
exec(callback?: (err: any, res: T) => void): Promise<T>;
exec(operation: string, callback?: (err: any, res: T) => void): Promise<T>;
exec(operation: Function, callback?: (err: any, res: T) => void): Promise<T>;
all(val: number): Query<T>;
all(path: string, val: number): Query<T>;
and(array: Object[]): Query<T>;
box(val: Object): Query<T>;
box(a: number[], b: number[]): Query<T>;
batchSize(val: number): Query<T>;
cast<U extends Document>(model: Model<U>, obj: Object): U;
//center(): Query<T>;
//centerSphere(path: string, val: Object): Query<T>;
circle(area: Object): Query<T>;
circle(path: string, area: Object): Query<T>;
comment(val: any): Query<T>;
count(callback?: (err: any, count: number) => void): Query<T>;
count(criteria: Object, callback?: (err: any, count: number) => void): Query<T>;
distinct(callback?: (err: any, res: T) => void): Query<T>;
distinct(field: string, callback?: (err: any, res: T) => void): Query<T>;
distinct(criteria: Object, field: string, callback?: (err: any, res: T) => void): Query<T>;
distinct(criteria: Query<T>, field: string, callback?: (err: any, res: T) => void): Query<T>;
elemMatch(criteria: Object): Query<T>;
elemMatch(criteria: (elem: Query<T>) => void): Query<T>;
elemMatch(path: string, criteria: Object): Query<T>;
elemMatch(path: string, criteria: (elem: Query<T>) => void): Query<T>;
equals(val: Object): Query<T>;
exists(val?: boolean): Query<T>;
exists(path: string, val?: boolean): Query<T>;
find(callback?: (err: any, res: T) => void): Query<T>;
find(criteria: Object, callback?: (err: any, res: T) => void): Query<T>;
findOne(callback?: (err: any, res: T) => void): Query<T>;
findOne(criteria: Object, callback?: (err: any, res: T) => void): Query<T>;
findOneAndRemove(callback?: (err: any, res: T) => void): Query<T>;
findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query<T>;
findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query<T>;
findOneAndUpdate(callback?: (err: any, res: T) => void): Query<T>;
findOneAndUpdate(update: Object, callback?: (err: any, res: T) => void): Query<T>;
findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query<T>;
findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query<T>;
geometry(object: Object): Query<T>;
gt(val: number): Query<T>;
gt(path: string, val: number): Query<T>;
gte(val: number): Query<T>;
gte(path: string, val: number): Query<T>;
hint(val: Object): Query<T>;
in(val: any[]): Query<T>;
in(path: string, val: any[]): Query<T>;
intersects(arg?: Object): Query<T>;
lean(bool?: boolean): Query<T>;
limit(val: number): Query<T>;
lt(val: number): Query<T>;
lt(path: string, val: number): Query<T>;
lte(val: number): Query<T>;
lte(path: string, val: number): Query<T>;
maxDistance(val: number): Query<T>;
maxDistance(path: string, val: number): Query<T>;
maxScan(val: number): Query<T>;
merge(source: Query<T>): Query<T>;
merge(source: Object): Query<T>;
mod(val: number[]): Query<T>;
mod(path: string, val: number[]): Query<T>;
ne(val: any): Query<T>;
ne(path: string, val: any): Query<T>;
near(val: Object): Query<T>;
near(path: string, val: Object): Query<T>;
nearSphere(val: Object): Query<T>;
nearSphere(path: string, val: Object): Query<T>;
nin(val: any[]): Query<T>;
nin(path: string, val: any[]): Query<T>;
nor(array: Object[]): Query<T>;
or(array: Object[]): Query<T>;
polygon(...coordinatePairs: number[][]): Query<T>;
polygon(path: string, ...coordinatePairs: number[][]): Query<T>;
populate(path: string, select?: string, match?: Object, options?: Object): Query<T>;
populate(path: string, select: string, model: string, match?: Object, options?: Object): Query<T>;
populate(opt: PopulateOption): Query<T>;
read(pref: string, tags?: Object[]): Query<T>;
regex(val: RegExp): Query<T>;
regex(path: string, val: RegExp): Query<T>;
remove(callback?: (err: any, res: T) => void): Query<T>;
remove(criteria: Object, callback?: (err: any, res: T) => void): Query<T>;
select(arg: string): Query<T>;
select(arg: Object): Query<T>;
setOptions(options: Object): Query<T>;
size(val: number): Query<T>;
size(path: string, val: number): Query<T>;
skip(val: number): Query<T>;
slaveOk(v?: boolean): Query<T>;
slice(val: number): Query<T>;
slice(val: number[]): Query<T>;
slice(path: string, val: number): Query<T>;
slice(path: string, val: number[]): Query<T>;
snapshot(v?: boolean): Query<T>;
sort(arg: Object): Query<T>;
sort(arg: string): Query<T>;
stream(options?: { transform?: Function; }): QueryStream;
tailable(v?: boolean): Query<T>;
toConstructor(): Query<T>;
update(callback?: (err: any, affectedRows: number, doc: T) => void): Query<T>;
update(doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query<T>;
update(criteria: Object, doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query<T>;
update(criteria: Object, doc: Object, options: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query<T>;
where(path?: string, val?: any): Query<T>;
where(path?: Object, val?: any): Query<T>;
within(val?: Object): Query<T>;
within(coordinate: number[], ...coordinatePairs: number[][]): Query<T>;
$where(argument: string): Query<T>;
$where(argument: Function): Query<T>;
static use$geoWithin: boolean;
}
export interface PopulateOption {
path: string;
select?: string;
model?: string;
match?: Object;
options?: Object;
}
export interface QueryStream extends NodeJS.EventEmitter {
destory(err?: any): void;
pause(): void;
resume(): void;
pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
paused: number;
readable: boolean;
}
export interface Document {
id?: string;
_id: string;
equals(doc: Document): boolean;
get(path: string, type?: new(...args: any[]) => any): any;
inspect(options?: Object): string;
invalidate(path: string, errorMsg: string, value: any): void;
invalidate(path: string, error: Error, value: any): void;
isDirectModified(path: string): boolean;
isInit(path: string): boolean;
isModified(path?: string): boolean;
isSelected(path: string): boolean;
markModified(path: string): void;
modifiedPaths(): string[];
populate<T>(callback?: (err: any, res: T) => void): Document;
populate<T>(path?: string, callback?: (err: any, res: T) => void): Document;
populate<T>(opt: PopulateOption, callback?: (err: any, res: T) => void): Document;
populated(path: string): any;
remove<T>(callback?: (err: any) => void): Query<T>;
save<T>(callback?: (err: any, res: T) => void): void;
set(path: string, val: any, type?: new(...args: any[]) => any, options?: Object): void;
set(path: string, val: any, options?: Object): void;
set(value: Object): void;
toJSON(options?: Object): Object;
toObject(options?: Object): Object;
toString(): string;
update<T>(doc: Object, options: Object, callback: (err: any, affectedRows: number, raw: any) => void): Query<T>;
validate(cb: (err: any) => void): void;
isNew: boolean;
errors: Object;
schema: Object;
}
export class Aggregate<T> {
constructor(...options: Object[]);
append(...options: Object[]): Aggregate<T>;
group(arg: Object): Aggregate<T>;
limit(num: number): Aggregate<T>;
match(arg: Object): Aggregate<T>;
near(parameters: Object): Aggregate<T>;
project(arg: string): Aggregate<T>;
project(arg: Object): Aggregate<T>;
select(filter: string): Aggregate<T>;
skip(num: number): Aggregate<T>;
sort(arg: string): Aggregate<T>;
sort(arg: Object): Aggregate<T>;
unwind(fiels: string, ...rest: string[]): Aggregate<T>;
exec(callback?: (err: any, result: T) => void): Promise<T>;
read(pref: string, ...tags: Object[]): Aggregate<T>;
}
export class Promise<T> {
constructor(fn?: (err: any, result: T) => void);
then<U>(onFulFill: (result: T) => void, onReject?: (err: any) => void): Promise<U>;
end(): void;
fulfill(result: T): Promise<T>;
reject(err: any): Promise<T>;
resolve(err: any, result: T): Promise<T>;
onFulfill(listener: (result: T) => void): Promise<T>;
onReject(listener: (err: any) => void): Promise<T>;
onResolve(listener: (err: any, result: T) => void): Promise<T>;
on(event: string, listener: Function): Promise<T>;
// Deprecated methods.
addBack(listener: (err: any, result: T) => void): Promise<T>;
addCallback(listener: (result: T) => void): Promise<T>;
addErrback(listener: (err: any) => void): Promise<T>;
complete(result: T): Promise<T>;
error(err: any): Promise<T>;
}
}
+287 -1
View File
@@ -1,4 +1,5 @@
/// <reference path="ng-grid.d.ts" />
/// <reference path="ng-grid.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
var options1: ngGrid.IGridOptions = {
data: [{ 'Name': 'Bob' }, { 'Name': 'Jane' }]
@@ -25,3 +26,288 @@ var options4: ngGrid.IGridOptions = {
currentPage: 1
}
};
var columnDef: ngGrid.IColumnDef = {
width:{},
minWidth:{},
visible:false,
field:'',
displayName:'',
sortable:false,
resizable:false,
groupable:false,
pinnable:false,
editableCellTemplate:'',
enableCellEdit:false,
cellEditableCondition:'',
sortFn:(a:any, b:any):number=> { return 0 },
cellTemplate:'',
cellClass:'',
headerClass:'',
headerCellTemplate:'',
cellFilter:'',
aggLabelFilter:'',
pinned:false
}
var searchProvider: ngGrid.ISearchProvider = <ngGrid.ISearchProvider>{};
searchProvider.fieldMap = {};
searchProvider.extFilter = false;
searchProvider.evalFilter();
var nr:number;
var selectionProvider: ngGrid.ISelectionProvider = <ngGrid.ISelectionProvider>{};
selectionProvider.multi = false;
selectionProvider.selectedItems = [];
selectionProvider.selectedIndex = 1;
selectionProvider.lastClickedRow = {};
selectionProvider.ignoreSelectedItemChanges = false;
selectionProvider.pKeyParser = <ng.ICompiledExpression>{};
selectionProvider.ChangeSelection({}, {});
nr = selectionProvider.getSelection({});
nr = selectionProvider.getSelectionIndex({});
selectionProvider.setSelection(<ngGrid.IRow>{}, false);
selectionProvider.toggleSelectAll(true, false, false);
var eventProvider: ngGrid.IEventProvider = <ngGrid.IEventProvider>{};
eventProvider.colToMove = <ngGrid.IColumn>{};
eventProvider.groupToMove = {};
eventProvider.assignEvents();
eventProvider.assignGridEventHandlers();
eventProvider.dragStart({});
eventProvider.dragOver({});
eventProvider.setDraggables();
eventProvider.onGroupMouseDown({});
eventProvider.onGroupDrop({});
eventProvider.onHeaderMouseDown({});
eventProvider.onHeaderDrop({});
var aggregate: ngGrid.IAggregate = <ngGrid.IAggregate>{};
aggregate.rowIndex = 0;
aggregate.offsetTop = 0;
aggregate.entity = {};
aggregate.label = '';
aggregate.field = '';
aggregate.depth = 0;
aggregate.parent = {};
aggregate.children = [];
aggregate.aggChildren = [];
aggregate.aggIndex = 0;
aggregate.collapsed = false;
aggregate.groupInitState = false;
aggregate.rowFactory = <ngGrid.IRowFactory>{};
aggregate.rowHeight = 0;
aggregate.isAggRow = false;
aggregate.offsetLeft = 0;
aggregate.aggLabelFilter = {};
var rowConfig: ngGrid.IRowConfig = <ngGrid.IRowConfig>{};
rowConfig.enableCellSelection = false;
rowConfig.enableRowSelection = false;
rowConfig.jqueryUITheme = false;
rowConfig.rowClasses = [''];
rowConfig.rowHeight = 0;
rowConfig.selectWithCheckboxOnly = false;
rowConfig.selectedItems = [];
rowConfig.afterSelectionChangeCallback();
rowConfig.beforeSelectionChangeCallback();
var renderedRange: ngGrid.IRenderedRange = <ngGrid.IRenderedRange>{};
renderedRange.bottomRow = 0;
renderedRange.topRow = 0;
var rowFactory: ngGrid.IRowFactory = <ngGrid.IRowFactory>{};
rowFactory.aggCache= null;
rowFactory.dataChanged= false;
rowFactory.groupedData= null;
rowFactory.numberOfAggregates = 0;
rowFactory.parentCache= [];
rowFactory.parsedData= [];
rowFactory.renderedRange = <ngGrid.IRenderedRange>{};
rowFactory.rowConfig = <ngGrid.IRowConfig>{};
rowFactory.rowHeight = 0;
rowFactory.selectionProvider = <ngGrid.ISelectionProvider>{};
rowFactory.UpdateViewableRange(<ngGrid.IRenderedRange>{});
aggregate = rowFactory.buildAggregateRow({}, 0);
var row:ngGrid.IRow = rowFactory.buildEntityRow({}, 0);
rowFactory.filteredRowsChanged();
rowFactory.fixRowCache();
rowFactory.getGrouping({});
rowFactory.parseGroupData({});
rowFactory.renderedChange();
rowFactory.renderedChangeNoGroups();
var dimension: ngGrid.IDimension = <ngGrid.IDimension>{};
dimension.outerHeight = 0;
dimension.outerWidth = 0;
dimension.autoFitHeight = false;
var elmDimension: ngGrid.IElementDimension = <ngGrid.IElementDimension>{};
elmDimension.rootMaxH = 0;
elmDimension.rootMaxW = 0;
elmDimension.rowIndexCellW = 0;
elmDimension.rowSelectedCellW = 0;
elmDimension.scrollH = 0;
elmDimension.scrollW = 0;
var row: ngGrid.IRow = <ngGrid.IRow>{};
row.entity= {};
row.config = <ngGrid.IRowConfig>{};
row.selectionProvider = <ngGrid.ISelectionProvider>{};
row.rowIndex = 0;
row.utils= {};
row.selected = false;
row.cursor = '';
row.offsetTop = 0;
row.rowDisplayIndex = 0;
row.afterSelectionChange();
row.beforeSelectionChange();
row.setSelection(false);
row.continueSelection({});
row.ensureEntity({});
var b:boolean = row.toggleSelected({});
row.alternatingRowClass();
var a:any = row.getProperty('');
var r:ngGrid.IRow = row.copy();
row.setVars(<ngGrid.IRow>{});
var column: ngGrid.IColumn = <ngGrid.IColumn>{};
column.colDef = <ngGrid.IColumnDef>{};
column.width = 0;
column.groupIndex = 0;
column.isGroupedBy = false;
column.minWidth = 0;
column.maxWidth = 0;
column.enableCellEdit = false;
column.cellEditableCondition = {};
column.headerRowHeight = 0;
column.displayName = '';
column.index = 0;
column.isAggCol = false;
column.cellClass = '';
column.sortPriority = 0;
column.cellFilter = {};
column.field = '';
column.aggLabelFilter = {};
column.visible = false;
column.sortable = false;
column.resizable = false;
column.pinnable = false;
column.pinned = false;
column.originalIndex = 0;
column.groupable = false;
column.sortDirection = '';
column.sortingAlgorithm = ()=>{};
column.headerClass = '';
column.cursor = '';
column.headerCellTemplate = '';
column.cellTemplate = '';
var s:string = column.groupedByClass();
column.toggleVisible();
b = column.showSortButtonUp();
b = column.showSortButtonDown();
b = column.noSortVisible();
b = column.sort({});
a = column.gripClick();
a = column.gripOnMouseDown({});
column.onMouseMove({});
column.gripOnMouseUp({});
var c:ngGrid.IColumn = column.copy();
column.setVars(c);
var gridScope: ngGrid.IGridScope = <ngGrid.IGridScope>{};
gridScope.elementsNeedMeasuring = false;
gridScope.columns = [];
gridScope.renderedRows = [];
gridScope.renderedColumns = [];
gridScope.headerRow = {};
gridScope.rowHeight = 0;
gridScope.jqueryUITheme = {};
gridScope.showSelectionCheckbox = false;
gridScope.enableCellSelection = false;
gridScope.enableCellEditOnFocus = false;
gridScope.footer = <ngGrid.IFooter>{};
gridScope.selectedItems = [];
gridScope.multiSelect = false;
gridScope.showFooter = false;
gridScope.footerRowHeight = 0;
gridScope.showColumnMenu = false;
gridScope.forceSyncScrolling = false;
gridScope.showMenu = false;
gridScope.configGroups = [];
gridScope.gridId = '';
gridScope.enablePaging = false;
gridScope.pagingOptions = <ngGrid.IPagingOptions>{};
gridScope.i18n = {};
gridScope.selectionProvider = <ngGrid.ISelectionProvider>{};
gridScope.adjustScrollLeft(0);
gridScope.adjustScrollTop(0, true);
gridScope.toggleShowMenu();
gridScope.toggleSelectAll();
nr = gridScope.totalFilteredItemsLength();
a = gridScope.showGroupPanel();
nr = gridScope.topPanelHeight();
nr = gridScope.viewportDimHeight();
gridScope.groupBy(<ngGrid.IColumn>{});
gridScope.removeGroup(0);
gridScope.togglePin(<ngGrid.IColumn>{});
nr = gridScope.totalRowWidth();
a = gridScope.headerScrollerDim();
var gridInstance: ngGrid.IGridInstance = <ngGrid.IGridInstance>{};
gridInstance.$canvas = <ng.IAugmentedJQuery>{};
gridInstance.$viewport = <ng.IAugmentedJQuery>{};
gridInstance.$groupPanel = <ng.IAugmentedJQuery>{};
gridInstance.$footerPanel = <ng.IAugmentedJQuery>{};
gridInstance.$headerScroller = <ng.IAugmentedJQuery>{};
gridInstance.$headerContainer = <ng.IAugmentedJQuery>{};
gridInstance.$headers = <ng.IAugmentedJQuery>{};
gridInstance.$topPanel = <ng.IAugmentedJQuery>{};
gridInstance.$root = <ng.IAugmentedJQuery>{};
gridInstance.config = <ngGrid.IGridOptions>{};
gridInstance.data = {};
gridInstance.elementDims = <ngGrid.IElementDimension>{};
gridInstance.eventProvider = <ngGrid.IEventProvider>{};
gridInstance.filteredRows = [<ngGrid.IRow>{}];
gridInstance.footerController = {};
gridInstance.gridId = '';
gridInstance.lastSortedColumns = [<ngGrid.IColumn>{}];
gridInstance.lateBindColumns = false;
gridInstance.maxCanvasHt = 0;
gridInstance.prevScrollIndex = 0;
gridInstance.prevScrollTop = 0;
gridInstance.rootDim = <ngGrid.IDimension>{};
gridInstance.rowCache = [<ngGrid.IRow>{}];
gridInstance.rowFactory = <ngGrid.IRowFactory>{};
gridInstance.rowMap = [<ngGrid.IRow>{}];
gridInstance.searchProvider = <ngGrid.ISearchProvider>{};
gridInstance.styleProvider = <ngGrid.IStyleProvider>{};
gridInstance.buildColumnDefsFromData();
gridInstance.buildColumns();
gridInstance.calcMaxCanvasHeight();
gridInstance.clearSortingData();
gridInstance.configureColumnWidths();
gridInstance.fixColumnIndexes();
gridInstance.fixGroupIndexes();
var p:ng.IPromise<any> = gridInstance.getTemplate('');
p = gridInstance.init();
p = gridInstance.initTemplates();
gridInstance.minRowsToRender();
gridInstance.refreshDomSizes();
gridInstance.resizeOnData(<ngGrid.IColumn>{});
gridInstance.setRenderedRows([<ngGrid.IRow>{}]);
gridInstance.sortActual();
gridInstance.sortColumnsInit();
gridInstance.sortData(<ngGrid.IColumn>{}, {});
var test_styleProvider:ngGrid.IStyleProvider = new ngStyleProvider(<ngGrid.IGridScope>{}, <ngGrid.IGridInstance>{});
var test_searchProvider:ngGrid.ISearchProvider = new ngSearchProvider(<ngGrid.IGridScope>{}, <ngGrid.IGridInstance>{}, <ng.IFilterService>{});
var test_selectionProvider:ngGrid.ISelectionProvider = new ngSelectionProvider(<ngGrid.IGridInstance>{}, <ngGrid.IGridScope>{}, <ng.IParseService>{});
var test_eventProvider:ngGrid.IEventProvider = new ngEventProvider(<ngGrid.IGridInstance>{}, <ngGrid.IGridScope>{}, <ngGrid.service.IDomUtilityService>{}, <ng.ITimeoutService>{});
var test_aggregate:ngGrid.IAggregate = new ngAggregate({}, <ngGrid.IRowFactory>{}, 10, true);
var test_renderedRange:ngGrid.IRenderedRange = new ngRenderedRange(1, 2);
var test_dimension:ngGrid.IDimension = new ngDimension({});
var test_row:ngGrid.IRow = new ngRow({}, <ngGrid.IRowConfig>{}, <ngGrid.ISelectionProvider>{}, 0, {});
var test_column:ngGrid.IColumn = new ngColumn(<ngGrid.IGridOptions>{}, <ngGrid.IGridScope>{}, <ngGrid.IGridInstance>{}, <ngGrid.service.IDomUtilityService>{}, <ng.ITemplateCacheService>{}, {});
var test_footer:ngGrid.IFooter = new ngFooter(<ngGrid.IGridScope>{}, <ngGrid.IGridInstance>{});
+453 -5
View File
@@ -1,23 +1,358 @@
// Type definitions for ng-grid
// Project: http://angular-ui.github.io/ng-grid/
// Definitions by: Ken Smith <https://github.com/smithkl42>
// Definitions by: Ken Smith <https://github.com/smithkl42> and Roland Zwaga <https://github.com/rolandzwaga> and Kent Cooper <https://github.com/kentcooper>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
// These are very definitely preliminary. Please feel free to improve.
// Changelog:
// 25/4/2014: Added interfaces for all classes and services
/// <reference path='../angularjs/angular.d.ts' />
declare class ngGridReorderable {
constructor();
}
declare var ngStyleProvider:ngGrid.IStyleProviderStatic;
declare var ngSearchProvider:ngGrid.ISearchProviderStatic;
declare var ngSelectionProvider:ngGrid.ISelectionProviderStatic;
declare var ngEventProvider:ngGrid.IEventProviderStatic;
declare var ngAggregate:ngGrid.IAggregateStatic;
declare var ngRenderedRange:ngGrid.IRenderedRangeStatic;
declare var ngDimension:ngGrid.IDimensionStatic;
declare var ngRow:ngGrid.IRowStatic;
declare var ngColumn:ngGrid.IColumnStatic;
declare var ngFooter:ngGrid.IFooterStatic;
declare module ngGrid {
export interface IDomAccessProvider {
previousColumn:IColumn;
grid:IGridInstance;
changeUserSelect(elm:ng.IAugmentedJQuery, value:string):void;
focusCellElement($scope:IGridScope, index:number):void;
selectionHandlers($scope:IGridScope, elm:ng.IAugmentedJQuery):void;
}
export interface IStyleProviderStatic {
new($scope:IGridScope, grid:IGridInstance):IStyleProvider;
}
export interface IStyleProvider {
}
export interface ISearchProviderStatic {
new($scope:IGridScope, grid:IGridInstance, $filter:ng.IFilterService):ISearchProvider;
}
export interface ISearchProvider {
fieldMap:any;
extFilter:boolean;
evalFilter():void;
}
export interface ISelectionProviderStatic {
new(grid:IGridInstance, $scope:IGridScope, $parse:ng.IParseService):ISelectionProvider;
}
export interface ISelectionProvider {
multi:boolean;
selectedItems:any[];
selectedIndex:number;
lastClickedRow:any;
ignoreSelectedItemChanges:boolean;
pKeyParser:ng.ICompiledExpression;
ChangeSelection(rowItem:any, event:any):void;
getSelection(entity:any):number;
getSelectionIndex(entity:any):number;
setSelection(rowItem:IRow, isSelected:boolean):void;
toggleSelectAll(checkAll:boolean, bypass:boolean, selectFiltered:boolean):void;
}
export interface IEventProviderStatic {
new(grid:IGridInstance, $scope:IGridScope, domUtilityService:service.IDomUtilityService, $timeout:ng.ITimeoutService):IEventProvider;
}
export interface IEventProvider {
colToMove:IColumn;
groupToMove:any;
assignEvents():void;
assignGridEventHandlers():void;
dragStart(event:any):void;
dragOver(event:any):void;
setDraggables():void;
onGroupMouseDown(event:any):void;
onGroupDrop(event:any):void;
onHeaderMouseDown(event:any):void;
onHeaderDrop(event:any):void;
}
export interface IAggregateStatic {
new(aggEntity:any, rowFactory:IRowFactory, rowHeight:number, groupInitState:boolean):IAggregate;
}
export interface IAggregate {
rowIndex:number;
offsetTop:number;
entity:any;
label:string;
field:string;
depth:number;
parent:any;
children:any[];
aggChildren:any[];
aggIndex:number;
collapsed:boolean;
groupInitState:boolean;
rowFactory:IRowFactory;
rowHeight:number;
isAggRow:boolean;
offsetLeft:number;
aggLabelFilter:any;
}
export interface IRowConfig {
enableCellSelection:boolean;
enableRowSelection:boolean;
jqueryUITheme:boolean;
rowClasses:string[];
rowHeight:number;
selectWithCheckboxOnly:boolean;
selectedItems:any[];
afterSelectionChangeCallback():void;
beforeSelectionChangeCallback():void;
}
export interface IRenderedRangeStatic {
new(top:number, bottom:number):IRenderedRange;
}
export interface IRenderedRange {
bottomRow:number;
topRow:number;
}
export interface IRowFactory {
aggCache:any;
dataChanged:boolean;
groupedData:any;
numberOfAggregates:number;
parentCache:any[];
parsedData:any[];
renderedRange:IRenderedRange;
rowConfig:IRowConfig;
rowHeight:number;
selectionProvider:ISelectionProvider;
UpdateViewableRange(newRange:IRenderedRange):void;
buildAggregateRow(aggEntity:any, rowIndex:number):IAggregate;
buildEntityRow(entity:any, rowIndex:number):IRow;
filteredRowsChanged():void;
fixRowCache():void;
getGrouping(groups:any):void;
parseGroupData(groupData:any):void;
renderedChange():void;
renderedChangeNoGroups():void;
}
export interface IDimensionStatic {
new(options:any):IDimension;
}
export interface IDimension {
outerHeight?:number;
outerWidth?:number;
autoFitHeight?:boolean;
}
export interface IElementDimension {
rootMaxH?:number;
rootMaxW?:number;
rowIndexCellW?:number;
rowSelectedCellW?:number;
scrollH?:number;
scrollW?:number;
}
export interface IRowStatic {
new(entity:any, config:IRowConfig, selectionProvider:ISelectionProvider, rowIndex:number, $utils:any):IRow;
}
export interface IRow {
entity:any;
config:IRowConfig;
selectionProvider:ISelectionProvider;
rowIndex:number;
utils:any;
selected:boolean;
cursor:string;
offsetTop:number;
rowDisplayIndex:number;
afterSelectionChange():void;
beforeSelectionChange():void;
setSelection(isSelected:boolean):void;
continueSelection(event:any):void;
ensureEntity(expected:any):void;
toggleSelected(event:any):boolean;
alternatingRowClass():void;
getProperty(path:string):any;
copy():IRow;
setVars(fromRow:IRow):void;
}
export interface IColumnStatic {
new(config:IGridOptions, $scope:IGridScope, grid:IGridInstance, domUtilityService:service.IDomUtilityService, $templateCache:ng.ITemplateCacheService, $utils:any):IColumn;
}
export interface IColumn {
colDef:IColumnDef;
width:number;
groupIndex:number;
isGroupedBy:boolean;
minWidth:number;
maxWidth:number;
enableCellEdit:boolean;
cellEditableCondition:any;
headerRowHeight:number;
displayName:string;
index:number;
isAggCol:boolean;
cellClass:string;
sortPriority:number;
cellFilter:any;
field:string;
aggLabelFilter:any;
visible:boolean;
sortable:boolean;
resizable:boolean;
pinnable:boolean;
pinned:boolean;
originalIndex:number;
groupable:boolean;
sortDirection:string;
sortingAlgorithm:Function;
headerClass:string;
cursor:string;
headerCellTemplate:string;
cellTemplate:string;
groupedByClass():string;
toggleVisible():void;
showSortButtonUp():boolean;
showSortButtonDown():boolean;
noSortVisible():boolean;
sort(event:any):boolean;
gripClick():any;
gripOnMouseDown(event:any):any;
onMouseMove(event:any):void;
gripOnMouseUp(event:any):void;
copy():IColumn;
setVars(fromCol:IColumn):void;
}
export interface IGridScope extends ng.IScope {
elementsNeedMeasuring:boolean;
columns:any[];
renderedRows:any[];
renderedColumns:any[];
headerRow:any;
rowHeight:number;
jqueryUITheme:any;
showSelectionCheckbox:boolean;
enableCellSelection:boolean;
enableCellEditOnFocus:boolean;
footer:IFooter;
selectedItems:any[];
multiSelect:boolean;
showFooter:boolean;
footerRowHeight:number;
showColumnMenu:boolean;
forceSyncScrolling:boolean;
showMenu:boolean;
configGroups:any[];
gridId:string;
enablePaging:boolean;
pagingOptions:IPagingOptions;
i18n:any;
selectionProvider:ISelectionProvider;
adjustScrollLeft(scrollLeft:number):void;
adjustScrollTop(scrollTop:number, force:boolean):void;
toggleShowMenu():void;
toggleSelectAll():void;
totalFilteredItemsLength():number;
showGroupPanel():any;
topPanelHeight():number;
viewportDimHeight():number;
groupBy(col:IColumn):void;
removeGroup(index:number):void;
togglePin(col:IColumn):void;
totalRowWidth():number;
headerScrollerDim():any;
}
export interface IGridInstance {
$canvas:ng.IAugmentedJQuery;
$viewport:ng.IAugmentedJQuery;
$groupPanel:ng.IAugmentedJQuery;
$footerPanel:ng.IAugmentedJQuery;
$headerScroller:ng.IAugmentedJQuery;
$headerContainer:ng.IAugmentedJQuery;
$headers:ng.IAugmentedJQuery;
$topPanel:ng.IAugmentedJQuery;
$root:ng.IAugmentedJQuery;
config:IGridOptions;
data:any;
elementDims:IElementDimension;
eventProvider:IEventProvider;
filteredRows:IRow[];
footerController:any;
gridId:string;
lastSortedColumns:IColumn[];
lateBindColumns:boolean;
maxCanvasHt:number;
prevScrollIndex:number;
prevScrollTop:number;
rootDim:IDimension;
rowCache:IRow[];
rowFactory:IRowFactory;
rowMap:IRow[];
searchProvider:ISearchProvider;
styleProvider:IStyleProvider;
buildColumnDefsFromData():void;
buildColumns():void;
calcMaxCanvasHeight():void;
clearSortingData():void;
configureColumnWidths():void;
fixColumnIndexes():void;
fixGroupIndexes():void;
getTemplate(key:string):ng.IPromise<any>;
init():ng.IPromise<any>;
initTemplates():ng.IPromise<any>;
minRowsToRender():void;
refreshDomSizes():void;
resizeOnData(col:IColumn):void;
setRenderedRows(newRows:IRow[]):void;
sortActual():void;
sortColumnsInit():void;
sortData(col:IColumn, event:any):void;
}
export interface IFooterStatic {
new($scope:IGridScope, grid:IGridInstance):IFooter;
}
export interface IFooter {
}
export interface IGridOptions {
/** Define an aggregate template to customize the rows when grouped. See github wiki for more details. */
aggregateTemplate?: string;
/** Callback for when you want to validate something after selection. */
afterSelectionChange?: (rowItem?: any, event?: any) => void ;
afterSelectionChange?: (rowItem?: IRow, event?: any) => void ;
/** Callback if you want to inspect something before selection,
return false if you want to cancel the selection. return true otherwise.
@@ -25,7 +360,7 @@ declare module ngGrid {
use rowItem.changeSelection(event) method after returning false initially.
Note: when shift+ Selecting multiple items in the grid this will only get called
once and the rowItem will be an array of items that are queued to be selected. */
beforeSelectionChange?: (rowItem?: any, event?: any) => boolean ;
beforeSelectionChange?: (rowItem?: IRow, event?: any) => boolean ;
/** checkbox templates. */
checkboxCellTemplate?: string;
@@ -176,11 +511,68 @@ declare module ngGrid {
}
export interface IColumnDef {
/**
* This can be an absolute numberor it can also be defined in percentages (20%, 30%),
* in weighted *s, or "auto" (which sizes the column based on data length)
* (much like WPF/Silverlight)/ note: "auto" only works in single page apps currently because the re-size
* happens on "document.ready
*/
width?: any;
/** The minum width the column is allowed to be. See width for the different options */
minWidth?: any;
/** Set the default visiblity of the column */
visible?: boolean;
/** Can also be a property path on your data model. "foo.bar.myField", "Name.First", etc..*/
field?: string;
width?: any; //**this can be a string containing a relatively, absolute size units or a number: '30%','54px',45 /*
/** What to display in the column header */
displayName?: string;
cellTemplate?: string;
/** Restrict or allow the column to be sorted */
sortable?: boolean;
/** Restrict or allow the column to be resized */
resizable?: boolean;
/** Allows the column to be grouped with drag and drop, but has no effect on gridOptions.groups */
groupable?: boolean;
/** Allows the column to be pinned when enablePinning is set to true */
pinnable?: boolean;
/** The template to use while editing */
editableCellTemplate?: string;
/** Allows the cell to use an edit template when focused (grid option enableCellSelection must be enabled)*/
enableCellEdit?: boolean;
/** Controls when to use the edit template on per-row basis using an angular expression (enableCellEdit must also be true for editing)*/
cellEditableCondition?: string;
/** The funtion to use when filtering values in this column */
sortFn?: (a: any, b: any) => number;
/** Html template used to render the cell */
cellTemplate?: string;
/** User defined CSS class name */
cellClass?: string;
/** User defined CSS class name for the header cell */
headerClass?: string;
/** Html template used to render the header cell */
headerCellTemplate?: string;
/** string name for filter to use on the cell ('currency', 'date', etc..) */
cellFilter?: string;
/** String name for filter to use on the aggregate label ('currency', 'date', etc..) defaults to cellFilter if not set. */
aggLabelFilter?: string;
pinned?: boolean;
}
@@ -199,4 +591,60 @@ declare module ngGrid {
/** currentPage: the uhm... current page. */
currentPage?: number;
}
export interface IPlugin {
init(childScope:IGridScope, gridInstance:IGridInstance, services:any):void;
}
export module service {
export interface IDomUtilityService {
eventStorage:any;
numberOfGrids:number;
immediate:number;
AssignGridContainers($scope:IGridScope, rootel:ng.IAugmentedJQuery, grid:IGridInstance):void;
getRealWidth(obj:IDimension):number;
UpdateGridLayout($scope:IGridScope, grid:IGridInstance):void;
setStyleText(grid:IGridInstance, css:string):void;
BuildStyles($scope:IGridScope, grid:IGridInstance, digest:boolean):void;
setColLeft(col:IColumn, colLeft:number, grid:IGridInstance):void;
RebuildGrid($scope:IGridScope, grid:IGridInstance):void;
digest($scope:IGridScope):void;
ScrollH:number;
ScrollW:number;
LetterW:number;
}
export interface ISortInfo {
fields:string[];
}
export interface ISortService {
colSortFnCache:any;
isCustomSort:boolean;
isSorting:boolean;
guessSortFn(item:any):(a:any, b:any)=>number;
basicSort(a:any, b:any):number;
sortNumber(a:number, b:number):number;
sortNumberStr(a:string, b:string):number;
sortAlpha(a:string, b:string):number;
sortDate(a:Date, b:Date):number;
sortBool(a:boolean, b:boolean):number;
sortData(sortInfo:ISortInfo, data:any):void;
Sort(sortInfo:ISortInfo, data:any):void;
getSortFn(col:IColumn, data:any):(a:any, b:any)=>number;
}
export interface IUtilityService {
visualLength(node:any):number;
forIn(obj:any, action:(value:any, property:string)=>{}):void;
evalProperty(entity:any, path:string):any;
endsWith(str:string, suffix:string):boolean;
isNullOrUndefined(obj:any):boolean;
getElementsByClassName(cl:string):any[];
newId():string;
seti18n($scope:IGridScope, language:string):void;
getInstanceType(o:any):string;
}
}
}
+1 -1
View File
@@ -46,7 +46,7 @@ interface UUID {
v4(options?: UUIDOptions, buffer?: Buffer, offset?: number): string
}
declare module 'uuid' {
declare module "node-uuid" {
var uuid: UUID;
export = uuid;
}
+5
View File
@@ -200,6 +200,7 @@ interface NodeBuffer {
[index: number]: number;
write(string: string, offset?: number, length?: number, encoding?: string): number;
toString(encoding?: string, start?: number, end?: number): string;
toJSON(): any;
length: number;
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
slice(start?: number, end?: number): Buffer;
@@ -239,6 +240,10 @@ interface NodeBuffer {
* MODULES *
* *
************************************************/
declare module "buffer" {
export var INSPECT_MAX_BYTES: number;
}
declare module "querystring" {
export function stringify(obj: any, sep?: string, eq?: string): string;
export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any;
+127 -113
View File
@@ -1,145 +1,159 @@
/// <reference path="restangular.d.ts" />
function test_basic() {
var $scope;
Restangular.all('accounts');
Restangular.one('accounts', 1234);
Restangular.all('users').getList().then(function (users) {
$scope.user = users[0];
})
$scope.cars = $scope.user.getList('cars');
$scope.user.sendMessage();
$scope.user.one('message', 123).all('unread').getList();
var myApp = angular.module('testModule');
var baseAccounts = Restangular.all('accounts');
myApp.config((RestangularProvider: restangular.IProvider) => {
RestangularProvider.setBaseUrl('/api/v1');
RestangularProvider.setExtraFields(['name']);
RestangularProvider.setResponseExtractor(function (response, operation) {
return response.data;
});
$scope.allAccounts = baseAccounts.getList();
RestangularProvider.setDefaultHttpFields({ cache: true });
RestangularProvider.setMethodOverriders(["put", "patch"]);
var newAccount = { name: "Gonto's account" };
RestangularProvider.setErrorInterceptor(function (response) {
console.error('' + response.status + ' ' + response.data);
});
baseAccounts.post(newAccount);
RestangularProvider.setRequestSuffix('.json');
Restangular.one('accounts', 123).one('buildings', 456).get()
RestangularProvider.setRequestInterceptor(function (element, operation, route, url) {
});
Restangular.one('accounts', 123).all('buildings').getList()
RestangularProvider.addElementTransformer('accounts', false, function (elem) {
elem.accountName = 'Changed';
return elem;
});
baseAccounts.getList().then(function (accounts) {
RestangularProvider.setRestangularFields({
id: "_id",
route: "restangularRoute",
selfLink: "self.href"
});
var firstAccount = accounts[0];
$scope.buildings = firstAccount.getList("buildings");
$scope.loggedInPlaces = firstAccount.getList("places", { query: 'wuut' }, { 'x-user': 'mgonto' })
RestangularProvider.addRequestInterceptor(function(element, operation, route, url) {
delete element.name;
return element;
});
firstAccount.name = "Gonto"
var editFirstAccount = Restangular.copy(firstAccount);
firstAccount.put();
editFirstAccount.put();
firstAccount.remove();
var myBuilding = {
name: "Gonto's Building",
place: "Argentina"
};
RestangularProvider.setFullRequestInterceptor(function(element, operation, route, url, headers, params, httpConfig) {
delete element.name;
return {
element: element,
params: params,
headers: headers,
httpConfig: httpConfig
};
});
});
firstAccount.post("Buildings", myBuilding).then(function () {
console.log("Object saved OK");
}, function () {
console.log("There was an error saving");
});
firstAccount.getList("users", { query: 'wuut' }).then(function (users) {
users.post({ userName: 'unknown' });
users.customGET("messages", { param: "myParam" })
var firstUser = users[0];
$scope.userFromServer = firstUser.get();
firstUser.head()
});
}, function errorCallback() {
alert("Oops error from server :(");
})
var account = Restangular.one("accounts", 123);
$scope.account = account.get({ single: true });
account.customPOST({ name: "My Message" }, "messages", { param: "myParam" }, {})
interface MyAppScope extends ng.IScope {
accounts: string[];
allAccounts: any[];
account: any;
buildings: restangular.ICollectionPromise<any>;
loggedInPlaces: restangular.ICollectionPromise<any>;
userFromServer: restangular.IPromise<any>;
}
function test_config() {
RestangularProvider.setBaseUrl('/api/v1');
RestangularProvider.setExtraFields(['name']);
RestangularProvider.setResponseExtractor(function (response, operation) {
return response.data;
myApp.controller('TestCtrl', (
$scope: MyAppScope,
Restangular: restangular.IService
) => {
var baseAccounts = Restangular.all('accounts');
baseAccounts.getList().then(function(accounts) {
$scope.allAccounts = accounts;
});
$scope.accounts = Restangular.all('accounts').getList().$object;
var newAccount = {name: "Gonto's account"};
baseAccounts.post(newAccount);
Restangular.allUrl('googlers', 'http://www.google.com/').getList();
Restangular.oneUrl('googlers', 'http://www.google.com/1').get();
Restangular.one('accounts', 123).one('buildings', 456).get();
Restangular.one('accounts', 123).getList('buildings');
baseAccounts.getList().then(function (accounts) {
var firstAccount = accounts[0];
$scope.buildings = firstAccount.getList("buildings");
$scope.loggedInPlaces = firstAccount.getList("places", {query: "param"}, {'x-user': 'mgonto'});
firstAccount.name = "Gonto";
var editFirstAccount = Restangular.copy(firstAccount);
firstAccount.put();
editFirstAccount.put();
firstAccount.save();
firstAccount.remove();
var myBuilding = {
name: "Gonto's Building",
place: "Argentina"
};
firstAccount.post("Buildings", myBuilding).then(function() {
console.log("Object saved OK");
}, function() {
console.log("There was an error saving");
});
RestangularProvider.setDefaultHttpFields({ cache: true });
RestangularProvider.setMethodOverriders(["put", "patch"]);
firstAccount.getList("users", {query: "params"}).then(function(users) {
users.post({userName: 'unknown'});
users.customGET("messages", {param: "myParam"});
RestangularProvider.setErrorInterceptor(function (response) {
var firstUser = users[0];
$scope.userFromServer = firstUser.get();
firstUser.head()
});
}, function errorCallback() {
alert("Oops error from server :(");
});
var account = Restangular.one("accounts", 123);
$scope.account = account.get({single: true});
account.customPOST({name: "My Message"}, "messages", {param: "myParam"}, {});
Restangular.one('accounts', 123).withHttpConfig({timeout: 100}).getList('buildings');
$scope.account = Restangular.one('accounts', 123);
$scope.account.withHttpConfig({timeout: 100}).put();
var myRestangular = Restangular.withConfig((configurer: restangular.IProvider) => {
configurer.setBaseUrl('/api/v1');
configurer.setExtraFields(['name']);
configurer.setErrorInterceptor(function (response) {
console.error('' + response.status + ' ' + response.data);
});
configurer.setResponseExtractor(function (response, operation) {
return response.data;
});
configurer.setDefaultHttpFields({ cache: true });
configurer.setMethodOverriders(["put", "patch"]);
RestangularProvider.setRestangularFields({
configurer.setRestangularFields({
id: "_id",
route: "restangularRoute"
});
RestangularProvider.setRequestSuffix('.json');
configurer.setRequestSuffix('.json');
RestangularProvider.setRequestInterceptor(function (element, operation, route, url) {
configurer.setRequestInterceptor(function (element, operation, route, url) {
});
RestangularProvider.addElementTransformer('accounts', false, function (elem) {
configurer.addElementTransformer('accounts', false, function (elem) {
elem.accountName = 'Changed';
return elem;
});
var myRestangular = Restangular.withConfig((configurer: RestangularProvider) => {
configurer.setBaseUrl('/api/v1');
configurer.setExtraFields(['name']);
configurer.setErrorInterceptor(function (response) {
console.error('' + response.status + ' ' + response.data);
});
configurer.setResponseExtractor(function (response, operation) {
return response.data;
});
configurer.setDefaultHttpFields({ cache: true });
configurer.setMethodOverriders(["put", "patch"]);
configurer.setRestangularFields({
id: "_id",
route: "restangularRoute"
});
configurer.setRequestSuffix('.json');
configurer.setRequestInterceptor(function (element, operation, route, url) {
});
configurer.addElementTransformer('accounts', false, function (elem) {
elem.accountName = 'Changed';
return elem;
});
});
}
function test_withHttpConfig() {
var $scope;
Restangular.one('accounts', 123).withHttpConfig({timeout: 100}).getList('buildings');
$scope.account = Restangular.one('accounts', 123);
$scope.account.withHttpConfig({timeout: 100}).put();
}
});
});
+101 -79
View File
@@ -1,4 +1,4 @@
// Type definitions for Restangular v1.2.2
// Type definitions for Restangular v1.4.0
// Project: https://github.com/mgonto/restangular
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -6,7 +6,23 @@
/// <reference path="../angularjs/angular.d.ts" />
interface RestangularRequestConfig {
declare module restangular {
interface IPromise<T> extends ng.IPromise<T> {
call(methodName: string, params?: any): IPromise<T>;
get(fieldName: string): IPromise<T>;
$object: T;
}
interface ICollectionPromise<T> extends ng.IPromise<T> {
push(object: any): ICollectionPromise<T>;
call(methodName: string, params?: any): ICollectionPromise<T>;
get(fieldName: string): ICollectionPromise<T>;
$object: T[];
}
interface IRequestConfig {
params?: any;
headers?: any;
cache?: any;
@@ -15,81 +31,9 @@ interface RestangularRequestConfig {
transformRequest?: any;
transformResponse?: any;
timeout?: any; // number | promise
}
}
interface Restangular extends RestangularCustom {
one(route: string, id?: number): RestangularElement;
one(route: string, id?: string): RestangularElement;
oneUrl(route: string, url: string): RestangularElement;
all(route: string): RestangularCollection;
allUrl(route: string, url: string): RestangularCollection;
copy(fromElement: any): RestangularElement;
withConfig(configurer: (RestangularProvider: RestangularProvider) => any): Restangular;
restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): RestangularElement;
restangularizeCollection(parent: any, element: any, route: string): RestangularCollection;
stripRestangular(element: any): any;
}
interface RestangularElement extends Restangular {
get(queryParams?: any, headers?: any): ng.IPromise<any>;
getList(subElement: any, queryParams?: any, headers?: any): ng.IPromise<any>;
put(queryParams?: any, headers?: any): ng.IPromise<any>;
post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): ng.IPromise<any>;
remove(queryParams?: any, headers?: any): ng.IPromise<any>;
head(queryParams?: any, headers?: any): ng.IPromise<any>;
trace(queryParams?: any, headers?: any): ng.IPromise<any>;
options(queryParams?: any, headers?: any): ng.IPromise<any>;
patch(queryParams?: any, headers?: any): ng.IPromise<any>;
withHttpConfig(httpConfig: RestangularRequestConfig): RestangularElement;
getRestangularUrl(): string;
}
interface RestangularCollection extends Restangular {
getList(queryParams?: any, headers?: any): ng.IPromise<any>;
post(elementToPost: any, queryParams?: any, headers?: any): ng.IPromise<any>;
head(queryParams?: any, headers?: any): ng.IPromise<any>;
trace(queryParams?: any, headers?: any): ng.IPromise<any>;
options(queryParams?: any, headers?: any): ng.IPromise<any>;
patch(queryParams?: any, headers?: any): ng.IPromise<any>;
putElement(idx: any, params: any, headers: any): ng.IPromise<any>;
withHttpConfig(httpConfig: RestangularRequestConfig): RestangularCollection;
getRestangularUrl(): string;
}
interface RestangularCustom {
customGET(path: string, params?: any, headers?: any): ng.IPromise<any>;
customGETLIST(path: string, params?: any, headers?: any): ng.IPromise<any>;
customDELETE(path: string, params?: any, headers?: any): ng.IPromise<any>;
customPOST(elem?: any, path?: string, params?: any, headers?: any): ng.IPromise<any>;
customPUT(elem?: any, path?: string, params?: any, headers?: any): ng.IPromise<any>;
customOperation(operation: string, path: string, params?: any, headers?: any, elem?: any): ng.IPromise<any>;
addRestangularMethod(name: string, operation: string, path?: string, params?: any, headers?: any, elem?: any): ng.IPromise<any>;
}
interface RestangularProvider {
setBaseUrl(baseUrl: string): void;
setExtraFields(fields: string[]): void;
setParentless(parentless: boolean, routes: string[]): void;
setDefaultHttpFields(httpFields: any): void;
addElementTransformer(route: string, transformer: Function): void;
addElementTransformer(route: string, isCollection: boolean, transformer: Function): void;
setOnElemRestangularized(callback: (elem: any, isCollection: boolean, what: string, restangular: Restangular) => any): void;
setResponseInterceptor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: RestangularResponse, deferred: ng.IDeferred<any>) => any): void;
setResponseExtractor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: RestangularResponse, deferred: ng.IDeferred<any>) => any): void;
setRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string) => any): void;
setFullRequestInterceptor(fullRequestInterceptor: (element: any, operation: string, what: string, url: string, headers: any, params: any) => {element: any; headers: any; params: any}): void;
setErrorInterceptor(errorInterceptor: (response: RestangularResponse) => any): void;
setRestangularFields(fields: {[fieldName: string]: string}): void;
setMethodOverriders(overriders: string[]): void;
setDefaultRequestParams(params: any): void;
setDefaultRequestParams(methods: any, params: any): void;
setFullResponse(fullResponse: boolean): void;
setDefaultHeaders(headers: any): void;
setRequestSuffix(suffix: string): void;
setUseCannonicalId(useCannonicalId: boolean): void;
}
interface RestangularResponse {
interface IResponse {
status: number;
data: any;
config: {
@@ -97,7 +41,85 @@ interface RestangularResponse {
url: string;
params: any;
}
}
}
declare var Restangular: Restangular;
declare var RestangularProvider: RestangularProvider;
interface IProvider {
setBaseUrl(baseUrl: string): void;
setExtraFields(fields: string[]): void;
setParentless(parentless: boolean, routes: string[]): void;
setDefaultHttpFields(httpFields: any): void;
addElementTransformer(route: string, transformer: Function): void;
addElementTransformer(route: string, isCollection: boolean, transformer: Function): void;
setTransformOnlyServerElements(active: boolean): void;
setOnElemRestangularized(callback: (elem: any, isCollection: boolean, what: string, restangular: IService) => any): void;
setResponseInterceptor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: IResponse, deferred: ng.IDeferred<any>) => any): void;
setResponseExtractor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: IResponse, deferred: ng.IDeferred<any>) => any): void;
addResponseInterceptor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: IResponse, deferred: ng.IDeferred<any>) => any): void;
setRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string) => any): void;
addRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string) => any): void;
setFullRequestInterceptor(fullRequestInterceptor: (element: any, operation: string, what: string, url: string, headers: any, params: any, httpConfig: IRequestConfig) => {element: any; headers: any; params: any}): void;
addFullRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string, headers: any, params: any, httpConfig: IRequestConfig) => {headers: any; params: any; element: any; httpConfig: IRequestConfig}): void;
setErrorInterceptor(errorInterceptor: (response: IResponse, deferred: ng.IDeferred<any>) => any): void;
setRestangularFields(fields: {[fieldName: string]: string}): void;
setMethodOverriders(overriders: string[]): void;
setJsonp(jsonp: boolean): void;
setDefaultRequestParams(params: any): void;
setDefaultRequestParams(method: string, params: any): void;
setDefaultRequestParams(methods: string[], params: any): void;
setFullResponse(fullResponse: boolean): void;
setDefaultHeaders(headers: any): void;
setRequestSuffix(suffix: string): void;
setUseCannonicalId(useCannonicalId: boolean): void;
setEncodeIds(encode: boolean): void;
}
interface ICustom {
customGET(path: string, params?: any, headers?: any): IPromise<any>;
customGETLIST(path: string, params?: any, headers?: any): ICollectionPromise<any>;
customDELETE(path: string, params?: any, headers?: any): IPromise<any>;
customPOST(elem?: any, path?: string, params?: any, headers?: any): IPromise<any>;
customPUT(elem?: any, path?: string, params?: any, headers?: any): IPromise<any>;
customOperation(operation: string, path: string, params?: any, headers?: any, elem?: any): IPromise<any>;
addRestangularMethod(name: string, operation: string, path?: string, params?: any, headers?: any, elem?: any): IPromise<any>;
}
interface IService extends ICustom {
one(route: string, id?: number): IElement;
one(route: string, id?: string): IElement;
oneUrl(route: string, url: string): IElement;
all(route: string): IElement;
allUrl(route: string, url: string): IElement;
copy(fromElement: any): IElement;
withConfig(configurer: (RestangularProvider: IProvider) => any): IService;
restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): IElement;
restangularizeCollection(parent: any, element: any, route: string): ICollection;
stripRestangular(element: any): any;
}
interface IElement extends IService {
get(queryParams?: any, headers?: any): IPromise<any>;
getList(subElement?: any, queryParams?: any, headers?: any): ICollectionPromise<any>;
put(queryParams?: any, headers?: any): IPromise<any>;
post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): IPromise<any>;
post(elementToPost: any, queryParams?: any, headers?: any): IPromise<any>;
remove(queryParams?: any, headers?: any): IPromise<any>;
head(queryParams?: any, headers?: any): IPromise<any>;
trace(queryParams?: any, headers?: any): IPromise<any>;
options(queryParams?: any, headers?: any): IPromise<any>;
patch(queryParams?: any, headers?: any): IPromise<any>;
withHttpConfig(httpConfig: IRequestConfig): IElement;
getRestangularUrl(): string;
}
interface ICollection extends IService {
getList(queryParams?: any, headers?: any): ICollectionPromise<any>;
post(elementToPost: any, queryParams?: any, headers?: any): IPromise<any>;
head(queryParams?: any, headers?: any): IPromise<any>;
trace(queryParams?: any, headers?: any): IPromise<any>;
options(queryParams?: any, headers?: any): IPromise<any>;
patch(queryParams?: any, headers?: any): IPromise<any>;
putElement(idx: any, params: any, headers: any): IPromise<any>;
withHttpConfig(httpConfig: IRequestConfig): ICollection;
getRestangularUrl(): string;
}
}
+3
View File
@@ -60,6 +60,9 @@ declare var footstepsBuffer: any;
lowpassFilter.connect(wet1);
dry1.connect(masterDry);
wet1.connect(reverb);
source1.loop = true;
source1.loopStart = 0;
source1.loopEnd = 300;
// Connect source2
var dry2 = context.createGain();
+16 -1
View File
@@ -1,5 +1,5 @@
// Type definitions for Web Audio API
// Project: http://www.w3.org/TR/2012/WD-webaudio-20121213/
// Project: http://www.w3.org/TR/webaudio/
// Definitions by: Baruch Berger <https://github.com/bbss>, Kon <http://phyzkit.net/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -520,6 +520,21 @@ interface AudioBufferSourceNode extends AudioSourceNode {
*/
loop: boolean;
/**
* An optional value in seconds where looping should begin if the loop attribute is true. Its default value is 0, and it may usefully be set to any value between 0 and the duration of the buffer.
*/
loopStart: number;
/**
* An optional value in seconds where looping should end if the loop attribute is true. Its default value is 0, and it may usefully be set to any value between 0 and the duration of the buffer.
*/
loopEnd: number;
/**
* A property used to set the EventHandler for the ended event that is dispatched to AudioBufferSourceNode node types. When the playback of the buffer for an AudioBufferSourceNode is finished, an event of type Event will be dispatched to the event handler.
*/
onended: EventListener;
/**
* Schedules a sound to playback at an exact time.
*
+59 -125
View File
@@ -25,7 +25,49 @@ and limitations under the License.
**/
interface Element {
winControl: any; // TODO: This should be control?
}/**
}
/**
* Utility class for easy access to operations on application folders
**/
interface IOHelper {
/**
* Instance of the currently wrapped application folder
**/
folder: Windows.Storage.StorageFolder;
/**
* Determines whether the specified file exists in the folder.
* @param filename The name of the file.
* @returns A promise that completes with a value of either true (if the file exists) or false.
**/
exists(filename: string): WinJS.Promise<boolean>;
/**
* Reads the specified file. If the file doesn't exist, the specified default value is returned.
* @param fileName The file to read from.
* @param def The default value to be returned if the file failed to open.
* @returns A promise that completes with a value that is either the contents of the file, or the specified default value.
**/
readText(fileName: string, def?: string): WinJS.Promise<string>;
/**
* Deletes a file from the folder.
* @param fileName The file to be deleted.
* @returns A promise that is fulfilled when the file has been deleted.
**/
remove(fileName: string): WinJS.Promise<void>;
/**
* Writes the specified text to the specified file.
* @param fileName The name of the file.
* @param text The content to be written to the file.
* @returns A promise that completes with a value that is the number of characters written.
**/
writeText(fileName: string, text: string): WinJS.Promise<number>;
}
/**
* Provides application-level functionality, for example activation, storage, and application events.
**/
declare module WinJS.Application {
@@ -34,128 +76,23 @@ declare module WinJS.Application {
/**
* The local storage of the application.
**/
var local: {
//#region Methods
/**
* Determines whether the specified file exists in the folder.
* @param filename The name of the file.
* @returns A promise that completes with a value of either true (if the file exists) or false.
**/
exists(filename: string): Promise<boolean>;
/**
* Reads the specified file. If the file doesn't exist, the specified default value is returned.
* @param fileName The file to read from.
* @param def The default value to be returned if the file failed to open.
* @returns A promise that completes with a value that is either the contents of the file, or the specified default value.
**/
readText(fileName: string, def?: string): Promise<string>;
/**
* Deletes a file from the folder.
* @param fileName The file to be deleted.
* @returns A promise that is fulfilled when the file has been deleted.
**/
remove(fileName: string): Promise<void>;
/**
* Writes the specified text to the specified file.
* @param fileName The name of the file.
* @param text The content to be written to the file.
* @returns A promise that completes with a value that is the number of characters written.
**/
writeText(fileName: string, text: string): Promise<void>;
//#endregion Methods
};
var local: IOHelper;
/**
* The roaming storage of the application.
**/
var roaming: {
//#region Methods
var roaming: IOHelper;
/**
* Determines whether the specified file exists in the folder.
* @param filename The name of the file.
* @returns A promise that completes with a value of either true (if the file exists) or false.
**/
exists(filename: string): Promise<boolean>;
/**
* Reads the specified file. If the file doesn't exist, the specified default value is returned.
* @param fileName The file to read from.
* @param def The default value to be returned if the file failed to open.
* @returns A promise that completes with a value that is either the contents of the file, or the specified default value.
**/
readText(fileName: string, def?: string): Promise<string>;
/**
* Deletes a file from the folder.
* @param fileName The file to be deleted.
* @returns A promise that is fulfilled when the file has been deleted.
**/
remove(fileName: string): Promise<void>;
/**
* Writes the specified text to the specified file.
* @param fileName The name of the file.
* @param text The content to be written to the file.
* @returns A promise that completes with a value that is the number of characters written.
**/
writeText(fileName: string, text: string): Promise<void>;
//#endregion Methods
};
/**
* The temp storage of the application.
**/
var temp: IOHelper;
/**
* An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content.
**/
var sessionState: any;
/**
* The temp storage of the application.
**/
var temp: {
//#region Methods
/**
* Determines whether the specified file exists in the folder.
* @param filename The name of the file.
* @returns A promise that completes with a value of either true (if the file exists) or false.
**/
exists(filename: string): Promise<boolean>;
/**
* Reads the specified file. If the file doesn't exist, the specified default value is returned.
* @param fileName The file to read from.
* @param def The default value to be returned if the file failed to open.
* @returns A promise that completes with a value that is either the contents of the file, or the specified default value.
**/
readText(fileName: string, def?: string): Promise<string>;
/**
* Deletes a file from the folder.
* @param fileName The file to be deleted.
* @returns A promise that is fulfilled when the file has been deleted.
**/
remove(fileName: string): Promise<void>;
/**
* Writes the specified text to the specified file.
* @param fileName The name of the file.
* @param text The text to write.
* @returns A Promise that completes with the number of bytes successfully written to the file.
**/
writeText(fileName: string, text: string): Promise<void>;
//#endregion Methods
};
//#endregion Objects
//#region Methods
@@ -7967,18 +7904,7 @@ declare module WinJS.Utilities {
/**
* Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection.
**/
class QueryCollection<T> {
//#region Constructors
/**
* Initializes a new instance of a QueryCollection.
* @constructor
* @param items The items resulting from the query.
**/
constructor(items: T[]);
//#endregion Constructors
interface QueryCollection<T> extends Array<T> {
//#region Methods
/**
@@ -8125,6 +8051,14 @@ declare module WinJS.Utilities {
}
/**
* Constructor support for QueryCollection interface
**/
export var QueryCollection: {
new <T>(items: T[]): QueryCollection<T>;
prototype: QueryCollection<any>;
}
//#endregion Objects
//#region Functions
@@ -8306,7 +8240,7 @@ declare module WinJS.Utilities {
* @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document.
* @returns A QueryCollection with zero or one elements matching the specified selector query.
**/
function query(query: any, element: HTMLElement): QueryCollection<HTMLElement>;
function query(query: any, element?: HTMLElement): QueryCollection<HTMLElement>;
/**
* Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded.