diff --git a/types/angular-gettext/index.d.ts b/types/angular-gettext/index.d.ts index 107d9e10e2..5b6eb1d90f 100644 --- a/types/angular-gettext/index.d.ts +++ b/types/angular-gettext/index.d.ts @@ -9,6 +9,7 @@ import * as angular from 'angular'; +export type gettextCatalog = angular.gettext.gettextCatalog; declare module 'angular' { export namespace gettext { diff --git a/types/angular-local-storage/index.d.ts b/types/angular-local-storage/index.d.ts index 76ab65b1b5..6e8c64416a 100644 --- a/types/angular-local-storage/index.d.ts +++ b/types/angular-local-storage/index.d.ts @@ -8,6 +8,10 @@ import * as angular from 'angular'; +export type ILocalStorageServiceProvider = angular.local.storage.ILocalStorageServiceProvider; +export type ILocalStorageService = angular.local.storage.ILocalStorageService; +export type ICookie = angular.local.storage.ICookie; + declare module 'angular' { export namespace local.storage { interface ILocalStorageServiceProvider extends angular.IServiceProvider { diff --git a/types/angular-mocks/angular-mocks-tests.ts b/types/angular-mocks/angular-mocks-tests.ts index cabbf7c578..f04c9a2a30 100644 --- a/types/angular-mocks/angular-mocks-tests.ts +++ b/types/angular-mocks/angular-mocks-tests.ts @@ -1,70 +1,91 @@ - /////////////////////////////////////// // IAngularStatic /////////////////////////////////////// -var angular: ng.IAngularStatic; -var mock: ng.IMockStatic; +let angular: ng.IAngularStatic; +let mock: ng.IMockStatic; mock = angular.mock; - /////////////////////////////////////// // IMockStatic /////////////////////////////////////// -var date: Date; +let date: Date; mock.dump({ key: 'value' }); mock.inject( - function () { return 1; }, - function () { return 2; } - ); + function() { + return 1; + }, + function() { + return 2; + } +); -mock.inject( - ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }]); +mock.inject([ + '$rootScope', + function($rootScope: ng.IRootScopeService) { + return 1; + } +]); // This overload is not documented on the website, but flows from // how the injector works. mock.inject( - ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }], - ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 2; }]); + [ + '$rootScope', + function($rootScope: ng.IRootScopeService) { + return 1; + } + ], + [ + '$rootScope', + function($rootScope: ng.IRootScopeService) { + return 2; + } + ] +); mock.module('module1', 'module2'); mock.module( - function () { return 1; }, - function () { return 2; } - ); -mock.module({ module1: function () { return 1; } }); + function() { + return 1; + }, + function() { + return 2; + } +); +mock.module({ + module1: () => { + return 1; + } +}); mock.module.sharedInjector(); date = mock.TzDate(-7, '2013-1-1T15:00:00Z'); date = mock.TzDate(-8, 12345678); - /////////////////////////////////////// // IExceptionHandlerProvider /////////////////////////////////////// -var exceptionHandlerProvider: ng.IExceptionHandlerProvider; +let exceptionHandlerProvider: ng.IExceptionHandlerProvider; exceptionHandlerProvider.mode('log'); - /////////////////////////////////////// // ITimeoutService /////////////////////////////////////// -var timeoutService: ng.ITimeoutService; +let timeoutService: ng.ITimeoutService; timeoutService.flush(); timeoutService.flush(1234); -timeoutService.flushNext(); -timeoutService.flushNext(1234); timeoutService.verifyNoPendingTasks(); //////////////////////////////////////// // IIntervalService //////////////////////////////////////// -var intervalService: ng.IIntervalService; -var intervalServiceTimeActuallyAdvanced: number; +let intervalService: ng.IIntervalService; +let intervalServiceTimeActuallyAdvanced: number; intervalServiceTimeActuallyAdvanced = intervalService.flush(); intervalServiceTimeActuallyAdvanced = intervalService.flush(1234); @@ -72,9 +93,9 @@ intervalServiceTimeActuallyAdvanced = intervalService.flush(1234); /////////////////////////////////////// // ILogService, ILogCall /////////////////////////////////////// -var logService: ng.ILogService; -var logCall: ng.ILogCall; -var logs: string[]; +let logService: ng.ILogService; +let logCall: ng.ILogCall; +let logs: string[]; logService.assertEmpty(); logService.reset(); @@ -90,29 +111,31 @@ logs = logCall.logs; /////////////////////////////////////// // ControllerService mock /////////////////////////////////////// -var $controller: ng.IControllerService; -$controller(class TestController {}, {}, {myBinding: 'works!'}); -$controller(function TestController() {}, {someLocal: 42}, {myBinding: 'works!'}); -$controller('TestController', {}, {myBinding: 'works!'}); - +let $controller: ng.IControllerService; +$controller(class TestController {}, {}, { myBinding: 'works!' }); +$controller(function TestController() {}, { someLocal: 42 }, { myBinding: 'works!' }); +$controller('TestController', {}, { myBinding: 'works!' }); /////////////////////////////////////// // IComponentControllerService /////////////////////////////////////// -var $componentController: ng.IComponentControllerService; -$componentController<{}, {}>('Test controller', { $scope: {} }); -$componentController<{}, {}>('Test controller', { $scope: {}, test: true }); -$componentController<{}, { test: boolean }>('Test controller', { $scope: {} }, { test: true}); -$componentController<{}, { test?: boolean }>('Test controller', { $scope: {} }, {}); -$componentController<{}, {}>('Test controller', { $scope: {} }, {}, 'identity'); -$componentController<{ cb: () => void }, {}>('Test controller', { $scope: {} }); -$componentController<{}, { test: {name: string} }>('Test controller', { test: {name: 'Test Local'} }); +let $componentController: ng.IComponentControllerService; +let $scope: ng.IScope; +$componentController<{}, {}>('Test controller', { $scope }); +$componentController<{}, {}>('Test controller', { $scope, test: true }); +$componentController<{}, { test: boolean }>('Test controller', { $scope }, { test: true }); +$componentController<{}, { test?: boolean }>('Test controller', { $scope }, {}); +$componentController<{}, {}>('Test controller', { $scope }, {}, 'identity'); +$componentController<{ cb: () => void }, {}>('Test controller', { $scope }); +$componentController<{}, { test: { name: string } }>('Test controller', { + test: { name: 'Test Local' } +}); /////////////////////////////////////// // IHttpBackendService /////////////////////////////////////// -var httpBackendService: ng.IHttpBackendService; -var requestHandler: ng.mock.IRequestHandler; +let httpBackendService: ng.IHttpBackendService; +let requestHandler: ng.mock.IRequestHandler; httpBackendService.flush(); httpBackendService.flush(1234); @@ -123,342 +146,1362 @@ httpBackendService.verifyNoOutstandingRequest(); requestHandler = httpBackendService.expect('GET', 'http://test.local'); requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data'); -requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', { header: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', { + header: 'value' +}); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', function( + headers: object +): boolean { + return true; +}); requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/); -requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.expect('GET', 'http://test.local', function( + data: string +): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + 'http://test.local', + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect( + 'GET', + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, function( + headers: object +): boolean { + return true; +}); requestHandler = httpBackendService.expect('GET', /test.local/); requestHandler = httpBackendService.expect('GET', /test.local/, 'response data'); -requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, 'response data', function (headers: Object): boolean { return true; }, ['id']); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { + header: 'value' +}); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + /test.local\/(\d+)/, + 'response data', + function(headers: object): boolean { + return true; + }, + ['id'] +); requestHandler = httpBackendService.expect('GET', /test.local/, /response data/); -requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, /response data/, function (headers: Object): boolean { return true; }, ['id']); -requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }, ['id']); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + /test.local\/(\d+)/, + /response data/, + function(headers: object): boolean { + return true; + }, + ['id'] +); +requestHandler = httpBackendService.expect('GET', /test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + /test.local/, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + }, + ['id'] +); requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, { key: 'value' }, function (headers: Object): boolean { return true; }, ['id']); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect( + 'GET', + /test.local/, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + /test.local\/(\d+)/, + { key: 'value' }, + function(headers: object): boolean { + return true; + }, + ['id'] +); +requestHandler = httpBackendService.expect('GET', (url: string) => { + return true; +}); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + 'response data' +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + 'response data', + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + /response data/ +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + /response data/, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.expect( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' }, + function(headers: object): boolean { + return true; + } +); requestHandler = httpBackendService.expectDELETE('http://test.local'); requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' }); requestHandler = httpBackendService.expectDELETE(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectDELETE((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectDELETE( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectGET('http://test.local'); requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' }); requestHandler = httpBackendService.expectGET(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectGET((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectGET( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectHEAD('http://test.local'); requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' }); requestHandler = httpBackendService.expectHEAD(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectHEAD((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectHEAD( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectJSONP('http://test.local'); requestHandler = httpBackendService.expectJSONP(/test.local/); requestHandler = httpBackendService.expectJSONP(/test.local\/(\d+)/, ['id']); -requestHandler = httpBackendService.expectJSONP((url: string) => { return true; }); +requestHandler = httpBackendService.expectJSONP((url: string) => { + return true; +}); requestHandler = httpBackendService.expectPATCH('http://test.local'); requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data'); -requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/); -requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expectPATCH('http://test.local', function( + data: string +): boolean { + return true; +}); +requestHandler = httpBackendService.expectPATCH( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPATCH(/test.local/); requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data'); requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPATCH( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/); requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPATCH(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expectPATCH( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH( + /test.local/, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPATCH((url: string) => { + return true; +}); +requestHandler = httpBackendService.expectPATCH((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.expectPATCH( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPOST('http://test.local'); requestHandler = httpBackendService.expectPOST('http://test.local', 'response data'); -requestHandler = httpBackendService.expectPOST('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.expectPOST('http://test.local', /response data/); -requestHandler = httpBackendService.expectPOST('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expectPOST('http://test.local', function( + data: string +): boolean { + return true; +}); +requestHandler = httpBackendService.expectPOST( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPOST(/test.local/); requestHandler = httpBackendService.expectPOST(/test.local/, 'response data'); requestHandler = httpBackendService.expectPOST(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPOST( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPOST(/test.local/, /response data/); requestHandler = httpBackendService.expectPOST(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPOST(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expectPOST( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPOST((url: string) => { + return true; +}); +requestHandler = httpBackendService.expectPOST((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.expectPOST((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.expectPOST( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPUT('http://test.local'); requestHandler = httpBackendService.expectPUT('http://test.local', 'response data'); -requestHandler = httpBackendService.expectPUT('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.expectPUT('http://test.local', /response data/); -requestHandler = httpBackendService.expectPUT('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.expectPUT('http://test.local', function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expectPUT( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.expectPUT(/test.local/); requestHandler = httpBackendService.expectPUT(/test.local/, 'response data'); requestHandler = httpBackendService.expectPUT(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPUT( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPUT(/test.local/, /response data/); requestHandler = httpBackendService.expectPUT(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.expectPUT( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPUT(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.expectPUT( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPUT( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.expectPUT((url: string) => { + return true; +}); +requestHandler = httpBackendService.expectPUT((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.expectPUT((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.expectPUT( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.when('GET', 'http://test.local'); requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data'); -requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', { header: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', { + header: 'value' +}); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', function( + headers: object +): boolean { + return true; +}); requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/); -requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.when('GET', 'http://test.local', function( + data: string +): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + 'http://test.local', + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when( + 'GET', + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, function( + headers: object +): boolean { + return true; +}); requestHandler = httpBackendService.when('GET', /test.local/); requestHandler = httpBackendService.when('GET', /test.local/, 'response data'); requestHandler = httpBackendService.when('GET', /test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, 'response data', function (headers: Object): boolean { return true; }, ['id']); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + 'response data', + function(headers: object): boolean { + return true; + }, + ['id'] +); requestHandler = httpBackendService.when('GET', /test.local/, /response data/); requestHandler = httpBackendService.when('GET', /test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, /response data/, function (headers: Object): boolean { return true; }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }, ['id']); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + /response data/, + function(headers: object): boolean { + return true; + }, + ['id'] +); +requestHandler = httpBackendService.when('GET', /test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.when( + 'GET', + /test.local/, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + }, + ['id'] +); requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, { key: 'value' }, function (headers: Object): boolean { return true; }, ['id']); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when( + 'GET', + /test.local/, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function( + headers: object +): boolean { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + /test.local\/(\d+)/, + { key: 'value' }, + function(headers: object): boolean { + return true; + }, + ['id'] +); +requestHandler = httpBackendService.when('GET', (url: string) => { + return true; +}); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + 'response data' +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + 'response data', + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + /response data/ +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + /response data/, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + function(headers: object): boolean { + return true; + } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); +requestHandler = httpBackendService.when( + 'GET', + (url: string) => { + return true; + }, + { key: 'value' }, + function(headers: object): boolean { + return true; + } +); requestHandler = httpBackendService.whenDELETE('http://test.local'); requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' }); requestHandler = httpBackendService.whenDELETE(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenDELETE((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenDELETE( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenGET('http://test.local'); requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' }); requestHandler = httpBackendService.whenGET(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenGET((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenGET( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenHEAD('http://test.local'); requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' }); requestHandler = httpBackendService.whenHEAD(/test.local\/(\d+)/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenHEAD((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenHEAD( + (url: string) => { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenJSONP('http://test.local'); requestHandler = httpBackendService.whenJSONP(/test.local/); requestHandler = httpBackendService.whenJSONP(/test.local\/(\d+)/, ['id']); -requestHandler = httpBackendService.whenJSONP((url: string) => { return true; }); +requestHandler = httpBackendService.whenJSONP((url: string) => { + return true; +}); requestHandler = httpBackendService.whenPATCH('http://test.local'); requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data'); -requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/); -requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.whenPATCH('http://test.local', function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPATCH( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPATCH(/test.local/); requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data'); requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPATCH( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/); requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPATCH( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPATCH(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPATCH( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPATCH( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPATCH((url: string) => { + return true; +}); +requestHandler = httpBackendService.whenPATCH((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.whenPATCH((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.whenPATCH( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPOST('http://test.local'); requestHandler = httpBackendService.whenPOST('http://test.local', 'response data'); -requestHandler = httpBackendService.whenPOST('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.whenPOST('http://test.local', /response data/); -requestHandler = httpBackendService.whenPOST('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.whenPOST('http://test.local', function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPOST( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPOST(/test.local/); requestHandler = httpBackendService.whenPOST(/test.local/, 'response data'); requestHandler = httpBackendService.whenPOST(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPOST( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPOST(/test.local/, /response data/); requestHandler = httpBackendService.whenPOST(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPOST( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPOST(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPOST( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPOST( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPOST((url: string) => { + return true; +}); +requestHandler = httpBackendService.whenPOST((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.whenPOST((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.whenPOST( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPUT('http://test.local'); requestHandler = httpBackendService.whenPUT('http://test.local', 'response data'); -requestHandler = httpBackendService.whenPUT('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', 'response data', { + header: 'value' +}); requestHandler = httpBackendService.whenPUT('http://test.local', /response data/); -requestHandler = httpBackendService.whenPUT('http://test.local', /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', /response data/, { + header: 'value' +}); +requestHandler = httpBackendService.whenPUT('http://test.local', function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPUT( + 'http://test.local', + function(data: string): boolean { + return true; + }, + { header: 'value' } +); requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }); -requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT( + 'http://test.local', + { key: 'value' }, + { header: 'value' } +); requestHandler = httpBackendService.whenPUT(/test.local/); requestHandler = httpBackendService.whenPUT(/test.local/, 'response data'); requestHandler = httpBackendService.whenPUT(/test.local/, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPUT( + /test.local\/(\d+)/, + 'response data', + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPUT(/test.local/, /response data/); requestHandler = httpBackendService.whenPUT(/test.local/, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); +requestHandler = httpBackendService.whenPUT( + /test.local\/(\d+)/, + /response data/, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPUT(/test.local/, function(data: string): boolean { + return true; +}); +requestHandler = httpBackendService.whenPUT( + /test.local/, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPUT( + /test.local\/(\d+)/, + function(data: string): boolean { + return true; + }, + { header: 'value' }, + ['id'] +); requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' }); -requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data'); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data', { header: 'value' }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/, { header: 'value' }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }); -requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); - +requestHandler = httpBackendService.whenPUT( + /test.local\/(\d+)/, + { key: 'value' }, + { header: 'value' }, + ['id'] +); +requestHandler = httpBackendService.whenPUT((url: string) => { + return true; +}); +requestHandler = httpBackendService.whenPUT((url: string) => { + return true; +}, 'response data'); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + 'response data', + { header: 'value' } +); +requestHandler = httpBackendService.whenPUT((url: string) => { + return true; +}, /response data/); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + /response data/, + { header: 'value' } +); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + } +); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + function(data: string): boolean { + return true; + }, + { header: 'value' } +); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + { key: 'value' } +); +requestHandler = httpBackendService.whenPUT( + (url: string) => { + return true; + }, + { key: 'value' }, + { header: 'value' } +); /////////////////////////////////////// // IRequestHandler /////////////////////////////////////// -var expectedData = { key: 'value'}; +let expectedData = { key: 'value' }; requestHandler.passThrough(); requestHandler.passThrough().passThrough(); -requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']); -requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']).respond({}); -requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; }); +requestHandler.respond((method, url, data, headers) => [ + 404, + 'data', + { header: 'value' }, + 'responseText' +]); +requestHandler + .respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']) + .respond({}); +requestHandler.respond((method, url, data, headers) => { + return [404, { key: 'value' }, { header: 'value' }, 'responseText']; +}); requestHandler.respond((method, url, data, headers, params) => { - if(params.id === 1) { - return [200, { key: 'value'}, { header: 'value'}, 'responseText']; - } else { - return [404, { key: 'value' }, { header: 'value' }, 'responseText']; - } + if (params.id === '1') { + return [200, { key: 'value' }, { header: 'value' }, 'responseText']; + } else { + return [404, { key: 'value' }, { header: 'value' }, 'responseText']; + } }); requestHandler.respond('data'); requestHandler.respond('data').respond({}); @@ -471,3 +1514,7 @@ requestHandler.respond(404, 'data').respond({}); requestHandler.respond(404, { key: 'value' }); requestHandler.respond(404, { key: 'value' }, { header: 'value' }); requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText'); + +browserTrigger(document.body, 'click'); +browserTrigger(angular.element(document.body), 'click'); +browserTrigger(angular.element(document.body), 'click', { which: 1, keys: ['ctrl'] }); diff --git a/types/angular-mocks/index.d.ts b/types/angular-mocks/index.d.ts index 051539e2ac..c652443eac 100644 --- a/types/angular-mocks/index.d.ts +++ b/types/angular-mocks/index.d.ts @@ -1,10 +1,9 @@ -// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.5 +// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.6 // Project: http://angularjs.org // Definitions by: Diego Vilar , Tony Curtis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 -/// /// import * as angular from 'angular'; @@ -13,7 +12,6 @@ import * as angular from 'angular'; // ngMock module (angular-mocks.js) /////////////////////////////////////////////////////////////////////////////// declare module 'angular' { - /////////////////////////////////////////////////////////////////////////// // AngularStatic // We reopen it to add the MockStatic definition @@ -23,27 +21,27 @@ declare module 'angular' { } // see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject + // Depending on context, it might return a function, however having `void | (() => void)` + // as a return type seems to be not useful. E.g. it requires type assertions in `beforeEach(inject(...))`. interface IInjectStatic { - (...fns: Function[]): any; - (...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works - strictDi(val?: boolean): void; + (...fns: Array void>>): any; // void | (() => void); + strictDi(val?: boolean): any; // void | (() => void); } interface IMockStatic { // see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump dump(obj: any): string; - inject: IInjectStatic + inject: IInjectStatic; // see https://docs.angularjs.org/api/ngMock/function/angular.mock.module module: { (...modules: any[]): any; sharedInjector(): void; - } + }; // see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate - TzDate(offset: number, timestamp: number): Date; - TzDate(offset: number, timestamp: string): Date; + TzDate(offset: number, timestamp: number | string): Date; } /////////////////////////////////////////////////////////////////////////// @@ -62,7 +60,6 @@ declare module 'angular' { /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { flush(delay?: number): void; - flushNext(expectedDelay?: number): void; verifyNoPendingTasks(): void; } @@ -96,9 +93,11 @@ declare module 'angular' { /////////////////////////////////////////////////////////////////////////// interface IControllerService { // Although the documentation doesn't state this, locals are optional - (controllerConstructor: new (...args: any[]) => T, locals?: any, bindings?: any): T; - (controllerConstructor: (...args: any[]) => T, locals?: any, bindings?: any): T; - (controllerName: string, locals?: any, bindings?: any): T; + ( + controllerConstructor: (new (...args: any[]) => T) | ((...args: any[]) => T) | string, + locals?: any, + bindings?: any + ): T; } /////////////////////////////////////////////////////////////////////////// @@ -108,268 +107,473 @@ declare module 'angular' { interface IComponentControllerService { // TBinding is an interface exposed by a component as per John Papa's style guide // https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#accessible-members-up-top - (componentName: string, locals: { $scope?: IScope, [key: string]: any }, bindings?: TBinding, ident?: string): T; + ( + componentName: string, + locals: { $scope?: IScope; [key: string]: any }, + bindings?: TBinding, + ident?: string + ): T; } - /////////////////////////////////////////////////////////////////////////// // HttpBackendService // see https://docs.angularjs.org/api/ngMock/service/$httpBackend /////////////////////////////////////////////////////////////////////////// interface IHttpBackendService { /** - * Flushes pending requests using the trained responses. Requests are flushed in the order they were made, but it is also possible to skip one or more requests (for example to have them flushed later). This is useful for simulating scenarios where responses arrive from the server in any order. - * - * If there are no pending requests to flush when the method is called, an exception is thrown (as this is typically a sign of programming error). - * @param count Number of responses to flush. If undefined/null, all pending requests (starting after `skip`) will be flushed. - * @param skip Number of pending requests to skip. For example, a value of 5 would skip the first 5 pending requests and start flushing from the 6th onwards. _(default: 0)_ - */ + * Flushes pending requests using the trained responses. Requests are flushed in the order they + * were made, but it is also possible to skip one or more requests (for example to have them + * flushed later). This is useful for simulating scenarios where responses arrive from the server + * in any order. + * + * If there are no pending requests to flush when the method is called, an exception is thrown (as + * this is typically a sign of programming error). + * + * @param count Number of responses to flush. If undefined/null, all pending requests (starting + * after `skip`) will be flushed. + * @param skip Number of pending requests to skip. For example, a value of 5 would skip the first 5 pending requests and start flushing from the 6th onwards. _(default: 0)_ + */ flush(count?: number, skip?: number): void; /** - * Resets all request expectations, but preserves all backend definitions. - */ + * Resets all request expectations, but preserves all backend definitions. + */ resetExpectations(): void; /** - * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception. - * @param digest Do digest before checking expectation. Pass anything except false to trigger digest. NOTE this flag is purposely undocumented by Angular, which means it's not to be used in normal client code. - */ + * Verifies that all of the requests defined via the `expect` api were made. If any of the + * requests were not made, verifyNoOutstandingExpectation throws an exception. + * @param digest Do digest before checking expectation. Pass anything except false to trigger digest. + * NOTE: this flag is purposely undocumented by Angular, which means it's not to be used in normal client code. + */ verifyNoOutstandingExpectation(digest?: boolean): void; /** - * Verifies that there are no outstanding requests that need to be flushed. - */ + * Verifies that there are no outstanding requests that need to be flushed. + */ verifyNoOutstandingRequest(): void; - /** - * Creates a new request expectation. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param method HTTP method. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param method HTTP method. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expect( + method: string, + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for DELETE requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected. - * @param headers HTTP headers object to be compared with the HTTP headers in the request. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for DELETE requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectDELETE( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for GET requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object to be compared with the HTTP headers in the request. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for GET requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectGET( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for HEAD requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object to be compared with the HTTP headers in the request. - * @param keys Array of keys to assign to regex matches in the request url. - */ + /** + * Creates a new request expectation for HEAD requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ - expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + expectHEAD( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for JSONP requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for JSONP requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectJSONP( + url: string | RegExp | ((url: string) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for PATCH requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for PATCH requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectPATCH( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for POST requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for POST requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectPOST( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new request expectation for PUT requests. - * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation for PUT requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectPUT( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition. - * Returns an object with respond method that controls how a matched request is handled. - * @param method HTTP method. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new request expectation that compares only with the requested route. + * This method offers colon delimited matching of the url path, ignoring the query string. + * This allows declarations similar to how application routes are configured with `$routeProvider`. + * As this method converts the definition url to regex, declaration order is important. + * @param method HTTP method + * @param url HTTP url string that supports colon param matching + */ + expectRoute(method: string, url: string): mock.IRequestHandler; - /** - * Creates a new backend definition for DELETE requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition. + * Returns an object with respond method that controls how a matched request is handled. + * @param method HTTP method. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + when( + method: string, + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for GET requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in request url described above - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for DELETE requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenDELETE( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for HEAD requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for GET requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in request url described above + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenGET( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for JSONP requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for HEAD requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenHEAD( + url: string | RegExp | ((url: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for PATCH requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for JSONP requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenJSONP( + url: string | RegExp | ((url: string) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for POST requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for PATCH requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenPATCH( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; - /** - * Creates a new backend definition for PUT requests. - * Returns an object with respond method that controls how a matched request is handled. - * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. - * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. - * @param keys Array of keys to assign to regex matches in the request url. - */ - whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; + /** + * Creates a new backend definition for POST requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true + * if the url matches the current definition. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenPOST( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; + + /** + * Creates a new backend definition for PUT requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true + * if the url matches the current definition. + * @param data HTTP request body or function that receives data string and returns true if the data + * is as expected. + * @param headers HTTP headers or function that receives http header object and returns true if the + * headers match the current definition. + * @param keys Array of keys to assign to regex matches in the request url. + */ + whenPUT( + url: string | RegExp | ((url: string) => boolean), + data?: string | RegExp | object | ((data: string) => boolean), + headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean), + keys?: string[] + ): mock.IRequestHandler; + + /** + * Creates a new backend definition that compares only with the requested route. + * This method offers colon delimited matching of the url path, ignoring the query string. + * This allows declarations similar to how application routes are configured with `$routeProvider`. + * As this method converts the definition url to regex, declaration order is important. + * @param method HTTP method. + * @param url HTTP url string that supports colon param matching. + */ + whenRoute(method: string, url: string): mock.IRequestHandler; } /////////////////////////////////////////////////////////////////////////// // AnimateService // see https://docs.angularjs.org/api/ngMock/service/$animate /////////////////////////////////////////////////////////////////////////// - module animate { + namespace animate { interface IAnimateService { - /** - * This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining animation frames and/or callbacks. + * This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining + * animation frames and/or callbacks. */ closeAndFlush(): void; /** - * This method is used to flush the pending callbacks and animation frames to either start an animation or conclude an animation. Note that this will not actually close an actively running animation (see `closeAndFlush()` for that). + * This method is used to flush the pending callbacks and animation frames to either start + * an animation or conclude an animation. Note that this will not actually close an + * actively running animation (see `closeAndFlush()`} for that). */ flush(): void; } } - export module mock { - // returned interface by the the mocked HttpBackendService expect/when methods + namespace mock { + /** Object returned by the the mocked HttpBackendService expect/when methods */ interface IRequestHandler { - - /** - * Controls the response for a matched request using a function to construct the response. - * Returns the RequestHandler object for possible overrides. - * @param func Function that receives the request HTTP method, url, data, headers, and an array of keys to regex matches in the request url and returns an array containing response status (number), data, headers, and status text. - */ - respond(func: ((method: string, url: string, data: string | Object, headers: Object, params?: any) => [number, string | Object, Object, string])): IRequestHandler; - - /** - * Controls the response for a matched request using supplied static data to construct the response. - * Returns the RequestHandler object for possible overrides. - * @param status HTTP status code to add to the response. - * @param data Data to add to the response. - * @param headers Headers object to add to the response. - * @param responseText Response text to add to the response. - */ - respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler; - - /** - * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. - * Returns the RequestHandler object for possible overrides. - * @param data Data to add to the response. - * @param headers Headers object to add to the response. - * @param responseText Response text to add to the response. - */ - respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler; - - // Available when ngMockE2E is loaded /** - * Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.) - */ + * Controls the response for a matched request using a function to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param func Function that receives the request HTTP method, url, data, headers, and an array of keys + * to regex matches in the request url and returns an array containing response status (number), data, + * headers, and status text. + */ + respond( + func: (( + method: string, + url: string, + data: string | object, + headers: IHttpHeaders, + params: { [key: string]: string } + ) => [number, string | object, IHttpHeaders, string]) + ): IRequestHandler; + + /** + * Controls the response for a matched request using supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param status HTTP status code to add to the response. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond( + status: number, + data: string | object, + headers?: IHttpHeaders, + responseText?: string + ): IRequestHandler; + + /** + * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond( + data: string | object, + headers?: IHttpHeaders, + responseText?: string + ): IRequestHandler; + + /** + * Any request matching a backend definition or expectation with passThrough handler will be + * passed through to the real backend (an XHR request will be made to the server.) + * Available when ngMockE2E is loaded + */ passThrough(): IRequestHandler; } + interface IHttpHeaders { + [headerName: string]: any; + } + + /** + * Contains additional event data used by the `browserTrigger` function when creating an event. + */ + interface IBrowserTriggerEventData { + /** + * [Event.bubbles](https://developer.mozilla.org/docs/Web/API/Event/bubbles). + * Not applicable to all events. + */ + bubbles?: boolean; + /** + * [Event.cancelable](https://developer.mozilla.org/docs/Web/API/Event/cancelable). + * Not applicable to all events. + */ + cancelable?: boolean; + /** + * [charCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/charcode) + * for keyboard events (keydown, keypress, and keyup). + */ + charcode?: number; + /** + * The elapsedTime for + * [TransitionEvent](https://developer.mozilla.org/docs/Web/API/TransitionEvent) + * and [AnimationEvent](https://developer.mozilla.org/docs/Web/API/AnimationEvent). + */ + elapsedTime?: number; + /** + * [keyCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/keycode) + * for keyboard events (keydown, keypress, and keyup). + */ + keycode?: number; + /** + * An array of possible modifier keys (ctrl, alt, shift, meta) for + * [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent) and + * keyboard events (keydown, keypress, and keyup). + */ + keys?: Array<'ctrl' | 'alt' | 'shift' | 'meta'>; + /** + * The [relatedTarget](https://developer.mozilla.org/docs/Web/API/MouseEvent/relatedTarget) + * for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent). + */ + relatedTarget?: Node; + /** + * [which](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/which) + * for keyboard events (keydown, keypress, and keyup). + */ + which?: number; + /** + * x-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent) + * and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent). + */ + x?: number; + /** + * y-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent) + * and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent). + */ + y?: number; + } } } /////////////////////////////////////////////////////////////////////////////// // functions attached to global object (window) /////////////////////////////////////////////////////////////////////////////// -//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs. -//declare var module: (...modules: any[]) => any; +// Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs. +// declare var module: (...modules: any[]) => any; declare global { - export var inject: angular.IInjectStatic; + const inject: angular.IInjectStatic; + + /** + * This is a global (window) function that is only available when the `ngMock` module is included. + * It can be used to trigger a native browser event on an element, which is useful for unit testing. + * + * @param element Either a wrapped jQuery/jqLite node or a DOM element + * @param eventType Optional event type. If none is specified, the function tries to determine + * the right event type for the element, e.g. `change` for `input[text]`. + * @param eventData An optional object which contains additional event data used when creating the event. + */ + function browserTrigger( + element: JQuery | Element, + eventType?: string, + eventData?: angular.mock.IBrowserTriggerEventData + ): void; } diff --git a/types/angular-mocks/mocks.d.ts b/types/angular-mocks/mocks.d.ts index 17c077008c..e8cc13c0a8 100644 --- a/types/angular-mocks/mocks.d.ts +++ b/types/angular-mocks/mocks.d.ts @@ -1,14 +1,14 @@ declare module "angular-mocks/ngMock" { - var _: string; + const _: string; export = _; } declare module "angular-mocks/ngMockE2E" { - var _: string; + const _: string; export = _; } declare module "angular-mocks/ngAnimateMock" { - var _: string; + const _: string; export = _; -} \ No newline at end of file +} diff --git a/types/angular-mocks/tslint.json b/types/angular-mocks/tslint.json index a41bf5d19a..e91317558b 100644 --- a/types/angular-mocks/tslint.json +++ b/types/angular-mocks/tslint.json @@ -1,79 +1,10 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json", + "rules": { + "callable-types": false, + "interface-name": false, + "no-declare-current-package": false, + "no-unnecessary-generics": false, + "only-arrow-functions": false + } } diff --git a/types/angular-translate/index.d.ts b/types/angular-translate/index.d.ts index 719fcb5d5c..f35fb57570 100644 --- a/types/angular-translate/index.d.ts +++ b/types/angular-translate/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Translate (pascalprecht.translate module) 2.15 +// Type definitions for Angular Translate (pascalprecht.translate module) 2.16 // Project: https://github.com/PascalPrecht/angular-translate // Definitions by: Michel Salib , Gabriel Gil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -47,8 +47,8 @@ declare module 'angular' { } interface ITranslateService { - (translationId: string, interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string): angular.IPromise; - (translationId: string[], interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string): angular.IPromise<{ [key: string]: string }>; + (translationId: string, interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string, sanitizeStrategy?: string): angular.IPromise; + (translationId: string[], interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string, sanitizeStrategy?: string): angular.IPromise<{ [key: string]: string }>; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 89e897a7ad..6b82a2bcb4 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -4,6 +4,7 @@ // Georgii Dolzhykov // Caleb St-Denis // Leonard Thieu +// Steffen Kowalski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -484,6 +485,76 @@ declare namespace angular { $broadcast(name: string, ...args: any[]): IAngularEvent; $destroy(): void; $digest(): void; + + /** + * Suspend watchers of this scope subtree so that they will not be invoked during digest. + * + * This can be used to optimize your application when you know that running those watchers + * is redundant. + * + * **Warning** + * + * Suspending scopes from the digest cycle can have unwanted and difficult to debug results. + * Only use this approach if you are confident that you know what you are doing and have + * ample tests to ensure that bindings get updated as you expect. + * + * Some of the things to consider are: + * + * * Any external event on a directive/component will not trigger a digest while the hosting + * scope is suspended - even if the event handler calls `$apply()` or `$rootScope.$digest()`. + * * Transcluded content exists on a scope that inherits from outside a directive but exists + * as a child of the directive's containing scope. If the containing scope is suspended the + * transcluded scope will also be suspended, even if the scope from which the transcluded + * scope inherits is not suspended. + * * Multiple directives trying to manage the suspended status of a scope can confuse each other: + * * A call to `$suspend()` on an already suspended scope is a no-op. + * * A call to `$resume()` on a non-suspended scope is a no-op. + * * If two directives suspend a scope, then one of them resumes the scope, the scope will no + * longer be suspended. This could result in the other directive believing a scope to be + * suspended when it is not. + * * If a parent scope is suspended then all its descendants will be also excluded from future + * digests whether or not they have been suspended themselves. Note that this also applies to + * isolate child scopes. + * * Calling `$digest()` directly on a descendant of a suspended scope will still run the watchers + * for that scope and its descendants. When digesting we only check whether the current scope is + * locally suspended, rather than checking whether it has a suspended ancestor. + * * Calling `$resume()` on a scope that has a suspended ancestor will not cause the scope to be + * included in future digests until all its ancestors have been resumed. + * * Resolved promises, e.g. from explicit `$q` deferreds and `$http` calls, trigger `$apply()` + * against the `$rootScope` and so will still trigger a global digest even if the promise was + * initiated by a component that lives on a suspended scope. + */ + $suspend(): void; + + /** + * Call this method to determine if this scope has been explicitly suspended. It will not + * tell you whether an ancestor has been suspended. + * To determine if this scope will be excluded from a digest triggered at the $rootScope, + * for example, you must check all its ancestors: + * + * ``` + * function isExcludedFromDigest(scope) { + * while(scope) { + * if (scope.$isSuspended()) return true; + * scope = scope.$parent; + * } + * return false; + * ``` + * + * Be aware that a scope may not be included in digests if it has a suspended ancestor, + * even if `$isSuspended()` returns false. + * + * @returns true if the current scope has been suspended. + */ + $isSuspended(): boolean; + + /** + * Resume watchers of this scope subtree in case it was suspended. + * + * See {$rootScope.Scope#$suspend} for information about the dangers of using this approach. + */ + $resume(): void; + /** * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. * diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 0c64fd361b..fc070f62df 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -39,7 +39,10 @@ const showOptions : Auth0LockShowOptions = { type: "error", text: "an error has occurred" }, - rememberLastLogin: false + rememberLastLogin: false, + languageDictionary: { + title: "test" + } }; lock.show(showOptions); diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 27639834db..7dc20ae176 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -161,6 +161,7 @@ interface Auth0LockShowOptions { initialScreen?: "login" | "signUp" | "forgotPassword"; flashMessage?: Auth0LockFlashMessageOptions; rememberLastLogin?: boolean; + languageDictionary?: any; } interface AuthResult { diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index aa82e908e5..be87ceed2c 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -350,6 +350,7 @@ export interface Identity { user_id: string; provider: string; isSocial: boolean; + access_token?: string; profileData?: { email?: string; email_verified?: boolean; @@ -882,4 +883,4 @@ export class UsersManager { impersonate(userId: string, settings: ImpersonateSettingOptions): Promise; impersonate(userId: string, settings: ImpersonateSettingOptions, cb: (err: Error, data: any) => void): void; -} \ No newline at end of file +} diff --git a/types/bardjs/index.d.ts b/types/bardjs/index.d.ts index 5f2a5a1863..f701d4c368 100644 --- a/types/bardjs/index.d.ts +++ b/types/bardjs/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/wardbell/bardjs // Definitions by: Andrew Archibald // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// /// diff --git a/types/browser-sync/browser-sync-tests.ts b/types/browser-sync/browser-sync-tests.ts index c63cb0c862..1c7e7e5996 100644 --- a/types/browser-sync/browser-sync-tests.ts +++ b/types/browser-sync/browser-sync-tests.ts @@ -1,4 +1,5 @@ import browserSync = require("browser-sync"); +import { EventEmitter } from "events"; (() => { //make sure that the interfaces are correctly exposed @@ -391,6 +392,57 @@ bs.init({ bs.reload(); +browserSync.use( + { + plugin: function(opts: object, bs: browserSync.BrowserSyncInstance) { + console.log(opts); + }, + "plugin:name": "test" + }, + { files: "*.css" } +); + +browserSync.use({ + plugin: function(opts: object, bs: browserSync.BrowserSyncInstance) { + console.log(bs.name); + } +}); + +browserSync( + { + server: { + baseDir: "test/fixtures" + }, + logLevel: "silent", + open: false + } +); + +var instanceName = "TestInstance"; +var namedInstance = browserSync.create(instanceName); +namedInstance.init({ + server: { index: "./app" }, + https: true +}); + +console.log(namedInstance.getOption("https")); // Should output true. + +var existingInstance = browserSync.get(instanceName); + +browserSync.create("InstanceWithEventEmitter", new EventEmitter()); + +// Should output something greater than 0. +console.log(browserSync.instances.length); + +browserSync.reset(); + +// Should output 0. +console.log(browserSync.instances.length); + +var cleanupTestInstance = browserSync.create("CleanupTest"); +cleanupTestInstance.cleanup(); +console.log(cleanupTestInstance.active); // Should output false. + function browserSyncInit(): browserSync.BrowserSyncInstance { var browser = browserSync.create(); browser.init(); diff --git a/types/browser-sync/index.d.ts b/types/browser-sync/index.d.ts index de0a457266..bcf0aa966e 100644 --- a/types/browser-sync/index.d.ts +++ b/types/browser-sync/index.d.ts @@ -456,11 +456,15 @@ declare namespace browserSync { * depending on your use-case. */ (config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance; + /** + * + */ + instances: Array; /** * Create a Browsersync instance * @param name an identifier that can used for retrieval later */ - create(name?: string): BrowserSyncInstance; + create(name?: string, emitter?: NodeJS.EventEmitter): BrowserSyncInstance; /** * Get a single instance by name. This is useful if you have your build scripts in separate files * @param name the identifier used for retrieval @@ -471,6 +475,11 @@ declare namespace browserSync { * @param name the name of the instance */ has(name: string): boolean; + /** + * Reset the state of the module. + * (should only be needed for test environments) + */ + reset(): void; } interface BrowserSyncInstance { @@ -481,6 +490,24 @@ declare namespace browserSync { * depending on your use-case. */ init(config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance; + /** + * This method will close any running server, stop file watching & exit the current process. + */ + exit(): void; + /** + * Helper method for browser notifications + * @param message Can be a simple message such as 'Connected' or HTML + * @param timeout How long the message will remain in the browser. @since 1.3.0 + */ + notify(message: string, timeout?: number): void; + /** + * Method to pause file change events + */ + pause(): void; + /** + * Method to resume paused watchers + */ + resume(): void; /** * Reload the browser * The reload method will inform all browsers about changed files and will either cause the browser @@ -510,28 +537,30 @@ declare namespace browserSync { */ stream(opts?: StreamOptions): NodeJS.ReadWriteStream; /** - * Helper method for browser notifications - * @param message Can be a simple message such as 'Connected' or HTML - * @param timeout How long the message will remain in the browser. @since 1.3.0 + * Instance Cleanup. */ - notify(message: string, timeout?: number): void; + cleanup(fn?: (error: NodeJS.ErrnoException, bs: BrowserSyncInstance) => void): void; /** - * This method will close any running server, stop file watching & exit the current process. + * Register a plugin. + * Must implement at least a 'plugin' property that returns + * callable function. + * + * @method use + * @param {object} module The object to be `required`. + * @param {object} options The + * @param {any} cb A callback function that will return any errors. */ - exit(): void; + use(module: { "plugin:name"?: string, plugin: (opts: object, bs: BrowserSyncInstance) => any }, options?: object, cb?: any): void; + /** + * Callback helper to examine what options have been set. + * @param {string} name The key to search options map for. + */ + getOption(name: string): any; /** * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system */ watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) : NodeJS.EventEmitter; - /** - * Method to pause file change events - */ - pause(): void; - /** - * Method to resume paused watchers - */ - resume(): void; /** * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use * this to emit your own events, such as changed files, logging etc. diff --git a/types/buffer-reader/buffer-reader-tests.ts b/types/buffer-reader/buffer-reader-tests.ts new file mode 100644 index 0000000000..9868131c93 --- /dev/null +++ b/types/buffer-reader/buffer-reader-tests.ts @@ -0,0 +1,28 @@ +import BufferReader from 'buffer-reader'; + +const buffer = new Buffer(1000); +const reader = new BufferReader(buffer); +reader.append(new Buffer(1)); +reader.tell(); +reader.seek(1); +reader.move(2); +reader.restAll(); +reader.nextBuffer(2); +reader.nextString(5); +reader.nextString(5, 'utf8'); +reader.nextStringZero(); +reader.nextStringZero('utf8'); +reader.nextInt8(); +reader.nextUInt8(); +reader.nextInt16LE(); +reader.nextUInt16LE(); +reader.nextInt16BE(); +reader.nextUInt16BE(); +reader.nextInt32LE(); +reader.nextUInt32LE(); +reader.nextInt32BE(); +reader.nextUInt32BE(); +reader.nextFloatLE(); +reader.nextFloatBE(); +reader.nextDouble32LE(); +reader.nextDouble32BE(); diff --git a/types/buffer-reader/index.d.ts b/types/buffer-reader/index.d.ts new file mode 100644 index 0000000000..e83f081e69 --- /dev/null +++ b/types/buffer-reader/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for buffer-reader 0.1 +// Project: https://github.com/villadora/node-buffer-reader +// Definitions by: nrlquaker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +export = BufferReader; + +declare class BufferReader { + /** + * Create a new reader, if no buffer provided, a empty buffer will be used. + */ + constructor(buffer?: Buffer) + /** + * Append new buffer to the end of current reader. + * @param buffer buffer to append + */ + append(buffer: Buffer): void; + /** + * Return current position of the reader. + */ + tell(): number; + /** + * Set new position of the reader, if the pos is invalid, an exception will be raised. + * @param position new position + */ + seek(position: number): void; + /** + * Move the position of reader by offset, offset can be negative; it can be used to skip some bytes. + * @param offset offset to move by + */ + move(offset: number): void; + /** + * Get all the remaining bytes as a Buffer. + */ + restAll(): Buffer; + /** + * Read a buffer with specified length. + * @param length specified length + */ + nextBuffer(length: number): Buffer; + /** + * Read next length of bytes as String, encoding default is 'utf8'. + * @param length length of the string to read + * @param encoding encoding of the string + */ + nextString(length: number, encoding?: string): string; + /** + * Read next bytes till the end of buffer as null-terminated string, encoding default is 'utf8'. + * @param encoding encoding of the string + */ + nextStringZero(encoding?: string): string; + /** + * Read next bytes as Int8, the value is just as the same format Buffer in nodejs doc. + */ + nextInt8(): number; + /** + * Read next bytes as UInt8, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt8(): number; + /** + * Read next bytes as Int16LE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt16LE(): number; + /** + * Read next bytes as UInt16LE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt16LE(): number; + /** + * Read next bytes as Int16BE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt16BE(): number; + /** + * Read next bytes as UInt16BE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt16BE(): number; + /** + * Read next bytes as Int32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt32LE(): number; + /** + * Read next bytes as UInt32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt32LE(): number; + /** + * Read next bytes as Int32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt32BE(): number; + /** + * Read next bytes as UInt32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt32BE(): number; + /** + * Read next bytes as FloatLE, the value is just as the same format Buffer in nodejs doc. + */ + nextFloatLE(): number; + /** + * Read next bytes as FloatBE, the value is just as the same format Buffer in nodejs doc. + */ + nextFloatBE(): number; + /** + * Read next bytes as Double32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextDouble32LE(): number; + /** + * Read next bytes as Double32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextDouble32BE(): number; +} diff --git a/types/buffer-reader/tsconfig.json b/types/buffer-reader/tsconfig.json new file mode 100644 index 0000000000..da70d80fe1 --- /dev/null +++ b/types/buffer-reader/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "esModuleInterop": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "buffer-reader-tests.ts" + ] +} diff --git a/types/buffer-reader/tslint.json b/types/buffer-reader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/buffer-reader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index f19514fe71..2c81c42aeb 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1361,6 +1361,39 @@ suite('assert', () => { assert.notDeepEqual(circularObject, secondCircularObject); }); + test('deepStrictEqual', () => { + assert.deepStrictEqual({tea: 'chai'}, {tea: 'chai'}); + assert.throws(() => assert.deepStrictEqual({tea: 'chai'}, {tea: 'black'})); + + const obja = Object.create({tea: 'chai'}); + const objb = Object.create({tea: 'chai'}); + + assert.deepStrictEqual(obja, objb); + + const obj1 = Object.create({tea: 'chai'}); + const obj2 = Object.create({tea: 'black'}); + + assert.throws(() => assert.deepStrictEqual(obj1, obj2)); + }); + + test('deepStrictEqual (ordering)', () => { + const a = {a: 'b', c: 'd'}; + const b = {c: 'd', a: 'b'}; + assert.deepStrictEqual(a, b); + }); + + test('deepStrictEqual (circular)', () => { + const circularObject: any = {}; + const secondCircularObject: any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepStrictEqual(circularObject, secondCircularObject); + + secondCircularObject.field2 = secondCircularObject; + assert.deepStrictEqual(circularObject, secondCircularObject); + }); + test('isNull', () => { assert.isNull(null); assert.isNull(undefined); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index d0f5ab099c..d260973b71 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -353,7 +353,7 @@ declare namespace Chai { notStrictEqual(actual: T, expected: T, message?: string): void; /** - * Asserts that actual is deeply equal to expected. + * Asserts that actual is deeply equal (==) to expected. * * @type T Type of the objects. * @param actual Actual value. @@ -363,7 +363,7 @@ declare namespace Chai { deepEqual(actual: T, expected: T, message?: string): void; /** - * Asserts that actual is not deeply equal to expected. + * Asserts that actual is not deeply equal (==) to expected. * * @type T Type of the objects. * @param actual Actual value. @@ -372,6 +372,16 @@ declare namespace Chai { */ notDeepEqual(actual: T, expected: T, message?: string): void; + /** + * Asserts that actual is deeply strict equal (===) to expected. + * + * @type T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepStrictEqual(actual: T, expected: T, message?: string): void; + /** * Asserts valueToCheck is strictly greater than (>) valueToBeAbove. * diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index cb3db72855..8063cf2629 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -506,6 +506,7 @@ declare namespace Chart { } interface CommonAxe { + bounds?: string; type?: ScaleType | string; display?: boolean; id?: string; diff --git a/types/chromecast-caf-receiver/cast.framework.events.d.ts b/types/chromecast-caf-receiver/cast.framework.events.d.ts index 0c69727a05..03b70ca459 100644 --- a/types/chromecast-caf-receiver/cast.framework.events.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.events.d.ts @@ -367,9 +367,15 @@ declare namespace cast.framework.events { total?: number, whenSkippable?: number, endedReason?: EndedReason, - breakClipId?: string + breakClipId?: string, + breakId?: string ); + /** + * The break's id. Refer to Break.id + */ + breakId?: string; + /** * The break clip's id. Refer to BreakClip.id */ diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts index a75834b0a8..08ce57cf86 100644 --- a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -8,7 +8,8 @@ import { } from "chromecast-caf-receiver/cast.framework.system"; import { RequestEvent, - Event + Event, + BreaksEvent } from "chromecast-caf-receiver/cast.framework.events"; import { QueueBase, @@ -29,12 +30,16 @@ import { MediaMetadata } from "chromecast-caf-receiver/cast.framework.messages"; +const breaksEvent = new BreaksEvent('BREAK_STARTED'); +breaksEvent.breakId = 'some-break-id'; +breaksEvent.breakClipId = 'some-break-clip-id'; + const track = new Track(1, "TEXT"); const breakClip = new BreakClip("id"); const adBreak = new Break("id", ["id"], 1); const rEvent = new RequestEvent("BITRATE_CHANGED", { requestId: 2 }); const pManager = new PlayerManager(); -pManager.addEventListener("STALLED", () => {}); +pManager.addEventListener("STALLED", () => { }); const ttManager = new TextTracksManager(); const qManager = new QueueManager(); const qBase = new QueueBase(); @@ -47,10 +52,10 @@ const breakManager: BreakManager = { getBreakClips: () => [breakClip], getBreaks: () => [adBreak], getPlayWatchedBreak: () => true, - setBreakClipLoadInterceptor: () => {}, - setBreakSeekInterceptor: () => {}, - setPlayWatchedBreak: () => {}, - setVastTrackingInterceptor: () => {} + setBreakClipLoadInterceptor: () => { }, + setBreakSeekInterceptor: () => { }, + setPlayWatchedBreak: () => { }, + setVastTrackingInterceptor: () => { } }; const lrd: LoadRequestData = { @@ -103,4 +108,4 @@ const pData: PlayerData = { whenSkippable: 321 }; const binder = new PlayerDataBinder(pData); -binder.addEventListener("ANY_CHANGE", e => {}); +binder.addEventListener("ANY_CHANGE", e => { }); diff --git a/types/cytoscape/cytoscape-tests.ts b/types/cytoscape/cytoscape-tests.ts index 25d6151259..39be1cd0e7 100644 --- a/types/cytoscape/cytoscape-tests.ts +++ b/types/cytoscape/cytoscape-tests.ts @@ -1,6 +1,26 @@ 'use strict'; -import cytoscape = require('cytoscape'); +// TODO: document all aliases as aliases, not as duplicates! + +const assert = (tag: boolean) => { if (!tag) throw new Error(); }; +const aliases = (...obj: Array<{}>) => { if (obj.slice(1).some((alias) => alias !== obj[0])) throw new Error(); }; +const events = (obj: any) => { + aliases(obj.on, obj.bind, obj.listen, obj.addListener); + aliases(obj.promiseOn, obj.pon); + aliases(obj.off, obj.unbind, obj.unlisten, obj.removeListener); + aliases(obj.emit, obj.trigger); +}; + +// definitions +function oneOf(a: A, b: B, c: C, d: D, e: E): A | B | C | D | E; +function oneOf(a: A, b: B, c: C, d: D): A | B | C | D; +function oneOf(a: A, b: B, c: C): A | B | C; +function oneOf(a: A, b: B): A | B; +function oneOf(...array: T[]): T { + return array[0]; +} + +import cytoscape = require('cytoscape'); const parentCSS = { 'padding-top': '10px', 'padding-left': '10px', @@ -69,6 +89,34 @@ const cy = cytoscape({ ] }, + // initial viewport state: + zoom: 1, + pan: { x: 0, y: 0 }, + + // interaction options: + minZoom: 1e-50, + maxZoom: 1e50, + zoomingEnabled: true, + userZoomingEnabled: true, + panningEnabled: true, + userPanningEnabled: true, + selectionType: 'single', + touchTapThreshold: 8, + desktopTapThreshold: 4, + autolock: false, + autoungrabify: false, + + // rendering options: + headless: false, + styleEnabled: true, + hideEdgesOnViewport: false, + hideLabelsOnViewport: false, + textureOnViewport: false, + motionBlur: false, + motionBlurOpacity: 0.2, + wheelSensitivity: 1, + pixelRatio: 'auto', + layout: { name: 'preset', padding: 5 @@ -80,6 +128,42 @@ cy.on('zoom', (event) => { cy.nodes('$node > node').style('opacity', 0); } }); +cy.off('zoom'); +events(cy); + +cy.add({ data: { id: 'g' }, position: {x: 200, y: 150} }); +cy.add([ + { data: { id: 'h' }, position: {x: 250, y: 100} } +]); +const nodesBeforeDelete = cy.nodes(); +const edgesBeforeDelete = cy.edges(); + +const removed = cy.remove('#g #h'); +cy.add(removed); +const diffNodes = nodesBeforeDelete.diff(cy.nodes()); +const diffEdges = edgesBeforeDelete.diff(cy.edges()); +assert(diffNodes.left.size() === 0 && diffNodes.right.size() === 0 && diffNodes.both.size() === cy.nodes().size()); +assert(nodesBeforeDelete.same(cy.nodes())); +assert(edgesBeforeDelete.same(cy.edges())); + +const gh = cy.collection().add(cy.$id('g')).union(cy.getElementById('h')); +const gh2 = cy.$('#g #h'); +const gh3 = cy.nodes('#g #h'); +assert(gh2.same(gh)); +assert(gh3.same(gh)); +assert(gh.same(removed)); + +assert(cy.container() === null); // headless mode! + +cy.center(); +cy.center(gh); +aliases(cy.center, cy.centre); + +cy.fit(cy.$('#a #b #h')); + +const {x1, y1, x2, y2, w, h} = cy.extent(); + +aliases(cy.resize, cy.invalidateDimensions); cy.animate({ fit: { @@ -89,8 +173,323 @@ cy.animate({ duration: 500 }); -const node = cy.nodes()[0]; cy.animate({ - center: {eles: node}, + center: {eles: cy.nodes()[0]}, duration: 500 }); + +const anim = cy.animation({ + zoom: { + level: 1, + position: {x: 0, y: 0} + }, + pan: {x: 100, y: 100}, + duration: 100, + easing: 'ease' +}); +cy.stop(true, true); +anim.play(); +assert(anim.playing()); +anim.progress(anim.progress() + 50); +anim.time(anim.time() - 50); +anim.stop(); + +aliases(cy.layout, cy.createLayout, cy.makeLayout); + +// Preconfigured data for layouts (as it could be passed) +const boundingBox = oneOf({x1: 0, x2: 100, y1: 0, y2: 100}, {x1: 0, w: 100, y1: 0, h: 100}); +const positions = oneOf({a: {x: 100, y: 100}}, (node: cytoscape.NodeCollection): cytoscape.Position => ({x: 100, y: 100})); + +// TODO: uncomment after we have the way to add layout options properties from extensions +// const layouts = [ +// cy.layout({ +// name: 'null', +// ready: () => {}, +// stop: () => {} +// }), +// cy.layout({ +// name: 'random', +// fit: true, +// padding: 30, +// boundingBox, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'preset', +// positions, +// zoom: 1, +// pan: {x: 100, y: 100}, +// fit: false, +// padding: 30, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-out', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'grid', +// fit: true, +// padding: 30, +// boundingBox, +// avoidOverlap: true, +// avoidOverlapPadding: 10, +// nodeDimensionsIncludeLabels: false, +// spacingFactor: oneOf(1, undefined), +// condense: false, +// rows: oneOf(10, undefined), +// cols: oneOf(10, undefined), +// position: (node) => ({ row: 1, col: 1 }), +// sort: (a, b) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-out', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'circle', +// fit: true, +// padding: 30, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// spacingFactor: oneOf(1, undefined), +// radius: oneOf(1, undefined), +// startAngle: 3 / 2 * Math.PI, +// sweep: oneOf(6, undefined), +// clockwise: true, +// sort: (a, b) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'concentric', +// fit: true, +// padding: 30, +// startAngle: 3 / 2 * Math.PI, +// sweep: oneOf(6, undefined), +// clockwise: true, +// equidistant: false, +// minNodeSpacing: 10, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// height: oneOf(500, undefined), +// width: oneOf(500, undefined), +// spacingFactor: oneOf(1, undefined), +// concentric: (node) => 1, +// levelWidth: (nodes) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-out-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'breadthfirst', +// fit: true, +// directed: false, +// padding: 30, +// circle: false, +// spacingFactor: 1.75, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// maximalAdjustments: 0, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-out-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'cose', +// ready: () => {}, +// stop: () => {}, +// animate: oneOf(true, false, 'end'), +// animationEasing: oneOf('ease-in-quad', undefined), +// animationDuration: oneOf(500, undefined), +// animateFilter: function ( node, i ){ return true; }, +// animationThreshold: 250, +// refresh: 20, +// fit: true, +// padding: 30, +// boundingBox: undefined, +// nodeDimensionsIncludeLabels: false, +// randomize: false, +// componentSpacing: 40, +// nodeRepulsion: (node) => 2048, +// nodeOverlap: 4, +// idealEdgeLength: (edge) => 32, +// edgeElasticity: (edge) => 32, +// nestingFactor: 1.2, +// gravity: 1, +// numIter: 1000, +// initialTemp: 1000, +// coolingFactor: 0.99, +// minTemp: 1.0, +// weaver: false +// }) +// ]; +// const lay = layouts[0]; +// aliases(lay.run, lay.start); +// events(lay); +// layouts.map(layout => { +// layout.run(); +// layout.stop(); +// }); + +// TODO: cy.style + +cy.png({ + output: oneOf('base64uri', 'base64', 'blob', undefined), + bg: oneOf('#ffffff', undefined), + full: true, + scale: 2, + maxWidth: 100, + maxHeight: 100 +}); +aliases(cy.jpg, cy.jpeg); +cy.jpg({ + output: oneOf('base64uri', 'base64', 'blob', undefined), + bg: oneOf('#ffffff', undefined), + full: true, + scale: 2, + maxWidth: 100, + maxHeight: 100, + quality: 0.5 +}); +cy.json(cy.json()); + +// Types possible to call methods +const ele = oneOf(cy.nodes()[0], cy.edges()[0]); +const eles = cy.elements(); +const node = cy.nodes()[0]; +const nodes = cy.nodes(); +const edge = cy.edges()[0]; +const edges = cy.edges(); + +assert(ele.cy() === cy); +eles.remove(); +assert(eles.removed()); +assert(!eles.inside()); +eles.restore(); + +([ele, eles, node, nodes, edge, edges] as cytoscape.CollectionReturnValue[]).forEach((elem) => { + aliases(elem.clone, elem.copy); + events(elem); + aliases(elem.data, elem.attr); + aliases(elem.removeData, elem.removeAttr); +}); +// TODO: tests for data flow + +const loops = oneOf(true, false); +node.degree(loops); node.indegree(loops); node.outdegree(loops); +nodes.totalDegree(loops); nodes.minDegree(loops); nodes.maxDegree(loops); +nodes.minIndegree(loops); nodes.maxIndegree(loops); nodes.minOutdegree(loops); nodes.maxOutdegree(loops); + +// tslint:disable-next-line:ban-types +const getsetPos = (func: T): T => { + func('x', func('x')); + func(func()); + func({x: 100, y: 100}); + return func; +}; + +aliases(node.modelPosition, node.point, node.position); +getsetPos(node.position); + +nodes.shift('x', 100); +nodes.shift({x: -100, y: 0}); + +aliases(nodes.modelPositions, nodes.positions, nodes.points); +nodes.positions((node, i) => Object.assign(node.position(), {x: node.position('x') + i})); + +aliases(node.renderedPosition, node.renderedPoint); +getsetPos(node.renderedPoint); + +// TODO: tests for compound nodes (relativePosition, in particular) + +const sizes: number[] = [ + ele.width(), ele.outerWidth(), ele.renderedWidth(), ele.renderedOuterWidth(), + ele.height(), ele.outerHeight(), ele.renderedHeight(), ele.renderedOuterHeight() +]; + +aliases(eles.boundingBox, eles.boundingbox); +aliases(eles.renderedBoundingBox, eles.renderedBoundingbox); + +const flags: boolean[] = [ + node.grabbed(), node.grabbable(), node.locked(), ele.active(), +]; + +const edgePoints: cytoscape.Position[] = [ + ...edge.controlPoints(), ...edge.segmentPoints(), edge.sourceEndpoint(), edge.targetEndpoint(), edge.midpoint() +]; + +aliases(eles.layout, eles.createLayout, eles.makeLayout); +const layout = eles.layout({name: 'random'}).run(); + +eles.select(); +assert(ele.selected()); // as we selected all, and this too +aliases(eles.unselect, eles.deselect); +eles.selectify(); +assert(ele.selectable()); +eles.unselectify(); + +eles.addClass('test'); +eles.toggleClass('test', oneOf(true, false, undefined)); +eles.removeClass('test'); +eles.classes(oneOf('test', undefined)); +eles.flashClass('test flash', oneOf(1000, undefined)); +assert(ele.hasClass('test')); + +eles.style('background-color', 'green'); +Object.keys(eles.style()).map(key => eles.style(key)); +eles.style(eles.style()); +aliases(eles.style, eles.css); +aliases(ele.renderedCss, ele.renderedStyle); + +eles.anySame(nodes); +aliases(eles.contains, eles.has); +aliases(eles.allAreNeighbors, eles.allAreNeighbours); +eles.is('#g'); +eles.allAre('#g'); +eles.some((el, i, els) => true); +eles.every((el, i, els) => true); + +aliases(eles.forEach, eles.each); +const selected: cytoscape.SingularElementArgument[] = [eles.eq(0), eles.first(), eles.last()]; +const collSel = cy.collection(selected); +const selectedNodes: cytoscape.NodeSingular[] = [nodes.eq(0), nodes.first(), nodes.last()]; +const collNodes = cy.collection(selectedNodes); +const selectedEdges: cytoscape.EdgeSingular[] = [edges.eq(0), edges.first(), edges.last()]; +eles.slice(0, -1); +eles.toArray(); + +aliases(eles.getElementById, eles.$id); +aliases(eles.union, eles.add, eles.or, eles.u, eles['+'], eles['|']); +aliases(eles.difference, eles.not, eles.subtract, eles.relativeComplement, eles['\\'], eles['!'], eles['-']); +aliases(eles.absoluteComplement, eles.abscomp, eles.complement); +aliases(eles.intersection, eles.intersect, eles.and, eles.n, eles['&'], eles['.']); +aliases(eles.symmetricDifference, eles.symdiff, eles.xor, eles['^'], eles['(+)'], eles['(-)']); +cy.collection([nodes[0]]).union(nodes[1]).union(eles.$id('g')); +eles.difference(collNodes).abscomp().intersection(collSel).symdiff(collNodes); +const diff = collSel.diff(collNodes); +cy.collection().merge(diff.left).merge(diff.right).merge(diff.both).unmerge(collSel).filter((ele, i, eles) => true); + +eles.sort((a, b) => 1).map((ele, i, eles) => [i, ele]); +eles.reduce((prev, ele, i, eles) => [...prev, [ele, i]], []).concat(['finish']); +const min = eles.min((ele, i, eles) => ele.id.length + i); min.ele.scratch('min', min.value); +const max = eles.max((ele, i, eles) => ele.id.length + i); max.ele.scratch('max', max.value); + +// TODO: traversing (need to actively check the nodes/edeges distinction) +// TODO: algorithms +// TODO: compound nodes (there aren't any in current test case) diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index e85041861a..a3226defd2 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Cytoscape.js 3.1 +// Type definitions for Cytoscape.js 3.2 // Project: http://js.cytoscape.org/ // Definitions by: Fabian Schmidt and Fred Eisele // Shenghan Gao @@ -9,7 +9,7 @@ // // Translation from Objects in help to Typescript interface. // http://js.cytoscape.org/#notation/functions -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /** * cy --> Cy.Core @@ -361,7 +361,7 @@ declare namespace cytoscape { * * The default value is 1. */ - pixelRatio?: number; + pixelRatio?: number | 'auto'; } /** @@ -386,35 +386,42 @@ declare namespace cytoscape { /** * Add elements to the graph and return them. */ - add(eles: ElementDefinition | ElementDefinition[] | Collection): CollectionElements; + add(eles: ElementDefinition | ElementDefinition[] | CollectionArgument): CollectionReturnValue; /** * Remove elements in collecion or match the selector from the graph and return them. */ - remove(eles: Collection | Selector): CollectionElements; + remove(eles: CollectionArgument | Selector): CollectionReturnValue; /** * Get a collection from elements in the graph matching the specified selector or from an array of elements. * If no parameter specified, an empty collection will be returned */ - collection(eles?: Selector | CollectionElements[]): CollectionElements; + collection(eles?: Selector | CollectionArgument[]): CollectionReturnValue; /** * Get an element from its ID in a very performant way. + * http://js.cytoscape.org/#cy.getElementById */ - getElementById(id: string): CollectionElements; + getElementById(id: string): CollectionReturnValue; + + /** + * Get an element from its ID in a very performant way. + * http://js.cytoscape.org/#cy.getElementById + */ + $id(id: string): CollectionReturnValue; /** * Get elements in the graph matching the specified selector. * http://js.cytoscape.org/#cy.$ */ - $(selector: Selector): CollectionElements; + $(selector: Selector): CollectionReturnValue; /** * Get elements in the graph matching the specified selector. * http://js.cytoscape.org/#cy.$ */ - elements(selector?: Selector): CollectionElements; + elements(selector?: Selector): CollectionReturnValue; /** * Get nodes in the graph matching the specified selector. @@ -428,7 +435,7 @@ declare namespace cytoscape { /** * Get elements in the graph matching the specified selector or filter function. */ - filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionArgument) => boolean)): CollectionReturnValue; /** * Allow for manipulation of elements without triggering multiple style calculations or multiple redraws. @@ -599,14 +606,20 @@ declare namespace cytoscape { ready(fn: EventHandler): void; } - interface ZoomOptions { - /** The zoom level to set. */ - level: number; + interface ZoomOptionsModel { /** The position about which to zoom. */ position: Position; + } + interface ZoomOptionsRendered { /** The rendered position about which to zoom. */ renderedPosition: Position; } + interface ZoomOptionsLevel { + /** The zoom level to set. */ + level: number; + } + type ZoomOptions = ZoomOptionsLevel & (ZoomOptionsModel | ZoomOptionsRendered); + /** * http://js.cytoscape.org/#core/viewport-manipulation */ @@ -615,14 +628,21 @@ declare namespace cytoscape { * Get the HTML DOM element in which the graph is visualised. * A null value is returned if the Core is headless. */ - container(): any; + container(): Element | null; /** * Pan the graph to the centre of a collection. * * @param eles The collection to centre upon. */ - center(eles?: Collection): CollectionElements; + center(eles?: CollectionArgument): this; + + /** + * Pan the graph to the centre of a collection. + * + * @param eles The collection to centre upon. + */ + centre(eles?: CollectionArgument): this; /** * Pan and zooms the graph to fit to a collection. @@ -631,13 +651,13 @@ declare namespace cytoscape { * @param eles [optional] The collection to fit to. * @param padding [optional] An amount of padding (in pixels) to have around the graph */ - fit(eles?: Collection, padding?: number): CollectionElements; + fit(eles?: CollectionArgument, padding?: number): this; /** * Reset the graph to the default zoom level and panning position. * http://js.cytoscape.org/#cy.reset */ - reset(): CollectionElements; + reset(): this; /** * Get the panning position of the graph. @@ -651,7 +671,7 @@ declare namespace cytoscape { * * @param renderedPosition The rendered position to pan the graph to. */ - pan(renderedPosition?: Position): void; + pan(renderedPosition?: Position): this; /** * Relatively pan the graph by a specified rendered position vector. @@ -659,7 +679,7 @@ declare namespace cytoscape { * * @param renderedPosition The rendered position vector to pan the graph by. */ - panBy(renderedPosition: Position): void; + panBy(renderedPosition: Position): this; /** * Get whether panning is enabled. @@ -867,7 +887,8 @@ declare namespace cytoscape { * there is no resize or style event for arbitrary DOM elements. * http://js.cytoscape.org/#cy.resize */ - resize(): CollectionElements; + resize(): this; + invalidateDimensions(): this; } /** @@ -875,15 +896,15 @@ declare namespace cytoscape { * */ interface AnimationFitOptions { - eles: CollectionElements | Selector; // to which the viewport will be fitted. + eles: CollectionArgument | Selector; // to which the viewport will be fitted. padding: number; // Padding to use with the fitting. } interface CenterOptions { - eles: CollectionElements | Selector; // to which the viewport will be selected. + eles: CollectionArgument | Selector; // to which the viewport will be selected. } - interface AnimateOptionsCommon { + interface AnimationOptions { /** A zoom level to which the graph will be animated. */ - zoom?: number; + zoom?: ZoomOptions; /** A panning position to which the graph will be animated. */ pan?: Position; /** A relative panning position to which the graph will be animated. */ @@ -892,11 +913,13 @@ declare namespace cytoscape { fit?: AnimationFitOptions; /** An object containing centring options from which the graph will be animated. */ center?: CenterOptions; + /** easing - A transition-timing-function easing style string that shapes the animation progress curve. */ + easing?: string; // TODO: explicit type /** duration - The duration of the animation in milliseconds. */ duration?: number; } - interface AnimateOptions extends AnimateOptionsCommon { + interface AnimateOptions extends AnimationOptions { /** queue - A boolean indicating whether to queue the animation. */ queue?: boolean; /** complete - A function to call when the animation is done. */ @@ -904,14 +927,6 @@ declare namespace cytoscape { /** step - A function to call each time the animation steps. */ step?(): void; } - interface AnimationOptions extends AnimateOptionsCommon { - /** queue - A transition-timing-function easing style string that shapes the animation progress curve. */ - easing?: boolean; - /** complete - A function to call when the animation is done. */ - complete?(): void; - /** step - A function to call each time the animation steps. */ - step?(): void; - } interface CoreAnimation { /** @@ -993,6 +1008,7 @@ declare namespace cytoscape { * An analogue to make a layout on a subset of the graph exists as eles.makeLayout(). */ makeLayout(options: LayoutOptions): LayoutManipulation; + createLayout(options: LayoutOptions): LayoutManipulation; } /** @@ -1080,17 +1096,18 @@ declare namespace cytoscape { /** * Export the current graph view as a JPG image in Base64 representation. */ - jpg(options?: ExportOptions): string; + jpg(options?: ExportJpgOptions): string; /** * Export the current graph view as a JPG image in Base64 representation. */ - jpeg(options?: ExportOptions): string; + jpeg(options?: ExportJpgOptions): string; /** * Export the graph as JSON, the same format used at initialisation. */ - json(): string; + json(): object; + json(json: object): this; } /** @@ -1100,13 +1117,14 @@ declare namespace cytoscape { * The input can be any element (node and edge) collection. * http://js.cytoscape.org/#collection */ - interface Collection extends Singular, + interface Collection + extends Singular, CollectionGraphManipulation, CollectionEvents, CollectionData, CollectionPosition, CollectionLayout, CollectionSelection, CollectionStyle, CollectionAnimation, - CollectionComparision, CollectionIteration, - CollectionBuildingUnion, CollectionAlgorithms { } + CollectionComparision, CollectionIteration, + CollectionBuildingFiltering, CollectionAlgorithms { } /** * ele --> Cy.Singular @@ -1127,7 +1145,8 @@ declare namespace cytoscape { /** * The output is a collection of node and edge elements OR single element. */ - type CollectionElements = EdgeCollection | NodeCollection | SingularElement; + type CollectionArgument = EdgeCollection | NodeCollection | SingularElementArgument; + type CollectionReturnValue = EdgeCollection & NodeCollection & SingularElementReturnValue; /** * edges -> Cy.EdgeCollection @@ -1135,7 +1154,7 @@ declare namespace cytoscape { * * The output is a collection of edge elements OR single edge. */ - interface EdgeCollection extends Collection, EdgeSingular, + interface EdgeCollection extends Collection, EdgeSingular, EdgeCollectionTraversing { } /** * nodes -> Cy.NodeCollection @@ -1143,19 +1162,18 @@ declare namespace cytoscape { * * The output is a collection of node elements OR single node. */ - interface NodeCollection extends Collection, NodeSingular, + interface NodeCollection extends Collection, NodeSingular, NodeCollectionMetadata, NodeCollectionPosition, NodeCollectionTraversing, NodeCollectionCompound { } - interface SingularElement extends EdgeSingular, NodeSingular { - // Intentionally empty. - } + type SingularElementArgument = EdgeSingular | NodeSingular; + type SingularElementReturnValue = EdgeSingular & NodeSingular; /** * edge --> Cy.EdgeSingular * a collection of a single edge */ interface EdgeSingular extends Singular, - EdgeSingularData, EdgeSingularTraversing { } + EdgeSingularData, EdgeSingularPoints, EdgeSingularTraversing { } /** * node --> Cy.NodeSingular @@ -1172,24 +1190,24 @@ declare namespace cytoscape { * Remove the elements from the graph. * http://js.cytoscape.org/#eles.remove */ - remove(): CollectionElements; + remove(): CollectionReturnValue; /** * Put removed elements back into the graph. * http://js.cytoscape.org/#eles.restore */ - restore(): CollectionElements; + restore(): CollectionReturnValue; /** * Get a new collection containing clones (i.e. copies) of the elements in the calling collection. * http://js.cytoscape.org/#eles.clone */ - clone(): CollectionElements; + clone(): CollectionReturnValue; /** * Get a new collection containing clones (i.e. copies) of the elements in the calling collection. * http://js.cytoscape.org/#eles.clone */ - copy(): CollectionElements; + copy(): CollectionReturnValue; /** * Effectively move edges to different nodes. The modified (actually new) elements are returned. @@ -1207,6 +1225,10 @@ declare namespace cytoscape { * http://js.cytoscape.org/#collection/graph-manipulation */ interface SingularGraphManipulation { + /** + * Get the core instance that owns the element. + */ + cy(): Core; /** * Get whether the element has been removed from the graph. * http://js.cytoscape.org/#ele.removed @@ -1279,8 +1301,8 @@ declare namespace cytoscape { * http://js.cytoscape.org/#eles.removeData * @param names A space-separated list of fields to delete. */ - removeData(names?: string): CollectionElements; - removeAttr(names?: string): CollectionElements; + removeData(names?: string): CollectionReturnValue; + removeAttr(names?: string): CollectionReturnValue; /** * Get an array of the plain JavaScript object @@ -1313,6 +1335,22 @@ declare namespace cytoscape { * @param obj The object containing name- value pairs to update data fields. */ data(obj: any): void; + /** + * Get a particular data field for the element. + * @param name The name of the field to get. + */ + attr(name?: string): any; + /** + * Set a particular data field for the element. + * @param name The name of the field to set. + * @param value The value to set for the field. + */ + attr(name: string, value: any): void; + /** + * Update multiple data fields at once via an object. + * @param obj The object containing name- value pairs to update data fields. + */ + attr(obj: any): void; /** * Get or set the scratchpad at a particular namespace, @@ -1461,17 +1499,77 @@ declare namespace cytoscape { * Get the (model) position of a node. */ position(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + position(dimension: PositionDimension): number; /** * Set the value of a specified position dimension. * @param dimension The position dimension to set. * @param value The value to set to the dimension. */ - position(dimension: PositionDimension, value?: Position): void; + position(dimension: PositionDimension, value: number): this; /** * Set the position using name-value pairs in the specified object. * @param pos An object specifying name-value pairs representing dimensions to set. */ - position(pos: Position): void; + position(pos: Position): this; + /** + * Get the (model) position of a node. + */ + modelPosition(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + modelPosition(dimension: PositionDimension): number; + /** + * Set the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + modelPosition(dimension: PositionDimension, value: number): this; + /** + * Set the position using name-value pairs in the specified object. + * @param pos An object specifying name-value pairs representing dimensions to set. + */ + modelPosition(pos: Position): this; + /** + * Get the (model) position of a node. + */ + point(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + point(dimension: PositionDimension): number; + /** + * Set the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + point(dimension: PositionDimension, value: number): this; + /** + * Set the position using name-value pairs in the specified object. + * @param pos An object specifying name-value pairs representing dimensions to set. + */ + point(pos: Position): this; + + /** + * Shift the positions of the nodes by a given model position vector. + * @param dimension The position dimension to shift. + * @param value The value to shift the dimension. + */ + shift(dimension: PositionDimension, value?: number): this; + /** + * Shift the positions of the nodes by a given model position vector. + * @param pos An object specifying name-value pairs representing dimensions to shift. + */ + shift(pos: Position): this; /** * Get or set the rendered (on-screen) position of a node. @@ -1542,8 +1640,8 @@ declare namespace cytoscape { * @param ele The element being iterated over for which the function should return a position to set. * @param ix The index of the element when iterating over the elements in the collection. */ - type ElementPositionFunction = (ele: CollectionElements, ix: number) => void; - type ElementCollectionFunction = (ele: CollectionElements, ix: number, eles: CollectionElements) => void; + type ElementPositionFunction = (ele: NodeSingular, ix: number) => void; + type ElementCollectionFunction = (ele: NodeSingular, ix: number, eles: CollectionArgument) => void; /** * http://js.cytoscape.org/#collection/position--dimensions @@ -1556,9 +1654,7 @@ declare namespace cytoscape { * http://js.cytoscape.org/#nodes.positions */ positions(handler: ElementPositionFunction | Position): void; - modelPositions(handler: ElementPositionFunction | Position): void; - points(handler: ElementPositionFunction | Position): void; /** @@ -1647,11 +1743,13 @@ declare namespace cytoscape { * http://js.cytoscape.org/#eles.boundingBox */ boundingBox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; + boundingbox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; /** * Get the bounding box of the elements in rendered coordinates. * @param options An object containing options for the function. */ renderedBoundingBox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; + renderedBoundingbox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; } /** @@ -1668,9 +1766,9 @@ declare namespace cytoscape { * * @param options The layout options. */ - layout(options: LayoutOptions): CollectionElements; - makeLayout(options: LayoutOptions): CoreLayout; - createLayout(options: LayoutOptions): CoreLayout; + layout(options: LayoutOptions): LayoutManipulation; + makeLayout(options: LayoutOptions): LayoutManipulation; + createLayout(options: LayoutOptions): LayoutManipulation; } /** @@ -1684,7 +1782,7 @@ declare namespace cytoscape { // easing of animation, if enabled animationEasing?: number; // collection of elements involved in the layout; set by cy.layout() or eles.layout() - eles: CollectionElements; + eles: CollectionArgument; // whether to fit the viewport to the graph fit?: boolean; // padding to leave between graph and viewport @@ -1811,11 +1909,50 @@ declare namespace cytoscape { flashClass(classes: ClassNames, duration?: number): void; /** - * Get or set a particular style property value. - * @param name The name of the visual style property to get. + * Set a particular style property value. + * @param name The name of the visual style property to set. * @param value The value to which the property is set. */ - style(name?: string, value?: any): any; + style(name: string, value: any): this; + /** + * Get a particular style property value. + * @param name The name of the visual style property to get. + */ + style(name: string): any; + /** + * Set several particular style property values. + * @param obj An object of style property name-value pairs to set. + */ + style(obj: object): this; + /** + * Get a name-value pair object containing visual style properties and their values for the element. + */ + style(): {[index: string]: any}; + /** + * Set a particular style property value. + * @param name The name of the visual style property to set. + * @param value The value to which the property is set. + */ + css(name: string, value: any): this; + /** + * Get a particular style property value. + * @param name The name of the visual style property to get. + */ + css(name: string): any; + /** + * Set several particular style property values. + * @param obj An object of style property name-value pairs to set. + */ + css(obj: object): this; + /** + * Get a name-value pair object containing visual style properties and their values for the element. + */ + css(): {[index: string]: any}; + /** + * Remove all or specific style overrides. + * @param names A space-separated list of property names to remove overrides + */ + removeStyle(names?: string): this; } /** @@ -1977,27 +2114,36 @@ declare namespace cytoscape { * * @param eles The other elements to compare to. */ - same(eles: Collection): boolean; + same(eles: CollectionArgument): boolean; /** * Determine whether this collection contains any of the same elements as another collection. * * @param eles The other elements to compare to. */ - anySame(eles: Collection): boolean; + anySame(eles: CollectionArgument): boolean; + + /** + * Determine whether this collection contains all of the elements of another collection. + */ + contains(eles: CollectionArgument): boolean; + /** + * Determine whether this collection contains all of the elements of another collection. + */ + has(eles: CollectionArgument): boolean; /** * Determine whether all elements in the specified collection are in the neighbourhood of the calling collection. * * @param eles The other elements to compare to. */ - allAreNeighbors(eles: Collection): boolean; + allAreNeighbors(eles: CollectionArgument): boolean; /** * Determine whether all elements in the specified collection are in the neighbourhood of the calling collection. * * @param eles The other elements to compare to. */ - allAreNeighbours(eles: Collection): boolean; + allAreNeighbours(eles: CollectionArgument): boolean; /** * Determine whether any element in this collection matches a selector. @@ -2021,7 +2167,7 @@ declare namespace cytoscape { * eles - The collection of elements being tested. * @param thisArg [optional] The value for this within the test function. */ - some(test: (ele: CollectionElements, i: number, eles: CollectionElements) => boolean, thisArg?: any): boolean; + some(test: (ele: CollectionArgument, i: number, eles: CollectionArgument) => boolean, thisArg?: any): boolean; /** * Determine whether all elements in this collection satisfy the specified test function. @@ -2032,13 +2178,13 @@ declare namespace cytoscape { * eles - The collection of elements being tested. * @param thisArg [optional] The value for this within the test function. */ - every(test: (ele: CollectionElements, i: number, eles: CollectionElements) => boolean, thisArg?: any): boolean; + every(test: (ele: CollectionArgument, i: number, eles: CollectionArgument) => boolean, thisArg?: any): boolean; } /** * http://js.cytoscape.org/#collection/iteration */ - interface CollectionIteration { + interface CollectionIteration { /** * Get the number of elements in the collection. */ @@ -2070,8 +2216,8 @@ declare namespace cytoscape { * eles - The collection of elements being iterated. * @param thisArg [optional] The value for this within the iterating function. */ - each(each: (ele: CollectionElements, i: number, eles: CollectionElements) => void | boolean, thisArg?: any): void; - forEach(each: (ele: CollectionElements, i: number, eles: CollectionElements) => void | boolean, thisArg?: any): void; + each(each: (ele: TIn, i: number, eles: this) => void | boolean, thisArg?: any): void; + forEach(each: (ele: TIn, i: number, eles: this) => void | boolean, thisArg?: any): void; /** * Get an element at a particular index in the collection. @@ -2080,21 +2226,21 @@ declare namespace cytoscape { * * @param index The index of the element to get. */ - eq(index: number): CollectionElements; + eq(index: number): TOut; /** * Get an element at a particular index in the collection. * * @param index The index of the element to get. */ - [index: number]: CollectionElements; + [index: number]: TOut; /** * Get the first element in the collection. */ - first(): CollectionElements; + first(): TOut; /** * Get the last element in the collection. */ - last(): CollectionElements; + last(): TOut; /** * Get a subset of the elements in the collection based on specified indices. @@ -2106,7 +2252,12 @@ declare namespace cytoscape { * If omitted, all elements from the start position and to the end of the array will be selected. * Use negative numbers to select from the end of an array. */ - slice(start?: number, end?: number): CollectionElements; + slice(start?: number, end?: number): this; + + /** + * Get the collection as an array, maintaining the order of the elements. + */ + toArray(): SingularElementReturnValue[]; } /** @@ -2118,7 +2269,7 @@ declare namespace cytoscape { * @param eles The elements or array of elements to add or elements in the graph matching the selector. * http://js.cytoscape.org/#eles.union */ - type CollectionBuildingUnionFunc = (eles: Collection | Collection[] | Selector) => CollectionElements; + type CollectionBuildingUnionFunc = (eles: CollectionArgument | CollectionArgument[] | Selector) => CollectionReturnValue; /** * Get a new collection, resulting from the collection without some specified elements. @@ -2126,7 +2277,7 @@ declare namespace cytoscape { * @param eles The elements that will not be in the resultant collection. * Elements from the calling collection matching this selector will not be in the resultant collection. */ - type CollectionBuildingDifferenceFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionBuildingDifferenceFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * Get the elements in both this collection and another specified collection. @@ -2135,7 +2286,7 @@ declare namespace cytoscape { * A selector representing the elements to intersect with. * All elements in the graph matching the selector are used as the passed collection. */ - type CollectionBuildingIntersectionFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionBuildingIntersectionFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * Get the elements that are in the calling collection or the passed collection but not in both. @@ -2144,40 +2295,52 @@ declare namespace cytoscape { * A selector representing the elements to apply the symmetric difference with. * All elements in the graph matching the selector are used as the passed collection. */ - type CollectionSymmetricDifferenceFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionSymmetricDifferenceFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * http://js.cytoscape.org/#collection/building--filtering */ - interface CollectionBuildingUnion { + interface CollectionBuildingFiltering { + /** + * Get an element in the collection from its ID in a very performant way. + * @param id The ID of the element to get. + */ + getElementById(id: string): TOut; + /** + * Get an element in the collection from its ID in a very performant way. + * @param id The ID of the element to get. + */ + $id(id: string): TOut; + /** * Get a new collection, resulting from adding the collection with another one * http://js.cytoscape.org/#eles.union */ union: CollectionBuildingUnionFunc; - // [index: "u"]: CollectionBuildingUnionFunc; + u: CollectionBuildingUnionFunc; add: CollectionBuildingUnionFunc; - // [index: "+"]: CollectionBuildingUnionFunc; + '+': CollectionBuildingUnionFunc; or: CollectionBuildingUnionFunc; - // [index: "|"]: CollectionBuildingUnionFunc; + '|': CollectionBuildingUnionFunc; /** * Get a new collection, resulting from the collection without some specified elements. * http://js.cytoscape.org/#eles.difference */ difference: CollectionBuildingDifferenceFunc; - // [index: "\\"]: CollectionBuildingDifferenceFunc; + subtract: CollectionBuildingDifferenceFunc; + '\\': CollectionBuildingDifferenceFunc; not: CollectionBuildingDifferenceFunc; - // [index: "!"]: CollectionBuildingDifferenceFunc; + '!': CollectionBuildingDifferenceFunc; relativeComplement: CollectionBuildingDifferenceFunc; - // [index: "-"]: CollectionBuildingDifferenceFunc; + '-': CollectionBuildingDifferenceFunc; /** * Get all elements in the graph that are not in the calling collection. * http://js.cytoscape.org/#eles.absoluteComplement */ - absoluteComplement(): CollectionElements; - abscomp(): CollectionElements; - complement(): CollectionElements; + absoluteComplement(): CollectionReturnValue; + abscomp(): CollectionReturnValue; + complement(): CollectionReturnValue; /** * Get the elements in both this collection and another specified collection. @@ -2186,9 +2349,9 @@ declare namespace cytoscape { intersection: CollectionSymmetricDifferenceFunc; intersect: CollectionSymmetricDifferenceFunc; and: CollectionSymmetricDifferenceFunc; - // [index: "n"]: CollectionSymmetricDifferenceFunc; - // [index: "&"]: CollectionSymmetricDifferenceFunc; - // [index: "."]: CollectionSymmetricDifferenceFunc; + n: CollectionSymmetricDifferenceFunc; + '&': CollectionSymmetricDifferenceFunc; + '.': CollectionSymmetricDifferenceFunc; /** * Get the elements that are in the calling collection @@ -2198,11 +2361,9 @@ declare namespace cytoscape { symmetricDifference: CollectionSymmetricDifferenceFunc; symdiff: CollectionSymmetricDifferenceFunc; xor: CollectionSymmetricDifferenceFunc; - // [index: "^"]: CollectionSymmetricDifferenceFunc; - // [index: "(+)"]: CollectionSymmetricDifferenceFunc; - // [index: "(-)"]: CollectionSymmetricDifferenceFunc; - - // [index: string]: CollectionBuildingDifferenceFunc |CollectionBuildingUnionFunc | CollectionBuildingDifferenceFunc | CollectionSymmetricDifferenceFunc; + '^': CollectionSymmetricDifferenceFunc; + '(+)': CollectionSymmetricDifferenceFunc; + '(-)': CollectionSymmetricDifferenceFunc; /** * Perform a traditional left/right diff on the two collections. @@ -2216,12 +2377,62 @@ declare namespace cytoscape { * both - is the set of elements in both collections. * http://js.cytoscape.org/#eles.diff */ - diff(selector: Selector | Collection): { - left: CollectionElements, - right: CollectionElements, - both: CollectionElements + diff(selector: Selector | CollectionArgument): { + left: CollectionReturnValue, + right: CollectionReturnValue, + both: CollectionReturnValue }; + /** + * Perform a in-place merge of the given elements into the calling collection. + * @param eles The elements to merge in-place or a selector representing the elements to merge. + * All elements in the graph matching the selector are used as the passed collection. + * + * This function modifies the calling collection instead of returning a new one. + * Use of this function should be considered for performance in some cases, but otherwise should be avoided. Consider using eles.union() instead. + * Use this function only on new collections that you create yourself, using cy.collection(). + * This ensures that you do not unintentionally modify another collection. + * + * Examples + * With a collection: + * @example + * var col = cy.collection(); // new, empty collection + * var j = cy.$('#j'); + * var e = cy.$('#e'); + * col.merge( j ).merge( e ); + * + * With a selector: + * @example + * var col = cy.collection(); // new, empty collection + * col.merge('#j').merge('#e'); + */ + merge(eles: CollectionArgument | string): this; + /** + * Perform an in-place operation on the calling collection to remove the given elements. + * @param eles The elements to remove in-place or a selector representing the elements to remove . + * All elements in the graph matching the selector are used as the passed collection. + * + * This function modifies the calling collection instead of returning a new one. + * Use of this function should be considered for performance in some cases, but otherwise should be avoided. Consider using eles.filter() or eles.remove() instead. + * Use this function only on new collections that you create yourself, using cy.collection(). + * This ensures that you do not unintentionally modify another collection. + * + * Examples + * With a collection: + * @example + * var col = cy.collection(); // new, empty collection + * var e = cy.$('#e'); + * col.merge( cy.nodes() ); + * col.unmerge( e ); + * + * With a selector: + * @example + * var col = cy.collection(); // new, empty collection + * col.merge( cy.nodes() ); + * col.unmerge('#e'); + */ + unmerge(eles: CollectionArgument | string): this; + /** * Get a new collection containing elements that are accepted by the specified filter. * @@ -2231,21 +2442,21 @@ declare namespace cytoscape { * ele - The element being considered. * http://js.cytoscape.org/#eles.filter */ - filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: TOut, i: number, eles: CollectionArgument) => boolean)): CollectionReturnValue; /** * Get the nodes that match the specified selector. * * @param selector The selector to match against. * http://js.cytoscape.org/#eles.filter */ - nodes(selector: Selector): NodeCollection; + nodes(selector?: Selector): NodeCollection; /** * Get the edges that match the specified selector. * * @param selector The selector to match against. * http://js.cytoscape.org/#eles.filter */ - edges(selector: Selector): EdgeCollection; + edges(selector?: Selector): EdgeCollection; /** * Get a new collection containing the elements sorted by the @@ -2257,7 +2468,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.sort */ - sort(sort: (ele1: CollectionElements, ele2: CollectionElements) => number): CollectionElements; + sort(sort: (ele1: CollectionArgument, ele2: CollectionArgument) => number): CollectionReturnValue; /** * Get an array containing values mapped from the collection. @@ -2270,7 +2481,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.map */ - map(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): any[]; + map(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): any[]; /** * Reduce a single value by applying a @@ -2282,11 +2493,13 @@ declare namespace cytoscape { * ele The current element. * ix The index of the current element. * eles The collection of elements being reduced. - * + * @param initialValue The initial value for reducing + * It is used also for type inference of output, but the type can be + * also stated explicitly as generic * http://js.cytoscape.org/#eles.reduce */ - reduce(fn: (prevVal: any, ele: CollectionElements, - ix: number, eles: CollectionElements) => any): number[]; + reduce(fn: (prevVal: T, ele: SingularElementReturnValue, + ix: number, eles: CollectionReturnValue) => T, initialValue: T): T; /** * Find a minimum value in a collection. @@ -2299,7 +2512,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.min */ - min(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): { + min(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): { /** * The minimum value found. */ @@ -2307,7 +2520,7 @@ declare namespace cytoscape { /** * The element that corresponds to the minimum value. */ - ele: CollectionElements + ele: CollectionArgument }; /** @@ -2321,7 +2534,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.max */ - max(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): { + max(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): { /** * The maximum value found. */ @@ -2329,7 +2542,7 @@ declare namespace cytoscape { /** * The element that corresponds to the maximum value. */ - ele: CollectionElements + ele: CollectionArgument }; } @@ -2351,7 +2564,7 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - neighborhood(selector?: Selector): CollectionElements; + neighborhood(selector?: Selector): CollectionReturnValue; /** * Get the open neighbourhood of the elements. @@ -2362,7 +2575,7 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - openNeighborhood(selector?: Selector): CollectionElements; + openNeighborhood(selector?: Selector): CollectionReturnValue; /** * Get the closed neighbourhood of the elements. * @@ -2372,13 +2585,54 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - closedNeighborhood(selector?: Selector): CollectionElements; + closedNeighborhood(selector?: Selector): CollectionReturnValue; /** * Get the connected components, considering only the elements in the calling collection. * An array of collections is returned, with each collection representing a component. */ - components(): Collection; + components(): CollectionReturnValue[]; + } + /** + * http://js.cytoscape.org/#collection/edge-points + */ + interface EdgeSingularPoints { + /** + * Get an array of control point model positions for a {@code curve-style: bezier) or {@code curve-style: unbundled-bezier} edge. + * + * While the control points may be specified relatively in the CSS, + * this function returns the absolute model positions of the control points. + * The points are specified in the order of source-to-target direction. + * This function works for bundled beziers, but it is not applicable to the middle, straight-line edge in the bundle. + */ + controlPoints(): Position[]; + /** + * Get an array of segment point model positions (i.e. bend points) for a {@code curve-style: segments} edge. + * + * While the segment points may be specified relatively in the stylesheet, + * this function returns the absolute model positions of the segment points. + * The points are specified in the order of source-to-target direction. + */ + segmentPoints(): Position[]; + /** + * Get the model position of where the edge ends, towards the source node. + */ + sourceEndpoint(): Position; + /** + * Get the model position of where the edge ends, towards the target node. + */ + targetEndpoint(): Position; + /** + * Get the model position of the midpoint of the edge. + * + * The midpoint is, by default, where the edge’s label is centred. It is also the position towards which mid arrows point. + * For curve-style: unbundled-bezier edges, the midpoint is the middle extremum if the number of control points is odd. + * For an even number of control points, the midpoint is where the two middle-most control points meet. + * This is the middle inflection point for bilaterally symmetric or skew symmetric edges, for example. + * For curve-style: segments edges, the midpoint is the middle segment point if the number of segment points is odd. + * For an even number of segment points, the overall midpoint is the midpoint of the middle-most line segment (i.e. the mean of the middle two segment points). + */ + midpoint(): Position; } interface EdgeSingularTraversing { /** @@ -2457,7 +2711,7 @@ declare namespace cytoscape { * @param eles The other collection. * @param selector The other collection, specified as a selector which is matched against all elements in the graph. */ - edgesWith(eles: Collection | Selector): EdgeCollection; + edgesWith(eles: CollectionArgument | Selector): EdgeCollection; /** * Get the edges coming from the collection (i.e. the source) going to another collection (i.e. the target). @@ -2465,7 +2719,7 @@ declare namespace cytoscape { * @param eles The other collection. * @param selector The other collection, specified as a selector which is matched against all elements in the graph. */ - edgesTo(eles: Collection | Selector): EdgeCollection; + edgesTo(eles: CollectionArgument | Selector): EdgeCollection; /** * Get the edges connected to the nodes in the collection. @@ -2537,7 +2791,7 @@ declare namespace cytoscape { /** * The root nodes (selector or collection) to start the search from. */ - roots: Selector | Collection; + roots: Selector | CollectionArgument; /** * A handler function that is called when a node is visited in the search. */ @@ -2552,7 +2806,7 @@ declare namespace cytoscape { * The path of the search. * - The path returned includes edges such that if path[i] is a node, then path[i - 1] is the edge used to get to that node. */ - path: CollectionElements; + path: CollectionArgument; /** * The node found by the search * - If no node was found, then found is empty. @@ -2568,7 +2822,7 @@ declare namespace cytoscape { /** * The root node (selector or collection) where the algorithm starts. */ - root: Selector | Collection; + root: Selector | CollectionArgument; /** * A function that returns the positive numeric weight for this edge. @@ -2596,14 +2850,14 @@ declare namespace cytoscape { * The path starts with the source node and includes the edges between the nodes in the path such that if pathTo(node)[i] is an edge, * then pathTo(node)[i-1] is the previous node in the path and pathTo(node)[i+1] is the next node in the path. */ - pathTo(node: NodeSingular): Collection; + pathTo(node: NodeSingular): CollectionReturnValue; } /** * http://js.cytoscape.org/#eles.aStar */ interface SearchAStarOptions { - root: Selector | Collection; - goal: Selector | Collection; + root: Selector | CollectionArgument; + goal: Selector | CollectionArgument; weight?: WeightFn; heuristic?(node: NodeCollection): number; directed?: boolean; @@ -2614,7 +2868,7 @@ declare namespace cytoscape { interface SearchAStarResult { found: boolean; distance: number; - path: Collection; + path: CollectionReturnValue; } /** @@ -2641,7 +2895,7 @@ declare namespace cytoscape { * then pathTo(node)[i-1] is the previous node in the path and pathTo(node)[i+1] * is the next node in the path. */ - path(fromNode: NodeSingular | CollectionSelection, toNode: NodeSingular | Selector): Collection; + path(fromNode: NodeSingular | CollectionSelection, toNode: NodeSingular | Selector): CollectionReturnValue; } /** @@ -2670,7 +2924,7 @@ declare namespace cytoscape { * function that computes the shortest path from root node to the argument node * (either objects or selector string) */ - pathTo(node: NodeSingular | Selector): Collection; + pathTo(node: NodeSingular | Selector): CollectionReturnValue; /** * function that computes the shortest distance from root node to argument node @@ -4368,13 +4622,13 @@ declare namespace cytoscape { * Start running the layout * http://js.cytoscape.org/#layout.run */ - run(): void; - start(): void; + run(): this; + start(): this; /** * Stop running the (asynchronous/discrete) layout * http://js.cytoscape.org/#layout.stop */ - stop(): void; + stop(): this; } interface LayoutEvents { /** diff --git a/types/d3/v3/index.d.ts b/types/d3/v3/index.d.ts index 9a2f9ae34a..9f32212f6b 100644 --- a/types/d3/v3/index.d.ts +++ b/types/d3/v3/index.d.ts @@ -3277,7 +3277,7 @@ declare namespace d3 { round(round: boolean): Treemap; sticky(): boolean; - sticky(sticky: boolean): boolean; + sticky(sticky: boolean): Treemap; mode(): string; mode(mode: "squarify"): Treemap; diff --git a/types/decompress/decompress-tests.ts b/types/decompress/decompress-tests.ts index 9cb8949d99..5ed96c0b46 100644 --- a/types/decompress/decompress-tests.ts +++ b/types/decompress/decompress-tests.ts @@ -19,3 +19,24 @@ decompress('unicorn.zip', 'dist', { }).then((files: decompress.File[]) => { console.log('done!'); }); + +// Test decompress with no output to filesystem +decompress('unicorn.zip') + .then( + (files: decompress.File[]) => { + console.log(`Decompressed ${files.length} files with no write to filesystem`); + } + ); + +// Test decompress with DecompressOptions as second argument +decompress( + 'unicorn.zip', + { + filter: file => path.extname(file.path) !== '.exe' + } +) + .then( + (files: decompress.File[]) => { + console.log(`Decompressed ${files.length} files with filter options`); + } + ); diff --git a/types/decompress/index.d.ts b/types/decompress/index.d.ts index 745bebcd2e..2c4f464558 100644 --- a/types/decompress/index.d.ts +++ b/types/decompress/index.d.ts @@ -1,13 +1,14 @@ // Type definitions for decompress 4.2 // Project: https://github.com/kevva/decompress#readme // Definitions by: York Yao +// Jesse Bethke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// export = decompress; -declare function decompress(input: string | Buffer, output: string, opts?: decompress.DecompressOptions): Promise; +declare function decompress(input: string | Buffer, output?: string | decompress.DecompressOptions, opts?: decompress.DecompressOptions): Promise; declare namespace decompress { interface File { diff --git a/types/ethereumjs-util/index.d.ts b/types/ethereumjs-util/index.d.ts index eb47d3a6a9..c5ae356f5b 100644 --- a/types/ethereumjs-util/index.d.ts +++ b/types/ethereumjs-util/index.d.ts @@ -1,15 +1,15 @@ -// Type definitions for ethereumjs-util 5.1 +// Type definitions for ethereumjs-util 5.2 // Project: https://github.com/ethereumjs/ethereumjs-util#readme // Definitions by: Juan J. Jimenez-Anca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -// TODO: import types for [`BN`](https://github.com/indutny/bn.js) -// TODO: MAX_INTEGER as type of BN // TODO: import types for [`rlp`](https://github.com/ethereumjs/rlp) // TODO: import types for [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) +import BN = require("bn.js"); + export const SHA3_NULL_S: string; export const SHA3_RLP_ARRAY_S: string; @@ -18,13 +18,11 @@ export const SHA3_RLP_S: string; export function addHexPrefix(str: string): string; -export function arrayContainsArray(superset: any, subset: any, some: any): any; - -export function baToJSON(ba: Buffer | Uint8Array | string[]): Buffer | Uint8Array | string[]; +export function baToJSON(ba: Buffer | Uint8Array | string[]): Buffer | Uint8Array | string[] | null; export function bufferToHex(buf: Buffer | Uint8Array): string; -export function bufferToInt(buf: Buffer | Uint8Array): string; +export function bufferToInt(buf: Buffer | Uint8Array): number; export function defineProperties(self: {[k: string]: any}, fields: string[], data: {[k: string]: any}): {[k: string]: any}; @@ -34,14 +32,16 @@ export function ecsign(msgHash: Buffer | Uint8Array, privateKey: Buffer | Uint8A export function fromRpcSig(sig: string): {[k: string]: any}; -export function fromSigned(num: Buffer | Uint8Array): any; +export function fromSigned(num: Buffer | Uint8Array): BN; export function generateAddress(from: Buffer | Uint8Array, nonce: Buffer | Uint8Array): Buffer | Uint8Array; -export function hashPersonalMessage(message: string): Buffer | Uint8Array; +export function hashPersonalMessage(message: Buffer | Uint8Array | any[]): Buffer | Uint8Array; export function importPublic(publicKey: Buffer | Uint8Array): Buffer | Uint8Array; +export function isPrecompiled(address: Buffer | Uint8Array): boolean; + export function isValidAddress(address: string): boolean; export function isValidChecksumAddress(address: Buffer | Uint8Array): boolean; @@ -52,11 +52,17 @@ export function isValidPublic(publicKey: Buffer | Uint8Array, sanitize?: boolean export function isValidSignature(v: Buffer | Uint8Array, r: Buffer | Uint8Array, s: Buffer | Uint8Array, homestead?: boolean): boolean; +export function isZeroAddress(address: string): boolean; + +export function keccak(a: Buffer | Uint8Array | any[] | string | number, bits?: number): Buffer | Uint8Array; + +export function keccak256(a: Buffer | Uint8Array | any[] | string | number): Buffer | Uint8Array; + export function privateToAddress(privateKey: Buffer | Uint8Array): Buffer | Uint8Array; export function privateToPublic(privateKey: Buffer | Uint8Array): Buffer | Uint8Array; -export function pubToAddress(pubKey: Buffer | Uint8Array, sanitize: boolean): Buffer | Uint8Array; +export function pubToAddress(pubKey: Buffer | Uint8Array, sanitize?: boolean): Buffer | Uint8Array; export function ripemd160(a: Buffer | Uint8Array | any[] | string | number, padded: boolean): Buffer | Uint8Array; @@ -76,8 +82,10 @@ export function toChecksumAddress(address: string): string; export function toRpcSig(v: number, r: Buffer | Uint8Array, s: Buffer | Uint8Array): string; -export function toUnsigned(num: any): Buffer | Uint8Array; +export function toUnsigned(num: BN): Buffer | Uint8Array; export function unpad(a: T): T; export function zeros(bytes: number): Buffer | Uint8Array; + +export function zeroAddress(): string; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index e556e5255a..952cd4a086 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -7,6 +7,8 @@ // Fernando Helwanger // Umidbek Karimov // Moshe Feuchtwanger +// Michael Prokopchuk +// Tina Roh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -788,11 +790,31 @@ export interface CameraProps extends ViewProps { } export interface CameraConstants { - readonly Type: string; - readonly FlashMode: string; - readonly AutoFocus: string; - readonly WhiteBalance: string; - readonly VideoQuality: string; + readonly Type: { + back: string; + front: string; + }; + readonly FlashMode: { + on: string; + off: string; + auto: string; + torch: string; + }; + readonly AutoFocus: { + on: string; + off: string; + }; + readonly WhiteBalance: { + auto: string; + sunny: string; + cloudy: string; + shadow: string; + fluorescent: string; + incandescent: string; + }; + readonly VideoQuality: { + [videoQuality: string]: number; + }; readonly BarCodeType: { aztec: string; codabar: string; @@ -878,7 +900,7 @@ export namespace Constants { }; appKey?: string; androidStatusBar?: { - barStyle?: 'lignt-content' | 'dark-content', + barStyle?: 'light-content' | 'dark-content', backgroundColor?: string }; androidShowExponentNotificationInShellApp?: boolean; @@ -1390,12 +1412,24 @@ export namespace Font { } // #region GLView +export interface ExpoWebGLRenderingContext extends WebGLRenderingContext { + endFrameEXP(): void; +} + /** - * GLView + * A View that acts as an OpenGL ES render target. On mounting, an OpenGL ES + * context is created. Its drawing buffer is presented as the contents of + * the View every frame. */ export interface GLViewProps extends ViewProps { - onContextCreate(): void; - msaaSamples: number; + /** + * A function that will be called when the OpenGL ES context is created. + * Passes an object with a WebGLRenderingContext interface as an argument. + */ + onContextCreate(gl: ExpoWebGLRenderingContext): void; + + /** Number of MSAA samples to use on iOS. Defaults to 4. Ignored on Android. */ + msaaSamples?: number; } export class GLView extends Component { } diff --git a/types/expo/v26/index.d.ts b/types/expo/v26/index.d.ts index 4e7a0ebdb3..f1641ea643 100644 --- a/types/expo/v26/index.d.ts +++ b/types/expo/v26/index.d.ts @@ -6,6 +6,7 @@ // Sergio Sánchez // Fernando Helwanger // Umidbek Karimov +// Tina Roh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -787,11 +788,31 @@ export interface CameraProps extends ViewProps { } export interface CameraConstants { - readonly Type: string; - readonly FlashMode: string; - readonly AutoFocus: string; - readonly WhiteBalance: string; - readonly VideoQuality: string; + readonly Type: { + back: string; + front: string; + }; + readonly FlashMode: { + on: string; + off: string; + auto: string; + torch: string; + }; + readonly AutoFocus: { + on: string; + off: string; + }; + readonly WhiteBalance: { + auto: string; + sunny: string; + cloudy: string; + shadow: string; + fluorescent: string; + incandescent: string; + }; + readonly VideoQuality: { + [videoQuality: string]: number; + }; readonly BarCodeType: { aztec: string; codabar: string; @@ -877,7 +898,7 @@ export namespace Constants { }; appKey?: string; androidStatusBar?: { - barStyle?: 'lignt-content' | 'dark-content', + barStyle?: 'light-content' | 'dark-content', backgroundColor?: string }; androidShowExponentNotificationInShellApp?: boolean; diff --git a/types/express-brute/index.d.ts b/types/express-brute/index.d.ts index b7961ea597..8f1b6fbf11 100644 --- a/types/express-brute/index.d.ts +++ b/types/express-brute/index.d.ts @@ -67,19 +67,19 @@ declare namespace ExpressBrute { * @summary Allows you to override the value of failCallback for this middleware. * @type {Function} */ - failCallback: Function; + failCallback?: Function; /** * @summary Disregard IP address when matching requests if set to true. Defaults to false. * @type {boolean} */ - ignoreIP: boolean; + ignoreIP?: boolean; /** * @summary Key. * @type {any} */ - key: any; + key?: any; } /** @@ -156,5 +156,13 @@ declare namespace ExpressBrute { reset(key: string, callback: (error: any) => void): void; } } + +declare module "express-serve-static-core" { + export interface Request { + brute?: { + reset?: (callback?: () => void) => void + }; + } +} export = ExpressBrute; diff --git a/types/express-socket.io-session/express-socket.io-session-tests.ts b/types/express-socket.io-session/express-socket.io-session-tests.ts index 46dd000882..6937952dd6 100644 --- a/types/express-socket.io-session/express-socket.io-session-tests.ts +++ b/types/express-socket.io-session/express-socket.io-session-tests.ts @@ -26,3 +26,19 @@ io.use(sharedsession(session)); io.use(sharedsession(session, { autoSave: true, saveUninitialized: true })); io.use(sharedsession(session, cookieParser)); io.use(sharedsession(session, cookieParser, { autoSave: true, saveUninitialized: true })); + +io.on('connection', (socket) => { + const sessionID = [ + socket.handshake.sessionID, + socket.handshake.session!.id + ]; + const sessionData = [ + socket.handshake.session!['sessionEntry'], + socket.handshake.session!.anotherSessionEntry + ]; + socket.handshake.session!.touch(() => {}); + socket.handshake.session!.regenerate(() => {}); + socket.handshake.session!.save(() => {}); + socket.handshake.session!.reload(() => {}); + socket.handshake.session!.destroy(() => {}); +}); diff --git a/types/express-socket.io-session/index.d.ts b/types/express-socket.io-session/index.d.ts index 39a1fb4ff6..07acac556a 100644 --- a/types/express-socket.io-session/index.d.ts +++ b/types/express-socket.io-session/index.d.ts @@ -7,6 +7,13 @@ import socketio = require('socket.io'); import express = require('express'); +declare module "socket.io" { + interface Handshake { + session?: Express.Session; + sessionID?: string; + } +} + declare function sharedsession( expressSessionMiddleware: express.RequestHandler, cookieParserMiddleware: express.RequestHandler, diff --git a/types/google-adwords-scripts/index.d.ts b/types/google-adwords-scripts/index.d.ts index 3e64730056..adf58cb4a4 100644 --- a/types/google-adwords-scripts/index.d.ts +++ b/types/google-adwords-scripts/index.d.ts @@ -1387,7 +1387,7 @@ interface hasStartAndEndDateBuilder { } interface hasStats { - getStatsFor(dateRange: DayOfWeekString): AdWordsStats; + getStatsFor(dateRange: DateRange): AdWordsStats; getStatsFor(dateFrom: AdWordsDate | string, dateTo: AdWordsDate | string): AdWordsStats; } diff --git a/types/google-apps-script/google-apps-script.card.d.ts b/types/google-apps-script/google-apps-script.card.d.ts index 62d497eb4f..d879d30091 100644 --- a/types/google-apps-script/google-apps-script.card.d.ts +++ b/types/google-apps-script/google-apps-script.card.d.ts @@ -82,6 +82,10 @@ declare namespace GoogleAppsScript { * Sets the URL to navigate to when the action is activated. */ setOpenLink(openLink: OpenLink): ActionResponseBuilder; + /** + * Sets a flag to indicate that this action changed the existing data state. + */ + setStateChanged(stateChanged: boolean): ActionResponseBuilder; } export interface AuthorizationAction { diff --git a/types/grecaptcha/grecaptcha-tests.ts b/types/grecaptcha/grecaptcha-tests.ts index f1da1b35b4..288836d6b3 100644 --- a/types/grecaptcha/grecaptcha-tests.ts +++ b/types/grecaptcha/grecaptcha-tests.ts @@ -4,8 +4,10 @@ const params: ReCaptchaV2.Parameters = { type: "image", size: "normal", tabindex: 5, + isolated: false, callback: (response: string) => { }, "expired-callback": () => { }, + "error-callback": () => { }, }; const size1: ReCaptchaV2.Size = "compact"; @@ -25,6 +27,7 @@ const id1: number = grecaptcha.render("foo"); const id2: number = grecaptcha.render("foo", params); const id3: number = grecaptcha.render(document.getElementById("foo")); const id4: number = grecaptcha.render(document.getElementById("foo"), params); +const id5: number = grecaptcha.render(document.getElementById("foo"), params, true); // response takes a number and returns a string const response1: string = grecaptcha.getResponse(id1); diff --git a/types/grecaptcha/index.d.ts b/types/grecaptcha/index.d.ts index 067139e6c9..c9dedbfb74 100644 --- a/types/grecaptcha/index.d.ts +++ b/types/grecaptcha/index.d.ts @@ -1,19 +1,24 @@ // Type definitions for Google Recaptcha 2.0 // Project: https://www.google.com/recaptcha -// Definitions by: Kristof Mattei , Martin Costello , Ruslan Arkhipau +// Definitions by: Kristof Mattei +// Martin Costello +// Ruslan Arkhipau +// Rafael Tavares // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var grecaptcha: ReCaptchaV2.ReCaptcha; declare namespace ReCaptchaV2 { - class ReCaptcha { + interface ReCaptcha { /** * Renders the container as a reCAPTCHA widget and returns the ID of the newly created widget. * @param container The HTML element to render the reCAPTCHA widget. Specify either the ID of the container (string) or the DOM element itself. * @param parameters An object containing parameters as key=value pairs, for example, {"sitekey": "your_site_key", "theme": "light"}. See @see render parameters. + * @param inherit Invisible reCAPTCHA only. Use existing data-* attributes on the element if the corresponding parameter is not specified. + * The values in parameters will take precedence over the attributes. * @return the ID of the newly created widget. */ - render(container: (string | HTMLElement), parameters?: Parameters): number; + render(container: (string | HTMLElement), parameters?: Parameters, inherit?: boolean): number; /** * Resets the reCAPTCHA widget. * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. @@ -65,11 +70,6 @@ declare namespace ReCaptchaV2 { * If other elements in your page use tabindex, it should be set to make user navigation easier. */ tabindex?: number; - /** - * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. - * The user's response, g-recaptcha-response, will be the input for your callback function. - */ - callback?(response: string): void; /** * Optional. The badge location for g-recaptcha with size of "invisible". * @@ -77,10 +77,29 @@ declare namespace ReCaptchaV2 { */ badge?: Badge; /** - * Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. + * Optional. Invisible reCAPTCHA only. For plugin owners to not interfere with existing reCAPTCHA installations on a page. + * If true, this reCAPTCHA instance will be part of a separate ID space. + * + * @default false + */ + isolated?: boolean; + /** + * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. + * The user's response, g-recaptcha-response, will be the input for your callback function. + */ + callback?(response: string): void; + /** + * Optional. Your callback function that's executed when the reCAPTCHA response expires and the user needs to solve a new CAPTCHA. */ // Notice to the reader // I need to surround this object with quotes, this will however break intellisense in VS 2013. "expired-callback"?(): void; + /** + * Optional. Your callback function that's executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. + * If you specify this function, you are responsible for informing the user that they should retry. + */ + // Notice to the reader + // I need to surround this object with quotes, this will however break intellisense in VS 2013. + "error-callback"?(): void; } } diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 3858cab780..6e67a5b592 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -32,6 +32,11 @@ export interface IFrameOptions { * CSS margin attribute, for example '8px 3em'. A number value is converted into px. */ bodyMargin?: number | string; + /** + * Override the default body padding style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyPadding?: number | string; /** * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. * If your iFrame navigates between different domains, ports or protocols; then you will need to diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index ce0ff1439a..d11f79df64 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jest 23.0 +// Type definitions for Jest 23.1 // Project: http://facebook.github.io/jest/ // Definitions by: Asana // Ivo Stratev @@ -12,10 +12,9 @@ // Douglas Duteil // Ahn // Josh Goldberg -// Bradley Ayers // Jeff Lau // Andrew Makarov -// Paweł Mikołajczyk +// Martin Hochel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -884,6 +883,164 @@ declare namespace jest { type SnapshotUpdateState = 'all' | 'new' | 'none'; + interface DefaultOptions { + automock: boolean; + bail: boolean; + browser: boolean; + cache: boolean; + cacheDirectory: Path; + changedFilesWithAncestor: boolean; + clearMocks: boolean; + collectCoverage: boolean; + collectCoverageFrom: Maybe; + coverageDirectory: Maybe; + coveragePathIgnorePatterns: string[]; + coverageReporters: string[]; + coverageThreshold: Maybe<{global: {[key: string]: number}}>; + errorOnDeprecated: boolean; + expand: boolean; + filter: Maybe; + forceCoverageMatch: Glob[]; + globals: ConfigGlobals; + globalSetup: Maybe; + globalTeardown: Maybe; + haste: HasteConfig; + detectLeaks: boolean; + detectOpenHandles: boolean; + moduleDirectories: string[]; + moduleFileExtensions: string[]; + moduleNameMapper: {[key: string]: string}; + modulePathIgnorePatterns: string[]; + noStackTrace: boolean; + notify: boolean; + notifyMode: string; + preset: Maybe; + projects: Maybe>; + resetMocks: boolean; + resetModules: boolean; + resolver: Maybe; + restoreMocks: boolean; + rootDir: Maybe; + roots: Maybe; + runner: string; + runTestsByPath: boolean; + setupFiles: Path[]; + setupTestFrameworkScriptFile: Maybe; + skipFilter: boolean; + snapshotSerializers: Path[]; + testEnvironment: string; + testEnvironmentOptions: object; + testFailureExitCode: string | number; + testLocationInResults: boolean; + testMatch: Glob[]; + testPathIgnorePatterns: string[]; + testRegex: string; + testResultsProcessor: Maybe; + testRunner: Maybe; + testURL: string; + timers: 'real' | 'fake'; + transform: Maybe<{[key: string]: string}>; + transformIgnorePatterns: Glob[]; + watchPathIgnorePatterns: string[]; + useStderr: boolean; + verbose: Maybe; + watch: boolean; + watchman: boolean; + } + + interface InitialOptions { + automock?: boolean; + bail?: boolean; + browser?: boolean; + cache?: boolean; + cacheDirectory?: Path; + clearMocks?: boolean; + changedFilesWithAncestor?: boolean; + changedSince?: string; + collectCoverage?: boolean; + collectCoverageFrom?: Glob[]; + collectCoverageOnlyFrom?: {[key: string]: boolean}; + coverageDirectory?: string; + coveragePathIgnorePatterns?: string[]; + coverageReporters?: string[]; + coverageThreshold?: {global: {[key: string]: number}}; + detectLeaks?: boolean; + detectOpenHandles?: boolean; + displayName?: string; + expand?: boolean; + filter?: Path; + findRelatedTests?: boolean; + forceCoverageMatch?: Glob[]; + forceExit?: boolean; + json?: boolean; + globals?: ConfigGlobals; + globalSetup?: Maybe; + globalTeardown?: Maybe; + haste?: HasteConfig; + reporters?: Array; + logHeapUsage?: boolean; + lastCommit?: boolean; + listTests?: boolean; + mapCoverage?: boolean; + moduleDirectories?: string[]; + moduleFileExtensions?: string[]; + moduleLoader?: Path; + moduleNameMapper?: {[key: string]: string}; + modulePathIgnorePatterns?: string[]; + modulePaths?: string[]; + name?: string; + noStackTrace?: boolean; + notify?: boolean; + notifyMode?: string; + onlyChanged?: boolean; + outputFile?: Path; + passWithNoTests?: boolean; + preprocessorIgnorePatterns?: Glob[]; + preset?: Maybe; + projects?: Glob[]; + replname?: Maybe; + resetMocks?: boolean; + resetModules?: boolean; + resolver?: Maybe; + restoreMocks?: boolean; + rootDir?: Path; + roots?: Path[]; + runner?: string; + runTestsByPath?: boolean; + scriptPreprocessor?: string; + setupFiles?: Path[]; + setupTestFrameworkScriptFile?: Path; + silent?: boolean; + skipFilter?: boolean; + skipNodeResolution?: boolean; + snapshotSerializers?: Path[]; + errorOnDeprecated?: boolean; + testEnvironment?: string; + testEnvironmentOptions?: object; + testFailureExitCode?: string | number; + testLocationInResults?: boolean; + testMatch?: Glob[]; + testNamePattern?: string; + testPathDirs?: Path[]; + testPathIgnorePatterns?: string[]; + testRegex?: string; + testResultsProcessor?: Maybe; + testRunner?: string; + testURL?: string; + timers?: 'real' | 'fake'; + transform?: {[key: string]: string}; + transformIgnorePatterns?: Glob[]; + watchPathIgnorePatterns?: string[]; + unmockedModulePathPatterns?: string[]; + updateSnapshot?: boolean; + useStderr?: boolean; + verbose?: Maybe; + watch?: boolean; + watchAll?: boolean; + watchman?: boolean; + watchPlugins?: string[]; + } + interface GlobalConfig { bail: boolean; collectCoverage: boolean; diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 393890025b..a03c49330b 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -1,765 +1,961 @@ -// TODO: Avoid requiring things that don't exist. -declare var require: { - (s: string): any; - requireActual(s: string): any; - requireMock(s: string): any; +/* Lifecycle events */ + +beforeAll(() => {}); +beforeAll((done: jest.DoneCallback) => {}); +beforeAll((done: jest.DoneCallback) => done.fail(), 9001); + +beforeEach(() => {}); +beforeEach((done: jest.DoneCallback) => {}); +beforeEach((done: jest.DoneCallback) => done.fail(), 9001); + +afterAll(() => {}); +afterAll((done: jest.DoneCallback) => {}); +afterAll((done: jest.DoneCallback) => done.fail(), 9001); + +afterEach(() => {}); +afterEach((done: jest.DoneCallback) => {}); +afterEach((done: jest.DoneCallback) => done.fail(), 9001); + +/* describe */ + +describe(0, () => {}); +describe("name", () => {}); +describe(() => {}, () => {}); +describe({ name: "name" }, () => {}); + +describe.only(0, () => {}); +describe.only("name", () => {}); +describe.only(() => {}, () => {}); +describe.only({ name: "name" }, () => {}); + +describe.skip(0, () => {}); +describe.skip("name", () => {}); +describe.skip(() => {}, () => {}); +describe.skip({ name: "name" }, () => {}); + +fdescribe(0, () => {}); +fdescribe("name", () => {}); +fdescribe(() => {}, () => {}); +fdescribe({ name: "name" }, () => {}); + +fdescribe.only(0, () => {}); +fdescribe.only("name", () => {}); +fdescribe.only(() => {}, () => {}); +fdescribe.only({ name: "name" }, () => {}); + +fdescribe.skip(0, () => {}); +fdescribe.skip("name", () => {}); +fdescribe.skip(() => {}, () => {}); +fdescribe.skip({ name: "name" }, () => {}); + +xdescribe(0, () => {}); +xdescribe("name", () => {}); +xdescribe(() => {}, () => {}); +xdescribe({ name: "name" }, () => {}); + +xdescribe.only(0, () => {}); +xdescribe.only("name", () => {}); +xdescribe.only(() => {}, () => {}); +xdescribe.only({ name: "name" }, () => {}); + +xdescribe.skip(0, () => {}); +xdescribe.skip("name", () => {}); +xdescribe.skip(() => {}, () => {}); +xdescribe.skip({ name: "name" }, () => {}); + +/* it */ + +it("name", () => {}); +it("name", async () => {}); +it("name", () => {}, 9001); +it("name", async () => {}, 9001); +it("name", (callback: jest.DoneCallback) => {}, 9001); + +it.only("name", () => {}); +it.only("name", async () => {}); +it.only("name", () => {}, 9001); +it.only("name", async () => {}, 9001); +it.only("name", (callback: jest.DoneCallback) => {}, 9001); + +it.skip("name", () => {}); +it.skip("name", async () => {}); +it.skip("name", () => {}, 9001); +it.skip("name", async () => {}, 9001); +it.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +it.concurrent("name", () => {}); +it.concurrent("name", async () => {}); +it.concurrent("name", () => {}, 9001); +it.concurrent("name", async () => {}, 9001); +it.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +fit("name", () => {}); +fit("name", async () => {}); +fit("name", () => {}, 9001); +fit("name", async () => {}, 9001); +fit("name", (callback: jest.DoneCallback) => {}, 9001); + +fit.only("name", () => {}); +fit.only("name", async () => {}); +fit.only("name", () => {}, 9001); +fit.only("name", async () => {}, 9001); +fit.only("name", (callback: jest.DoneCallback) => {}, 9001); + +fit.skip("name", () => {}); +fit.skip("name", async () => {}); +fit.skip("name", () => {}, 9001); +fit.skip("name", async () => {}, 9001); +fit.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +fit.concurrent("name", () => {}); +fit.concurrent("name", async () => {}); +fit.concurrent("name", () => {}, 9001); +fit.concurrent("name", async () => {}, 9001); +fit.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +xit("name", () => {}); +xit("name", async () => {}); +xit("name", () => {}, 9001); +xit("name", async () => {}, 9001); +xit("name", (callback: jest.DoneCallback) => {}, 9001); + +xit.only("name", () => {}); +xit.only("name", async () => {}); +xit.only("name", () => {}, 9001); +xit.only("name", async () => {}, 9001); +xit.only("name", (callback: jest.DoneCallback) => {}, 9001); + +xit.skip("name", () => {}); +xit.skip("name", async () => {}); +xit.skip("name", () => {}, 9001); +xit.skip("name", async () => {}, 9001); +xit.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +xit.concurrent("name", () => {}); +xit.concurrent("name", async () => {}); +xit.concurrent("name", () => {}, 9001); +xit.concurrent("name", async () => {}, 9001); +xit.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +test("name", () => {}); +test("name", async () => {}); +test("name", () => {}, 9001); +test("name", async () => {}, 9001); +test("name", (callback: jest.DoneCallback) => {}, 9001); + +test.only("name", () => {}); +test.only("name", async () => {}); +test.only("name", () => {}, 9001); +test.only("name", async () => {}, 9001); +test.only("name", (callback: jest.DoneCallback) => {}, 9001); + +test.skip("name", () => {}); +test.skip("name", async () => {}); +test.skip("name", () => {}, 9001); +test.skip("name", async () => {}, 9001); +test.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +test.concurrent("name", () => {}); +test.concurrent("name", async () => {}); +test.concurrent("name", () => {}, 9001); +test.concurrent("name", async () => {}, 9001); +test.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +xtest("name", () => {}); +xtest("name", async () => {}); +xtest("name", () => {}, 9001); +xtest("name", async () => {}, 9001); +xtest("name", (callback: jest.DoneCallback) => {}, 9001); + +xtest.only("name", () => {}); +xtest.only("name", async () => {}); +xtest.only("name", () => {}, 9001); +xtest.only("name", async () => {}, 9001); +xtest.only("name", (callback: jest.DoneCallback) => {}, 9001); + +xtest.skip("name", () => {}); +xtest.skip("name", async () => {}); +xtest.skip("name", () => {}, 9001); +xtest.skip("name", async () => {}, 9001); +xtest.skip("name", (callback: jest.DoneCallback) => {}, 9001); + +xtest.concurrent("name", () => {}); +xtest.concurrent("name", async () => {}); +xtest.concurrent("name", () => {}, 9001); +xtest.concurrent("name", async () => {}, 9001); +xtest.concurrent("name", (callback: jest.DoneCallback) => {}, 9001); + +/* Done callbacks */ + +describe("", () => { + it("", (callback: jest.DoneCallback): void => { + callback(); + callback(""); + callback("", 3); + callback.fail(); + callback.fail("error"); + callback.fail({ message: "message" }); + }); +}); + +/* NodeRequire interface (require extensions) */ + +declare const nodeRequire: NodeRequire; + +// $ExpectType any +nodeRequire.requireActual("moduleName"); + +// $ExpectType any +nodeRequire.requireMock("moduleName"); + +/* Top-level jest namespace functions */ + +const customMatcherFactories: jasmine.CustomMatcherFactories = {}; + +jest + .addMatchers(customMatcherFactories) + .addMatchers({}) + .addMatchers(customMatcherFactories) + .autoMockOff() + .autoMockOn() + .clearAllMocks() + .clearAllTimers() + .resetAllMocks() + .restoreAllMocks() + .clearAllTimers() + .deepUnmock("moduleName") + .disableAutomock() + .doMock("moduleName") + .doMock("moduleName", jest.fn()) + .doMock("moduleName", jest.fn(), {}) + .doMock("moduleName", jest.fn(), { virtual: true }) + .dontMock("moduleName") + .enableAutomock() + .mock("moduleName") + .mock("moduleName", jest.fn()) + .mock("moduleName", jest.fn(), {}) + .mock("moduleName", jest.fn(), { virtual: true }) + .resetModuleRegistry() + .resetModules() + .runAllImmediates() + .runAllTicks() + .runAllTimers() + .runOnlyPendingTimers() + .runTimersToTime(9001) + .advanceTimersByTime(9001) + .setMock("moduleName", {}) + .setMock<{}>("moduleName", {}) + .setMock<{ a: "b" }>("moduleName", { a: "b" }) + .setTimeout(9001) + .unmock("moduleName") + .useFakeTimers() + .useRealTimers(); + +/* Mocks and spies */ + +const mock1: jest.Mock = jest.fn(); +const mock2: jest.Mock = jest.fn(() => undefined); +const mock3: jest.Mock = jest.fn(() => "abc"); +const mock4: jest.Mock<"abc"> = jest.fn((): "abc" => "abc"); +const mock5: jest.Mock = jest.fn((...args: string[]) => args.join("")); +const mock6: jest.Mock = jest.fn((arg: {}) => arg); + +const genMockModule1: {} = jest.genMockFromModule("moduleName"); +const genMockModule2: { a: "b" } = jest.genMockFromModule<{ a: "b" }>("moduleName"); + +const isStringMock: boolean = jest.isMockFunction("foo"); +const isMockMock: boolean = jest.isMockFunction(mock1); + +const maybeMock = () => {}; +if (jest.isMockFunction(maybeMock)) { + maybeMock.getMockName(); +} + +const mockName: string = jest.fn().getMockName(); +const mockContextVoid: jest.MockContext = jest.fn().mock; +const mockContextString: jest.MockContext = jest.fn(() => "").mock; + +jest.fn().mockClear(); + +jest.fn().mockReset(); + +const spiedTarget = { + returnsVoid(): void { }, + returnsString(): string { + return ""; + } }; -// TODO: use real jquery types? -declare const $: any; -// Tests based on the Jest website -jest.unmock('../sum'); +const spy1 = jest.spyOn(spiedTarget, "returnsVoid"); +const spy2 = jest.spyOn(spiedTarget, "returnsVoid", "get"); +const spy3 = jest.spyOn(spiedTarget, "returnsString", "set"); -class TestClass { } +const spy1Name: string = spy1.getMockName(); -describe(TestClass, () => { }); +const spy2Calls: any[][] = spy2.mock.calls; -describe('sum', () => { - it('adds 1 + 2 to equal 3', () => { - const sum: (a: number, b: number) => number = require('../sum'); - expect(sum(1, 2)).toBe(3); - }); +spy2.mockClear(); +spy2.mockReset(); + +const spy3Mock: jest.Mock<() => string> = spy3 + .mockImplementation(() => "") + .mockImplementation((arg: {}) => arg) + .mockImplementation((...args: string[]) => args.join("")) + .mockName("name") + .mockReturnThis() + .mockReturnValue("value") + .mockReturnValueOnce("value") + .mockResolvedValue("value") + .mockResolvedValueOnce("value") + .mockRejectedValue("value") + .mockRejectedValueOnce("value"); + +/* Snapshot serialization */ + +const snapshotSerializerPlugin: jest.SnapshotSerializerPlugin = { + print: () => "", + test: () => true, +}; + +expect.addSnapshotSerializer(snapshotSerializerPlugin); + +expect.addSnapshotSerializer({ + print: (value: {}) => "", + test: (value: {}) => value === value, }); -describe('restoreAllMocks', () => { - afterEach(() => { - jest.restoreAllMocks(); - }); +expect.addSnapshotSerializer({ + print: ( + value: {}, + serialize: ((val: {}) => string), + indent: ((str: string) => string), + opts: {}, + ) => "", + test: (value: {}) => value === value, }); -describe('fetchCurrentUser', () => { - it('calls the callback when $.ajax requests are finished', () => { - const fetchCurrentUser = require('../fetchCurrentUser'); +expect.addSnapshotSerializer({ + print(value, serialize, indent, opts, colors) { + let result = ""; - // Create a mock function for our callback - const callback = jest.fn(); - fetchCurrentUser(callback); + if (opts.callToJSON !== undefined && opts.callToJSON) { + result += " "; + } - // Now we emulate the process by which `$.ajax` would execute its own - // callback - $.ajax.mock.calls[0 /*first call*/][0 /*first argument*/].success({ - firstName: 'Bobby', - lastName: '");DROP TABLE Users;--' - }); + result += opts.edgeSpacing; + result += opts.spacing; - // And finally we assert that this emulated call by `$.ajax` incurred a - // call back into the mock function we provided as a callback - expect(callback.mock.calls[0/*first call*/][0/*first arg*/]).toEqual({ - loggedIn: true, - fullName: 'Bobby ");DROP TABLE Users;--' - }); - }); + if (opts.escapeRegex !== undefined && opts.escapeRegex) { + result += " "; + } + + if (opts.indent !== undefined) { + for (let i = 0; i < opts.indent; i += 1) { + result += "\t"; + } + } + + if (opts.maxDepth !== undefined) { + result = result.substring(0, opts.maxDepth); + } + + if (opts.min !== undefined && opts.min) { + result += " "; + } + + if (opts.plugins !== undefined) { + for (const plugin of opts.plugins) { + expect.addSnapshotSerializer(plugin); + } + } + + if (opts.printFunctionName !== undefined && opts.printFunctionName) { + result += " "; + } + + if (opts.theme) { + if (opts.theme.comment !== undefined) { + result += opts.theme.comment; + } + + if (opts.theme.content !== undefined) { + result += opts.theme.content; + } + + if (opts.theme.prop !== undefined) { + result += opts.theme.prop; + } + + if (opts.theme.tag !== undefined) { + result += opts.theme.tag; + } + + if (opts.theme.value !== undefined) { + result += opts.theme.value; + } + } + + for (const color of [ + colors.comment, + colors.content, + colors.prop, + colors.tag, + colors.value, + ]) { + result += color.open; + result += color.close; + } + + return result; + }, + test: (value: {}) => value === value, }); -// unmock is the recommended approach for unmocking... -jest.unmock('../displayUser.js'); +/* expect extensions */ -describe('displayUser', () => { - it('displays a user after a click', () => { - // Set up our document body - document.body.innerHTML = - '
' + - ' ' + - '
'; +const expectExtendMap: jest.ExpectExtendMap = {}; - const displayUser = require.requireActual('../displayUser'); - const $ = require('jquery'); - const fetchCurrentUser = require('../fetchCurrentUser'); - - // Tell the fetchCurrentUser mock function to automatically invoke - // its callback with some data - fetchCurrentUser.mockImplementation((cb: (...args: any[]) => any) => { - cb({ - loggedIn: true, - fullName: 'Johnny Cash' - }); - }); - - // Use jquery to emulate a click on our button - $('#button').click(); - - // Assert that the fetchCurrentUser function was called, and that the - // #username span's innter text was updated as we'd it expect. - expect(fetchCurrentUser).toBeCalled(); - expect($('#username').text()).toEqual('Johnny Cash - Logged In'); - }); -}); - -jest.unmock('../CheckboxWithLabel.js'); -describe('CheckboxWithLabel', () => { - it('changes the text after click', () => { - const React = require('react/addons'); - const CheckboxWithLabel = require('../CheckboxWithLabel.js'); - const TestUtils = React.addons.TestUtils; - - // Render a checkbox with label in the document - const checkbox = TestUtils.renderIntoDocument( - CheckboxWithLabel({ - labelOn: "On", - labelOff: "Off" - }) - ); - - // Verify that it's Off by default - const label = TestUtils.findRenderedDOMComponentWithTag( - checkbox, 'label'); - expect(label.getDOMNode().textContent).toEqual('Off'); - - // Simulate a click and verify that it is now On - const input = TestUtils.findRenderedDOMComponentWithTag( - checkbox, 'input'); - TestUtils.Simulate.change(input); - expect(label.getDOMNode().textContent).toEqual('On'); - }); -}); - -jest.runAllTicks(); -xdescribe('Hooks and Suits', () => { - let tested: boolean; - - beforeEach(() => { - tested = false; - }); - - afterEach(() => { - tested = true; - }); - - test('tested', () => { - expect(tested).toBeTruthy(); - expect(tested).not.toBeFalsy(); - }); - - fit('tested', () => { - expect(tested).toBeDefined(); - expect(tested).not.toBeUndefined(); - }); - - xit('expect null to be null', () => { - expect(null).toBeNull(); - }); - - xit('expect NaN to be NaN', () => { - expect(NaN).toBeNaN(); - }); -}); - -describe('compartion', () => { - const sum: (a: number, b: number) => number = require.requireMock('../sum'); - - it('compares is 7 + 2 greater than 3', () => { - expect(sum(7, 2)).toBeGreaterThan(3); - }); - - it('compares is 2 + 7 greater than or equal to 3', () => { - expect(sum(2, 7)).toBeGreaterThanOrEqual(3); - }); - - it('compares is 3 less than 3 + 4', () => { - expect(3).toBeLessThan(sum(3, 4)); - }); - - it('compares is 3 less than or equal to 4 + 3', () => { - expect(3).toBeLessThanOrEqual(sum(4, 3)); - }); - - it('works sanely with simple decimals', () => { - expect(0.2 + 0.1).toBeCloseTo(0.3, 5); - }); - - it('works sanely with simple decimals and the default delta', () => { - expect(0.2 + 0.1).toBeCloseTo(0.3); - }); -}); - -describe('toThrow API', () => { - function throwTypeError(): void { - throw new TypeError('toThrow Definition was out of date'); - } - - it('throws', () => { - expect(throwTypeError()).toThrow(); - expect(throwTypeError()).toThrowError(); - }); - - it('throws TypeError', () => { - expect(throwTypeError()).toThrow(TypeError); - expect(throwTypeError()).toThrowError(TypeError); - }); - - it('throws \'Definition was out of date\'', () => { - expect(throwTypeError()).toThrow(/Definition was out of date/); - expect(throwTypeError()).toThrowError(/Definition was out of date/); - }); - - it('throws \'toThorow Definition was out of date\'', () => { - expect(throwTypeError()).toThrow('toThrow Definition was out of date'); - expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); - }); -}); - -describe('Assymetric matchers', () => { - it('works', () => { - expect({ - timestamp: 1480807810388, - text: 'Some text content, but we care only about *this part*', - color: '#bada55', - greeting: 'hello, world!', - }).toEqual({ - timestamp: expect.any(Number), - text: expect.stringMatching('*this part*'), - color: expect.stringMatching(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i), - greeting: expect.stringContaining('hello'), - }); - - expect("foo").toStrictEqual("foo"); - expect({ a: "foo" }).toStrictEqual({ a: "foo" }); - - const callback = jest.fn(); - expect(callback).toEqual(expect.any(Function)); - callback(5, "test"); - expect(callback).toBeCalledWith(expect.any(Number), expect.any(String)); - const obj = { - items: [1] +expect.extend(expectExtendMap); +expect.extend({}); +expect.extend({ + foo(this: jest.MatcherUtils, received: {}, ...actual: Array<{}>) { + return { + message: () => JSON.stringify(received), + pass: false, }; - expect(obj).toEqual(expect.objectContaining({ - items: expect.arrayContaining([ - expect.any(Number) - ]) + } +}); + +/* Basic matchers */ + +describe("", () => { + it("", () => { + expect(jest.fn()).lastCalledWith(); + expect(jest.fn()).lastCalledWith("jest"); + expect(jest.fn()).lastCalledWith({}, {}); + + expect(jest.fn()).lastReturnedWith("jest"); + expect(jest.fn()).lastReturnedWith({}); + + expect(jest.fn()).nthReturnedWith(0, "jest"); + expect(jest.fn()).nthReturnedWith(1, {}); + + expect({}).toBe({}); + expect([]).toBe([]); + expect(10).toBe(10); + + expect(jest.fn()).toBeCalled(); + + expect(jest.fn()).toBeCalledWith(); + expect(jest.fn()).toBeCalledWith("jest"); + expect(jest.fn()).toBeCalledWith({}, {}); + + expect(0).toBeCloseTo(1); + expect(0).toBeCloseTo(1, 2); + + expect(undefined).toBeDefined(); + expect({}).toBeDefined(); + + expect(true).toBeFalsy(); + expect(false).toBeFalsy(); + expect(0).toBeFalsy(); + + expect(0).toBeGreaterThan(1); + + expect(0).toBeGreaterThanOrEqual(1); + + expect(3).toBeInstanceOf(Number); + + expect(0).toBeLessThan(1); + + expect(0).toBeLessThanOrEqual(1); + + expect(null).toBeNull(); + expect(undefined).toBeNull(); + + expect(true).toBeTruthy(); + expect(false).toBeFalsy(); + expect(1).toBeTruthy(); + + expect(undefined).toBeUndefined(); + expect({}).toBeUndefined(); + + expect(NaN).toBeNaN(); + expect(Infinity).toBeNaN(); + + expect([]).toContain({}); + expect(["abc"]).toContain("abc"); + expect(["abc"]).toContain("def"); + + expect([]).toContainEqual({}); + expect(["abc"]).toContainEqual("def"); + + expect([]).toEqual([]); + expect({}).toEqual({}); + + expect(jest.fn()).toHaveBeenCalled(); + + expect(jest.fn()).toHaveBeenCalledTimes(0); + expect(jest.fn()).toHaveBeenCalledTimes(1); + + expect(jest.fn()).toHaveBeenCalledWith(); + expect(jest.fn()).toHaveBeenCalledWith("jest"); + expect(jest.fn()).toHaveBeenCalledWith({}, {}); + + expect(jest.fn()).toHaveBeenCalledWith(0); + expect(jest.fn()).toHaveBeenCalledWith(1, "jest"); + expect(jest.fn()).toHaveBeenCalledWith(2, {}, {}); + + expect(jest.fn()).toHaveBeenLastCalledWith(); + expect(jest.fn()).toHaveBeenLastCalledWith("jest"); + expect(jest.fn()).toHaveBeenLastCalledWith({}, {}); + + expect(jest.fn()).toHaveLastReturnedWith("jest"); + expect(jest.fn()).toHaveLastReturnedWith({}); + + expect([]).toHaveLength(0); + expect("").toHaveLength(1); + + expect(jest.fn()).toHaveNthReturnedWith(0, "jest"); + expect(jest.fn()).toHaveNthReturnedWith(1, {}); + + expect({}).toHaveProperty("property"); + expect({}).toHaveProperty("property", {}); + expect({}).toHaveProperty(["property"]); + expect({}).toHaveProperty(["property"], {}); + expect({}).toHaveProperty(["property", "deep"]); + expect({}).toHaveProperty(["property", "deep"], {}); + + expect(jest.fn()).toHaveReturned(); + + expect(jest.fn()).toHaveReturnedTimes(0); + expect(jest.fn()).toHaveReturnedTimes(1); + + expect(jest.fn()).toHaveReturnedWith("jest"); + expect(jest.fn()).toHaveReturnedWith({}); + + expect("").toMatch(""); + expect("").toMatch(/foo/); + + expect({}).toMatchObject({}); + expect({ abc: "def" }).toMatchObject({ abc: "def" }); + expect({}).toMatchObject([{}, {}]); + expect({ abc: "def" }).toMatchObject([{ abc: "def" }, { invalid: "property" }]); + + expect({}).toMatchSnapshot(); + expect({}).toMatchSnapshot("snapshotName"); + + expect(jest.fn()).toReturn(); + + expect(jest.fn()).toReturnTimes(0); + expect(jest.fn()).toReturnTimes(1); + + expect(jest.fn()).toReturnWith("jest"); + expect(jest.fn()).toReturnWith({}); + + expect(true).toStrictEqual(false); + expect({}).toStrictEqual({}); + + expect(() => {}).toThrow(); + expect(() => { throw new Error(); }).toThrow(""); + expect(jest.fn()).toThrow(Error); + expect(jest.fn(() => { throw new Error(); })).toThrow(/foo/); + + expect(() => {}).toThrowErrorMatchingSnapshot(); + expect(() => { throw new Error(); }).toThrowErrorMatchingSnapshot(); + expect(jest.fn()).toThrowErrorMatchingSnapshot(); + expect(jest.fn(() => { throw new Error(); })).toThrowErrorMatchingSnapshot(); + + /* not */ + + expect({}).not.toEqual({}); + expect([]).not.toStrictEqual([]); + + /* Promise matchers */ + + expect(Promise.reject("jest")).rejects.toEqual("jest"); + expect(Promise.reject({})).rejects.toEqual({}); + expect(Promise.resolve("jest")).rejects.toEqual("jest"); + expect(Promise.resolve({})).rejects.toEqual({}); + + expect(Promise.reject("jest")).resolves.toEqual("jest"); + expect(Promise.reject({})).resolves.toEqual({}); + expect(Promise.resolve("jest")).resolves.toEqual("jest"); + expect(Promise.resolve({})).resolves.toEqual({}); + + /* type matchers */ + + expect({}).toBe(expect.anything()); + + expect({}).toBe(expect.any(class Foo { })); + expect(new Error()).toBe(expect.any(Error)); + expect(7).toBe(expect.any(Number)); + + expect({}).toBe(expect.arrayContaining(["a", "b"])); + expect(["abc"]).toBe(expect.arrayContaining(["a", "b"])); + + expect.objectContaining({}); + expect.stringMatching("foo"); + expect.stringMatching(/foo/); + expect.stringContaining("foo"); + + expect({ abc: "def" }).toBe(expect.objectContaining({ + abc: expect.arrayContaining([expect.any(Date), {}]), + def: expect.objectContaining({ + foo: "bar", + }), + ghi: expect.stringMatching("foo"), })); - expect.assertions(4); + /* Miscellaneous */ - interface Test { - a: number; - b: string; + expect.hasAssertions(); + expect.assertions(0); + expect.assertions(9001); + }); +}); + +/* Test framework and config */ + +const globalConfig: jest.GlobalConfig = { + bail: true, + collectCoverage: false, + collectCoverageFrom: ["glob"], + collectCoverageOnlyFrom: { + abc: true, + def: false, + }, + coverageDirectory: "", + coverageReporters: [""], + coverageThreshold: { + global: { + abc: 90, + def: 100, + }, + }, + expand: true, + forceExit: false, + logHeapUsage: true, + mapCoverage: false, + noStackTrace: true, + notify: false, + projects: ["projects"], + replname: "", + reporters: [ + ["abc", {}], + ["def", {}], + ], + rootDir: "path", + silent: true, + testNamePattern: "", + testPathPattern: "", + testResultsProcessor: "", + updateSnapshot: "all" as "all" | "new" | "none", + useStderr: true, + verbose: false, + watch: true, + watchman: false, +}; + +const projectConfig: jest.ProjectConfig = { + automock: true, + browser: false, + cache: true, + cacheDirectory: "", + clearMocks: true, + coveragePathIgnorePatterns: [""], + cwd: "", + detectLeaks: true, + displayName: "", + forceCoverageMatch: ["abc", "def"], + globals: { + "ts-jest": {}, + }, + haste: { + defaultPlatform: "", + hasteImplModulePath: "", + platforms: ["win95", "win2000", "clippy"], + providesModuleNodeModules: ["abc", "def"], + }, + moduleDirectories: ["", ""], + moduleFileExtensions: [".ts", ".json"], + moduleLoader: "laoder", + moduleNameMapper: [ + ["abc", "def"], + ["ghi", "jkl"], + ], + modulePathIgnorePatterns: ["abc", "def"], + modulePaths: ["abc", "def"], + name: "", + resetMocks: true, + resetModules: false, + resolver: "", + rootDir: "", + roots: ["", ""], + runner: "", + setupFiles: ["abc", "def"], + setupTestFrameworkScriptFile: "", + skipNodeResolution: true, + snapshotSerializers: ["abc", "def"], + testEnvironment: "", + testEnvironmentOptions: {}, + testLocationInResults: true, + testMatch: [".test.ts"], + testPathIgnorePatterns: ["*.spec.*"], + testRegex: "abc", + testRunner: "m", + testURL: "localhost:3000", + timers: "real", + transform: [ + ["abc", "def"], + ], + transformIgnorePatterns: ["", ""], + unmockedModulePathPatterns: ["abc"], + watchPathIgnorePatterns: ["def"], +}; + +const environment = { + global: {}, + fakeTimers: { + clearAllTimers() { }, + runAllImmediates() { }, + runAllTicks() { }, + runAllTimers() { }, + runTimersToTime(time: number) { }, + advanceTimersByTime(time: number) { }, + runOnlyPendingTimers() { }, + runWithRealTimers(callback: () => void) { + callback(); + }, + useFakeTimers() { }, + useRealTimers() { }, + }, + testFilePath: "", + moduleMocker: {}, + dispose() {}, + runScript(script: "") { + return {}; + }, +}; + +const workTestFramework = async (testFramework: jest.TestFramework): Promise => { + return testFramework( + globalConfig, + projectConfig, + environment, + {}, + "testPath" + ); +}; + +/* Jasmine status changers */ + +describe("", () => { + it("", () => { + pending(); + pending("reason"); + + fail(); + fail("error"); + fail(new Error("reason")); + fail({}); + }); +}); + +/* Jasmine clocks and timing */ + +jasmine.DEFAULT_TIMEOUT_INTERVAL = 9001; + +const clock = jasmine.clock(); + +clock.install(); + +clock.mockDate(); +clock.mockDate(undefined); +clock.mockDate(new Date()); + +clock.tick(0); +clock.tick(9001); + +/* Jasmine matchers */ + +expect({}).toBe(jasmine.anything()); + +expect({}).toBe(jasmine.any(class Foo { })); +expect(new Error()).toBe(jasmine.any(Error)); +expect(7).toBe(jasmine.any(Number)); + +expect({}).toBe(jasmine.arrayContaining(["a", "b"])); +expect(["abc"]).toBe(jasmine.arrayContaining(["a", "b"])); + +jasmine.arrayContaining([]); +new (jasmine.arrayContaining([]))([]); +const arrayContained: boolean = jasmine + .arrayContaining([]) + .asymmetricMatch([]); +const arrayContainedName: string = jasmine + .arrayContaining([]) + .jasmineToString(); + +jasmine.objectContaining({}); +new (jasmine.objectContaining({}))({}); +const objectContained: boolean = jasmine + .objectContaining({}) + .jasmineMatches({}, ["abc"], ["def"]); +const objectContainedName: string = jasmine + .objectContaining({}) + .jasmineToString(); + +jasmine.stringMatching("foo"); +jasmine.stringMatching(/foo/); +new (jasmine.stringMatching("foo"))({}); +const stringContained: boolean = jasmine + .stringMatching(/foo/) + .jasmineMatches({}); +const stringContainedName: string = jasmine + .stringMatching("foo") + .jasmineToString(); + +expect({ abc: "def" }).toBe(jasmine.objectContaining({ + abc: jasmine.arrayContaining([jasmine.any(Date), {}]), + def: jasmine.objectContaining({ + foo: "bar", + }), + ghi: jasmine.stringMatching("foo"), +})); + +/* Jasmine spies */ + +describe("", () => { + it("", () => { + let spy = jasmine.createSpy(); + jasmine.createSpy("name"); + jasmine.createSpy("name", () => {}); + jasmine.createSpy("name", (arg: {}) => arg); + jasmine.createSpy("name", (...args: string[]) => args.join("")); + + spy = jasmine.createSpy() + .and.callFake(() => {}) + .and.callFake((arg: {}) => arg) + .and.callFake((...args: string[]) => args.join("")) + .and.callThrough() + .and.returnValue("jasmine") + .and.returnValue({}) + .and.returnValues() + .and.returnValues("jasmine") + .and.returnValues({}, {}) + .and.stub() + .and.throwError("message"); + + const identity: string = spy.identity; + + let args: any[]; + args = spy.mostRecentCall.args; + args = spy.argsForCall[0]; + args = spy.calls.allArgs(); + args = spy.calls.argsFor(0); + + const spyCalled: boolean = spy.calls.any(); + + const wasCalled: boolean = spy.wasCalled; + + for (const call of [ + ...spy.calls.all(), + spy.calls.first(), + spy.calls.mostRecent(), + ]) { + const callType: jasmine.CallInfo = call; + const callArgs: any[] = call.args; + const { object, returnValue } = call; } - // It's useful to create expected objects before the test call for refactoring purposes - // Assymetric matchers must return any in this case to constrain the required type - const test: Test = { - a: expect.any(Number), - b: expect.anything() + spy.calls.reset(); + + const spyReturn = spy(); + + /* Jasmine spy objects */ + + let spyObject = { + abc() { + return ""; + }, + def: 7, }; - expect(callback).toHaveBeenCalledWith(test); + + spyObject = jasmine.createSpyObj("baseName", ["abc"]); + spyObject = jasmine.createSpyObj("baseName", ["abc"]); + + const newSpyObject: typeof spyObject = jasmine.createSpyObj("baseName", ["abc"]); }); }); -describe('setTimeout', () => { - it('works as expected', done => { - jest.setTimeout(1000); +/* Jasmine pp */ - setTimeout(() => { - expect(true).toBeTruthy(); - done(); - }, 900); - }); -}); +const pp: string = jasmine.pp({}); -describe("spy call matchers", () => { - const spy = jest.fn(); +/* Jasmine equality testers */ - expect(spy).lastReturnedWith("foo"); - expect(spy).nthReturnedWith(3, "foo"); - expect(spy).toHaveBeenCalled(); - expect(spy).toHaveBeenCalledTimes(7); - expect(spy).toHaveBeenCalledWith("foo"); - expect(spy).toHaveBeenLastCalledWith("foo"); - expect(spy).toHaveBeenNthCalledWith(3, "foo"); - expect(spy).toHaveReturned(); - expect(spy).toHaveReturnedTimes(7); - expect(spy).toHaveReturnedWith("foo"); - expect(spy).toHaveLastReturnedWith("foo"); - expect(spy).toHaveNthReturnedWith(3, "foo"); - expect(spy).toReturn(); - expect(spy).toReturnTimes(3); - expect(spy).toReturnWith("foo"); -}); +const equalityTesterObject = (first: {}, second: {}) => false; +const equalityTesterString: jasmine.CustomEqualityTester = (first: string, second: string) => first === second; -describe('Extending extend', () => { - it('works', () => { - expect.extend({ - toBeNumber(received: any, actual: any) { - const pass = received === actual; - const message = - () => `expected ${received} ${pass ? 'not ' : ''} to be ${actual}`; - return { message, pass }; - }, - toBeVariadicMatcher(received: any, floor: number, ceiling: number) { - const pass = received >= floor && received <= ceiling; - const message = - () => `expected ${received} ${pass ? 'not ' : ''} to be within range ${floor}-${ceiling}`; - return { message, pass }; - }, - toBeTest(received: any, actual: any) { - this.utils.ensureNoExpected(received); - this.utils.ensureActualIsNumber(received); - this.utils.ensureExpectedIsNumber(actual); - this.utils.ensureNumbers(received, actual); +jasmine.addCustomEqualityTester(equalityTesterObject); +jasmine.addCustomEqualityTester(equalityTesterObject); - return { - message: () => ` - ${this.utils.getType(received).toLowerCase()} \n\n - ${this.utils.matcherHint(".not.toBe")} ${this.utils.printExpected(actual)} ${this.utils.printReceived(received)}\n\n - `, - pass: true - }; - } - }); - }); -}); - -describe('missing tests', () => { - it('creates closures', () => { - class Closure { - private arg: T; - - constructor(private readonly fn: (arg: T) => void) { - this.fn = fn; - } - - bind(arg: T): void { - this.arg = arg; - } - - call(): void { - this.fn(this.arg); - } - } - - type StringClosure = (arg: string) => void; - const spy: jest.Mock = jest.fn(); - const closure: Closure = new Closure(spy); - closure.bind('jest'); - closure.call(); - expect(spy).lastCalledWith('jest'); - expect(spy).toBeCalledWith('jest'); - expect(jest.isMockFunction(spy)).toBeTruthy(); - }); - - it('tests all missing Mocks functionality', () => { - type FruitsGetter = () => string[]; - const mock: jest.Mock = jest.fn(); - mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum']); - jest.setMock('./../tesks/getFruits', mock); - const getFruits: FruitsGetter = require('./../tesks/getFruits'); - expect(getFruits()).toContain('Orange'); - mock.mockReturnValueOnce(['Apple', 'Plum']); - expect(mock()).not.toContain('Orange'); - const myBeverage: any = {delicious: true, sour: false}; - expect(myBeverage).toContainEqual({delicious: true, sour: false}); - mock.mockReturnValue([]); // Deprecated: Use jest.fn(() => value) instead. - mock.mockClear(); - const thisMock: jest.Mock = jest.fn().mockReturnThis(); - expect(thisMock()).toBe(this); - }); - - it('async test with mockResolvedValue and mockResolvedValueOnce', async () => { - const asyncMock = jest - .fn() - .mockResolvedValue('default') - .mockResolvedValueOnce('first call') - .mockResolvedValueOnce('second call'); - - await asyncMock(); // first call - await asyncMock(); // second call - await asyncMock(); // default - await asyncMock(); // default - }); - - it('async test with mockRejectedValue', async () => { - const asyncMock = jest.fn().mockRejectedValue(new Error('Async error')); - - await asyncMock(); // throws "Async error" - }); - - it('async test with mockResolvedValueOnce and mockRejectedValueOnce', async () => { - const asyncMock = jest - .fn() - .mockResolvedValueOnce('first call') - .mockRejectedValueOnce(new Error('Async error')); - - await asyncMock(); // first call - await asyncMock(); // throws "Async error" - }); - - it('tests mock name functionality', () => { - const mock: jest.Mock = jest.fn(); - mock.mockName('Carrot'); - expect(mock.getMockName()).toBe('Carrot'); - }); - - it('tests mock name functionality', () => { - const mock = spyOn(console, 'warn'); - expect(mock).toHaveBeenCalled(); - }); - - it('creates snapshoter', () => { - jest.disableAutomock().mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); - const render: () => string = require('./render'); - expect(render()).toMatch(/Link/); - jest.enableAutomock(); - }); - - it('runs only pending timers', () => { - jest.useRealTimers(); - setTimeout(() => expect(1).not.toEqual(0), 3000); - jest.runOnlyPendingTimers().runTimersToTime(300); - }); - - it('runs all timers', () => { - jest.clearAllTimers(); - jest.useFakeTimers(); - setTimeout(() => expect(0).not.toEqual(1), 3000); - jest.runAllTimers(); - }); - - it('cleares cache', () => { - const sum1 = require('../sum'); - jest.resetModules(); - const sum2 = require('../sum'); - expect(sum1).not.toBe(sum2); - }); -}); - -describe('toMatchSnapshot', () => { - it('compares snapshots', () => { - expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); - }); - - it('can give name to snapshot', () => { - expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot('given name'); - }); -}); - -describe('toThrowErrorMatchingSnapshot', () => { - it('compares snapshots', () => { - expect(() => { throw new Error('descriptiton'); }).toThrowErrorMatchingSnapshot(); - }); -}); - -const testSerializerPluginString = "set by testSerializerPlugin"; -let testSerializerPluginCallCount = 0; -expect.addSnapshotSerializer({ - print(val, serialize, indent, opts, colors) { - val.willOverwrite = testSerializerPluginString; - testSerializerPluginCallCount += 1; - return 'plugin called: ' + serialize(val.willOverwrite); - }, - test(val) { - return val && val.willOverwrite && val.willOverwrite !== testSerializerPluginString; - }, -}); -describe('addSnapshotSerializer', () => { - it('the plugin does its work', () => { - testSerializerPluginCallCount = 0; - expect({ willOverwrite: { x: 1, y: 2, } }).toMatchSnapshot(); - expect({ willOverwrite: "this will get overwritten by testSerializerPlugin" }).toMatchSnapshot(); - expect({ willOverwrite: "so will this" }).toMatchSnapshot(); - expect({ foo: "this will not" }).toMatchSnapshot(); - expect(testSerializerPluginCallCount).toBe(3); - }); -}); - -function testInstances() { - const mockFn = jest.fn<(...args: any[]) => any>(); - const a = new mockFn(); - const b = new mockFn(); - - mockFn.mock.instances[0] === a; // true - mockFn.mock.instances[1] === b; // true -} - -function testMockImplementation() { - const mockFn = jest.fn<(...args: any[]) => any>().mockImplementation((scalar: number): number => { - return 42 + scalar; - }); - - const a = mockFn(0); - const b = mockFn(1); - - a === 42; // true - b === 43; // true - - mockFn.mock.calls[0][0] === 0; // true - mockFn.mock.calls[1][0] === 1; // true -} - -// Test from jest Docs: -describe('genMockFromModule', () => { - // Interfaces: - interface MockFiles { - [index: string]: string; - } - - interface MockedFS { - readdirSync(dir: string): string[]; - __setMockFiles(newMockFiles: MockFiles): void ; - } - - // ------------------------------------------------------------------------------------ - // FileSummarizer.ts - - const fs = require('fs'); - - function summarizeFilesInDirectorySync(directory: string): string[] { - return fs.readdirSync(directory).map((fileName: string) => ({ - fileName, - directory, - })); - } - - // export default summarizeFilesInDirectorySync; // For sake of compilation - - // ------------------------------------------------------------------------------------ - // __mocks__/fs.js - - const path = require('path'); - - const mockedFS: MockedFS = jest.genMockFromModule('fs'); - - let mockFiles: any = Object.create(null); - function __setMockFiles(newMockFiles: MockFiles): void { - mockFiles = Object.create(null); - for (const file in newMockFiles) { - const dir: string = path.dirname(file); - - if (!mockFiles[dir]) { - mockFiles[dir] = []; - } - mockFiles[dir].push(path.basename(file)); - } - } - - function readdirSync(directoryPath: string): string[] { - return mockFiles[directoryPath] || []; - } - - mockedFS.readdirSync = readdirSync; - mockedFS.__setMockFiles = __setMockFiles; - - // export = mockedFS; // For sake of compilation - // ------------------------------------------------------------------------------------ - // __tests__/FileSummarizer-test.js - - jest.mock('fs'); - - describe('listFilesInDirectorySync', () => { - const MOCK_FILE_INFO: MockFiles = { - '/path/to/file1.js': 'console.log("file1 contents");', - '/path/to/file2.txt': 'file2 contents', - }; - - beforeEach(() => { - // Set up some mocked out file info before each test - (require('fs') as MockedFS).__setMockFiles(MOCK_FILE_INFO); - }); - - it('includes all files in the directory in the summary', () => { - const FileSummarizer: (dir: string) => string[] = require('../FileSummarizer'); - const fileSummary = FileSummarizer('/path/to'); - - expect(fileSummary.length).toBe(2); - }); - }); -}); - -/** - * Pass strictNullChecks - */ -describe('strictNullChecks', () => { - it('does not complain when using done callback', (done) => { - done(); - }); -}); - -describe('beforeEach with timeout', () => { - beforeEach(() => { - // this shouldn't take more than a second - }, 1000); -}); - -class TestApi { - constructor() { } - testProp: boolean; - private readonly anotherProp: string; - testMethod(a: number): string { return ""; } -} - -declare function mockedFunc(a: number): string; - -declare function mockedFuncWithApi(api: TestApi): void; - -describe('Mocked type', () => { - it('Works', () => { - const mock: jest.Mocked = new TestApi() as any; - mock.testProp; - mock.testMethod.mockImplementation(() => 'test'); - mock.testMethod(5).toUpperCase(); - - mockedFuncWithApi(mock); - }); -}); - -describe('Mocks', () => { - it('jest.fn() without args is a function type', () => { - const test = jest.fn(); - test(); - new test(); - test.mock.instances[0]; - test.mockImplementation(() => { }); - }); - - it('jest.fn() with returned object infers type', () => { - const testMock = jest.fn(() => ({ a: 5, test: jest.fn() })); - - testMock(5, 5, 'a'); - testMock.mockImplementation(() => { }); - testMock.caller; - - const ins = new testMock(); - ins.a; - ins.test(); - ins.test.mockImplementation(() => 5); - ins.test.mock.calls; - - const anotherMock = jest.fn(() => { - const api: Partial = { - testMethod: jest.fn() - }; - return api; - }); - const anotherIns: jest.Mocked = new anotherMock() as any; - anotherIns.testMethod.mockImplementation(() => 1); - }); - - it('jest.fn() accepts constructor arguments', () => { - interface TestLog { - log(...msg: any[]): void; - } - - class LogMock extends jest.fn((verbose?: boolean) => { - const mockLog = () => { - if (verbose) { - return jest.fn((...args) => { - const subj = args.shift() || ""; - console.log(subj, ...args); - }); - } - return jest.fn(); - }; +/* Jasmine matchers */ +const customMatcherFactoriesNone = {}; +const customMatcherFactoriesIndex: { [i: string]: jasmine.CustomMatcherFactory } = {}; +const customMatcherFactoriesManual = { + abc: () => ({ + compare: (actual: "", expected: "", ...args: Array<{}>) => ({ + pass: true, + message: "", + }), + }), + def: (util: jasmine.MatchersUtil, customEqualityTestesr: jasmine.CustomEqualityTester): jasmine.CustomMatcher => ({ + compare(actual: T, expected: T): jasmine.CustomMatcherResult { return { - log: mockLog() + pass: actual === expected, + message: () => "foo", }; - }) { - } + }, + }), +}; - const nonVerboseLog = new LogMock(); - nonVerboseLog.log("this is completely catched by jest"); - expect(nonVerboseLog.log).toBeCalledWith("this is completely catched by jest"); - const verboseLog = new LogMock(true); - verboseLog.log("this should also be printed to the console"); - expect(verboseLog.log).toBeCalledWith("this should also be printed to the console"); - }); -}); +const matchersUtil1 = { + buildFailureMessage: () => "", + contains: (haystack: string, needle: string) => haystack.indexOf(needle) !== -1, + equals: (a: {}, b: {}) => false, +}; -// https://facebook.github.io/jest/docs/en/expect.html#resolves -describe('resolves', () => { - it('unwraps the expected Promise', () => { - const expectation = expect(Promise.resolve('test')).resolves.toEqual('test'); - expect(expectation instanceof Promise).toBeTruthy(); - return expectation; - }); +let matchersUtil2: jasmine.MatchersUtil = { + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: any[]): string { + return `${matcherName}${isNot ? "1" : "0"}${actual}${expected.join("")}`; + }, + contains(haystack: T[], needle: T, customTesters?: jasmine.CustomEqualityTester[]) { + return true; + }, + equals: (a: {}, b: {}, customTesters?: jasmine.CustomEqualityTester[]) => false, +}; - it('unwraps a .toHaveBeenCalledX', done => { - expect.assertions(2); +// Jest config - const fn = jest.fn(); - return expect(Promise.resolve(fn)).resolves.toHaveBeenCalledTimes(0).then(val => { - expect(val).toEqual(true); - done(); - }); - }); - - it('unwraps a not.toHaveBeenCalledX', done => { - expect.assertions(2); - - const fn = jest.fn(); - return expect(Promise.resolve(fn)).resolves.not.toHaveBeenCalledTimes(1).then(val => { - expect(val).toEqual(true); - done(); - }); - }); -}); - -// https://facebook.github.io/jest/docs/en/expect.html#rejects -describe('rejects', () => { - it('unwraps the expected Promise', () => { - const expectation = expect(Promise.reject(new Error('error'))).rejects.toMatch('error'); - expect(expectation instanceof Promise).toBeTruthy(); - return expectation; - }); -}); - -// https://facebook.github.io/jest/docs/en/expect.html#tohavepropertykeypath-value -describe('toHaveProperty', () => { - it('it accepts a keyPath as string', () => { - expect({ a: { b: {}}}).toHaveProperty('a'); - }); - it('it accepts a keyPath as string with dot notation', () => { - expect({ a: { b: {}}}).toHaveProperty('a.b'); - }); - it('it accepts a keyPath as an array', () => { - expect({ a: { b: {}}}).toHaveProperty(['a', 'b']); - }); - it('it accepts a keyPath as an array containing non-string values', () => { - expect({ a: ['b']}).toHaveProperty(['a', 0]); - }); -}); - -class MyTransformer implements jest.Transformer { - process(text: string, path: string) { - return ` - // some comments - ${text} - `; - } -} - -class MyReporter implements jest.Reporter { - onRunStart() { - console.log('hello world'); - } -} - -declare const testResult: jest.TestResult; -const myTestRunner: jest.TestFramework = () => Promise.resolve(testResult); - -const testResultsProcessor: jest.TestResultsProcessor = result => ({...result, numFailedTests: 1}); - -// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18826 -test('moduleName 1', () => { - jest.doMock('../moduleName', () => { - return jest.fn(() => 1); - }); - const moduleName = require('../moduleName'); - expect(moduleName()).toEqual(1); -}); -test('moduleName 2', () => { - jest.doMock('../moduleName', () => { - return jest.fn(() => 2); - }); - const moduleName = require('../moduleName'); - expect(moduleName()).toEqual(2); -}); - -describe('toHaveBeenNthCalledWith', () => { - const fn = jest.fn(); - - expect(fn).toHaveBeenNthCalledWith(3, "foo"); -}); +const testJestConfig = (defaults: jest.DefaultOptions) => { + const config: jest.InitialOptions = { + transform: { + '^.+\\.(ts|tsx)$': 'ts-jest' + }, + testMatch: [ + ...defaults.testMatch, + '**/__tests__/**/*.ts?(x)', + '**/?(*.)+(spec|test).ts?(x)' + ], + moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'], + globals: { + 'ts-jest': {} + } + }; +}; // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/26368 @@ -860,3 +1056,4 @@ test.only.each` `("returns $expected when $a is added $b", ({ a, b, expected }: Case) => { expect(a + b).toBe(expected); }); + diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 48e2a0327c..dbf60400b9 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for joi v13.0.1 +// Type definitions for joi v13.3.0 // Project: https://github.com/hapijs/joi // Definitions by: Bart van der Schoor // Laurence Dougal Myers @@ -12,6 +12,7 @@ // Anjun Wang // Rafael Kallis // Conan Lai +// Peter Thorson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -106,6 +107,13 @@ export interface EmailOptions { minDomainAtoms?: number; } +export interface HexOptions { + /** + * hex decoded representation must be byte aligned + */ + byteAligned: boolean; +} + export interface IpOptions { /** * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture @@ -512,6 +520,11 @@ export interface NumberSchema extends AnySchema { * Requires the number to be negative. */ negative(): this; + + /** + * Requires the number to be a TCP port, so between 0 and 65535. + */ + port(): this; } export interface StringSchema extends AnySchema { @@ -624,7 +637,7 @@ export interface StringSchema extends AnySchema { /** * Requires the string value to be a valid hexadecimal string. */ - hex(): this; + hex(options?: HexOptions): this; /** * Requires the string value to be a valid hostname as per RFC1123. @@ -714,10 +727,15 @@ export interface ArraySchema extends AnySchema { export interface ObjectSchema extends AnySchema { /** - * Sets the allowed object keys. + * Sets or extends the allowed object keys. */ keys(schema?: SchemaMap): this; + /** + * Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied. + */ + append(schema?: SchemaMap): this; + /** * Specifies the minimum number of keys in the object. */ @@ -966,7 +984,7 @@ export interface Rules

{ name: string; params?: ObjectSchema | {[key in keyof P]: SchemaLike; }; setup?(this: ExtensionBoundSchema, params: P): Schema | void; - validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): Err | R; + validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): any; description?: string | ((params: P) => string); } @@ -974,8 +992,8 @@ export interface Extension { name: string; base?: Schema; language?: LanguageOptions; - coerce?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R; - pre?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R; + coerce?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): any; + pre?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): any; describe?(this: Schema, description: Description): Description; rules?: Rules[]; } @@ -1101,10 +1119,13 @@ export function ref(key: string, options?: ReferenceOptions): Reference; export function isRef(ref: any): ref is Reference; /** - * Get a sub-schema of an existing schema based on a path. Path separator is a dot (.). + * Get a sub-schema of an existing schema based on a `path` that can be either a string or an array + * of strings For string values path separator is a dot (`.`) */ export function reach(schema: ObjectSchema, path: string): Schema; export function reach(schema: ObjectSchema, path: string): T; +export function reach(schema: ObjectSchema, path: string[]): Schema; +export function reach(schema: ObjectSchema, path: string[]): T; /** * Creates a new Joi instance customized with the extension(s) you provide included. diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 5ea9088a74..def9eaafd4 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -96,6 +96,12 @@ emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +let hexOpts: Joi.HexOptions = null; + +hexOpts = { byteAligned: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + let ipOpts: Joi.IpOptions = null; ipOpts = { version: str }; @@ -602,6 +608,7 @@ numSchema = numSchema.precision(num); numSchema = numSchema.multiple(num); numSchema = numSchema.positive(); numSchema = numSchema.negative(); +numSchema = numSchema.port(); namespace common { numSchema = numSchema.allow(x); @@ -659,6 +666,9 @@ objSchema = Joi.object(schemaMap); objSchema = objSchema.keys(); objSchema = objSchema.keys(schemaMap); +objSchema = objSchema.append(); +objSchema = objSchema.append(schemaMap); + objSchema = objSchema.min(num); objSchema = objSchema.max(num); objSchema = objSchema.length(num); @@ -801,6 +811,7 @@ strSchema = strSchema.guid(); strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] } as Joi.GuidOptions); strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); +strSchema = strSchema.hex(hexOpts); strSchema = strSchema.hostname(); strSchema = strSchema.isoDate(); strSchema = strSchema.lowercase(); @@ -969,6 +980,7 @@ description = Joi.describe(schema); description = schema.describe(); schema = Joi.reach(objSchema, ''); +schema = Joi.reach(objSchema, []); const Joi2 = Joi.extend({ name: '', base: schema }); @@ -988,13 +1000,13 @@ const Joi3 = Joi.extend({ { name: 'asd', params: { - allowF: Joi.boolean().default(false), + allowFalse: Joi.boolean().default(false), }, setup(params) { - const fIsAllowed = params.allowF; + const fIsAllowed = params.allowFalse; }, - validate(params, value, state, options) { - if (value === 'asd' || params.allowF && value === 'asdf') { + validate(params, value: boolean, state, options) { + if (value || params.allowFalse && !value) { return value; } return this.createError('asd', { v: value }, state, options); diff --git a/types/jquery-mockjax/index.d.ts b/types/jquery-mockjax/index.d.ts index 54cc036416..f1333b1028 100644 --- a/types/jquery-mockjax/index.d.ts +++ b/types/jquery-mockjax/index.d.ts @@ -1,11 +1,28 @@ -// Type definitions for jQuery Mockjax 2.0.1 +// Type definitions for jQuery Mockjax 2.3.0 // Project: https://github.com/jakerella/jquery-mockjax -// Definitions by: Laszlo Jakab , Vladimir Đokić +// Definitions by: +// Laszlo Jakab , +// Vladimir Đokić , +// James Johnson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// +type MockJaxLoggingFunction = (message?: any, ...additionalParameters: any[]) => void; + +interface MockJaxStandardLogger { + error?: MockJaxLoggingFunction; + warn?: MockJaxLoggingFunction; + info?: MockJaxLoggingFunction; + log?: MockJaxLoggingFunction; + debug?: MockJaxLoggingFunction; +} + +interface MockJaxCustomLogger { + [key: string]: MockJaxLoggingFunction; +} + interface MockJaxSettingsHeaders { [key: string]: string; } @@ -33,15 +50,22 @@ interface MockJaxSettings { onAfterSuccess?: Function; onAfterError?: Function; onAfterComplete?: Function; + logger?: MockJaxStandardLogger | MockJaxCustomLogger; + logLevelMethods?: string[]; + namespace?: string; + throwUnmocked?: boolean; + retainAjaxCalls?: boolean; } interface MockJaxStatic { (options: MockJaxSettings): number; + (options: MockJaxSettings[]): number[]; handler(id?: number): any; clear(id?: number): void; mockedAjaxCalls(): any[]; unfiredHandlers(): any[]; unmockedAjaxCalls(): any[]; + clearRetainedAjaxCalls(): void; } interface JQueryStatic { diff --git a/types/jquery-mockjax/jquery-mockjax-tests.ts b/types/jquery-mockjax/jquery-mockjax-tests.ts index 3090a1c3cc..31babd9cd8 100644 --- a/types/jquery-mockjax/jquery-mockjax-tests.ts +++ b/types/jquery-mockjax/jquery-mockjax-tests.ts @@ -192,6 +192,81 @@ class Tests { } }); }); + + t('Standard logger type gets called', (assert) => { + let done = assert.async(); + let wasLoggerCalled = false; + + let logFunction = () => wasLoggerCalled = true; + + let settings: MockJaxSettings = { + url: '/custom-logging-function', + logging: true, + logger: { + error: logFunction, + warn: logFunction, + info: logFunction, + log: logFunction, + debug: logFunction + } + }; + + $.mockjax(settings); + + $.ajax({ + url: '/custom-logging-function', + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(wasLoggerCalled, true, 'Standard logger was called'); + done(); + } + }); + }); + + t('Custom logger object gets called', (assert) => { + let done = assert.async(); + let wasLoggerCalled = false; + + let logFunction = () => wasLoggerCalled = true; + + let settings: MockJaxSettings = { + url: '/custom-logging-function', + logging: true, + logger: { + customName: logFunction + }, + logLevelMethods: ['customName', 'customName', 'customName', 'customName', 'customName'] + }; + + $.mockjax(settings); + + $.ajax({ + url: '/custom-logging-function', + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(wasLoggerCalled, true, 'Custom logger was called'); + done(); + } + }); + }); + + t('Throws when ajax call is not mocked', (assert) => { + let done = assert.async(); + + $.mockjaxSettings.throwUnmocked = true; + + $.ajax({ + url: '/unmocked-ajax-call', + error: (error) => { + assert.ok(error, 'Expected the call to fail because it was not mocked'); + done(); + }, + complete: (xhr) => { + assert.ok(false, 'Expected a failure'); + done(); + } + }); + }); } } diff --git a/types/ltx/lib/Element.d.ts b/types/ltx/lib/Element.d.ts index d0f50ae783..203eaa93b6 100644 --- a/types/ltx/lib/Element.d.ts +++ b/types/ltx/lib/Element.d.ts @@ -67,7 +67,7 @@ export declare class Element { getText(): string; - getChildText(name: string, xmlns: any): string; + getChildText(name: string, xmlns?: any): string; /** * Return all direct descendents that are Elements. diff --git a/types/ltx/ltx-tests.ts b/types/ltx/ltx-tests.ts index 1e617ad27d..522b7673c8 100644 --- a/types/ltx/ltx-tests.ts +++ b/types/ltx/ltx-tests.ts @@ -2,6 +2,11 @@ import * as ltx from 'ltx'; ltx.parse(''); +const getChildTextElement = ltx.parse('body text') as ltx.Element; +if (getChildTextElement.getChildText('child') !== 'body text') { + throw new Error("body does not match"); +} + const p = new ltx.Parser(); p.on('tree', (ignored: any) => {}); diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index d90ba90b13..94623c5abb 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -208,6 +208,7 @@ declare module 'luxon' { toLocaleParts(options?: DateTimeFormatOptions): any[]; toLocaleString(options?: DateTimeFormatOptions): string; toObject(options?: { includeConfig?: boolean }): DateObject; + toMillis(): number; toRFC2822(): string; toSQL(options?: Object): string; toSQLDate(): string; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index ce9d09ac8f..4396e8d7a2 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -54,6 +54,8 @@ DateTime.utc(); DateTime.local().toUTC(); DateTime.utc().toLocal(); +DateTime.fromMillis(1527780819458).toMillis(); + /* Duration */ const dur = Duration.fromObject({ hours: 2, minutes: 7 }); dt.plus(dur); diff --git a/types/marked/index.d.ts b/types/marked/index.d.ts index a4dc048cc8..034c0cca18 100644 --- a/types/marked/index.d.ts +++ b/types/marked/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for Marked 0.3 +// Type definitions for Marked 0.4 // Project: https://github.com/chjj/marked // Definitions by: William Orr // BendingBender +// CrossR // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace marked; @@ -202,21 +203,9 @@ declare namespace marked { interface MarkedOptions { /** - * Type: object Default: new Renderer() - * - * An object containing functions to render tokens to HTML. + * A prefix URL for any relative link. */ - renderer?: Renderer; - - /** - * Enable GitHub flavored markdown. - */ - gfm?: boolean; - - /** - * Enable GFM tables. This option requires the gfm option to be true. - */ - tables?: boolean; + baseUrl?: string; /** * Enable GFM line breaks. This option requires the gfm option to be true. @@ -224,34 +213,19 @@ declare namespace marked { breaks?: boolean; /** - * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. + * Enable GitHub flavored markdown. */ - pedantic?: boolean; + gfm?: boolean; /** - * Sanitize the output. Ignore any HTML that has been input. + * Include an id attribute when emitting headings. */ - sanitize?: boolean; + headerIds?: boolean; /** - * Optionally sanitize found HTML with a sanitizer function. + * Set the prefix for header tag ids. */ - sanitizer?(html: string): string; - - /** - * Mangle autolinks (). - */ - mangle?: boolean; - - /** - * Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic. - */ - smartLists?: boolean; - - /** - * Shows an HTML error message when rendering fails. - */ - silent?: boolean; + headerPrefix?: string; /** * A function to highlight code blocks. The function takes three arguments: code, lang, and callback. @@ -263,15 +237,52 @@ declare namespace marked { */ langPrefix?: string; + /** + * Mangle autolinks (). + */ + mangle?: boolean; + + /** + * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. + */ + pedantic?: boolean; + + /** + * Type: object Default: new Renderer() + * + * An object containing functions to render tokens to HTML. + */ + renderer?: Renderer; + + /** + * Sanitize the output. Ignore any HTML that has been input. + */ + sanitize?: boolean; + + /** + * Optionally sanitize found HTML with a sanitizer function. + */ + sanitizer?(html: string): string; + + /** + * Shows an HTML error message when rendering fails. + */ + silent?: boolean; + + /** + * Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic. + */ + smartLists?: boolean; + /** * Use "smart" typograhic punctuation for things like quotes and dashes. */ smartypants?: boolean; /** - * Set the prefix for header tag ids. + * Enable GFM tables. This option requires the gfm option to be true. */ - headerPrefix?: string; + tables?: boolean; /** * Generate closing slash for self-closing tags (
instead of
) diff --git a/types/marked/marked-tests.ts b/types/marked/marked-tests.ts index 9499de3a56..e1cb63042c 100644 --- a/types/marked/marked-tests.ts +++ b/types/marked/marked-tests.ts @@ -1,6 +1,7 @@ import * as marked from 'marked'; const options: marked.MarkedOptions = { + baseUrl: '', gfm: true, tables: true, breaks: false, @@ -16,23 +17,24 @@ const options: marked.MarkedOptions = { renderer: new marked.Renderer() }; -function callback() { - console.log('callback called'); +function callback(err: string, markdown: string) { + console.log("Callback called!"); + return markdown; } const myOldMarked: typeof marked = marked.setOptions(options); -console.log(marked('i am using __markdown__.')); -console.log(marked('i am using __markdown__.', options)); -console.log(marked('i am using __markdown__.', callback)); -console.log(marked('i am using __markdown__.', options, callback)); +console.log(marked('1) I am using __markdown__.')); +console.log(marked('2) I am using __markdown__.', options)); +console.log(marked('3) I am using __markdown__.', callback)); +console.log(marked('4) I am using __markdown__.', options, callback)); -console.log(marked.parse('i am using __markdown__.')); -console.log(marked.parse('i am using __markdown__.', options)); -console.log(marked.parse('i am using __markdown__.', callback)); -console.log(marked.parse('i am using __markdown__.', options, callback)); +console.log(marked.parse('5) I am using __markdown__.')); +console.log(marked.parse('6) I am using __markdown__.', options)); +console.log(marked.parse('7) I am using __markdown__.', callback)); +console.log(marked.parse('8) I am using __markdown__.', options, callback)); -const text = 'something'; +const text = 'Something'; const tokens: marked.TokensList = marked.lexer(text, options); console.log(marked.parser(tokens)); diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index cdecc3e1b4..eda68ade10 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -1,2252 +1,4546 @@ -// Type definitions for mathjs 3.21 +// Type definitions for mathjs 4.4 // Project: http://mathjs.org/ // Definitions by: Ilya Shestakov , -// Andy Patterson +// Andy Patterson , +// Brad Besserman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 -import { Decimal } from 'decimal.js'; +import { Decimal } from "decimal.js"; -declare const math: math.MathJsStatic; // tslint:disable-line strict-export-declare-modifiers -export as namespace math; // tslint:disable-line strict-export-declare-modifiers -export = math; // tslint:disable-line strict-export-declare-modifiers +declare const math: math.MathJsStatic; +export as namespace math; +export = math; -declare namespace math { // tslint:disable-line strict-export-declare-modifiers - type MathArray = number[]|number[][]; - type MathType = number|BigNumber|Fraction|Complex|Unit|MathArray|Matrix; - type MathExpression = string|string[]|MathArray|Matrix; +declare namespace math { + type MathArray = number[] | number[][]; + type MathType = + | number + | BigNumber + | Fraction + | Complex + | Unit + | MathArray + | Matrix; + type MathExpression = string | string[] | MathArray | Matrix; - interface MathJsStatic { - e: number; - pi: number; - i: number; - Infinity: number; - LN2: number; - LN10: number; - LOG2E: number; - LOG10E: number; - NaN: number; - null: number; - phi: number; - SQRT1_2: number; - SQRT2: number; - tau: number; + interface MathJsStatic { + e: number; + pi: number; + i: number; + Infinity: number; + LN2: number; + LN10: number; + LOG2E: number; + LOG10E: number; + NaN: number; + null: number; + phi: number; + SQRT1_2: number; + SQRT2: number; + tau: number; - uninitialized: any; - version: string; + uninitialized: any; + version: string; - expression: MathNode; + expression: MathNode; + json: MathJsJson; - config: (options: any) => void; + /************************************************************************* + * Core functions + ************************************************************************/ - /** - * Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix. - * @param L A N x N matrix or array (L) - * @param b A column vector with the b values - * @returns A column vector with the linear system solution (x) - */ - lsolve(L: Matrix|MathArray, b: Matrix|MathArray): Matrix|MathArray; + /** + * Set configuration options for math.js, and get current options. Will + * emit a ‘config’ event, with arguments (curr, prev, changes). + * @param options Available options: {number} epsilon Minimum relative + * difference between two compared values, used by all comparison + * functions. {string} matrix A string ‘Matrix’ (default) or ‘Array’. + * {string} number A string ‘number’ (default), ‘BigNumber’, or + * ‘Fraction’ {number} precision The number of significant digits for + * BigNumbers. Not applicable for Numbers. {string} parenthesis How to + * display parentheses in LaTeX and string output. {string} randomSeed + * Random seed for seeded pseudo random number generator. Set to null to + * randomly seed. + * @returns Returns the current configuration + */ + config: (options: ConfigOptions) => ConfigOptions; + /** + * Create a typed-function which checks the types of the arguments and + * can match them against multiple provided signatures. The + * typed-function automatically converts inputs in order to find a + * matching signature. Typed functions throw informative errors in case + * of wrong input arguments. + * @param name Optional name for the typed-function + * @param signatures Object with one or multiple function signatures + * @returns The created typed-function. + */ + typed: (name: string, signatures: Record any>) => ((...args: any[]) => any); - /** - * Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in two matrices (L, U) - * and a row permutation vector p where A[p,:] = L * U - * @param A A two dimensional matrix or array for which to get the LUP decomposition. - * @returns The lower triangular matrix, the upper triangular matrix and the permutation matrix. - */ - lup(A?: Matrix|MathArray): MathArray; + /************************************************************************* + * Construction functions + ************************************************************************/ - /** - * Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector. - * @param A Invertible Matrix or the Matrix LU decomposition - * @param b Column Vector - * @returns Column vector with the solution to the linear system A * x = b - */ - lusolve(A: Matrix|MathArray|number, b: Matrix|MathArray): Matrix|MathArray; + /** + * Create a BigNumber, which can store numbers with arbitrary precision. + * When a matrix is provided, all elements will be converted to + * BigNumber. + * @param x Value for the big number, 0 by default. + * @returns The created bignumber + */ + bignumber( + x?: + | number + | string + | Fraction + | BigNumber + | MathArray + | Matrix + | boolean + | Fraction + | null + ): BigNumber; - /** - * Calculate the Sparse Matrix LU decomposition with full pivoting. Sparse Matrix A is decomposed in - * two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U - * @param A A two dimensional sparse matrix for which to get the LU decomposition. - * @param order The Symbolic Ordering and Analysis order: 0 - Natural ordering, no permutation vector q is - * returned 1 - Matrix must be square, symbolic ordering and analisis is performed on M = A + A' 2 - Symbolic - * ordering and analysis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'. - * This is appropriate for LU factorization of non-symmetric matrices. 3 - Symbolic ordering and analysis is performed - * on M = A' * A. This is best used for LU factorization is matrix M has no dense rows. A dense row is a row with - * more than 10*sqr(columns) entries. - * @param threshold Partial pivoting threshold (1 for partial pivoting) - * @returns The lower triangular matrix, the upper triangular matrix and the permutation vectors. - */ - slu(A: Matrix, order: number, threshold: number): any; + /** + * Create a boolean or convert a string or number to a boolean. In case + * of a number, true is returned for non-zero numbers, and false in case + * of zero. Strings can be 'true' or 'false', or can contain a number. + * When value is a matrix, all elements will be converted to boolean. + * @param x A value of any type + * @returns The boolean value + */ + boolean( + x: string | number | boolean | MathArray | Matrix | null + ): boolean | MathArray | Matrix; - /** - * Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix. U * x = b - * @param U A N x N matrix or array (U) - * @param b A column vector with the b values - * @returns A column vector with the linear system solution (x) - */ - usolve(U: Matrix|MathArray, b: Matrix|MathArray): Matrix|MathArray; + /** + * Wrap any value in a chain, allowing to perform chained operations on + * the value. All methods available in the math.js library can be called + * upon the chain, and then will be evaluated with the value itself as + * first argument. The chain can be closed by executing chain.done(), + * which returns the final value. The chain has a number of special + * functions: done() Finalize the chain and return the chain's value. + * valueOf() The same as done() toString() Executes math.format() onto + * the chain's value, returning a string representation of the value. + * @param value A value of any type on which to start a chained + * operation. + * @returns The created chain + */ + chain(value?: any): MathJsChain; - /** - * Calculate the absolute value of a number. For matrices, the function is evaluated element wise. - * @param x A number or matrix for which to get the absolute value - * @returns Absolute value of x - */ - abs(x: number): number; - abs(x: BigNumber): BigNumber; - abs(x: Fraction): Fraction; - abs(x: Complex): Complex; - abs(x: MathArray): MathArray; - abs(x: Matrix): Matrix; - abs(x: Unit): Unit; + /** + * Create a complex value or convert a value to a complex value. + * @param args Arguments specifying the real and imaginary part of the + * complex number + * @returns Returns a complex value + */ + complex(arg?: Complex | string | PolarCoordinates): Complex; + complex(arg?: MathArray | Matrix): MathArray | Matrix; + /** + * @param re Argument specifying the real part of the complex number + * @param im Argument specifying the imaginary part of the complex + * number + * @returns Returns a complex value + */ + complex(re: number, im: number): Complex; - /** - * Add two values, x + y. For matrices, the function is evaluated element wise. - * @param x First value to add - * @param y Second value to add - * @returns Sum of x and y - */ - add(x: MathType, y: MathType): MathType; + /** + * Create a user-defined unit and register it with the Unit type. + * @param name The name of the new unit. Must be unique. Example: ‘knot’ + * @param definition Definition of the unit in terms of existing units. + * For example, ‘0.514444444 m / s’. + * @param options (optional) An object containing any of the following + * properties:
- prefixes {string} “none”, “short”, “long”, + * “binary_short”, or “binary_long”. The default is “none”.
- + * aliases {Array} Array of strings. Example: [‘knots’, ‘kt’, + * ‘kts’]
- offset {Numeric} An offset to apply when converting from + * the unit. For example, the offset for celsius is 273.15. Default is + * 0. + * @returns The new unit + */ + createUnit( + name: string, + definition?: string | UnitDefinition, + options?: CreateUnitOptions + ): Unit; + /** + * Create a user-defined unit and register it with the Unit type. + * @param units Definition of the unit + * @param options + * @returns The new unit + */ + createUnit( + units: Record, + options?: CreateUnitOptions + ): Unit; - /** - * Calculate the cubic root of a value. For matrices, the function is evaluated element wise. - * @param x Value for which to calculate the cubic root. - * @param allRoots Optional, false by default. Only applicable when x is a number or complex number. If true, all complex roots are returned, if false (default) the principal root is returned. - * @returns Returns the cubic root of x - */ - cbrt(x: number, allRoots?: boolean): number; - cbrt(x: BigNumber, allRoots?: boolean): BigNumber; - cbrt(x: Fraction, allRoots?: boolean): Fraction; - cbrt(x: Complex, allRoots?: boolean): Complex; - cbrt(x: MathArray, allRoots?: boolean): MathArray; - cbrt(x: Matrix, allRoots?: boolean): Matrix; - cbrt(x: Unit, allRoots?: boolean): Unit; + /** + * Create a fraction convert a value to a fraction. + * @param args Arguments specifying the numerator and denominator of the + * fraction + * @returns Returns a fraction + */ + fraction( + args: Fraction | MathArray | Matrix + ): Fraction | MathArray | Matrix; + /** + * @param numerator Argument specifying the numerator of the fraction + * @param denominator Argument specifying the denominator of the + * fraction + * @returns Returns a fraction + */ + fraction( + numerator: number | string | MathArray | Matrix, + denominator?: number | string | MathArray | Matrix + ): Fraction | MathArray | Matrix; - /** - * Round a value towards plus infinity If x is complex, both real and imaginary part are rounded towards plus infinity. For matrices, the function is evaluated element wise. - * @param x Number to be rounded - * @returns Rounded value - */ - ceil(x: number): number; - ceil(x: BigNumber): BigNumber; - ceil(x: Fraction): Fraction; - ceil(x: Complex): Complex; - ceil(x: MathArray): MathArray; - ceil(x: Matrix): Matrix; - ceil(x: Unit): Unit; + /** + * Create an index. An Index can store ranges having start, step, and + * end for multiple dimensions. Matrix.get, Matrix.set, and math.subset + * accept an Index as input. + * @param ranges Zero or more ranges or numbers. + * @returns Returns the created index + */ + index(...ranges: any[]): Index; - /** - * Compute the cube of a value, x * x * x. For matrices, the function is evaluated element wise. - * @param x Number for which to calculate the cube - * @returns Cube of x - */ - cube(x: number): number; - cube(x: BigNumber): BigNumber; - cube(x: Fraction): Fraction; - cube(x: Complex): Complex; - cube(x: MathArray): MathArray; - cube(x: Matrix): Matrix; - cube(x: Unit): Unit; + /** + * Create a Matrix. The function creates a new math.type.Matrix object + * from an Array. A Matrix has utility functions to manipulate the data + * in the matrix, like getting the size and getting or setting values in + * the matrix. Supported storage formats are 'dense' and 'sparse'. + * @param format The Matrix storage format + * @returns The created Matrix + */ + matrix(format?: "sparse" | "dense"): Matrix; + /** + * @param data A multi dimensional array + * @param format The Matrix storage format + * @param dataType The Matrix data type + * @returns The created Matrix + */ + matrix( + data: MathArray | Matrix, + format?: "sparse" | "dense", + dataType?: string + ): Matrix; - /** - * Divide two values, x / y. To divide matrices, x is multiplied with the inverse of y: x * inv(y). - * @param x Numerator - * @param y Denominator - * @returns Quotient, x / y - */ - divide(x: Unit, y: Unit): Unit; - divide(x: number, y: number): number; - divide(x: MathType, y: MathType): MathType; + /** + * Create a number or convert a string, boolean, or unit to a number. + * When value is a matrix, all elements will be converted to number. + * @param value Value to be converted + * @returns The created number + */ + number( + value?: + | string + | number + | BigNumber + | Fraction + | boolean + | MathArray + | Matrix + | Unit + | null + ): number | MathArray | Matrix; + /** + * @param value Value to be converted + * @param valuelessUnit A valueless unit, used to convert a unit to a + * number + * @returns The created number + */ + number(unit: Unit, valuelessUnit: Unit | string): number; - /** - * Divide two matrices element wise. The function accepts both matrices and scalar values. - * @param x Numerator - * @param y Denominator - * @returns Quotient, x ./ y - */ - dotDivide(x: MathType, y: MathType): MathType; + /** + * Create a Sparse Matrix. The function creates a new math.type.Matrix + * object from an Array. A Matrix has utility functions to manipulate + * the data in the matrix, like getting the size and getting or setting + * values in the matrix. + * @param data A two dimensional array + * @param dataType Sparse Matrix data type + * @returns The created matrix + */ + sparse(data?: MathArray | Matrix, dataType?: string): Matrix; - /** - * Multiply two matrices element wise. The function accepts both matrices and scalar values. - * @param x Left hand value - * @param y Right hand value - * @returns Multiplication of x and y - */ - dotMultiply(x: MathType, y: MathType): MathType; + /** + * Split a unit in an array of units whose sum is equal to the original + * unit. + * @param unit A unit to be split + * @param parts An array of strings or valueless units + * @returns An array of units + */ + splitUnit(unit: Unit, parts: Unit[]): Unit[]; - /** - * Calculates the power of x to y element wise. - * @param x The base - * @param y The exponent - * @returns The value of x to the power y - */ - dotPow(x: MathType, y: MathType): MathType; + /** + * Create a string or convert any object into a string. Elements of + * Arrays and Matrices are processed element wise. + * @param value A value to convert to a string + * @returns The created string + */ + string( + value: MathType | null + ): string | MathArray | Matrix; - /** - * Calculate the exponent of a value. For matrices, the function is evaluated element wise. - * @param x A number or matrix to exponentiate - * #returns Exponent of x - */ - exp(x: number): number; - exp(x: BigNumber): BigNumber ; - exp(x: Complex): Complex ; - exp(x: MathArray): MathArray ; - exp(x: Matrix): Matrix; + /** + * Create a unit. Depending on the passed arguments, the function will + * create and return a new math.type.Unit object. When a matrix is + * provided, all elements will be converted to units. + * @param unit The unit to be created + * @returns The created unit + */ + unit(unit: string): Unit; + /** + * @param value The value of the unit to be created + * @param unit The unit to be created + * @returns The created unit + */ + unit(value: number | MathArray | Matrix, unit: string): Unit; - /** - * Round a value towards zero. For matrices, the function is evaluated element wise. - * @param x Number to be rounded - * @returns Rounded value - */ - fix(x: number): number; - fix(x: BigNumber): BigNumber ; - fix(x: Fraction): Fraction ; - fix(x: Complex): Complex ; - fix(x: MathArray): MathArray ; - fix(x: Matrix): Matrix; + /************************************************************************* + * Expression functions + ************************************************************************/ - /** - * Round a value towards minus infinity. For matrices, the function is evaluated element wise. - * @param Number to be rounded - * @returns Rounded value - */ - floor(x: number): number; - floor(x: BigNumber): BigNumber ; - floor(x: Fraction): Fraction ; - floor(x: Complex): Complex ; - floor(x: MathArray): MathArray ; - floor(x: Matrix): Matrix; + /** + * Parse and compile an expression. Returns a an object with a function + * eval([scope]) to evaluate the compiled expression. + * @param expr The expression to be compiled + * @returns An object with the compiled expression + */ + compile(expr: MathExpression): EvalFunction; + /** + * @param exprs The expressions to be compiled + * @returns An array of objects with the compiled expressions + */ + compile(exprs: MathExpression[]): EvalFunction[]; - /** - * Calculate the greatest common divisor for two or more values or arrays. For matrices, the function is evaluated element wise. - */ - gcd(...args: number[]): number; - gcd(...args: BigNumber[]): BigNumber ; - gcd(...args: Fraction[]): Fraction ; - gcd(...args: MathArray[]): MathArray ; - gcd(...args: Matrix[]): Matrix; + /** + * Evaluate an expression. + * @param expr The expression to be evaluated + * @param scope Scope to read/write variables + * @returns The result of the expression + */ + eval( + expr: MathExpression | MathExpression[] | Matrix, + scope?: object + ): any; - /** - * Calculate the hypotenusa of a list with values. The hypotenusa is defined as: - * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) - * For matrix input, the hypotenusa is calculated for all values in the matrix. - */ - hypot(...args: number[]): number; - hypot(...args: BigNumber[]): BigNumber; + /** + * Retrieve help on a function or data type. Help files are retrieved + * from the documentation in math.expression.docs. + * @param search A function or function name for which to get help + * @returns A help object + */ + help(search: () => any): Help; + + /** + * Parse an expression. Returns a node tree, which can be evaluated by + * invoking node.eval(); + * @param expr Expression to be parsed + * @param options Available options: nodes - a set of custome nodes + * @returns A node + */ + parse(expr: MathExpression, options?: any): MathNode; + /** + * @param exprs Expressions to be parsed + * @param options Available options: nodes - a set of custome nodes + * @returns An arry of nodes + */ + parse(exprs: MathExpression[], options?: any): MathNode[]; + + /** + * Create a parser. The function creates a new math.expression.Parser + * object. + * @returns A Parser object + */ + parser(): Parser; + + /************************************************************************* + * Algebra functions + ************************************************************************/ + /** + * @param expr The expression to differentiate + * @param variable The variable over which to differentiate + * @param options There is one option available, simplify, which is true + * by default. When false, output will not be simplified. + * @returns The derivative of expr + */ + derivative( + expr: MathNode | string, + variable: MathNode | string, + options?: {simplify: boolean} + ): MathNode; + + /** + * Solves the linear equation system by forwards substitution. Matrix + * must be a lower triangular matrix. + * @param L A N x N matrix or array (L) + * @param b A column vector with the b values + * @returns A column vector with the linear system solution (x) + */ + lsolve( + L: Matrix | MathArray, + b: Matrix | MathArray + ): Matrix | MathArray; + + /** + * Calculate the Matrix LU decomposition with partial pivoting. Matrix A + * is decomposed in two matrices (L, U) and a row permutation vector p + * where A[p,:] = L * U + * @param A A two dimensional matrix or array for which to get the LUP + * decomposition. + * @returns The lower triangular matrix, the upper triangular matrix and + * the permutation matrix. + */ + lup( + A?: Matrix | MathArray + ): { L: MathArray | Matrix; U: MathArray | Matrix; P: number[] }; + + /** + * Solves the linear system A * x = b where A is an [n x n] matrix and b + * is a [n] column vector. + * @param A Invertible Matrix or the Matrix LU decomposition + * @param b Column Vector + * @param order The Symbolic Ordering and Analysis order, see slu for + * details. Matrix must be a SparseMatrix + * @param threshold Partial pivoting threshold (1 for partial pivoting), + * see slu for details. Matrix must be a SparseMatrix. + * @returns Column vector with the solution to the linear system A * x = + * b + */ + lusolve( + A: Matrix | MathArray | number, + b: Matrix | MathArray, + order?: number, + threshold?: number + ): Matrix | MathArray; + + /** + * Calculate the Matrix QR decomposition. Matrix A is decomposed in two + * matrices (Q, R) where Q is an orthogonal matrix and R is an upper + * triangular matrix. + * @param A A two dimensional matrix or array for which to get the QR + * decomposition. + * @returns Q: the orthogonal matrix and R: the upper triangular matrix + */ + qr( + A: Matrix | MathArray + ): { Q: MathArray | Matrix; R: MathArray | Matrix }; + + /** + * Transform a rationalizable expression in a rational fraction. If + * rational fraction is one variable polynomial then converts the + * numerator and denominator in canonical form, with decreasing + * exponents, returning the coefficients of numerator. + * @param expr The expression to check if is a polynomial expression + * @param optional scope of expression or true for already evaluated + * rational expression at input + * @param detailed optional True if return an object, false if return + * expression node (default) + * @returns The rational polynomial of expr + */ + rationalize(expr: MathNode | string, optional?: object | boolean, detailed?: true): { expression: MathNode | string, variables: string[], coefficients: MathType[] }; + rationalize(expr: MathNode | string, optional?: object | boolean, detailed?: false): MathNode; + + /** + * Simplify an expression tree. + * @param expr The expression to be simplified + * @param rules A list of rules are applied to an expression, repeating + * over the list until no further changes are made. It’s possible to + * pass a custom set of rules to the function as second argument. A rule + * can be specified as an object, string, or function. + * @param scope Scope to variables + * @returns Returns the simplified form of expr + */ + simplify( + expr: MathNode | string, + rules?: Array<({ l: string; r: string } | string | ((node: MathNode) => MathNode))>, + scope?: object + ): MathNode; + + /** + * Calculate the Sparse Matrix LU decomposition with full pivoting. + * Sparse Matrix A is decomposed in two matrices (L, U) and two + * permutation vectors (pinv, q) where P * A * Q = L * U + * @param A A two dimensional sparse matrix for which to get the LU + * decomposition. + * @param order The Symbolic Ordering and Analysis order: 0 - Natural + * ordering, no permutation vector q is returned 1 - Matrix must be + * square, symbolic ordering and analisis is performed on M = A + A' 2 - + * Symbolic ordering and analysis is performed on M = A' * A. Dense + * columns from A' are dropped, A recreated from A'. This is appropriate + * for LU factorization of non-symmetric matrices. 3 - Symbolic ordering + * and analysis is performed on M = A' * A. This is best used for LU + * factorization is matrix M has no dense rows. A dense row is a row + * with more than 10*sqr(columns) entries. + * @param threshold Partial pivoting threshold (1 for partial pivoting) + * @returns The lower triangular matrix, the upper triangular matrix and + * the permutation vectors. + */ + slu(A: Matrix, order: number, threshold: number): object; + + /** + * Solves the linear equation system by backward substitution. Matrix + * must be an upper triangular matrix. U * x = b + * @param U A N x N matrix or array (U) + * @param b A column vector with the b values + * @returns A column vector with the linear system solution (x) + */ + usolve( + U: Matrix | MathArray, + b: Matrix | MathArray + ): Matrix | MathArray; + + /************************************************************************* + * Arithmetic functions + ************************************************************************/ + + /** + * Calculate the absolute value of a number. For matrices, the function + * is evaluated element wise. + * @param x A number or matrix for which to get the absolute value + * @returns Absolute value of x + */ + abs(x: number): number; + abs(x: BigNumber): BigNumber; + abs(x: Fraction): Fraction; + abs(x: Complex): Complex; + abs(x: MathArray): MathArray; + abs(x: Matrix): Matrix; + abs(x: Unit): Unit; + + /** + * Add two values, x + y. For matrices, the function is evaluated + * element wise. + * @param x First value to add + * @param y Second value to add + * @returns Sum of x and y + */ + add(x: MathType, y: MathType): MathType; + + /** + * Calculate the cubic root of a value. For matrices, the function is + * evaluated element wise. + * @param x Value for which to calculate the cubic root. + * @param allRoots Optional, false by default. Only applicable when x is + * a number or complex number. If true, all complex roots are returned, + * if false (default) the principal root is returned. + * @returns Returns the cubic root of x + */ + cbrt(x: number, allRoots?: boolean): number; + cbrt(x: BigNumber, allRoots?: boolean): BigNumber; + cbrt(x: Fraction, allRoots?: boolean): Fraction; + cbrt(x: Complex, allRoots?: boolean): Complex; + cbrt(x: MathArray, allRoots?: boolean): MathArray; + cbrt(x: Matrix, allRoots?: boolean): Matrix; + cbrt(x: Unit, allRoots?: boolean): Unit; + + /** + * Round a value towards plus infinity If x is complex, both real and + * imaginary part are rounded towards plus infinity. For matrices, the + * function is evaluated element wise. + * @param x Number to be rounded + * @returns Rounded value + */ + ceil(x: number): number; + ceil(x: BigNumber): BigNumber; + ceil(x: Fraction): Fraction; + ceil(x: Complex): Complex; + ceil(x: MathArray): MathArray; + ceil(x: Matrix): Matrix; + ceil(x: Unit): Unit; + + /** + * Compute the cube of a value, x * x * x. For matrices, the function is + * evaluated element wise. + * @param x Number for which to calculate the cube + * @returns Cube of x + */ + cube(x: number): number; + cube(x: BigNumber): BigNumber; + cube(x: Fraction): Fraction; + cube(x: Complex): Complex; + cube(x: MathArray): MathArray; + cube(x: Matrix): Matrix; + cube(x: Unit): Unit; + + /** + * Divide two values, x / y. To divide matrices, x is multiplied with + * the inverse of y: x * inv(y). + * @param x Numerator + * @param y Denominator + * @returns Quotient, x / y + */ + divide(x: Unit, y: Unit): Unit; + divide(x: number, y: number): number; + divide(x: MathType, y: MathType): MathType; + + /** + * Divide two matrices element wise. The function accepts both matrices + * and scalar values. + * @param x Numerator + * @param y Denominator + * @returns Quotient, x ./ y + */ + dotDivide(x: MathType, y: MathType): MathType; + + /** + * Multiply two matrices element wise. The function accepts both + * matrices and scalar values. + * @param x Left hand value + * @param y Right hand value + * @returns Multiplication of x and y + */ + dotMultiply(x: MathType, y: MathType): MathType; + + /** + * Calculates the power of x to y element wise. + * @param x The base + * @param y The exponent + * @returns The value of x to the power y + */ + dotPow(x: MathType, y: MathType): MathType; + + /** + * Calculate the exponent of a value. For matrices, the function is + * evaluated element wise. + * @param x A number or matrix to exponentiate + * @returns Exponent of x + */ + exp(x: number): number; + exp(x: BigNumber): BigNumber; + exp(x: Complex): Complex; + exp(x: MathArray): MathArray; + exp(x: Matrix): Matrix; + + /** + * Calculate the value of subtracting 1 from the exponential value. For + * matrices, the function is evaluated element wise. + * @param x A number or matrix to apply expm1 + * @returns Exponent of x + */ + expm1(x: number): number; + expm1(x: BigNumber): BigNumber; + expm1(x: Complex): Complex; + expm1(x: MathArray): MathArray; + expm1(x: Matrix): Matrix; + + /** + * Round a value towards zero. For matrices, the function is evaluated + * element wise. + * @param x Number to be rounded + * @returns Rounded value + */ + fix(x: number): number; + fix(x: BigNumber): BigNumber; + fix(x: Fraction): Fraction; + fix(x: Complex): Complex; + fix(x: MathArray): MathArray; + fix(x: Matrix): Matrix; + + /** + * Round a value towards minus infinity. For matrices, the function is + * evaluated element wise. + * @param Number to be rounded + * @returns Rounded value + */ + floor(x: number): number; + floor(x: BigNumber): BigNumber; + floor(x: Fraction): Fraction; + floor(x: Complex): Complex; + floor(x: MathArray): MathArray; + floor(x: Matrix): Matrix; + + /** + * Calculate the greatest common divisor for two or more values or + * arrays. For matrices, the function is evaluated element wise. + * @param args Two or more integer numbers + * @returns The greatest common divisor + */ + gcd(...args: number[]): number; + gcd(...args: BigNumber[]): BigNumber; + gcd(...args: Fraction[]): Fraction; + gcd(...args: MathArray[]): MathArray; + gcd(...args: Matrix[]): Matrix; + + /** + * Calculate the hypotenusa of a list with values. The hypotenusa is + * defined as: hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) For + * matrix input, the hypotenusa is calculated for all values in the + * matrix. + * @param args A list with numeric values or an Array or Matrix. Matrix + * and Array input is flattened and returns a single number for the + * whole matrix. + * @returns Returns the hypothenuse of the input values. + */ + hypot(...args: number[]): number; + hypot(...args: BigNumber[]): BigNumber; + + /** + * Calculate the least common multiple for two or more values or arrays. + * lcm is defined as: lcm(a, b) = abs(a * b) / gcd(a, b) For matrices, + * the function is evaluated element wise. + * @param a An integer number + * @param b An integer number + * @returns The least common multiple + */ + lcm(a: number, b: number): number; + lcm(a: BigNumber, b: BigNumber): BigNumber; + lcm(a: MathArray, b: MathArray): MathArray; + lcm(a: Matrix, b: Matrix): Matrix; + + /** + * Calculate the logarithm of a value. For matrices, the function is + * evaluated element wise. + * @param x Value for which to calculate the logarithm. + * @param base Optional base for the logarithm. If not provided, the + * natural logarithm of x is calculated. Default value: e. + * @returns Returns the logarithm of x + */ + log( + x: number | BigNumber | Complex | MathArray | Matrix, + base?: number | BigNumber | Complex + ): number | BigNumber | Complex | MathArray | Matrix; + + /** + * Calculate the 10-base of a value. This is the same as calculating + * log(x, 10). For matrices, the function is evaluated element wise. + * @param x Value for which to calculate the logarithm. + * @returns Returns the 10-base logarithm of x + */ + log10(x: number): number; + log10(x: BigNumber): BigNumber; + log10(x: Complex): Complex; + log10(x: MathArray): MathArray; + log10(x: Matrix): Matrix; + + /** + * Calculate the logarithm of a value+1. For matrices, the function is + * evaluated element wise. + * @param x Value for which to calculate the logarithm. + * @returns Returns the logarithm of x+1 + */ + log1p(x: number, base?: number | BigNumber | Complex): number; + log1p(x: BigNumber, base?: number | BigNumber | Complex): BigNumber; + log1p(x: Complex, base?: number | BigNumber | Complex): Complex; + log1p(x: MathArray, base?: number | BigNumber | Complex): MathArray; + log1p(x: Matrix, base?: number | BigNumber | Complex): Matrix; + + /** + * Calculate the 2-base of a value. This is the same as calculating + * log(x, 2). For matrices, the function is evaluated element wise. + * @param x Value for which to calculate the logarithm. + * @returns Returns the 2-base logarithm of x + */ + log2(x: number): number; + log2(x: BigNumber): BigNumber; + log2(x: Complex): Complex; + log2(x: MathArray): MathArray; + log2(x: Matrix): Matrix; + + /** + * Calculates the modulus, the remainder of an integer division. For + * matrices, the function is evaluated element wise. The modulus is + * defined as: x - y * floor(x / y) + * @see http://en.wikipedia.org/wiki/Modulo_operation. + * @param x Dividend + * @param y Divisor + * @returns Returns the remainder of x divided by y + */ + mod( + x: number | BigNumber | Fraction | MathArray | Matrix, + y: number | BigNumber | Fraction | MathArray | Matrix + ): number | BigNumber | Fraction | MathArray | Matrix; + + /** + * Multiply two values, x * y. The result is squeezed. For matrices, the + * matrix product is calculated. + * @param x The first value to multiply + * @param y The second value to multiply + * @returns Multiplication of x and y + */ + multiply(x: Matrix | MathArray, y: MathType): Matrix | MathArray; + multiply(x: Unit, y: Unit): Unit; + multiply(x: number, y: number): number; + multiply(x: MathType, y: MathType): MathType; + + /** + * Calculate the norm of a number, vector or matrix. The second + * parameter p is optional. If not provided, it defaults to 2. + * @param x Value for which to calculate the norm + * @param p Vector space. Supported numbers include Infinity and + * -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The + * Frobenius norm) Default value: 2. + * @returns the p-norm + */ + norm( + x: number | BigNumber | Complex | MathArray | Matrix, + p?: number | BigNumber | string + ): number | BigNumber; + + /** + * Calculate the nth root of a value. The principal nth root of a + * positive real number A, is the positive real solution of the equation + * x^root = A For matrices, the function is evaluated element wise. + * @param a Value for which to calculate the nth root + * @param root The root. Default value: 2. + * @return The nth root of a + */ + nthRoot( + a: number | BigNumber | MathArray | Matrix | Complex, + root?: number | BigNumber + ): number | Complex | MathArray | Matrix; + + /** + * Calculates the power of x to y, x ^ y. Matrix exponentiation is + * supported for square matrices x, and positive integer exponents y. + * @param x The base + * @param y The exponent + * @returns x to the power y + */ + pow(x: MathType, y: number | BigNumber | Complex): MathType; + + /** + * Round a value towards the nearest integer. For matrices, the function + * is evaluated element wise. + * @param x Number to be rounded + * @param n Number of decimals Default value: 0. + * @returns Rounded value of x + */ + round( + x: number | BigNumber | Fraction | Complex | MathArray | Matrix, + n?: number | BigNumber | MathArray + ): number | BigNumber | Fraction | Complex | MathArray | Matrix; + + /** + * Compute the sign of a value. The sign of a value x is: 1 when x > 1 + * -1 when x < 0 0 when x == 0 For matrices, the function is evaluated + * element wise. + * @param x The number for which to determine the sign + * @returns The sign of x + */ + sign(x: number): number; + sign(x: BigNumber): BigNumber; + sign(x: Fraction): Fraction; + sign(x: Complex): Complex; + sign(x: MathArray): MathArray; + sign(x: Matrix): Matrix; + sign(x: Unit): Unit; + + /** + * Calculate the square root of a value. For matrices, the function is + * evaluated element wise. + * @param x Value for which to calculate the square root + * @returns Returns the square root of x + */ + sqrt(x: number): number; + sqrt(x: BigNumber): BigNumber; + sqrt(x: Complex): Complex; + sqrt(x: MathArray): MathArray; + sqrt(x: Matrix): Matrix; + sqrt(x: Unit): Unit; + + /** + * Compute the square of a value, x * x. For matrices, the function is + * evaluated element wise. + * @param x Number for which to calculate the square + * @returns Squared value + */ + square(x: number): number; + square(x: BigNumber): BigNumber; + square(x: Fraction): Fraction; + square(x: Complex): Complex; + square(x: MathArray): MathArray; + square(x: Matrix): Matrix; + square(x: Unit): Unit; + + /** + * Subtract two values, x - y. For matrices, the function is evaluated + * element wise. + * @param x Initial value + * @param y Value to subtract from x + * @returns Subtraction of x and y + */ + subtract(x: MathType, y: MathType): MathType; + + /** + * Inverse the sign of a value, apply a unary minus operation. For + * matrices, the function is evaluated element wise. Boolean values and + * strings will be converted to a number. For complex numbers, both real + * and complex value are inverted. + * @param x Number to be inverted + * @returns Retursn the value with inverted sign + */ + unaryMinus(x: number): number; + unaryMinus(x: BigNumber): BigNumber; + unaryMinus(x: Fraction): Fraction; + unaryMinus(x: Complex): Complex; + unaryMinus(x: MathArray): MathArray; + unaryMinus(x: Matrix): Matrix; + unaryMinus(x: Unit): Unit; + + /** + * Unary plus operation. Boolean values and strings will be converted to + * a number, numeric values will be returned as is. For matrices, the + * function is evaluated element wise. + * @param x Input value + * @returns Returns the input value when numeric, converts to a number + * when input is non-numeric. + */ + unaryPlus(x: number): number; + unaryPlus(x: BigNumber): BigNumber; + unaryPlus(x: Fraction): Fraction; + unaryPlus(x: string): string; + unaryPlus(x: Complex): Complex; + unaryPlus(x: MathArray): MathArray; + unaryPlus(x: Matrix): Matrix; + unaryPlus(x: Unit): Unit; + + /** + * Calculate the extended greatest common divisor for two values. See + * http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. + * @param a An integer number + * @param b An integer number + * @returns Returns an array containing 3 integers [div, m, n] where div + * = gcd(a, b) and a*m + b*n = div + */ + xgcd(a: number | BigNumber, b: number | BigNumber): MathArray; + + /************************************************************************* + * Bitwise functions + ************************************************************************/ + + /** + * Bitwise AND two values, x & y. For matrices, the function is + * evaluated element wise. + * @param x First value to and + * @param y Second value to and + * @returns AND of x and y + */ + bitAnd( + x: number | BigNumber | MathArray | Matrix, + y: number | BigNumber | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /** + * Bitwise NOT value, ~x. For matrices, the function is evaluated + * element wise. For units, the function is evaluated on the best prefix + * base. + * @param x Value to not + * @returns NOT of x + */ + bitNot(x: number): number; + bitNot(x: BigNumber): BigNumber; + bitNot(x: MathArray): MathArray; + bitNot(x: Matrix): Matrix; + + /** + * Bitwise OR two values, x | y. For matrices, the function is evaluated + * element wise. For units, the function is evaluated on the lowest + * print base. + * @param x First value to or + * @param y Second value to or + * @returns OR of x and y + */ + bitOr(x: number, y: number): number; + bitOr(x: BigNumber, y: BigNumber): BigNumber; + bitOr(x: MathArray, y: MathArray): MathArray; + bitOr(x: Matrix, y: Matrix): Matrix; + + /** + * Bitwise XOR two values, x ^ y. For matrices, the function is + * evaluated element wise. + * @param x First value to xor + * @param y Second value to xor + * @returns XOR of x and y + */ + bitXor( + x: number | BigNumber | MathArray | Matrix, + y: number | BigNumber | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /** + * Bitwise left logical shift of a value x by y number of bits, x << y. + * For matrices, the function is evaluated element wise. For units, the + * function is evaluated on the best prefix base. + * @param x Value to be shifted + * @param y Amount of shifts + * @returns x shifted left y times + */ + leftShift( + x: number | BigNumber | MathArray | Matrix, + y: number | BigNumber + ): number | BigNumber | MathArray | Matrix; + + /** + * Bitwise right arithmetic shift of a value x by y number of bits, x >> + * y. For matrices, the function is evaluated element wise. For units, + * the function is evaluated on the best prefix base. + * @param x Value to be shifted + * @param y Amount of shifts + * @returns x sign-filled shifted right y times + */ + rightArithShift( + x: number | BigNumber | MathArray | Matrix, + y: number | BigNumber + ): number | BigNumber | MathArray | Matrix; + + /** + * Bitwise right logical shift of value x by y number of bits, x >>> y. + * For matrices, the function is evaluated element wise. For units, the + * function is evaluated on the best prefix base. + * @param x Value to be shifted + * @param y Amount of shifts + * @returns x zero-filled shifted right y times + */ + rightLogShift( + x: number | MathArray | Matrix, + y: number + ): number | MathArray | Matrix; + + /************************************************************************* + * Combinatorics functions + ************************************************************************/ + + /** + * The Bell Numbers count the number of partitions of a set. A partition + * is a pairwise disjoint subset of S whose union is S. bellNumbers only + * takes integer arguments. The following condition must be enforced: n + * >= 0 + * @param n Total number of objects in the set + * @returns B(n) + */ + bellNumbers(n: number): number; + bellNumbers(n: BigNumber): BigNumber; + + /** + * The Catalan Numbers enumerate combinatorial structures of many + * different types. catalan only takes integer arguments. The following + * condition must be enforced: n >= 0 + * @param n nth Catalan number + * @returns Cn(n) + */ + catalan(n: number): number; + catalan(n: BigNumber): BigNumber; + + /** + * The composition counts of n into k parts. Composition only takes + * integer arguments. The following condition must be enforced: k <= n. + * @param n Total number of objects in the set + * @param k Number of objects in the subset + * @returns Returns the composition counts of n into k parts. + */ + composition( + n: number | BigNumber, + k: number | BigNumber + ): number | BigNumber; + + /** + * The Stirling numbers of the second kind, counts the number of ways to + * partition a set of n labelled objects into k nonempty unlabelled + * subsets. stirlingS2 only takes integer arguments. The following + * condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = + * 1 + * @param n Total number of objects in the set + * @param k Number of objects in the subset + * @returns S(n,k) + */ + stirlingS2( + n: number | BigNumber, + k: number | BigNumber + ): number | BigNumber; + + /************************************************************************* + * Complex functions + ************************************************************************/ + + /** + * Compute the argument of a complex value. For a complex number a + bi, + * the argument is computed as atan2(b, a). For matrices, the function + * is evaluated element wise. + * @param x A complex number or array with complex numbers + * @returns The argument of x + */ + arg(x: number | Complex): number; + arg(x: BigNumber | Complex): BigNumber; + arg(x: MathArray): MathArray; + arg(x: Matrix): Matrix; + + /** + * Compute the complex conjugate of a complex value. If x = a+bi, the + * complex conjugate of x is a - bi. For matrices, the function is + * evaluated element wise. + * @param x A complex number or array with complex numbers + * @returns The complex conjugate of x + */ + conj( + x: number | BigNumber | Complex | MathArray | Matrix + ): number | BigNumber | Complex | MathArray | Matrix; + + /** + * Get the imaginary part of a complex number. For a complex number a + + * bi, the function returns b. For matrices, the function is evaluated + * element wise. + * @param x A complex number or array with complex numbers + * @returns The imaginary part of x + */ + im( + x: number | BigNumber | Complex | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /** + * Get the real part of a complex number. For a complex number a + bi, + * the function returns a. For matrices, the function is evaluated + * element wise. + * @param x A complex number or array of complex numbers + * @returns The real part of x + */ + re( + x: number | BigNumber | Complex | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /************************************************************************* + * Geometry functions + ************************************************************************/ + + /** + * Calculates: The eucledian distance between two points in 2 and 3 + * dimensional spaces. Distance between point and a line in 2 and 3 + * dimensional spaces. Pairwise distance between a set of 2D or 3D + * points NOTE: When substituting coefficients of a line(a, b and c), + * use ax + by + c = 0 instead of ax + by = c For parametric equation of + * a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, + * c) + * @param x Coordinates of the first point + * @param y Coordinates of the second point + * @returns Returns the distance from two/three points + */ + distance( + x: MathArray | Matrix | object, + y: MathArray | Matrix | object + ): number | BigNumber; + + /** + * Calculates the point of intersection of two lines in two or three + * dimensions and of a line and a plane in three dimensions. The inputs + * are in the form of arrays or 1 dimensional matrices. The line + * intersection functions return null if the lines do not meet. Note: + * Fill the plane coefficients as x + y + z = c and not as x + y + z + c + * = 0. + * @param w Co-ordinates of first end-point of first line + * @param x Co-ordinates of second end-point of first line + * @param y Co-ordinates of first end-point of second line OR + * Coefficients of the plane's equation + * @param z Co-ordinates of second end-point of second line OR null if + * the calculation is for line and plane + * @returns Returns the point of intersection of lines/lines-planes + */ + intersect( + w: MathArray | Matrix, + x: MathArray | Matrix, + y: MathArray | Matrix, + z: MathArray | Matrix + ): MathArray; + + /************************************************************************* + * Logical functions + ************************************************************************/ + + /** + * Logical and. Test whether two values are both defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param x First value to and + * @param y Second value to and + * @returns Returns true when both inputs are defined with a + * nonzero/nonempty value. + */ + and( + x: number | BigNumber | Complex | Unit | MathArray | Matrix, + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): boolean | MathArray | Matrix; + + /** + * Logical not. Flips boolean value of a given parameter. For matrices, + * the function is evaluated element wise. + * @param x First value to not + * @returns Returns true when input is a zero or empty value. + */ + not( + x: number | BigNumber | Complex | Unit | MathArray | Matrix + ): boolean | MathArray | Matrix; + + /** + * Logical or. Test if at least one value is defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param x First value to or + * @param y Second value to or + * @returns Returns true when one of the inputs is defined with a + * nonzero/nonempty value. + */ + or( + x: number | BigNumber | Complex | Unit | MathArray | Matrix, + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): boolean | MathArray | Matrix; + + /** + * Logical xor. Test whether one and only one value is defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param x First value to xor + * @param y Second value to xor + * @returns Returns true when one and only one input is defined with a + * nonzero/nonempty value. + */ + xor( + x: number | BigNumber | Complex | Unit | MathArray | Matrix, + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): boolean | MathArray | Matrix; + + /************************************************************************* + * Matrix functions + ************************************************************************/ + + /** + * Concatenate two or more matrices. dim: number is a zero-based + * dimension over which to concatenate the matrices. By default the last + * dimension of the matrices. + * @param args Two or more matrices + * @returns Concatenated matrix + */ + concat(...args: Array): MathArray | Matrix; + + /** + * Calculate the cross product for two vectors in three dimensional + * space. The cross product of A = [a1, a2, a3] and B =[b1, b2, b3] is + * defined as: cross(A, B) = [ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 + * * b2 - a2 * b1 ] + * @param x First vector + * @param y Second vector + * @returns Returns the cross product of x and y + */ + cross(x: MathArray | Matrix, y: MathArray | Matrix): Matrix | MathArray; + + /** + * Calculate the determinant of a matrix. + * @param x A Matrix + * @returns the determinant of x + */ + det(x: MathArray | Matrix): number; + + /** + * Create a diagonal matrix or retrieve the diagonal of a matrix. When x + * is a vector, a matrix with vector x on the diagonal will be returned. + * When x is a two dimensional matrix, the matrixes kth diagonal will be + * returned as vector. When k is positive, the values are placed on the + * super diagonal. When k is negative, the values are placed on the sub + * diagonal. + * @param X A two dimensional matrix or a vector + * @param k The diagonal where the vector will be filled in or + * retrieved. Default value: 0. + * @param format The matrix storage format. Default value: 'dense'. + * @returns Diagonal matrix from input vector, or diagonal from input + * matrix + */ + diag(X: MathArray | Matrix, format?: string): Matrix; + diag( + X: MathArray | Matrix, + k: number | BigNumber, + format?: string + ): Matrix | MathArray; + + /** + * Calculate the dot product of two vectors. The dot product of A = [a1, + * a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as: dot(A, + * B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn + * @param x First vector + * @param y Second vector + * @returns Returns the dot product of x and y + */ + dot(x: MathArray | Matrix, y: MathArray | Matrix): number; + + /** + * Compute the matrix exponential, expm(A) = e^A. The matrix must be + * square. Not to be confused with exp(a), which performs element-wise + * exponentiation. The exponential is calculated using the Padé + * approximant with scaling and squaring; see “Nineteen Dubious Ways to + * Compute the Exponential of a Matrix,” by Moler and Van Loan. + * @param x A square matrix + * @returns The exponential of x + */ + expm(x: Matrix): Matrix; + + /** + * Create a 2-dimensional identity matrix with size m x n or n x n. The + * matrix has ones on the diagonal and zeros elsewhere. + * @param size The size for the matrix + * @param format The Matrix storage format + * @returns A matrix with ones on the diagonal + */ + eye( + size: number | number[] | Matrix | MathArray, + format?: string + ): Matrix | MathArray | number; + /** + * @param m The x dimension for the matrix + * @param n The y dimension for the matrix + * @param format The Matrix storage format + * @returns A matrix with ones on the diagonal + */ + eye(m: number, n: number, format?: string): Matrix | MathArray | number; + + /** + * Filter the items in an array or one dimensional matrix. + * @param x A one dimensional matrix or array to filter + * @param test A function or regular expression to test items. All + * entries for which test returns true are returned. When test is a + * function, it is invoked with three parameters: the value of the + * element, the index of the element, and the matrix/array being + * traversed. The function must return a boolean. + */ + filter( + x: Matrix | MathArray, + test: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray) | RegExp + ): Matrix | MathArray; + + /** + * Flatten a multi dimensional matrix into a single dimensional matrix. + * @param x Matrix to be flattened + * @returns Returns the flattened matrix + */ + flatten(x: MathArray | Matrix): MathArray | Matrix; + + /** + * Iterate over all elements of a matrix/array, and executes the given + * callback function. + * @param x The matrix to iterate on. + * @param callback The callback function is invoked with three + * parameters: the value of the element, the index of the element, and + * the Matrix/array being traversed. + */ + forEach(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => void)): void; + + /** + * Calculate the inverse of a square matrix. + * @param x Matrix to be inversed + * @returns The inverse of x + */ + inv( + x: number | Complex | MathArray | Matrix + ): number | Complex | MathArray | Matrix; /** * Calculate the kronecker product of two matrices or vectors - * @param x First Matrix - * @param y Second Matrix + * @param x First vector + * @param y Second vector + * @returns Returns the kronecker product of x and y */ - kron(x: Matrix|MathArray, y: Matrix|MathArray): Matrix; - - /** - * Calculate the least common multiple for two or more values or arrays. lcm is defined as: - * lcm(a, b) = abs(a * b) / gcd(a, b) - * For matrices, the function is evaluated element wise. - */ - lcm(a: number, b: number): number; - lcm(a: BigNumber , b: BigNumber): BigNumber ; - lcm(a: MathArray, b: MathArray): MathArray; - lcm(a: Matrix, b: Matrix): Matrix; - - /** - * Calculate the logarithm of a value. For matrices, the function is evaluated element wise. - * @param x Value for which to calculate the logarithm. - * @param base Optional base for the logarithm. If not provided, the natural logarithm of x is calculated. Default value: e. - */ - log(x: number|BigNumber|Complex|MathArray|Matrix, base?: number|BigNumber|Complex): number|BigNumber|Complex|MathArray|Matrix; - - /** - * Calculate the 10-base of a value. This is the same as calculating log(x, 10). For matrices, the function is evaluated element wise. - * @param x Value for which to calculate the logarithm. - */ - log10(x: number): number; - log10(x: BigNumber): BigNumber; - log10(x: Complex): Complex; - log10(x: MathArray): MathArray; - log10(x: Matrix): Matrix; - - /** - * Calculates the modulus, the remainder of an integer division. For matrices, the function is evaluated element wise. - * The modulus is defined as: - * x - y * floor(x / y) - * @see http://en.wikipedia.org/wiki/Modulo_operation. - * @param x Dividend - * @param y Divisor - */ - mod(x: number|BigNumber|Fraction|MathArray|Matrix, y: number|BigNumber|Fraction|MathArray|Matrix): number|BigNumber|Fraction|MathArray|Matrix; - - /** - * Multiply two values, x * y. The result is squeezed. For matrices, the matrix product is calculated. - */ - multiply(x: MathArray|Matrix, y: MathType): Matrix; - multiply(x: Unit, y: Unit): Unit; - multiply(x: number, y: number): number; - multiply(x: MathType, y: MathType): MathType; - - /** - * Calculate the norm of a number, vector or matrix. The second parameter p is optional. If not provided, it defaults to 2. - * @param x Value for which to calculate the norm - * @param p Vector space. Supported numbers include Infinity and -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm) Default value: 2. - * @returns the p-norm - */ - norm(x: number|BigNumber|Complex|MathArray|Matrix, p?: number|BigNumber|string): number|BigNumber; - - /** - * Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation - * x^root = A - * For matrices, the function is evaluated element wise. - * @param a Value for which to calculate the nth root - * @param root The root. Default value: 2. - */ - nthRoot(a: number|BigNumber|MathArray|Matrix|Complex, root?: number|BigNumber): number|Complex|MathArray|Matrix; - - /** - * Calculates the power of x to y, x ^ y. Matrix exponentiation is supported for square matrices x, and positive integer exponents y. - * @param x The base - * @param y The exponent - */ - pow(x: MathType, y: number|BigNumber|Complex): MathType; - - /** - * Round a value towards the nearest integer. For matrices, the function is evaluated element wise. - * @param x Number to be rounded - * @param n Number of decimals Default value: 0. - */ - round(x: number|BigNumber|Fraction|Complex|MathArray|Matrix, n?: number|BigNumber|MathArray): number|BigNumber|Fraction|Complex|MathArray|Matrix; - - /** - * Compute the sign of a value. The sign of a value x is: - * 1 when x > 1 - * -1 when x < 0 - * 0 when x == 0 - * For matrices, the function is evaluated element wise. - */ - sign(x: number): number; - sign(x: BigNumber): BigNumber; - sign(x: Fraction): Fraction ; - sign(x: Complex): Complex ; - sign(x: MathArray): MathArray; - sign(x: Matrix): Matrix; - sign(x: Unit): Unit; - - /** - * Calculate the square root of a value. For matrices, the function is evaluated element wise. - */ - sqrt(x: number): number; - sqrt(x: BigNumber): BigNumber; - sqrt(x: Complex): Complex ; - sqrt(x: MathArray): MathArray; - sqrt(x: Matrix): Matrix; - sqrt(x: Unit): Unit; - - /** - * Compute the square of a value, x * x. For matrices, the function is evaluated element wise. - */ - square(x: number): number; - square(x: BigNumber): BigNumber; - square(x: Fraction): Fraction ; - square(x: Complex): Complex ; - square(x: MathArray): MathArray; - square(x: Matrix): Matrix; - square(x: Unit): Unit; - - /** - * Subtract two values, x - y. For matrices, the function is evaluated element wise. - */ - subtract(x: MathType, y: MathType): MathType; - - /** - * Inverse the sign of a value, apply a unary minus operation. - * For matrices, the function is evaluated element wise. Boolean values and strings will be converted to a number. For complex numbers, both real and complex value are inverted. - */ - unaryMinus(x: number): number; - unaryMinus(x: BigNumber): BigNumber; - unaryMinus(x: Fraction): Fraction ; - unaryMinus(x: Complex): Complex ; - unaryMinus(x: MathArray): MathArray; - unaryMinus(x: Matrix): Matrix; - unaryMinus(x: Unit): Unit; - - /** - * Unary plus operation. Boolean values and strings will be converted to a number, numeric values will be returned as is. - * For matrices, the function is evaluated element wise. - */ - unaryPlus(x: number): number; - unaryPlus(x: BigNumber): BigNumber; - unaryPlus(x: Fraction): Fraction ; - unaryPlus(x: string): string; - unaryPlus(x: Complex): Complex ; - unaryPlus(x: MathArray): MathArray; - unaryPlus(x: Matrix): Matrix; - unaryPlus(x: Unit): Unit; - - /** - * Calculate the extended greatest common divisor for two values. See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. - */ - xgcd(a: number|BigNumber, b: number|BigNumber): MathArray; - - /** - * Bitwise AND two values, x & y. For matrices, the function is evaluated element wise. - */ - bitAnd(x: number|BigNumber|MathArray|Matrix, y: number|BigNumber|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Bitwise NOT value, ~x. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - */ - bitNot(x: number): number; - bitNot(x: BigNumber): BigNumber ; - bitNot(x: MathArray): MathArray; - bitNot(x: Matrix): Matrix; - - /** - * Bitwise OR two values, x | y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the lowest print base. - */ - bitOr(x: number): number; - bitOr(x: BigNumber): BigNumber ; - bitOr(x: MathArray): MathArray; - bitOr(x: Matrix): Matrix; - - /** - * Bitwise XOR two values, x ^ y. For matrices, the function is evaluated element wise. - */ - bitXor(x: number|BigNumber|MathArray|Matrix, y: number|BigNumber|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Bitwise left logical shift of a value x by y number of bits, x << y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - leftShift(x: number|BigNumber|MathArray|Matrix, y: number|BigNumber): number|BigNumber|MathArray|Matrix; - - /** - * Bitwise right arithmetic shift of a value x by y number of bits, x >> y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - rightArithShift(x: number|BigNumber|MathArray|Matrix, y: number|BigNumber): number|BigNumber|MathArray|Matrix; - - /** - * Bitwise right logical shift of value x by y number of bits, x >>> y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - rightLogShift(x: number|MathArray|Matrix, y: number): number|MathArray|Matrix; - - /** - * The Bell Numbers count the number of partitions of a set. - * A partition is a pairwise disjoint subset of S whose union is S. bellNumbers only takes integer arguments. - * The following condition must be enforced: n >= 0 - * @param n Total number of objects in the set - */ - bellNumbers(n: number): number; - bellNumbers(n: BigNumber): BigNumber; - - /** - * The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0 - * @param n nth Catalan number - */ - catalan(n: number): number; - catalan(n: BigNumber): BigNumber; - - /** - * The composition counts of n into k parts. Composition only takes integer arguments. The following condition must be enforced: k <= n. - * @param n Total number of objects in the set - * @param k Number of objects in the subset - * @returns Returns the composition counts of n into k parts. - */ - composition(n: number|BigNumber, k: number|BigNumber): number|BigNumber; - - /** - * The Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. - * stirlingS2 only takes integer arguments. The following condition must be enforced: k <= n. - * If n = k or k = 1, then s(n,k) = 1 - * @param n Total number of objects in the set - * @param k Number of objects in the subset - */ - stirlingS2(n: number|BigNumber, k: number|BigNumber): number|BigNumber; - - /** - * Compute the argument of a complex value. For a complex number a + bi, the argument is computed as atan2(b, a). For matrices, the function is evaluated element wise. - * @param x A complex number or array with complex numbers - */ - arg(x: number|Complex): number; - arg(x: MathArray): MathArray; - arg(x: Matrix): Matrix; - - /** - * Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate of x is a - bi. For matrices, the function is evaluated element wise. - * @param x A complex number or array with complex numbers - */ - conj(x: number|BigNumber|Complex|MathArray|Matrix): number|BigNumber|Complex|MathArray|Matrix; - - /** - * Get the imaginary part of a complex number. For a complex number a + bi, the function returns b. - * For matrices, the function is evaluated element wise. - */ - im(x: number|BigNumber|Complex|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Get the real part of a complex number. For a complex number a + bi, the function returns a. - * For matrices, the function is evaluated element wise. - */ - re(x: number|BigNumber|Complex|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Create a BigNumber, which can store numbers with arbitrary precision. When a matrix is provided, all elements will be converted to BigNumber. - */ - bignumber(x?: number|string|MathArray|Matrix|boolean): BigNumber; - - /** - * Create a boolean or convert a string or number to a boolean. - * In case of a number, true is returned for non-zero numbers, and false in case of zero. - * Strings can be 'true' or 'false', or can contain a number. When value is a matrix, all elements will be converted to boolean. - */ - boolean(x: string|number|boolean|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Wrap any value in a chain, allowing to perform chained operations on the value. - * All methods available in the math.js library can be called upon the chain, and then will be evaluated with the value itself as first argument. - * The chain can be closed by executing chain.done(), which returns the final value. - * The chain has a number of special functions: - * done() Finalize the chain and return the chain's value. - * valueOf() The same as done() - * toString() Executes math.format() onto the chain's value, returning a string representation of the value. - */ - chain(value?: any): MathJsChain; - - /** - * Create a complex value or convert a value to a complex value. - */ - complex(arg?: Complex|string|MathArray| PolarCoordinates): Complex; - complex(re: number, im: number): Complex; - - /** - * Create a fraction convert a value to a fraction. - */ - fraction(numerator: number|string|MathArray|Matrix, denominator?: number|string|MathArray|Matrix): Fraction|MathArray|Matrix; - - /** - * Create an index. An Index can store ranges having start, step, and end for multiple dimensions. Matrix.get, Matrix.set, and math.subset accept an Index as input. - */ - index(...ranges: any[]): Index; - - /** - * Create a Matrix. The function creates a new math.type.Matrix object from an Array. A Matrix has utility functions - * to manipulate the data in the matrix, like getting the size and getting or setting values in the matrix. Supported - * storage formats are 'dense' and 'sparse'. - */ - matrix(format?: 'sparse'|'dense'): Matrix; - matrix(data: MathArray|Matrix, format?: 'sparse'|'dense', dataType?: string): Matrix; - - /** - * Create a number or convert a string, boolean, or unit to a number. When value is a matrix, all elements will be converted to number. - */ - number(value?: string|number|boolean|MathArray|Matrix|Unit|BigNumber): number|MathArray|Matrix; - number(unit: Unit, valuelessUnit: Unit|string): number|MathArray|Matrix; - - /** - * Create a Sparse Matrix. The function creates a new math.type.Matrix object from an Array. A Matrix has utility - * functions to manipulate the data in the matrix, like getting the size and getting or setting values in the matrix. - * @param data A two dimensional array - */ - sparse(data?: MathArray|Matrix, dataType?: string): Matrix; - - /** - * Create a string or convert any object into a string. Elements of Arrays and Matrices are processed element wise. - * @param value A value to convert to a string - */ - string(value: any): string|MathArray|Matrix; - - /** - * Create a unit. Depending on the passed arguments, the function will create and return a new math.type.Unit object. - * When a matrix is provided, all elements will be converted to units. - */ - unit(unit: string): Unit; - unit(value: number, unit: string): Unit; - - /** - * Create a user-defined unit and register it with the Unit type. - */ - createUnit(name: string, definition?: string|UnitDefinition, options?: CreateUnitOptions): Unit; - createUnit(units: Record, options?: CreateUnitOptions): Unit; - - /** - * Parse and compile an expression. Returns a an object with a function eval([scope]) to evaluate the compiled expression. - */ - compile(expr: MathExpression): EvalFunction; - compile(exprs: MathExpression[]): EvalFunction[]; - - /** - * Evaluate an expression. - */ - eval(expr: MathExpression|MathExpression[], scope?: any): any; - - /** - * Retrieve help on a function or data type. Help files are retrieved from the documentation in math.expression.docs. - */ - help(search: any): Help; - - /** - * Parse an expression. Returns a node tree, which can be evaluated by invoking node.eval(); - */ - parse(expr: MathExpression, options?: any): MathNode; - parse(exprs: MathExpression[], options?: any): MathNode[]; - - /** - * Create a parser. The function creates a new math.expression.Parser object. - */ - parser(): Parser; - - /** - * Calculates: The eucledian distance between two points in 2 and 3 dimensional spaces. Distance between point - * and a line in 2 and 3 dimensional spaces. Pairwise distance between a set of 2D or 3D points NOTE: When - * substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c For parametric - * equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c) - */ - distance(x: MathType, y: MathType): number | BigNumber; - - /** - * Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in - * three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions - * return null if the lines do not meet. - * Note: Fill the plane coefficients as x + y + z = c and not as x + y + z + c = 0. - * @param w Co-ordinates of first end-point of first line - * @param x Co-ordinates of second end-point of first line - * @param y Co-ordinates of first end-point of second line OR Coefficients of the plane's equation - * @param z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane - * @returns Returns the point of intersection of lines/lines-planes - */ - intersect(w: MathArray|Matrix, x: MathArray|Matrix, y: MathArray|Matrix, z: MathArray|Matrix): MathArray; - - /** - * Logical and. Test whether two values are both defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - and(x: number|BigNumber|Complex|Unit|MathArray|Matrix, y: number|BigNumber|Complex|Unit|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Logical not. Flips boolean value of a given parameter. For matrices, the function is evaluated element wise. - */ - not(x: number|BigNumber|Complex|Unit|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Logical or. Test if at least one value is defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - or(x: number|BigNumber|Complex|Unit|MathArray|Matrix, y: number|BigNumber|Complex|Unit|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Logical xor. Test whether one and only one value is defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - xor(x: number|BigNumber|Complex|Unit|MathArray|Matrix, y: number|BigNumber|Complex|Unit|MathArray|Matrix): boolean|MathArray|Matrix; - - /** - * Concatenate two or more matrices. - * dim: number is a zero-based dimension over which to concatenate the matrices. By default the last dimension of the matrices. - */ - concat(...args: Array): MathArray|Matrix; - - /** - * Calculate the cross product for two vectors in three dimensional space. The cross product of A = [a1, a2, a3] - * and B =[b1, b2, b3] is defined as: - * cross(A, B) = [ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 ] - */ - cross(x: MathArray|Matrix, y: MathArray|Matrix): Matrix; - - /** - * Calculate the determinant of a matrix. - */ - det(x: MathArray|Matrix): number; - - /** - * Create a diagonal matrix or retrieve the diagonal of a matrix. - * When x is a vector, a matrix with vector x on the diagonal will be returned. When x is a two dimensional matrix, - * the matrixes kth diagonal will be returned - * as vector. When k is positive, the values are placed on the super diagonal. When k is negative, the values are - * placed on the sub diagonal. - * @param X A two dimensional matrix or a vector - * @param k The diagonal where the vector will be filled in or retrieved. Default value: 0. - * @param format The matrix storage format. Default value: 'dense'. - */ - diag(X: MathArray|Matrix, format?: string): Matrix; - diag(X: MathArray|Matrix, k: number|BigNumber, format?: string): Matrix; - - /** - * Calculate the dot product of two vectors. - * The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] - * is defined as: - * dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn - */ - dot(x: MathArray|Matrix, y: MathArray|Matrix): number; - - /** - * Create a 2-dimensional identity matrix with size m x n or n x n. The matrix has ones on the diagonal and zeros elsewhere. - */ - eye(n: number|number[], format?: string): Matrix; - eye(m: number, n: number, format?: string): Matrix; - - /** - * Flatten a multi dimensional matrix into a single dimensional matrix. - */ - flatten(x: MathArray|Matrix): MathArray|Matrix; - - /** - * Calculate the inverse of a square matrix. - */ - inv(x: number|Complex|MathArray|Matrix): number|Complex|MathArray|Matrix; - - /** - * Create a matrix filled with ones. The created matrix can have one or multiple dimensions. - */ - ones(n: number|number[], format?: string): MathArray|Matrix; - ones(m: number, n: number, format?: string): MathArray|Matrix; - - /** - * Create an array from a range. By default, the range end is excluded. This can be customized by providing an extra parameter includeEnd. - * @param str A string 'start:end' or 'start:step:end' - * @param start Start of the range - * @param end End of the range, excluded by default, included when parameter includeEnd=true - * @param step Step size. Default value is 1. - * @returns Parameters describing the ranges start, end, and optional step. - */ - range(str: string, includeEnd?: boolean): Matrix; - range(start: number|BigNumber, end: number|BigNumber, includeEnd?: boolean): Matrix; - range(start: number|BigNumber, end: number|BigNumber, step: number|BigNumber, includeEnd?: boolean): Matrix; - - /** - * Resize a matrix - * @param x Matrix to be resized - * @param size One dimensional array with numbers - * @param defaultValue Zero by default, except in case of a string, in that case defaultValue = ' ' Default value: 0. - */ - resize(x: MathArray|Matrix, size: MathArray|Matrix, defaultValue?: number|string): MathArray|Matrix; - - /** - * Calculate the size of a matrix or scalar. - */ - size(x: boolean|number|Complex|Unit|string|MathArray|Matrix): MathArray|Matrix; - - /** - * Squeeze a matrix, remove inner and outer singleton dimensions from a matrix. - */ - squeeze(x: MathArray|Matrix): Matrix|MathArray; - - /** - * Get or set a subset of a matrix or string. - * @param value An array, matrix, or string - * @param index An index containing ranges for each dimension - * @param replacement An array, matrix, or scalar. If provided, the subset is replaced with replacement. If not provided, the subset is returned - * @param defaultValue Default value, filled in on new entries when the matrix is resized. If not provided, math.matrix elements will be left undefined. Default value: undefined. - */ - subset(value: MathArray|Matrix|string, index: Index, replacement?: any, defaultValue?: any): MathArray|Matrix|string; - - /** - * Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix. - */ - trace(x: MathArray|Matrix): number; - - /** - * Transpose a matrix. All values of the matrix are reflected over its main diagonal. Only two dimensional matrices are supported. - */ - transpose(x: MathArray|Matrix): MathArray|Matrix; - - /** - * Create a matrix filled with zeros. The created matrix can have one or multiple dimensions. - */ - zeros(n: number|number[], format?: string): MathArray|Matrix; - zeros(m: number, n: number, format?: string): MathArray|Matrix; - - /** - * Compute the number of ways of picking k unordered outcomes from n possibilities. - * Combinations only takes integer arguments. The following condition must be enforced: k <= n. - */ - combinations(n: number|BigNumber, k: number|BigNumber): number|BigNumber; - - /** - * Create a distribution object with a set of random functions for given random distribution. - * @param name Name of a distribution. Choose from 'uniform', 'normal'. - */ - distribution(name: string): Distribution; - - /** - * Compute the factorial of a value - * Factorial only supports an integer value as argument. For matrices, the function is evaluated element wise. - */ - factorial(n: number|BigNumber|MathArray|Matrix): number|BigNumber|MathArray|Matrix; - - /** - * Compute the gamma function of a value using Lanczos approximation for small values, and an extended - * Stirling approximation for large values. - * For matrices, the function is evaluated element wise. - */ - gamma(n: number|MathArray|Matrix): number|MathArray|Matrix; - - /** - * Calculate the Kullback-Leibler (KL) divergence between two distributions - */ - kldivergence(x: MathArray|Matrix, y: MathArray|Matrix): number; - - /** - * Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from n possibilities. - * multinomial takes one array of integers as an argument. The following condition must be enforced: every ai <= 0 - */ - multinomial(a: number[]|BigNumber[]): number|BigNumber; - - /** - * Compute the number of ways of obtaining an ordered subset of k elements from a set of n elements. - * Permutations only takes integer arguments. The following condition must be enforced: k <= n. - * @param n The number of objects in total - * @param k The number of objects in the subset - */ - permutations(n: number|BigNumber, k?: number|BigNumber): number|BigNumber; - - /** - * Random pick a value from a one dimensional array. Array element is picked using a random function with uniform distribution. - */ - pickRandom(array: number[]): number; - - /** - * Return a random number larger or equal to min and smaller than max using a uniform distribution. - */ - random(min?: number, max?: number): number; - random(size: MathArray|Matrix, min?: number, max?: number): MathArray|Matrix; - - /** - * Return a random integer number larger or equal to min and smaller than max using a uniform distribution. - */ - randomInt(min: number, max?: number): number; - randomInt(size: MathArray|Matrix, min?: number, max?: number): MathArray|Matrix; - - /** - * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y. - * x and y are considered equal when the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - compare(x: MathType, y: MathType): number|BigNumber|Fraction|MathArray|Matrix; - - /** - * Test element wise whether two matrices are equal. The function accepts both matrices and scalar values. - */ - deepEqual(x: MathType, y: MathType): number|BigNumber|Fraction|Complex|Unit|MathArray|Matrix; - - /** - * Test whether two values are equal. - * - * The function tests whether the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. In case of complex numbers, x.re must equal y.re, and x.im must equal y.im. - * Values null and undefined are compared strictly, thus null is only equal to null and nothing else, and undefined is only equal to undefined and nothing else. - */ - equal(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether value x is larger than y. - * The function returns true when x is larger than y and the relative difference between x and y is larger than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - larger(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether value x is larger or equal to y. - * The function returns true when x is larger than y or the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - largerEq(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether value x is smaller than y. - * The function returns true when x is smaller than y and the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - smaller(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether value x is smaller or equal to y. - * The function returns true when x is smaller than y or the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. For matrices, the function is evaluated element wise. - */ - smallerEq(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Test whether two values are unequal. - * The function tests whether the relative difference between x and y is larger than the configured epsilon. The function cannot - * be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im. - * Values null and undefined are compared strictly, thus null is unequal with everything except null, and undefined is unequal with - * everything except undefined. - */ - unequal(x: MathType, y: MathType): boolean|MathArray|Matrix; - - /** - * Compute the maximum value of a matrix or a list with values. In case of a multi dimensional array, the maximum of the flattened - * array will be calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - max(...args: MathType[]): any; - max(A: MathArray|Matrix, dim?: number): any; - - /** - * Compute the mean value of matrix or a list with values. In case of a multi dimensional array, the mean of the flattened array will be - * calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - mean(...args: MathType[]): any; - mean(A: MathArray|Matrix, dim?: number): any; - - /** - * Compute the median of a matrix or a list with values. The values are sorted and the middle value is returned. In case of an - * even number of values, the average of the two middle values is returned. Supported types of values are: Number, BigNumber, Unit - * In case of a (multi dimensional) array or matrix, the median of all elements will be calculated. - */ - median(...args: MathType[]): any; - - /** - * Compute the maximum value of a matrix or a list of values. In case of a multi dimensional array, the maximum of the flattened - * array will be calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - min(...args: MathType[]): any; - min(A: MathArray|Matrix, dim?: number): any; - - /** - * Computes the mode of a set of numbers or a list with values(numbers or characters). If there are more than one modes, it returns a list of those values. - */ - mode(...args: MathType[]): any; - - /** - * Compute the product of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the sum of all elements will be calculated. - */ - prod(...args: MathType[]): any; - - /** - * Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. - * Supported types of sequence values are: Number, BigNumber, Unit Supported types of probability are: Number, BigNumber - * In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated. - */ - quantileSeq(A: MathArray|Matrix, prob: number|BigNumber|MathArray, sorted?: boolean): number|BigNumber|Unit|MathArray; - - /** - * Compute the standard deviation of a matrix or a list with values. The standard deviations is defined as the square root of the - * variance: std(A) = sqrt(var(A)). In case of a (multi dimensional) array or matrix, the standard deviation over all elements will - * be calculated. - * Optionally, the type of normalization can be specified as second parameter. The parameter normalization can be one of the following - * values: - * 'unbiased' (default) The sum of squared errors is divided by (n - 1) - * 'uncorrected' The sum of squared errors is divided by n - * 'biased' The sum of squared errors is divided by (n + 1) - */ - std(array: MathArray|Matrix, normalization?: string): number; - - /** - * Compute the sum of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the sum of all elements will be calculated. - */ - sum(...args: Array): any; - sum(array: MathArray|Matrix): any; - - /** - * Compute the variance of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the variance over all - * elements will be calculated. - * Optionally, the type of normalization can be specified as second parameter. The parameter normalization can be one of the - * following values: - * 'unbiased' (default) The sum of squared errors is divided by (n - 1) - * 'uncorrected' The sum of squared errors is divided by n - * 'biased' The sum of squared errors is divided by (n + 1) - * Note that older browser may not like the variable name var. In that case, the function can be called as math['var'](...) - * instead of math.var(...). - */ - var(...args: Array): any; - var(array: MathArray|Matrix, normalization?: string): any; - - /** - * Calculate the inverse cosine of a value. For matrices, the function is evaluated element wise. - */ - acos(x: number): number; - acos(x: BigNumber): BigNumber; - acos(x: Complex): Complex; - acos(x: MathArray): MathArray; - acos(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arccos of a value, defined as acosh(x) = ln(sqrt(x^2 - 1) + x). - * For matrices, the function is evaluated element wise. - */ - acosh(x: number): number; - acosh(x: BigNumber): BigNumber; - acosh(x: Complex): Complex; - acosh(x: MathArray): MathArray; - acosh(x: Matrix): Matrix; - - /** - * Calculate the inverse cotangent of a value. For matrices, the function is evaluated element wise. - */ - acot(x: number): number; - acot(x: BigNumber): BigNumber; - acot(x: MathArray): MathArray; - acot(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arccotangent of a value, defined as acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2. - * For matrices, the function is evaluated element wise. - */ - acoth(x: number): number; - acoth(x: BigNumber): BigNumber; - acoth(x: MathArray): MathArray; - acoth(x: Matrix): Matrix; - - /** - * Calculate the inverse cosecant of a value. For matrices, the function is evaluated element wise. - */ - acsc(x: number): number; - acsc(x: BigNumber): BigNumber; - acsc(x: MathArray): MathArray; - acsc(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arccosecant of a value, defined as acsch(x) = ln(1/x + sqrt(1/x^2 + 1)). - * For matrices, the function is evaluated element wise. - */ - acsch(x: number): number; - acsch(x: BigNumber): BigNumber; - acsch(x: MathArray): MathArray; - acsch(x: Matrix): Matrix; - - /** - * Calculate the inverse secant of a value. For matrices, the function is evaluated element wise. - */ - asec(x: number): number; - asec(x: BigNumber): BigNumber; - asec(x: MathArray): MathArray; - asec(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arcsecant of a value, defined as asech(x) = ln(sqrt(1/x^2 - 1) + 1/x). For matrices, the function is evaluated element wise. - */ - asech(x: number): number; - asech(x: BigNumber): BigNumber; - asech(x: MathArray): MathArray; - asech(x: Matrix): Matrix; - - /** - * Calculate the inverse sine of a value. For matrices, the function is evaluated element wise. - */ - asin(x: number): number; - asin(x: BigNumber): BigNumber; - asin(x: Complex): Complex; - asin(x: MathArray): MathArray; - asin(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic arcsine of a value, defined as asinh(x) = ln(x + sqrt(x^2 + 1)). For matrices, the function is evaluated element wise. - */ - asinh(x: number): number; - asinh(x: BigNumber): BigNumber; - asinh(x: MathArray): MathArray; - asinh(x: Matrix): Matrix; - - /** - * Calculate the inverse tangent of a value. For matrices, the function is evaluated element wise. - */ - atan(x: number): number; - atan(x: BigNumber): BigNumber; - atan(x: MathArray): MathArray; - atan(x: Matrix): Matrix; - - /** - * Calculate the inverse tangent function with two arguments, y/x. By providing two arguments, the right quadrant of the - * computed angle can be determined. - * For matrices, the function is evaluated element wise. - */ - atan2(y: number, x: number): number; - atan2(y: MathArray|Matrix, x: MathArray|Matrix): MathArray|Matrix; - - /** - * Calculate the hyperbolic arctangent of a value, defined as atanh(x) = ln((1 + x)/(1 - x)) / 2. - * For matrices, the function is evaluated element wise. - */ - atanh(x: number): number; - atanh(x: BigNumber): BigNumber; - atanh(x: MathArray): MathArray; - atanh(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic cosine of a value, defined as cosh(x) = 1/2 * (exp(x) + exp(-x)). For matrices, the function is evaluated element wise. - */ - cosh(x: number|Unit): number; - cosh(x: BigNumber): BigNumber; - cosh(x: Complex): Complex; - cosh(x: MathArray): MathArray; - cosh(x: Matrix): Matrix; - - /** - * Calculate the cotangent of a value. cot(x) is defined as 1 / tan(x). For matrices, the function is evaluated element wise. - */ - cot(x: number|Unit): number; - cot(x: Complex): Complex; - cot(x: MathArray): MathArray; - cot(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic cotangent of a value, defined as coth(x) = 1 / tanh(x). For matrices, the function is evaluated element wise. - */ - coth(x: number|Unit): number; - coth(x: Complex): Complex; - coth(x: MathArray): MathArray; - coth(x: Matrix): Matrix; - - /** - * Calculate the cosecant of a value, defined as csc(x) = 1/sin(x). For matrices, the function is evaluated element wise. - */ - csc(x: number|Unit): number; - csc(x: Complex): Complex; - csc(x: MathArray): MathArray; - csc(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic cosecant of a value, defined as csch(x) = 1 / sinh(x). For matrices, the function is evaluated element wise. - */ - csch(x: number|Unit): number; - csch(x: Complex): Complex; - csch(x: MathArray): MathArray; - csch(x: Matrix): Matrix; - - /** - * Calculate the secant of a value, defined as sec(x) = 1/cos(x). For matrices, the function is evaluated element wise. - */ - sec(x: number|Unit): number; - sec(x: Complex): Complex; - sec(x: MathArray): MathArray; - sec(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic secant of a value, defined as sech(x) = 1 / cosh(x). For matrices, the function is evaluated element wise. - */ - sech(x: number|Unit): number; - sech(x: Complex): Complex; - sech(x: MathArray): MathArray; - sech(x: Matrix): Matrix; - - /** - * Calculate the sine of a value. For matrices, the function is evaluated element wise. - */ - sin(x: number|Unit): number; - sin(x: BigNumber): BigNumber; - sin(x: Complex): Complex; - sin(x: MathArray): MathArray; - sin(x: Matrix): Matrix; - - /** - * Calculate the cosine of a value. For matrices, the function is evaluated element wise. - */ - cos(x: number|Unit): number; - cos(x: BigNumber): BigNumber; - cos(x: Complex): Complex; - cos(x: MathArray): MathArray; - cos(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic sine of a value, defined as sinh(x) = 1/2 * (exp(x) - exp(-x)). For matrices, the function is evaluated element wise. - */ - sinh(x: number|Unit): number; - sinh(x: BigNumber): BigNumber; - sinh(x: Complex): Complex; - sinh(x: MathArray): MathArray; - sinh(x: Matrix): Matrix; - - /** - * Calculate the tangent of a value. tan(x) is equal to sin(x) / cos(x). For matrices, the function is evaluated element wise. - */ - tan(x: number|Unit): number; - tan(x: BigNumber): BigNumber; - tan(x: Complex): Complex; - tan(x: MathArray): MathArray; - tan(x: Matrix): Matrix; - - /** - * Calculate the hyperbolic tangent of a value, defined as tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1). For matrices, the function is evaluated element wise. - */ - tanh(x: number|Unit): number; - tanh(x: BigNumber): BigNumber; - tanh(x: Complex): Complex; - tanh(x: MathArray): MathArray; - tanh(x: Matrix): Matrix; - - /** - * Change the unit of a value. For matrices, the function is evaluated element wise. - * @param x The unit to be converted. - * @param unit New unit. Can be a string like "cm" or a unit without value. - */ - to(x: Unit|MathArray|Matrix, unit: Unit|string): Unit|MathArray|Matrix; - - /** - * Clone an object. - */ - clone(x: any): any; - - /** - * Filter the items in an array or one dimensional matrix. - * @param x A one dimensional matrix or array to filter - * @param test - */ - filter(x: MathArray|Matrix, test: RegExp|((item: any) => boolean)): MathArray|Matrix; - - /** - * Iterate over all elements of a matrix/array, and executes the given callback function. - * @param x The matrix to iterate on. - * @param callback The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix/array being traversed. - */ - forEach: (x: MathArray|Matrix, callback: (item: any) => any) => void; - - /** - * Format a value of any type into a string. - * @param value The value to be formatted - */ - format(value: any, options?: FormatOptions|number|((item: any) => string)): string; - - /** - * Test whether a value is an integer number. The function supports number, BigNumber, and Fraction. - * The function is evaluated element-wise in case of Array or Matrix input. - */ - isInteger(x: any): boolean; - - /** - * Test whether a value is negative: smaller than zero. The function supports types number, BigNumber, Fraction, and Unit. - * The function is evaluated element-wise in case of Array or Matrix input. - */ - isNegative(x: any): boolean; - - /** - * Test whether a value is an numeric value. The function is evaluated element-wise in case of Array or Matrix input. - */ - isNumeric(x: any): boolean; - - /** - * Test whether a value is positive: larger than zero. The function supports types number, BigNumber, Fraction, and Unit. - * The function is evaluated element-wise in case of Array or Matrix input. - */ - isPositive(x: any): boolean; - - /** - * Test whether a value is zero. The function can check for zero for types number, BigNumber, Fraction, Complex, and Unit. - * The function is evaluated element-wise in case of Array or Matrix input. - */ - isZero(x: any): boolean; - - /** - * Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array. - * @param x The matrix to iterate on. - * @param callback The callback method is invoked with three parameters: the value of the element, the index of the element, and the matrix being traversed. - */ - map(x: MathArray|Matrix, callback: (item: any) => any): MathArray|Matrix; - - /** - * Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect. - * @param x A one dimensional matrix or array to sort - * @param k The kth smallest value to be retrieved; zero-based index - * @param compare An optional comparator function. The function is called as compare(a, b), and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. - * @returns Returns the kth lowest value. - */ - partitionSelect(x: MathArray|Matrix, k: number, compare?: string|((a: any, b: any) => number)): any; - - /** - * Interpolate values into a string template. - * @param template A string containing variable placeholders. - * @param values An object containing variables which will be filled in in the template. - * @param precision Number of digits to format numbers. If not provided, the value will not be rounded. - */ - print: (template: string, values: any, precision?: number) => void; - - /** - * Sort the items in a matrix. - * @param x A one dimensional matrix or array to sort - * @param compare An optional comparator function. The function is called as compare(a, b), and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. - */ - sort(x: MathArray|Matrix, compare?: string|((a: any, b: any) => number)): MathArray|Matrix; - - /** - * Determine the type of a variable. - */ - typeof(x: any): string; - } - - interface Matrix { - type: string; - storage(): string; - datatype(): string; - density(): number; - subset(index: Index, replacement?: any, defaultValue?: any): Matrix; - get(index: number[]): any; - set(index: number[], value: any, defaultValue?: number|string): Matrix; - resize(size: MathArray|Matrix, defaultValue?: number|string): Matrix; - clone(): Matrix; - size(): number[]; - map(callback: (a: any, b: number, c: Matrix) => any, skipZeros?: boolean): Matrix; - forEach: (callback: (a: any, b: number, c: Matrix) => void, skipZeros?: boolean) => void; - toJSON(): any; - diagonal(k?: number|BigNumber): any[]; - swapRows(i: number, j: number): Matrix; - } - - interface BigNumber extends Decimal {} // tslint:disable-line no-empty-interface - - interface Fraction { - s: number; - n: number; - d: number; - } - - interface Complex { - re: number; - im: number; - toPolar(): PolarCoordinates; - clone(): Complex; - } - - interface PolarCoordinates { - r: number; - phi: number; + kron(x: Matrix | MathArray, y: Matrix | MathArray): Matrix; + + /** + * Iterate over all elements of a matrix/array, and executes the given + * callback function. + * @param x The matrix to iterate on. + * @param callback The callback function is invoked with three + * parameters: the value of the element, the index of the element, and + * the Matrix/array being traversed. + * @returns Transformed map of x + */ + map(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)): Matrix | MathArray; + + /** + * Create a matrix filled with ones. The created matrix can have one or + * multiple dimensions. + * @param size The size of each dimension of the matrix + * @param format The matrix storage format + * @returns A matrix filled with ones + */ + ones(size: number | number[], format?: string): MathArray | Matrix; + /** + * @param m The x dimension of the matrix + * @param n The y dimension of the amtrix + * @param format The matrix storage format + * @returns A matrix filled with ones + */ + ones(m: number, n: number, format?: string): MathArray | Matrix; + + /** + * Partition-based selection of an array or 1D matrix. Will find the kth + * smallest value, and mutates the input array. Uses Quickselect. + * @param x A one dimensional matrix or array to sort + * @param k The kth smallest value to be retrieved; zero-based index + * @param compare An optional comparator function. The function is + * called as compare(a, b), and must return 1 when a > b, -1 when a < b, + * and 0 when a == b. Default value: 'asc'. + * @returns Returns the kth lowest value. + */ + partitionSelect( + x: MathArray | Matrix, + k: number, + compare?: "asc" | "desc" | ((a: any, b: any) => number) + ): any; + + /** + * Create an array from a range. By default, the range end is excluded. + * This can be customized by providing an extra parameter includeEnd. + * @param str A string 'start:end' or 'start:step:end' + * @param start Start of the range + * @param end End of the range, excluded by default, included when + * parameter includeEnd=true + * @param step Step size. Default value is 1. + * @param includeEnd: Option to specify whether to include the end or + * not. False by default + * @returns Parameters describing the ranges start, end, and optional + * step. + */ + range(str: string, includeEnd?: boolean): Matrix; + range( + start: number | BigNumber, + end: number | BigNumber, + includeEnd?: boolean + ): Matrix; + range( + start: number | BigNumber, + end: number | BigNumber, + step: number | BigNumber, + includeEnd?: boolean + ): Matrix; + + /** + * Reshape a multi dimensional array to fit the specified dimensions + * @param x Matrix to be reshaped + * @param sizes One dimensional array with integral sizes for each + * dimension + * @returns A reshaped clone of matrix x + */ + reshape( + x: MathArray | Matrix, + sizes: number[] + ): MathArray | Matrix; + + /** + * Resize a matrix + * @param x Matrix to be resized + * @param size One dimensional array with numbers + * @param defaultValue Zero by default, except in case of a string, in + * that case defaultValue = ' ' Default value: 0. + * @returns A resized clone of matrix x + */ + resize( + x: MathArray | Matrix, + size: MathArray | Matrix, + defaultValue?: number | string + ): MathArray | Matrix; + + /** + * Calculate the size of a matrix or scalar. + * @param A matrix + * @returns A vector with the size of x + */ + size( + x: boolean | number | Complex | Unit | string | MathArray | Matrix + ): MathArray | Matrix; + + /** + * Sort the items in a matrix + * @param x A one dimensional matrix or array to sort + * @param compare An optional _comparator function or name. The function + * is called as compare(a, b), and must return 1 when a > b, -1 when a < + * b, and 0 when a == b. Default value: ‘asc’ + * @returns Returns the sorted matrix + */ + sort( + x: Matrix | MathArray, + compare: ((a: any, b: any) => number) | "asc" | "desc" | "natural" + ): Matrix | MathArray; + + /** + * Calculate the principal square root of a square matrix. The principal + * square root matrix X of another matrix A is such that X * X = A. + * @param A The square matrix A + * @returns The principal square root of matrix A + */ + sqrtm(A: MathArray | Matrix): MathArray | Matrix; + + /** + * Squeeze a matrix, remove inner and outer singleton dimensions from a + * matrix. + * @param x Matrix to be squeezed + * @returns Squeezed matrix + */ + squeeze(x: MathArray | Matrix): Matrix | MathArray; + + /** + * Get or set a subset of a matrix or string. + * @param value An array, matrix, or string + * @param index An index containing ranges for each dimension + * @param replacement An array, matrix, or scalar. If provided, the + * subset is replaced with replacement. If not provided, the subset is + * returned + * @param defaultValue Default value, filled in on new entries when the + * matrix is resized. If not provided, math.matrix elements will be left + * undefined. Default value: undefined. + * @returns Either the retrieved subset or the updated matrix + */ + subset( + value: MathArray | Matrix | string, + index: Index, + replacement?: any, + defaultValue?: any + ): MathArray | Matrix | string; + + /** + * Calculate the trace of a matrix: the sum of the elements on the main + * diagonal of a square matrix. + * @param x A matrix + * @returns The trace of x + */ + trace(x: MathArray | Matrix): number; + + /** + * Transpose a matrix. All values of the matrix are reflected over its + * main diagonal. Only two dimensional matrices are supported. + * @param x Matrix to be transposed + * @returns The transposed matrix + */ + transpose(x: MathArray | Matrix): MathArray | Matrix; + + /** + * Create a matrix filled with zeros. The created matrix can have one or + * multiple dimensions. + * @param size The size of each dimension of the matrix + * @param format The matrix storage format + * @returns A matrix filled with zeros + */ + zeros(size: number | number[], format?: string): MathArray | Matrix; + /** + * @param m The x dimension of the matrix + * @param n The y dimension of the matrix + * @param format The matrix storage format + * @returns A matrix filled with zeros + */ + zeros(m: number, n: number, format?: string): MathArray | Matrix; + + /************************************************************************* + * Probability functions + ************************************************************************/ + + /** + * Compute the number of ways of picking k unordered outcomes from n + * possibilities. Combinations only takes integer arguments. The + * following condition must be enforced: k <= n. + * @param n Total number of objects in the set + * @param k Number of objects in the subset + * @returns Number of possible combinations + */ + combinations( + n: number | BigNumber, + k: number | BigNumber + ): number | BigNumber; + + /** + * Compute the factorial of a value Factorial only supports an integer + * value as argument. For matrices, the function is evaluated element + * wise. + * @param n An integer number + * @returns The factorial of n + */ + factorial( + n: number | BigNumber | MathArray | Matrix + ): number | BigNumber | MathArray | Matrix; + + /** + * Compute the gamma function of a value using Lanczos approximation for + * small values, and an extended Stirling approximation for large + * values. For matrices, the function is evaluated element wise. + * @param n A real or complex number + * @returns The gamma of n + */ + gamma(n: number | MathArray | Matrix): number | MathArray | Matrix; + + /** + * Calculate the Kullback-Leibler (KL) divergence between two + * distributions + * @param q First vector + * @param p Second vector + * @returns Returns disance between q and p + */ + kldivergence(q: MathArray | Matrix, p: MathArray | Matrix): number; + + /** + * Multinomial Coefficients compute the number of ways of picking a1, + * a2, ..., ai unordered outcomes from n possibilities. multinomial + * takes one array of integers as an argument. The following condition + * must be enforced: every ai <= 0 + * @param a Integer number of objects in the subset + * @returns multinomial coefficent + */ + multinomial(a: number[] | BigNumber[]): number | BigNumber; + + /** + * Compute the number of ways of obtaining an ordered subset of k + * elements from a set of n elements. Permutations only takes integer + * arguments. The following condition must be enforced: k <= n. + * @param n The number of objects in total + * @param k The number of objects in the subset + * @returns The number of permutations + */ + permutations( + n: number | BigNumber, + k?: number | BigNumber + ): number | BigNumber; + + /** + * Random pick a value from a one dimensional array. Array element is + * picked using a random function with uniform distribution. + * @param array A one dimensional array + * @param number An int or float + * @param weights An array of ints or floats + * @returns Returns a single random value from array when number is 1 or + * undefined. Returns an array with the configured number of elements + * when number is > 1. + */ + pickRandom( + array: number[], + number?: number, + weights?: number[] + ): number; + + /** + * Return a random number larger or equal to min and smaller than max + * using a uniform distribution. + * @param size If provided, an array or matrix with given size and + * filled with random values is returned + * @param min Minimum boundary for the random value, included + * @param max Maximum boundary for the random value, excluded + * @returns A random number + */ + random(min?: number, max?: number): number; + random( + size: MathArray | Matrix, + min?: number, + max?: number + ): MathArray | Matrix; + + /** + * Return a random integer number larger or equal to min and smaller + * than max using a uniform distribution. + * @param size If provided, an array or matrix with given size and + * filled with random values is returned + * @param min Minimum boundary for the random value, included + * @param max Maximum boundary for the random value, excluded + * @returns A random number + */ + randomInt(min: number, max?: number): number; + randomInt( + size: MathArray | Matrix, + min?: number, + max?: number + ): MathArray | Matrix; + + /************************************************************************* + * Relational functions + ************************************************************************/ + + /** + * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x + * == y. x and y are considered equal when the relative difference + * between x and y is smaller than the configured epsilon. The function + * cannot be used to compare values smaller than approximately 2.22e-16. + * For matrices, the function is evaluated element wise. + * @param x First value to compare + * @param y Second value to compare + * @returns Returns the result of the comparison: 1 when x > y, -1 when + * x < y, and 0 when x == y. + */ + compare( + x: MathType | string, + y: MathType | string + ): number | BigNumber | Fraction | MathArray | Matrix; + + /** + * Compare two values of any type in a deterministic, natural way. For + * numeric values, the function works the same as math.compare. For + * types of values that can’t be compared mathematically, the function + * compares in a natural way. + * @param x First value to compare + * @param y Second value to compare + * @returns Returns the result of the comparison: 1 when x > y, -1 when + * x < y, and 0 when x == y. + */ + compareNatural(x: any, y: any): number; + + /** + * Compare two strings lexically. Comparison is case sensitive. Returns + * 1 when x > y, -1 when x < y, and 0 when x == y. For matrices, the + * function is evaluated element wise. + * @param x First string to compare + * @param y Second string to compare + * @returns Returns the result of the comparison: 1 when x > y, -1 when + * x < y, and 0 when x == y. + */ + compareText( + x: string | MathArray | Matrix, + y: string | MathArray | Matrix + ): number | MathArray | Matrix; + + /** + * Test element wise whether two matrices are equal. The function + * accepts both matrices and scalar values. + * @param x First matrix to compare + * @param y Second amtrix to compare + * @returns Returns true when the input matrices have the same size and + * each of their elements is equal. + */ + deepEqual( + x: MathType, + y: MathType + ): number | BigNumber | Fraction | Complex | Unit | MathArray | Matrix; + + /** + * Test whether two values are equal. + * + * The function tests whether the relative difference between x and y is + * smaller than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. For matrices, the + * function is evaluated element wise. In case of complex numbers, x.re + * must equal y.re, and x.im must equal y.im. Values null and undefined + * are compared strictly, thus null is only equal to null and nothing + * else, and undefined is only equal to undefined and nothing else. + * @param x First value to compare + * @param y Second value to compare + * @returns Returns true when the compared values are equal, else + * returns false + */ + equal( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Check equality of two strings. Comparison is case sensitive. For + * matrices, the function is evaluated element wise. + * @param x First string to compare + * @param y Second string to compare + * @returns Returns true if the values are equal, and false if not. + */ + equalText( + x: string | MathArray | Matrix, + y: string | MathArray | Matrix + ): number | MathArray | Matrix; + + /** + * Test whether value x is larger than y. The function returns true when + * x is larger than y and the relative difference between x and y is + * larger than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. For matrices, the + * function is evaluated element wise. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when x is larger than y, else returns false + */ + larger( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Test whether value x is larger or equal to y. The function returns + * true when x is larger than y or the relative difference between x and + * y is smaller than the configured epsilon. The function cannot be used + * to compare values smaller than approximately 2.22e-16. For matrices, + * the function is evaluated element wise. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when x is larger than or equal to y, else + * returns false + */ + largerEq( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Test whether value x is smaller than y. The function returns true + * when x is smaller than y and the relative difference between x and y + * is smaller than the configured epsilon. The function cannot be used + * to compare values smaller than approximately 2.22e-16. For matrices, + * the function is evaluated element wise. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when x is smaller than y, else returns false + */ + smaller( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Test whether value x is smaller or equal to y. The function returns + * true when x is smaller than y or the relative difference between x + * and y is smaller than the configured epsilon. The function cannot be + * used to compare values smaller than approximately 2.22e-16. For + * matrices, the function is evaluated element wise. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when x is smaller than or equal to y, else + * returns false + */ + smallerEq( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /** + * Test whether two values are unequal. The function tests whether the + * relative difference between x and y is larger than the configured + * epsilon. The function cannot be used to compare values smaller than + * approximately 2.22e-16. For matrices, the function is evaluated + * element wise. In case of complex numbers, x.re must unequal y.re, or + * x.im must unequal y.im. Values null and undefined are compared + * strictly, thus null is unequal with everything except null, and + * undefined is unequal with everything except undefined. + * @param x First value to compare + * @param y Second value to vcompare + * @returns Returns true when the compared values are unequal, else + * returns false + */ + unequal( + x: MathType | string, + y: MathType | string + ): boolean | MathArray | Matrix; + + /************************************************************************* + * Set functions + ************************************************************************/ + + /** + * Create the cartesian product of two (multi)sets. Multi-dimension + * arrays will be converted to single-dimension arrays before the + * operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The cartesian product of two (multi)sets + */ + setCartesian( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /** + * Create the difference of two (multi)sets: every element of set1, that + * is not the element of set2. Multi-dimension arrays will be converted + * to single-dimension arrays before the operation + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The difference of two (multi)sets + */ + setDifference( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /** + * Collect the distinct elements of a multiset. A multi-dimension array + * will be converted to a single-dimension array before the operation. + * @param a A multiset + * @returns A set containing the distinct elements of the multiset + */ + setDistinct(a: MathArray | Matrix): MathArray | Matrix; + + /** + * Create the intersection of two (multi)sets. Multi-dimension arrays + * will be converted to single-dimension arrays before the operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The intersection of two (multi)sets + */ + setIntersect( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /** + * Check whether a (multi)set is a subset of another (multi)set. (Every + * element of set1 is the element of set2.) Multi-dimension arrays will + * be converted to single-dimension arrays before the operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns True if a1 is subset of a2, else false + */ + setIsSubset(a1: MathArray | Matrix, a2: MathArray | Matrix): boolean; + + /** + * Count the multiplicity of an element in a multiset. A multi-dimension + * array will be converted to a single-dimension array before the + * operation. + * @param e An element in the multiset + * @param a A multiset + * @returns The number of how many times the multiset contains the + * element + */ + setMultiplicity( + e: number | BigNumber | Fraction | Complex, + a: MathArray | Matrix + ): number; + + /** + * Create the powerset of a (multi)set. (The powerset contains very + * possible subsets of a (multi)set.) A multi-dimension array will be + * converted to a single-dimension array before the operation. + * @param a A multiset + * @returns The powerset of the (multi)set + */ + setPowerset(a: MathArray | Matrix): MathArray | Matrix; + + /** + * Count the number of elements of a (multi)set. When a second parameter + * is ‘true’, count only the unique values. A multi-dimension array will + * be converted to a single-dimension array before the operation. + * @param a A multiset + * @returns The number of elements of the (multi)set + */ + setSize(a: MathArray | Matrix): number; + + /** + * Create the symmetric difference of two (multi)sets. Multi-dimension + * arrays will be converted to single-dimension arrays before the + * operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The symmetric difference of two (multi)sets + */ + setSymDifference( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /** + * Create the union of two (multi)sets. Multi-dimension arrays will be + * converted to single-dimension arrays before the operation. + * @param a1 A (multi)set + * @param a2 A (multi)set + * @returns The union of two (multi)sets + */ + setUnion( + a1: MathArray | Matrix, + a2: MathArray | Matrix + ): MathArray | Matrix; + + /************************************************************************* + * Special functions + ************************************************************************/ + + /** + * Compute the erf function of a value using a rational Chebyshev + * approximations for different intervals of x. + * @param x A real number + * @returns The erf of x + */ + erf(x: number | MathArray | Matrix): number | MathArray | Matrix; + + /************************************************************************* + * Statistics functions + ************************************************************************/ + + /** + * Compute the median absolute deviation of a matrix or a list with + * values. The median absolute deviation is defined as the median of the + * absolute deviations from the median. + * @param array A single matrix or multiple scalar values. + * @returns The median absolute deviation + */ + mad(array: MathArray | Matrix): any; + + /** + * Compute the maximum value of a matrix or a list with values. In case + * of a multi dimensional array, the maximum of the flattened array will + * be calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param args A single matrix or multiple scalar values + * @returns The maximum value + */ + max(...args: MathType[]): any; + /** + * @param A A single matrix + * @param dim The maximum over the selected dimension + * @returns The maximum value + */ + max(A: MathArray | Matrix, dim?: number): any; + + /** + * Compute the mean value of matrix or a list with values. In case of a + * multi dimensional array, the mean of the flattened array will be + * calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param args A single matrix or multiple scalar values + * @returns The mean of all values + */ + mean(...args: MathType[]): any; + /** + * @param A A single matrix + * @param dim The mean over the selected dimension + * @returns The mean of all values + */ + mean(A: MathArray | Matrix, dim?: number): any; + + /** + * Compute the median of a matrix or a list with values. The values are + * sorted and the middle value is returned. In case of an even number of + * values, the average of the two middle values is returned. Supported + * types of values are: Number, BigNumber, Unit In case of a (multi + * dimensional) array or matrix, the median of all elements will be + * calculated. + * @param args A single matrix or or multiple scalar values + * @returns The median + */ + median(...args: MathType[]): any; + + /** + * Compute the maximum value of a matrix or a list of values. In case of + * a multi dimensional array, the maximum of the flattened array will be + * calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param args A single matrix or or multiple scalar values + * @returns The minimum value + */ + min(...args: MathType[]): any; + /** + * @param A A single matrix + * @param dim The minimum over the selected dimension + * @returns The minimum value + */ + min(A: MathArray | Matrix, dim?: number): any; + + /** + * Computes the mode of a set of numbers or a list with values(numbers + * or characters). If there are more than one modes, it returns a list + * of those values. + * @param args A single matrix + * @returns The mode of all values + */ + mode(...args: MathType[]): any; + + /** + * Compute the product of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the sum of all elements will be + * calculated. + * @param args A single matrix or multiple scalar values + * @returns The product of all values + */ + prod(...args: MathType[]): any; + + /** + * Compute the prob order quantile of a matrix or a list with values. + * The sequence is sorted and the middle value is returned. Supported + * types of sequence values are: Number, BigNumber, Unit Supported types + * of probability are: Number, BigNumber In case of a (multi + * dimensional) array or matrix, the prob order quantile of all elements + * will be calculated. + * @param A A single matrix or array + * @param probOrN prob is the order of the quantile, while N is the + * amount of evenly distributed steps of probabilities; only one of + * these options can be provided + * @param sorted =false is data sorted in ascending order + * @returns Quantile(s) + */ + quantileSeq( + A: MathArray | Matrix, + prob: number | BigNumber | MathArray, + sorted?: boolean + ): number | BigNumber | Unit | MathArray; + + /** + * Compute the standard deviation of a matrix or a list with values. The + * standard deviations is defined as the square root of the variance: + * std(A) = sqrt(var(A)). In case of a (multi dimensional) array or + * matrix, the standard deviation over all elements will be calculated. + * Optionally, the type of normalization can be specified as second + * parameter. The parameter normalization can be one of the following + * values: 'unbiased' (default) The sum of squared errors is divided by + * (n - 1) 'uncorrected' The sum of squared errors is divided by n + * 'biased' The sum of squared errors is divided by (n + 1) + * @param array A single matrix or multiple scalar values + * @param normalization Determines how to normalize the variance. Choose + * ‘unbiased’ (default), ‘uncorrected’, or ‘biased’. Default value: + * ‘unbiased’. + * @returns The standard deviation + */ + std( + array: MathArray | Matrix, + normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased" + ): number; + + /** + * Compute the sum of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the sum of all elements will be + * calculated. + * @param args A single matrix or multiple scalar values + * @returns The sum of all values + */ + sum(...args: Array): any; + /** + * @param array A single matrix + * @returns The sum of all values + */ + sum(array: MathArray | Matrix): any; + + /** + * Compute the variance of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the variance over all elements + * will be calculated. Optionally, the type of normalization can be + * specified as second parameter. The parameter normalization can be one + * of the following values: 'unbiased' (default) The sum of squared + * errors is divided by (n - 1) 'uncorrected' The sum of squared errors + * is divided by n 'biased' The sum of squared errors is divided by (n + + * 1) Note that older browser may not like the variable name var. In + * that case, the function can be called as math['var'](...) instead of + * math.var(...). + * @param args A single matrix or multiple scalar values + * @returns The variance + */ + var(...args: Array): any; + /** + * @param array A single matrix + * @param normalization normalization Determines how to normalize the + * variance. Choose ‘unbiased’ (default), ‘uncorrected’, or ‘biased’. + * Default value: ‘unbiased’. + * @returns The variance + */ + var( + array: MathArray | Matrix, + normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased" + ): any; + + /************************************************************************* + * String functions + ************************************************************************/ + + /** + * Format a value of any type into a string. + * @param value The value to be formatted + * @param options An object with formatting options. + * @param callback A custom formatting function, invoked for all numeric + * elements in value, for example all elements of a matrix, or the real + * and imaginary parts of a complex number. This callback can be used to + * override the built-in numeric notation with any type of formatting. + * Function callback is called with value as parameter and must return a + * string. + * @see http://mathjs.org/docs/reference/functions/format.html + * @returns The formatted value + */ + format( + value: any, + options?: FormatOptions | number | ((item: any) => string), + callback?: ((value: any) => string) + ): string; + + /** + * Interpolate values into a string template. + * @param template A string containing variable placeholders. + * @param values An object containing variables which will be filled in + * in the template. + * @param precision Number of digits to format numbers. If not provided, + * the value will not be rounded. + * @param options Formatting options, or the number of digits to format + * numbers. See function math.format for a description of all options. + * @returns Interpolated string + */ + print( + template: string, + values: any, + precision?: number, + options?: number | object + ): void; + + /************************************************************************* + * Trigonometry functions + ************************************************************************/ + + /** + * Calculate the inverse cosine of a value. For matrices, the function + * is evaluated element wise. + * @param x Function input + * @returns The arc cosine of x + */ + acos(x: number): number; + acos(x: BigNumber): BigNumber; + acos(x: Complex): Complex; + acos(x: MathArray): MathArray; + acos(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arccos of a value, defined as acosh(x) = + * ln(sqrt(x^2 - 1) + x). For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arccosine of x + */ + acosh(x: number): number; + acosh(x: BigNumber): BigNumber; + acosh(x: Complex): Complex; + acosh(x: MathArray): MathArray; + acosh(x: Matrix): Matrix; + + /** + * Calculate the inverse cotangent of a value. For matrices, the + * function is evaluated element wise. + * @param x Function input + * @returns The arc cotangent of x + */ + acot(x: number): number; + acot(x: BigNumber): BigNumber; + acot(x: MathArray): MathArray; + acot(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arccotangent of a value, defined as acoth(x) + * = (ln((x+1)/x) + ln(x/(x-1))) / 2. For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The hyperbolic arccotangent of x + */ + acoth(x: number): number; + acoth(x: BigNumber): BigNumber; + acoth(x: MathArray): MathArray; + acoth(x: Matrix): Matrix; + + /** + * Calculate the inverse cosecant of a value. For matrices, the function + * is evaluated element wise. + * @param x Function input + * @returns The arc cosecant of x + */ + acsc(x: number): number; + acsc(x: BigNumber): BigNumber; + acsc(x: MathArray): MathArray; + acsc(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arccosecant of a value, defined as acsch(x) + * = ln(1/x + sqrt(1/x^2 + 1)). For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arccosecant of x + */ + acsch(x: number): number; + acsch(x: BigNumber): BigNumber; + acsch(x: MathArray): MathArray; + acsch(x: Matrix): Matrix; + + /** + * Calculate the inverse secant of a value. For matrices, the function + * is evaluated element wise. + * @param x Function input + * @returns The arc secant of x + */ + asec(x: number): number; + asec(x: BigNumber): BigNumber; + asec(x: MathArray): MathArray; + asec(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arcsecant of a value, defined as asech(x) = + * ln(sqrt(1/x^2 - 1) + 1/x). For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arcsecant of x + */ + asech(x: number): number; + asech(x: BigNumber): BigNumber; + asech(x: MathArray): MathArray; + asech(x: Matrix): Matrix; + + /** + * Calculate the inverse sine of a value. For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The arc sine of x + */ + asin(x: number): number; + asin(x: BigNumber): BigNumber; + asin(x: Complex): Complex; + asin(x: MathArray): MathArray; + asin(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic arcsine of a value, defined as asinh(x) = + * ln(x + sqrt(x^2 + 1)). For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arcsine of x + */ + asinh(x: number): number; + asinh(x: BigNumber): BigNumber; + asinh(x: MathArray): MathArray; + asinh(x: Matrix): Matrix; + + /** + * Calculate the inverse tangent of a value. For matrices, the function + * is evaluated element wise. + * @param x Function input + * @returns The arc tangent of x + */ + atan(x: number): number; + atan(x: BigNumber): BigNumber; + atan(x: MathArray): MathArray; + atan(x: Matrix): Matrix; + + /** + * Calculate the inverse tangent function with two arguments, y/x. By + * providing two arguments, the right quadrant of the computed angle can + * be determined. For matrices, the function is evaluated element wise. + * @param x Function input + * @returns Four quadrant inverse tangent + */ + atan2(y: number, x: number): number; + atan2(y: MathArray | Matrix, x: MathArray | Matrix): MathArray | Matrix; + + /** + * Calculate the hyperbolic arctangent of a value, defined as atanh(x) = + * ln((1 + x)/(1 - x)) / 2. For matrices, the function is evaluated + * element wise. + * @param x Function input + * @returns The hyperbolic arctangent of x + */ + atanh(x: number): number; + atanh(x: BigNumber): BigNumber; + atanh(x: MathArray): MathArray; + atanh(x: Matrix): Matrix; + + /** + * Calculate the cosine of a value. For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The cosine of x + */ + cos(x: number | Unit): number; + cos(x: BigNumber): BigNumber; + cos(x: Complex): Complex; + cos(x: MathArray): MathArray; + cos(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic cosine of a value, defined as cosh(x) = 1/2 + * * (exp(x) + exp(-x)). For matrices, the function is evaluated element + * wise. + * @param x Function input + * @returns The hyperbolic cosine of x + */ + cosh(x: number | Unit): number; + cosh(x: BigNumber): BigNumber; + cosh(x: Complex): Complex; + cosh(x: MathArray): MathArray; + cosh(x: Matrix): Matrix; + + /** + * Calculate the cotangent of a value. cot(x) is defined as 1 / tan(x). + * For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The cotangent of x + */ + cot(x: number | Unit): number; + cot(x: Complex): Complex; + cot(x: MathArray): MathArray; + cot(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic cotangent of a value, defined as coth(x) = 1 + * / tanh(x). For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The hyperbolic cotangent of x + */ + coth(x: number | Unit): number; + coth(x: Complex): Complex; + coth(x: MathArray): MathArray; + coth(x: Matrix): Matrix; + + /** + * Calculate the cosecant of a value, defined as csc(x) = 1/sin(x). For + * matrices, the function is evaluated element wise. + * @param x Function input + * @returns The cosecant hof x + */ + csc(x: number | Unit): number; + csc(x: Complex): Complex; + csc(x: MathArray): MathArray; + csc(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic cosecant of a value, defined as csch(x) = 1 + * / sinh(x). For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The hyperbolic cosecant of x + */ + csch(x: number | Unit): number; + csch(x: Complex): Complex; + csch(x: MathArray): MathArray; + csch(x: Matrix): Matrix; + + /** + * Calculate the secant of a value, defined as sec(x) = 1/cos(x). For + * matrices, the function is evaluated element wise. + * @param x Function input + * @returns The secant of x + */ + sec(x: number | Unit): number; + sec(x: Complex): Complex; + sec(x: MathArray): MathArray; + sec(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic secant of a value, defined as sech(x) = 1 / + * cosh(x). For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The hyperbolic secant of x + */ + sech(x: number | Unit): number; + sech(x: Complex): Complex; + sech(x: MathArray): MathArray; + sech(x: Matrix): Matrix; + + /** + * Calculate the sine of a value. For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The sine of x + */ + sin(x: number | Unit): number; + sin(x: BigNumber): BigNumber; + sin(x: Complex): Complex; + sin(x: MathArray): MathArray; + sin(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic sine of a value, defined as sinh(x) = 1/2 * + * (exp(x) - exp(-x)). For matrices, the function is evaluated element + * wise. + * @param x Function input + * @returns The hyperbolic sine of x + */ + sinh(x: number | Unit): number; + sinh(x: BigNumber): BigNumber; + sinh(x: Complex): Complex; + sinh(x: MathArray): MathArray; + sinh(x: Matrix): Matrix; + + /** + * Calculate the tangent of a value. tan(x) is equal to sin(x) / cos(x). + * For matrices, the function is evaluated element wise. + * @param x Function input + * @returns The tangent of x + */ + tan(x: number | Unit): number; + tan(x: BigNumber): BigNumber; + tan(x: Complex): Complex; + tan(x: MathArray): MathArray; + tan(x: Matrix): Matrix; + + /** + * Calculate the hyperbolic tangent of a value, defined as tanh(x) = + * (exp(2 * x) - 1) / (exp(2 * x) + 1). For matrices, the function is + * evaluated element wise. + * @param x Function input + * @returns The hyperbolic tangent of x + */ + tanh(x: number | Unit): number; + tanh(x: BigNumber): BigNumber; + tanh(x: Complex): Complex; + tanh(x: MathArray): MathArray; + tanh(x: Matrix): Matrix; + + /************************************************************************* + * Unit functions + ************************************************************************/ + + /** + * Change the unit of a value. For matrices, the function is evaluated + * element wise. + * @param x The unit to be converted. + * @param unit New unit. Can be a string like "cm" or a unit without + * value. + * @returns Value with changed, fixed unit + */ + to( + x: Unit | MathArray | Matrix, + unit: Unit | string + ): Unit | MathArray | Matrix; + + /************************************************************************* + * Utils functions + ************************************************************************/ + + /** + * Clone an object. + * @param x Object to be cloned + * @returns A clone of object x + */ + clone(x: any): any; + + /** + * Test whether a value is an integer number. The function supports + * number, BigNumber, and Fraction. The function is evaluated + * element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x contains a numeric, integer value. + * Throws an error in case of an unknown data type. + */ + isInteger( + x: number | BigNumber | Fraction | MathArray | Matrix + ): boolean; + + /** + * Test whether a value is NaN (not a number). The function supports + * types number, BigNumber, Fraction, Unit and Complex. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is NaN. Throws an error in case of an + * unknown data type. + */ + isNaN( + x: number | BigNumber | Fraction | MathArray | Matrix | Unit + ): boolean; + + /** + * Test whether a value is negative: smaller than zero. The function + * supports types number, BigNumber, Fraction, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is larger than zero. Throws an error in + * case of an unknown data type. + */ + isNegative( + x: number | BigNumber | Fraction | MathArray | Matrix | Unit + ): boolean; + + /** + * Test whether a value is an numeric value. The function is evaluated + * element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is a number, BigNumber, Fraction, or + * boolean. Returns false for other types. Throws an error in case of + * unknown types. + */ + isNumeric(x: any): x is number | BigNumber | Fraction | boolean; + + /** + * Test whether a value is positive: larger than zero. The function + * supports types number, BigNumber, Fraction, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is larger than zero. Throws an error in + * case of an unknown data type. + */ + isPositive( + x: number | BigNumber | Fraction | MathArray | Matrix | Unit + ): boolean; + + /** + * Test whether a value is prime: has no divisors other than itself and + * one. The function supports type number, bignumber. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is larger than zero. Throws an error in + * case of an unknown data type. + */ + isPrime(x: number | BigNumber | MathArray | Matrix): boolean; + + /** + * Test whether a value is zero. The function can check for zero for + * types number, BigNumber, Fraction, Complex, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + * @param x Value to be tested + * @returns Returns true when x is zero. Throws an error in case of an + * unknown data type. + */ + isZero( + x: + | number + | BigNumber + | Fraction + | MathArray + | Matrix + | Unit + | Complex + ): boolean; + + /** + * Determine the type of a variable. + * @param x The variable for which to test the type + * @returns Returns the name of the type. Primitive types are lower + * case, non-primitive types are upper-camel-case. For example ‘number’, + * ‘string’, ‘Array’, ‘Date’. + */ + typeof(x: any): string; } - interface MathJSON { - mathjs?: string; - value: number; - unit: string; - fixPrefix?: boolean; - } + interface Matrix { + type: string; + storage(): string; + datatype(): string; + create(data: MathArray, datatype?: string): void; + density(): number; + subset(index: Index, replacement?: any, defaultValue?: any): Matrix; + get(index: number[]): any; + set( + index: number[], + value: any, + defaultValue?: number | string + ): Matrix; + resize( + size: MathArray | Matrix, + defaultValue?: number | string + ): Matrix; + clone(): Matrix; + size(): number[]; + map( + callback: (a: any, b: number, c: Matrix) => any, + skipZeros?: boolean + ): Matrix; + forEach( + callback: (a: any, b: number, c: Matrix) => void, + skipZeros?: boolean + ): void; + toArray(): MathArray | Matrix; + valueOff(): MathArray | Matrix; + format(options?: FormatOptions | number | ((value: any) => string)): string; + toString(): string; + toJSON(): any; + diagonal(k?: number | BigNumber): any[]; + swapRows(i: number, j: number): Matrix; + } - interface Unit { - to(unit: string): Unit; - toNumber(unit: string): number; - clone(): Unit; - equalBase(unit: Unit): boolean; - equals(unit: Unit): boolean; - format(options: FormatOptions): string; - fromJSON(json: MathJSON): Unit; - toJSON(): MathJSON; - splitUnit(parts: ReadonlyArray): Unit[]; - toNumeric(unit: string): number | Fraction | BigNumber; - toSI(): Unit; - toString(): string; - } + interface BigNumber extends Decimal {} // tslint:disable-line no-empty-interface - interface CreateUnitOptions { - override?: boolean; - } + interface Fraction { + s: number; + n: number; + d: number; + } - interface UnitDefinition { - definition?: string|Unit; - prefixes?: string; - offset?: number; - aliases?: string[]; - } + interface Complex { + re: number; + im: number; + clone(): Complex; + equals(other: Complex): boolean; + format(precision?: number): string; + fromJSON(json: object): Complex; + fromPolar(polar: object): Complex; + fromPolar(r: number, phi: number): Complex; + toJSON(): object; + toPolar(): PolarCoordinates; + toString(): string; + compare(a: Complex, b: Complex): number; + } - interface Index {} // tslint:disable-line no-empty-interface + interface PolarCoordinates { + r: number; + phi: number; + } - interface EvalFunction { - eval(scope?: any): any; - } + interface MathJSON { + mathjs?: string; + value: number; + unit: string; + fixPrefix?: boolean; + } - interface MathNode { - isNode: boolean; - isSymbolNode?: boolean; - isConstantNode?: boolean; - isOperatorNode?: boolean; - op?: string; - fn?: string; - args?: MathNode[]; - type: string; - name?: string; - value?: any; + interface Unit { + valueOf(): string; + clone(): Unit; + isDerived(): boolean; + hasBase(base: any): boolean; + equalBase(unit: Unit): boolean; + equals(unit: Unit): boolean; + multiply(unit: Unit): Unit; + divide(unit: Unit): Unit; + pow(unit: Unit): Unit; + abs(unit: Unit): Unit; + to(unit: string): Unit; + toNumber(unit: string): number; + toNumeric(unit: string): number | Fraction | BigNumber; + toString(): string; + toJSON(): MathJSON; + formatUnits(): string; + format(options: FormatOptions): string; + parse(str: DOMStringList): Unit; + isValuelessUnit(name: string): boolean; + fromJSON(json: MathJSON): Unit; + } - compile(): EvalFunction; - eval(expr?: string): any; - /** - * - * Filter nodes in an expression tree. The callback function is called as callback(node: Node, path: string, parent: Node) : boolean for every node in the tree, - * and must return a boolean. The function filter returns an array with nodes for which the test returned true. - * Parameter path is a string containing a relative JSON Path. - * - * Example: - * - * ``` - * var node = math.parse('x^2 + x/4 + 3*y'); - * var filtered = node.filter(function (node) { - * return node.isSymbolNode && node.name == 'x'; - * }); - * // returns an array with two entries: two SymbolNodes 'x' - * ``` - * - * The callback function is called as callback(node: Node, path: string, parent: Node) : boolean for every node in the tree, and must return a boolean. - * The function filter returns an array with nodes for which the test returned true. Parameter path is a string containing a relative JSON Path. - * @return Returns an array with nodes for which test returned true - */ - filter(callback: (node: MathNode, path: string, parent: MathNode) => any): MathNode[]; + interface CreateUnitOptions { + prefixes?: "none" | "short" | "long" | "binary_short" | "binary_long"; + aliases?: string[]; + offset?: number; + override?: boolean; + } - /** - * [forEach description] - */ - forEach(callback: (node: MathNode, path: string, parent: MathNode) => any): MathNode[]; + interface UnitDefinition { + definition?: string | Unit; + prefixes?: string; + offset?: number; + aliases?: string[]; + } - /** - * `traverse(callback)` - * - * Recursively traverse all nodes in a node tree. - * Executes given callback for this node and each of its child nodes. - * Similar to Array.forEach, except recursive. - * The callback function is a mapping function accepting a node, and returning a replacement for the node or the original node. - * Function callback is called as callback(node: Node, path: string, parent: Node) for every node in the tree. - * Parameter path is a string containing a relative JSON Path. Example: - * - * ``` - * var node = math.parse('3 * x + 2'); - * node.traverse(function (node, path, parent) { - * switch (node.type) { - * case 'OperatorNode': console.log(node.type, node.op); break; - * case 'ConstantNode': console.log(node.type, node.value); break; - * case 'SymbolNode': console.log(node.type, node.name); break; - * default: console.log(node.type); - * } - * }); - * // outputs: - * // OperatorNode + - * // OperatorNode * - * // ConstantNode 3 - * // SymbolNode x - * // ConstantNode 2 - * ``` - */ - traverse(callback: (node: MathNode, path: string, parent: MathNode) => void): any; - /** - * Recursively transform an expression tree via a transform function. Similar to Array.map, - * but recursively executed on all nodes in the expression tree. The callback function is a - * mapping function accepting a node, and returning a replacement for the node or the original node. - * Function callback is called as callback(node: Node, path: string, parent: Node) for every node in - * the tree, and must return a Node. Parameter path is a string containing a relative JSON Path. - * - * For example, to replace all nodes of type SymbolNode having name ‘x’ with a ConstantNode with value 3: - * ```js - * var node = math.parse('x^2 + 5*x'); - * var transformed = node.transform(function (node, path, parent) { - * if (node.SymbolNode && node.name == 'x') { - * return new math.expression.node.ConstantNode(3); - * } - * else { - * return node; - * } - * }); - * transformed.toString(); // returns '(3 ^ 2) + (5 * 3)' - * ``` - */ - transform(callback: (node: MathNode, path: string, parent: MathNode) => MathNode): MathNode; + interface Index {} // tslint:disable-line no-empty-interface - /** - * Transform a node. Creates a new Node having it’s child's be the results of calling the provided - * callback function for each of the child's of the original node. The callback function is called - * as `callback(child: Node, path: string, parent: Node)` and must return a Node. - * Parameter path is a string containing a relative JSON Path. - * - * - * See also transform, which is a recursive version of map. - */ - map(callback: (node: MathNode, path: string, parent: MathNode) => MathNode): MathNode; - } + interface EvalFunction { + eval(scope?: any): any; + } - interface Parser { - eval(expr: string): any; - get(variable: string): any; - set: (variable: string, value: any) => void; - clear: () => void; - } + interface MathNode { + isNode: boolean; + isAccessorNode?: boolean; + isArrayNode?: boolean; + isAssignmentNode?: boolean; + isBlockNode?: boolean; + isConditionalnode?: boolean; + isConstantNode?: boolean; + isFunctionAssignmentNode?: boolean; + isFunctionNode?: boolean; + isIndexNode?: boolean; + isObjectNode?: boolean; + isOperatorNode?: boolean; + isParenthesisNode?: boolean; + isRangeNode?: boolean; + isSymbolNode?: boolean; + isUpdateNode?: boolean; + comment?: string; + op?: string; + fn?: string; + args?: MathNode[]; + type: string; + name?: string; + value?: any; - interface Distribution { - random(size: any, min?: any, max?: any): any; - randomInt(min: any, max?: any): any; - pickRandom(array: any): any; - } + /** + * Create a shallow clone of the node. The node itself is cloned, its + * childs are not cloned. + */ + clone(): MathNode; + /** + * Create a deep clone of the node. Both the node as well as all its + * childs are cloned recursively. + */ + cloneDeep(): MathNode; + /** + * Compile an expression into optimized JavaScript code. compile returns + * an object with a function eval([scope]) to evaluate. Example: + */ + compile(): EvalFunction; + /** + * Compile and eval an expression, this is the equivalent of doing + * node.compile().eval(scope). Example: + */ + eval(expr?: any): any; + /** + * Test whether this node equals an other node. Does a deep comparison + * of the values of both nodes. + */ + equals(other: MathNode): boolean; + /** + * + * Filter nodes in an expression tree. The callback function is called + * as callback(node: MathNode, path: string, parent: MathNode) : boolean + * for every node in the tree, and must return a boolean. The function + * filter returns an array with nodes for which the test returned true. + * Parameter path is a string containing a relative JSON Path. + * + * Example: + * + * ``` + * var node = math.parse('x^2 + x/4 + 3*y'); + * var filtered = node.filter(function (node) { + * return node.isSymbolMathNode && node.name == 'x'; + * }); + * // returns an array with two entries: two SymbolMathNodes 'x' + * ``` + * + * The callback function is called as callback(node: MathNode, path: + * string, parent: MathNode) : boolean for every node in the tree, and + * must return a boolean. The function filter returns an array with + * nodes for which the test returned true. Parameter path is a string + * containing a relative JSON Path. + * @return Returns an array with nodes for which test returned true + */ + filter( + callback: (node: MathNode, path: string, parent: MathNode) => any + ): MathNode[]; - interface FormatOptions { - /** - * Number notation. Choose from: - * 'fixed' Always use regular number notation. For example '123.40' and '14000000' - * 'exponential' Always use exponential notation. For example '1.234e+2' and '1.4e+7' - * 'auto' (default) Regular number notation for numbers having an absolute value between lower and upper bounds, and - * uses exponential notation elsewhere. Lower bound is included, upper bound is excluded. For example '123.4' and '1.4e7'. - */ - notation?: string; + /** + * [forEach description] + */ + forEach( + callback: (node: MathNode, path: string, parent: MathNode) => any + ): MathNode[]; - /** - * A number between 0 and 16 to round the digits of the number. In case of notations 'exponential' and 'auto', - * precision defines the total number of significant digits returned and is undefined by default. In case of notation 'fixed', - * precision defines the number of significant digits after the decimal point, and is 0 by default. - */ - precision?: number; + /** + * Transform a node. Creates a new MathNode having it’s child's be the + * results of calling the provided callback function for each of the + * child's of the original node. The callback function is called as + * `callback(child: MathNode, path: string, parent: MathNode)` and must + * return a MathNode. Parameter path is a string containing a relative + * JSON Path. + * + * + * See also transform, which is a recursive version of map. + */ + map( + callback: ( + node: MathNode, + path: string, + parent: MathNode + ) => MathNode + ): MathNode; - /** - * An object containing two parameters, {number} lower and {number} upper, used by notation 'auto' to determine - * when to return exponential notation. Default values are lower=1e-3 and upper=1e5. Only applicable for notation auto. - */ - exponential?: {lower: number; upper: number}; + /** + * Get a HTML representation of the parsed expression. + */ + toHtml(options?: object): string; - /** - * Available values: 'ratio' (default) or 'decimal'. For example format(fraction(1, 3)) will output '1/3' when 'ratio' - * is configured, and will output 0.(3) when 'decimal' is configured. - */ - fraction?: string; + /** + * Get a string representation of the parsed expression. This is not + * exactly the same as the original input. + */ + toString(options?: object): string; - /** - * A custom formatting function. Can be used to override the built-in notations. Function fn is called with - * value as parameter and must return a string. Is useful for example to format all values inside a matrix in a particular way. - */ - fn?: (item: any) => string; - } + /** + * Get a LaTeX representation of the expression. + */ + toTex(options?: object): string; - interface Help { - toString(): string; - toJSON(): string; + /** + * Recursively transform an expression tree via a transform function. + * Similar to Array.map, but recursively executed on all nodes in the + * expression tree. The callback function is a mapping function + * accepting a node, and returning a replacement for the node or the + * original node. Function callback is called as callback(node: + * MathNode, path: string, parent: MathNode) for every node in the tree, + * and must return a MathNode. Parameter path is a string containing a + * relative JSON Path. + * + * For example, to replace all nodes of type SymbolMathNode having name + * ‘x’ with a ConstantMathNode with value 3: + * ```js + * var node = math.parse('x^2 + 5*x'); + * var transformed = node.transform(function (node, path, parent) { + * if (node.SymbolMathNode && node.name == 'x') { + * return new math.expression.node.ConstantMathNode(3); + * } + * else { + * return node; + * } + * }); + * transformed.toString(); // returns '(3 ^ 2) + (5 * 3)' + * ``` + */ + transform( + callback: ( + node: MathNode, + path: string, + parent: MathNode + ) => MathNode + ): MathNode; + + /** + * `traverse(callback)` + * + * Recursively traverse all nodes in a node tree. Executes given + * callback for this node and each of its child nodes. Similar to + * Array.forEach, except recursive. The callback function is a mapping + * function accepting a node, and returning a replacement for the node + * or the original node. Function callback is called as callback(node: + * MathNode, path: string, parent: MathNode) for every node in the tree. + * Parameter path is a string containing a relative JSON Path. Example: + * + * ``` + * var node = math.parse('3 * x + 2'); + * node.traverse(function (node, path, parent) { + * switch (node.type) { + * case 'OperatorMathNode': console.log(node.type, node.op); break; + * case 'ConstantMathNode': console.log(node.type, node.value); break; + * case 'SymbolMathNode': console.log(node.type, node.name); break; + * default: console.log(node.type); + * } + * }); + * // outputs: + * // OperatorMathNode + + * // OperatorMathNode * + * // ConstantMathNode 3 + * // SymbolMathNode x + * // ConstantMathNode 2 + * ``` + */ + traverse( + callback: (node: MathNode, path: string, parent: MathNode) => void + ): any; + } + + interface Parser { + eval(expr: string): any; + get(variable: string): any; + set: (variable: string, value: any) => void; + clear: () => void; + } + + interface Distribution { + random(size: any, min?: any, max?: any): any; + randomInt(min: any, max?: any): any; + pickRandom(array: any): any; + } + + interface FormatOptions { + /** + * Number notation. Choose from: 'fixed' Always use regular number + * notation. For example '123.40' and '14000000' 'exponential' Always + * use exponential notation. For example '1.234e+2' and '1.4e+7' 'auto' + * (default) Regular number notation for numbers having an absolute + * value between lower and upper bounds, and uses exponential notation + * elsewhere. Lower bound is included, upper bound is excluded. For + * example '123.4' and '1.4e7'. + */ + notation?: "fixed" | "exponential" | "engineering" | "auto"; + + /** + * A number between 0 and 16 to round the digits of the number. In case + * of notations 'exponential' and 'auto', precision defines the total + * number of significant digits returned and is undefined by default. In + * case of notation 'fixed', precision defines the number of significant + * digits after the decimal point, and is 0 by default. + */ + precision?: number; + + /** + * Exponent determining the lower boundary for formatting a value with + * an exponent when notation='auto. Default value is -3. + */ + lowerExp?: number; + + /** + * Exponent determining the upper boundary for formatting a value with + * an exponent when notation='auto. Default value is 5. + */ + upperExp?: number; + + /** + * Available values: 'ratio' (default) or 'decimal'. For example + * format(fraction(1, 3)) will output '1/3' when 'ratio' is configured, + * and will output 0.(3) when 'decimal' is configured. + */ + fraction?: string; + } + + interface Help { + toString(): string; + toJSON(): string; + } + + interface ConfigOptions { + epsilon?: number; + matrix?: string; + number?: string; + precision?: number; + parenthesis?: string; + randomSeed?: string; + } + + interface MathJsJson { + /** + * Returns reviver function that can be used as reviver in JSON.parse function. + */ + reviver(): (key: any, value: any) => any; } interface MathJsChain { - /** - * Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix. - * @param b A column vector with the b values - */ - lsolve(b: Matrix|MathArray): MathJsChain; + done(): any; - /** - * Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in two matrices (L, U) - * and a row permutation vector p where A[p,:] = L * U - */ - lup(): MathJsChain; + /************************************************************************* + * Construction functions + ************************************************************************/ - /** - * Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector. - * @param b Column Vector - */ - lusolve(b: Matrix|MathArray): MathJsChain; + /** + * Create a BigNumber, which can store numbers with arbitrary precision. + * When a matrix is provided, all elements will be converted to + * BigNumber. + */ + bignumber(): MathJsChain; - /** - * Calculate the Sparse Matrix LU decomposition with full pivoting. Sparse Matrix A is decomposed in - * two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U - * @param order The Symbolic Ordering and Analysis order: 0 - Natural ordering, no permutation vector q is - * returned 1 - Matrix must be square, symbolic ordering and analysis is performed on M = A + A' 2 - Symbolic - * ordering and analysis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'. - * This is appropriate for LU factorization of non-symmetric matrices. 3 - Symbolic ordering and analysis is performed - * on M = A' * A. This is best used for LU factorization is matrix M has no dense rows. A dense row is a row with - * more than 10*sqr(columns) entries. - * @param threshold Partial pivoting threshold (1 for partial pivoting) - * @returns The lower triangular matrix, the upper triangular matrix and the permutation vectors. - */ - slu(order: number, threshold: number): MathJsChain; + /** + * Create a boolean or convert a string or number to a boolean. In case + * of a number, true is returned for non-zero numbers, and false in case + * of zero. Strings can be 'true' or 'false', or can contain a number. + * When value is a matrix, all elements will be converted to boolean. + */ + boolean(): MathJsChain; - /** - * Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix. U * x = b - * @param b A column vector with the b values - * @returns A column vector with the linear system solution (x) - */ - usolve(b: Matrix|MathArray): MathJsChain; + /** + * Create a complex value or convert a value to a complex value. + * @param im Argument specifying the imaginary part of the complex + * number + */ + complex(im?: number): MathJsChain; - /** - * Calculate the absolute value of a number. For matrices, the function is evaluated element wise. - */ - abs(): MathJsChain; + /** + * Create a user-defined unit and register it with the Unit type. + * @param definition Definition of the unit in terms of existing units. + * For example, ‘0.514444444 m / s’. + * @param options (optional) An object containing any of the following + * properties:
- prefixes {string} “none”, “short”, “long”, + * “binary_short”, or “binary_long”. The default is “none”.
- + * aliases {Array} Array of strings. Example: [‘knots’, ‘kt’, + * ‘kts’]
- offset {Numeric} An offset to apply when converting from + * the unit. For example, the offset for celsius is 273.15. Default is + * 0. + */ + createUnit( + definition?: string | UnitDefinition, + options?: CreateUnitOptions + ): MathJsChain; + /** + * Create a user-defined unit and register it with the Unit type. + * @param options (optional) An object containing any of the following + * properties:
- prefixes {string} “none”, “short”, “long”, + * “binary_short”, or “binary_long”. The default is “none”.
- + * aliases {Array} Array of strings. Example: [‘knots’, ‘kt’, + * ‘kts’]
- offset {Numeric} An offset to apply when converting from + * the unit. For example, the offset for celsius is 273.15. Default is + * 0. + */ + createUnit(options?: CreateUnitOptions): MathJsChain; - /** - * Add two values, x + y. For matrices, the function is evaluated element wise. - * @param y Second value to add - */ - add(y: MathType): MathJsChain; + /** + * Create a fraction convert a value to a fraction. + * @param denominator Argument specifying the denominator of the + * fraction + */ + fraction( + denominator?: number | string | MathArray | Matrix + ): MathJsChain; - /** - * Calculate the cubic root of a value. For matrices, the function is evaluated element wise. - * @param allRoots Optional, false by default. Only applicable when x is a number or complex number. If true, all complex roots are returned, if false (default) the principal root is returned. - */ - cbrt(allRoots?: boolean): MathJsChain; + /** + * Create an index. An Index can store ranges having start, step, and + * end for multiple dimensions. Matrix.get, Matrix.set, and math.subset + * accept an Index as input. + */ + index(): MathJsChain; - /** - * Round a value towards plus infinity If x is complex, both real and imaginary part are rounded towards plus infinity. For matrices, the function is evaluated element wise. - */ - ceil(): MathJsChain; + /** + * Create a Matrix. The function creates a new math.type.Matrix object + * from an Array. A Matrix has utility functions to manipulate the data + * in the matrix, like getting the size and getting or setting values in + * the matrix. Supported storage formats are 'dense' and 'sparse'. + */ + matrix(format?: "sparse" | "dense", dataType?: string): MathJsChain; - /** - * Compute the cube of a value, x * x * x. For matrices, the function is evaluated element wise. - */ - cube(): MathJsChain; + /** + * Create a number or convert a string, boolean, or unit to a number. + * When value is a matrix, all elements will be converted to number. + * @param valuelessUnit A valueless unit, used to convert a unit to a + * number + */ + number(valuelessUnit?: Unit | string): MathJsChain; - /** - * Divide two values, x / y. To divide matrices, x is multiplied with the inverse of y: x * inv(y). - * @param y Denominator - */ - divide(y: MathType): MathJsChain; + /** + * Create a Sparse Matrix. The function creates a new math.type.Matrix + * object from an Array. A Matrix has utility functions to manipulate + * the data in the matrix, like getting the size and getting or setting + * values in the matrix. + * @param dataType Sparse Matrix data type + */ + sparse(dataType?: string): MathJsChain; - /** - * Divide two matrices element wise. The function accepts both matrices and scalar values. - * @param y Denominator - */ - dotDivide(y: MathType): MathJsChain; + /** + * Split a unit in an array of units whose sum is equal to the original + * unit. + * @param parts An array of strings or valueless units + */ + splitUnit(parts: Unit[]): MathJsChain; - /** - * Multiply two matrices element wise. The function accepts both matrices and scalar values. - * @param y Right hand value - */ - dotMultiply(y: MathType): MathJsChain; + /** + * Create a string or convert any object into a string. Elements of + * Arrays and Matrices are processed element wise. + */ + string(): MathJsChain; - /** - * Calculates the power of x to y element wise. - * @param y The exponent - */ - dotPow(y: MathType): MathJsChain; + /** + * Create a unit. Depending on the passed arguments, the function will + * create and return a new math.type.Unit object. When a matrix is + * provided, all elements will be converted to units. + * @param unit The unit to be created + */ + unit(unit?: string): MathJsChain; - /** - * Calculate the exponent of a value. For matrices, the function is evaluated element wise. - */ - exp(): MathJsChain; + /************************************************************************* + * Expression functions + ************************************************************************/ - /** - * Round a value towards zero. For matrices, the function is evaluated element wise. - */ - fix(): MathJsChain; + /** + * Parse and compile an expression. Returns a an object with a function + * eval([scope]) to evaluate the compiled expression. + */ + compile(): MathJsChain; - /** - * Round a value towards minus infinity. For matrices, the function is evaluated element wise. - */ - floor(): MathJsChain; + /** + * Evaluate an expression. + * @param scope Scope to read/write variables + */ + eval(scope?: object): MathJsChain; - /** - * Calculate the greatest common divisor for two or more values or arrays. For matrices, the function is evaluated element wise. - */ - gcd(...args: number[]): MathJsChain; - gcd(...args: BigNumber[]): MathJsChain ; - gcd(...args: Fraction[]): MathJsChain ; - gcd(...args: MathArray[]): MathJsChain ; - gcd(...args: Matrix[]): MathJsChain; + /** + * Retrieve help on a function or data type. Help files are retrieved + * from the documentation in math.expression.docs. + */ + help(): MathJsChain; - /** - * Calculate the hypotenuse of a list with values. The hypotenuse is defined as: - * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) - * For matrix input, the hypotenuse is calculated for all values in the matrix. - */ - hypot(...args: number[]): MathJsChain; - hypot(...args: BigNumber[]): MathJsChain; + /** + * Parse an expression. Returns a node tree, which can be evaluated by + * invoking node.eval(); + * @param options Available options: nodes - a set of custome nodes + */ + parse(options?: any): MathJsChain; + /** + * @param options Available options: nodes - a set of custome nodes + */ + parse(options?: any): MathJsChain; + + /** + * Create a parser. The function creates a new math.expression.Parser + * object. + */ + parser(): MathJsChain; + + /************************************************************************* + * Algebra functions + ************************************************************************/ + /** + * @param variable The variable over which to differentiate + * @param options There is one option available, simplify, which is true + * by default. When false, output will not be simplified. + */ + derivative(variable: MathNode | string, options?: {simplify: boolean}): MathJsChain; + + /** + * Solves the linear equation system by forwards substitution. Matrix + * must be a lower triangular matrix. + * @param b A column vector with the b values + */ + lsolve(b: Matrix | MathArray): MathJsChain; + + /** + * Calculate the Matrix LU decomposition with partial pivoting. Matrix A + * is decomposed in two matrices (L, U) and a row permutation vector p + * where A[p,:] = L * U + */ + lup(): MathJsChain; + + /** + * Solves the linear system A * x = b where A is an [n x n] matrix and b + * is a [n] column vector. + * @param b Column Vector + * @param order The Symbolic Ordering and Analysis order, see slu for + * details. Matrix must be a SparseMatrix + * @param threshold Partial pivoting threshold (1 for partial pivoting), + * see slu for details. Matrix must be a SparseMatrix. + */ + lusolve( + b: Matrix | MathArray, + order?: number, + threshold?: number + ): MathJsChain; + + /** + * Calculate the Matrix QR decomposition. Matrix A is decomposed in two + * matrices (Q, R) where Q is an orthogonal matrix and R is an upper + * triangular matrix. + */ + qr(): MathJsChain; + + /** + * Transform a rationalizable expression in a rational fraction. If + * rational fraction is one variable polynomial then converts the + * numerator and denominator in canonical form, with decreasing + * exponents, returning the coefficients of numerator. + * @param optional scope of expression or true for already evaluated + * rational expression at input + * @param detailed optional True if return an object, false if return + * expression node (default) + */ + rationalize(optional?: object | boolean, detailed?: boolean): MathJsChain; + + /** + * Simplify an expression tree. + * @param rules A list of rules are applied to an expression, repeating + * over the list until no further changes are made. It’s possible to + * pass a custom set of rules to the function as second argument. A rule + * can be specified as an object, string, or function. + * @param scope Scope to variables + */ + simplify( + rules?: Array<({ l: string; r: string } | string | ((node: MathNode) => MathNode))>, + scope?: object + ): MathJsChain; + + /** + * Calculate the Sparse Matrix LU decomposition with full pivoting. + * Sparse Matrix A is decomposed in two matrices (L, U) and two + * permutation vectors (pinv, q) where P * A * Q = L * U + * @param order The Symbolic Ordering and Analysis order: 0 - Natural + * ordering, no permutation vector q is returned 1 - Matrix must be + * square, symbolic ordering and analisis is performed on M = A + A' 2 - + * Symbolic ordering and analysis is performed on M = A' * A. Dense + * columns from A' are dropped, A recreated from A'. This is appropriate + * for LU factorization of non-symmetric matrices. 3 - Symbolic ordering + * and analysis is performed on M = A' * A. This is best used for LU + * factorization is matrix M has no dense rows. A dense row is a row + * with more than 10*sqr(columns) entries. + * @param threshold Partial pivoting threshold (1 for partial pivoting) + */ + slu(order: number, threshold: number): MathJsChain; + + /** + * Solves the linear equation system by backward substitution. Matrix + * must be an upper triangular matrix. U * x = b + * @param b A column vector with the b values + */ + usolve(b: Matrix | MathArray): MathJsChain; + + /************************************************************************* + * Arithmetic functions + ************************************************************************/ + + /** + * Calculate the absolute value of a number. For matrices, the function + * is evaluated element wise. + */ + abs(): MathJsChain; + + /** + * Add two values, x + y. For matrices, the function is evaluated + * element wise. + * @param y Second value to add + */ + add(y: MathType): MathJsChain; + + /** + * Calculate the cubic root of a value. For matrices, the function is + * evaluated element wise. + * @param allRoots Optional, false by default. Only applicable when x is + * a number or complex number. If true, all complex roots are returned, + * if false (default) the principal root is returned. + */ + cbrt(allRoots?: boolean): MathJsChain; + + /** + * Round a value towards plus infinity If x is complex, both real and + * imaginary part are rounded towards plus infinity. For matrices, the + * function is evaluated element wise. + */ + ceil(): MathJsChain; + + /** + * Compute the cube of a value, x * x * x. For matrices, the function is + * evaluated element wise. + */ + cube(): MathJsChain; + + /** + * Divide two values, x / y. To divide matrices, x is multiplied with + * the inverse of y: x * inv(y). + * @param y Denominator + */ + divide(y: MathType): MathJsChain; + + /** + * Divide two matrices element wise. The function accepts both matrices + * and scalar values. + * @param y Denominator + */ + dotDivide(y: MathType): MathJsChain; + + /** + * Multiply two matrices element wise. The function accepts both + * matrices and scalar values. + * @param y Right hand value + */ + dotMultiply(y: MathType): MathJsChain; + + /** + * Calculates the power of x to y element wise. + * @param y The exponent + */ + dotPow(y: MathType): MathJsChain; + + /** + * Calculate the exponent of a value. For matrices, the function is + * evaluated element wise. + */ + exp(): MathJsChain; + + /** + * Calculate the value of subtracting 1 from the exponential value. For + * matrices, the function is evaluated element wise. + */ + expm1(): MathJsChain; + + /** + * Round a value towards zero. For matrices, the function is evaluated + * element wise. + */ + fix(): MathJsChain; + + /** + * Round a value towards minus infinity. For matrices, the function is + * evaluated element wise. + */ + floor(): MathJsChain; + + /** + * Calculate the greatest common divisor for two or more values or + * arrays. For matrices, the function is evaluated element wise. + */ + gcd(): MathJsChain; + + /** + * Calculate the hypotenusa of a list with values. The hypotenusa is + * defined as: hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) For + * matrix input, the hypotenusa is calculated for all values in the + * matrix. + */ + hypot(): MathJsChain; + + /** + * Calculate the least common multiple for two or more values or arrays. + * lcm is defined as: lcm(a, b) = abs(a * b) / gcd(a, b) For matrices, + * the function is evaluated element wise. + * @param b An integer number + */ + lcm(b: number | BigNumber | MathArray | Matrix): MathJsChain; + + /** + * Calculate the logarithm of a value. For matrices, the function is + * evaluated element wise. + * @param base Optional base for the logarithm. If not provided, the + * natural logarithm of x is calculated. Default value: e. + */ + log(base?: number | BigNumber | Complex): MathJsChain; + + /** + * Calculate the 10-base of a value. This is the same as calculating + * log(x, 10). For matrices, the function is evaluated element wise. + */ + log10(): MathJsChain; + + /** + * Calculate the logarithm of a value+1. For matrices, the function is + * evaluated element wise. + */ + log1p(base?: number | BigNumber | Complex): MathJsChain; + /** + * Calculate the 2-base of a value. This is the same as calculating + * log(x, 2). For matrices, the function is evaluated element wise. + */ + log2(): MathJsChain; + /** + * Calculates the modulus, the remainder of an integer division. For + * matrices, the function is evaluated element wise. The modulus is + * defined as: x - y * floor(x / y) + * @see http://en.wikipedia.org/wiki/Modulo_operation. + * @param y Divisor + */ + mod(y: number | BigNumber | Fraction | MathArray | Matrix): MathJsChain; + + /** + * Multiply two values, x * y. The result is squeezed. For matrices, the + * matrix product is calculated. + * @param y The second value to multiply + */ + multiply(y: MathType): MathJsChain; + + /** + * Calculate the norm of a number, vector or matrix. The second + * parameter p is optional. If not provided, it defaults to 2. + * @param p Vector space. Supported numbers include Infinity and + * -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The + * Frobenius norm) Default value: 2. + */ + norm(p?: number | BigNumber | string): MathJsChain; + + /** + * Calculate the nth root of a value. The principal nth root of a + * positive real number A, is the positive real solution of the equation + * x^root = A For matrices, the function is evaluated element wise. + * @param root The root. Default value: 2. + */ + nthRoot(root?: number | BigNumber): MathJsChain; + + /** + * Calculates the power of x to y, x ^ y. Matrix exponentiation is + * supported for square matrices x, and positive integer exponents y. + * @param y The exponent + */ + pow(): MathJsChain; + + /** + * Round a value towards the nearest integer. For matrices, the function + * is evaluated element wise. + * @param n Number of decimals Default value: 0. + */ + round(n?: number | BigNumber | MathArray): MathJsChain; + + /** + * Compute the sign of a value. The sign of a value x is: 1 when x > 1 + * -1 when x < 0 0 when x == 0 For matrices, the function is evaluated + * element wise. + * @param x The number for which to determine the sign + * @returns The sign of x + */ + sign(): MathJsChain; + + /** + * Calculate the square root of a value. For matrices, the function is + * evaluated element wise. + */ + sqrt(): MathJsChain; + + /** + * Compute the square of a value, x * x. For matrices, the function is + * evaluated element wise. + */ + square(): MathJsChain; + + /** + * Subtract two values, x - y. For matrices, the function is evaluated + * element wise. + * @param y Value to subtract from x + */ + subtract(y: MathType): MathJsChain; + + /** + * Inverse the sign of a value, apply a unary minus operation. For + * matrices, the function is evaluated element wise. Boolean values and + * strings will be converted to a number. For complex numbers, both real + * and complex value are inverted. + */ + unaryMinus(): MathJsChain; + + /** + * Unary plus operation. Boolean values and strings will be converted to + * a number, numeric values will be returned as is. For matrices, the + * function is evaluated element wise. + */ + unaryPlus(): MathJsChain; + + /** + * Calculate the extended greatest common divisor for two values. See + * http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. + * @param b An integer number + */ + xgcd(b: number | BigNumber): MathJsChain; + + /************************************************************************* + * Bitwise functions + ************************************************************************/ + + /** + * Bitwise AND two values, x & y. For matrices, the function is + * evaluated element wise. + * @param y Second value to and + */ + bitAnd(y: number | BigNumber | MathArray | Matrix): MathJsChain; + + /** + * Bitwise NOT value, ~x. For matrices, the function is evaluated + * element wise. For units, the function is evaluated on the best prefix + * base. + */ + bitNot(): MathJsChain; + + /** + * Bitwise OR two values, x | y. For matrices, the function is evaluated + * element wise. For units, the function is evaluated on the lowest + * print base. + * @param y Second value to or + */ + bitOr(y: number | BigNumber | MathArray | Matrix): MathJsChain; + + /** + * Bitwise XOR two values, x ^ y. For matrices, the function is + * evaluated element wise. + * @param y Second value to xor + */ + bitXor(y: number | BigNumber | MathArray | Matrix): MathJsChain; + + /** + * Bitwise left logical shift of a value x by y number of bits, x << y. + * For matrices, the function is evaluated element wise. For units, the + * function is evaluated on the best prefix base. + * @param y Amount of shifts + */ + leftShift(y: number | BigNumber): MathJsChain; + + /** + * Bitwise right arithmetic shift of a value x by y number of bits, x >> + * y. For matrices, the function is evaluated element wise. For units, + * the function is evaluated on the best prefix base. + * @param y Amount of shifts + */ + rightArithShift(y: number | BigNumber): MathJsChain; + + /** + * Bitwise right logical shift of value x by y number of bits, x >>> y. + * For matrices, the function is evaluated element wise. For units, the + * function is evaluated on the best prefix base. + * @param y Amount of shifts + */ + rightLogShift(y: number): MathJsChain; + + /************************************************************************* + * Combinatorics functions + ************************************************************************/ + + /** + * The Bell Numbers count the number of partitions of a set. A partition + * is a pairwise disjoint subset of S whose union is S. bellNumbers only + * takes integer arguments. The following condition must be enforced: n + * >= 0 + */ + bellNumbers(): MathJsChain; + + /** + * The Catalan Numbers enumerate combinatorial structures of many + * different types. catalan only takes integer arguments. The following + * condition must be enforced: n >= 0 + */ + catalan(): MathJsChain; + + /** + * The composition counts of n into k parts. Composition only takes + * integer arguments. The following condition must be enforced: k <= n. + * @param k Number of objects in the subset + */ + composition(k: number | BigNumber): MathJsChain; + + /** + * The Stirling numbers of the second kind, counts the number of ways to + * partition a set of n labelled objects into k nonempty unlabelled + * subsets. stirlingS2 only takes integer arguments. The following + * condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = + * 1 + * @param k Number of objects in the subset + */ + stirlingS2(k: number | BigNumber): MathJsChain; + + /************************************************************************* + * Complex functions + ************************************************************************/ + + /** + * Compute the argument of a complex value. For a complex number a + bi, + * the argument is computed as atan2(b, a). For matrices, the function + * is evaluated element wise. + */ + arg(): MathJsChain; + + /** + * Compute the complex conjugate of a complex value. If x = a+bi, the + * complex conjugate of x is a - bi. For matrices, the function is + * evaluated element wise. + */ + conj(): MathJsChain; + + /** + * Get the imaginary part of a complex number. For a complex number a + + * bi, the function returns b. For matrices, the function is evaluated + * element wise. + */ + im(): MathJsChain; + + /** + * Get the real part of a complex number. For a complex number a + bi, + * the function returns a. For matrices, the function is evaluated + * element wise. + */ + re(): MathJsChain; + + /************************************************************************* + * Geometry functions + ************************************************************************/ + + /** + * Calculates: The eucledian distance between two points in 2 and 3 + * dimensional spaces. Distance between point and a line in 2 and 3 + * dimensional spaces. Pairwise distance between a set of 2D or 3D + * points NOTE: When substituting coefficients of a line(a, b and c), + * use ax + by + c = 0 instead of ax + by = c For parametric equation of + * a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, + * c) + * @param y Coordinates of the second point + */ + distance(y: MathArray | Matrix | object): MathJsChain; + + /** + * Calculates the point of intersection of two lines in two or three + * dimensions and of a line and a plane in three dimensions. The inputs + * are in the form of arrays or 1 dimensional matrices. The line + * intersection functions return null if the lines do not meet. Note: + * Fill the plane coefficients as x + y + z = c and not as x + y + z + c + * = 0. + * @param x Co-ordinates of second end-point of first line + * @param y Co-ordinates of first end-point of second line OR + * Coefficients of the plane's equation + * @param z Co-ordinates of second end-point of second line OR null if + * the calculation is for line and plane + */ + intersect( + x: MathArray | Matrix, + y: MathArray | Matrix, + z: MathArray | Matrix + ): MathJsChain; + + /************************************************************************* + * Logical functions + ************************************************************************/ + + /** + * Logical and. Test whether two values are both defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param y Second value to and + */ + and( + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): MathJsChain; + + /** + * Logical not. Flips boolean value of a given parameter. For matrices, + * the function is evaluated element wise. + */ + not(): MathJsChain; + + /** + * Logical or. Test if at least one value is defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param y Second value to or + */ + or( + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): MathJsChain; + + /** + * Logical xor. Test whether one and only one value is defined with a + * nonzero/nonempty value. For matrices, the function is evaluated + * element wise. + * @param y Second value to xor + */ + xor( + y: number | BigNumber | Complex | Unit | MathArray | Matrix + ): MathJsChain; + + /************************************************************************* + * Matrix functions + ************************************************************************/ + + /** + * Concatenate two or more matrices. dim: number is a zero-based + * dimension over which to concatenate the matrices. By default the last + * dimension of the matrices. + */ + concat(): MathJsChain; + + /** + * Calculate the cross product for two vectors in three dimensional + * space. The cross product of A = [a1, a2, a3] and B =[b1, b2, b3] is + * defined as: cross(A, B) = [ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 + * * b2 - a2 * b1 ] + * @param y Second vector + */ + cross(y: MathArray | Matrix): MathJsChain; + + /** + * Calculate the determinant of a matrix. + */ + det(): MathJsChain; + + /** + * Create a diagonal matrix or retrieve the diagonal of a matrix. When x + * is a vector, a matrix with vector x on the diagonal will be returned. + * When x is a two dimensional matrix, the matrixes kth diagonal will be + * returned as vector. When k is positive, the values are placed on the + * super diagonal. When k is negative, the values are placed on the sub + * diagonal. + * @param k The diagonal where the vector will be filled in or + * retrieved. Default value: 0. + * @param format The matrix storage format. Default value: 'dense'. + */ + diag(format?: string): MathJsChain; + diag(k: number | BigNumber, format?: string): MathJsChain; + + /** + * Calculate the dot product of two vectors. The dot product of A = [a1, + * a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as: dot(A, + * B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn + * @param y Second vector + */ + dot(y: MathArray | Matrix): MathJsChain; + + /** + * Compute the matrix exponential, expm(A) = e^A. The matrix must be + * square. Not to be confused with exp(a), which performs element-wise + * exponentiation. The exponential is calculated using the Padé + * approximant with scaling and squaring; see “Nineteen Dubious Ways to + * Compute the Exponential of a Matrix,” by Moler and Van Loan. + */ + expm(): MathJsChain; + + /** + * Create a 2-dimensional identity matrix with size m x n or n x n. The + * matrix has ones on the diagonal and zeros elsewhere. + * @param format The Matrix storage format + */ + eye(format?: string): MathJsChain; + /** + * @param n The y dimension for the matrix + * @param format The Matrix storage format + */ + eye(n: number, format?: string): MathJsChain; + + /** + * Filter the items in an array or one dimensional matrix. + */ + filter(test: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)| RegExp): MathJsChain; + + /** + * Flatten a multi dimensional matrix into a single dimensional matrix. + */ + flatten(): MathJsChain; + + /** + * Iterate over all elements of a matrix/array, and executes the given + * callback function. + */ + forEach(callback: ((value: any, index: any, matrix: Matrix | MathArray) => void)): MathJsChain; + + /** + * Calculate the inverse of a square matrix. + */ + inv(): MathJsChain; /** * Calculate the kronecker product of two matrices or vectors - * @param x First Matrix - * @param y Second Matrix + * @param y Second vector */ - kron(x: Matrix|MathArray, y: Matrix|MathArray): MathJsChain; - - /** - * Calculate the least common multiple for two or more values or arrays. lcm is defined as: - * lcm(a, b) = abs(a * b) / gcd(a, b) - * For matrices, the function is evaluated element wise. - */ - lcm(b: number|BigNumber|MathArray|Matrix): MathJsChain; - - /** - * Calculate the logarithm of a value. For matrices, the function is evaluated element wise. - * @param base Optional base for the logarithm. If not provided, the natural logarithm of x is calculated. Default value: e. - */ - log(base?: number|BigNumber|Complex): MathJsChain; - - /** - * Calculate the 10-base of a value. This is the same as calculating log(x, 10). For matrices, the function is evaluated element wise. - */ - log10(): MathJsChain; - - /** - * Calculates the modulus, the remainder of an integer division. For matrices, the function is evaluated element wise. - * The modulus is defined as: - * x - y * floor(x / y) - * @see http://en.wikipedia.org/wiki/Modulo_operation. - * @param y Divisor - */ - mod(y: number|BigNumber|Fraction|MathArray|Matrix): MathJsChain; - - /** - * Multiply two values, x * y. The result is squeezed. For matrices, the matrix product is calculated. - */ - multiply(y: MathType): MathJsChain; - - /** - * Calculate the norm of a number, vector or matrix. The second parameter p is optional. If not provided, it defaults to 2. - * @param p Vector space. Supported numbers include Infinity and -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm) Default value: 2. - */ - norm(p?: number|BigNumber|string): MathJsChain; - - /** - * Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation - * x^root = A - * For matrices, the function is evaluated element wise. - * @param root The root. Default value: 2. - */ - nthRoot(root?: number|BigNumber): MathJsChain; - - /** - * Calculates the power of x to y, x ^ y. Matrix exponentiation is supported for square matrices x, and positive integer exponents y. - * @param y The exponent - */ - pow(y: number|BigNumber|Complex): MathJsChain; - - /** - * Round a value towards the nearest integer. For matrices, the function is evaluated element wise. - * @param n Number of decimals Default value: 0. - */ - round(n?: number|BigNumber|MathArray): MathJsChain; - - /** - * Compute the sign of a value. The sign of a value x is: - * 1 when x > 1 - * -1 when x < 0 - * 0 when x == 0 - * For matrices, the function is evaluated element wise. - */ - sign(): MathJsChain; - - /** - * Calculate the square root of a value. For matrices, the function is evaluated element wise. - */ - sqrt(): MathJsChain; - - /** - * Compute the square of a value, x * x. For matrices, the function is evaluated element wise. - */ - square(): MathJsChain; - - /** - * Subtract two values, x - y. For matrices, the function is evaluated element wise. - */ - subtract(y: MathType): MathJsChain; - - /** - * Inverse the sign of a value, apply a unary minus operation. - * For matrices, the function is evaluated element wise. Boolean values and strings will be converted to a number. For complex numbers, both real and complex value are inverted. - */ - unaryMinus(): MathJsChain; - - /** - * Unary plus operation. Boolean values and strings will be converted to a number, numeric values will be returned as is. - * For matrices, the function is evaluated element wise. - */ - unaryPlus(): MathJsChain; - - /** - * Calculate the extended greatest common divisor for two values. See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. - */ - xgcd(b: number|BigNumber): MathJsChain; - - /** - * Bitwise AND two values, x & y. For matrices, the function is evaluated element wise. - */ - bitAnd(y: number|BigNumber|MathArray|Matrix): MathJsChain; - - /** - * Bitwise NOT value, ~x. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - */ - bitNot(): MathJsChain; - - /** - * Bitwise OR two values, x | y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the lowest print base. - */ - bitOr(): MathJsChain; - - /** - * Bitwise XOR two values, x ^ y. For matrices, the function is evaluated element wise. - */ - bitXor(y: number|BigNumber|MathArray|Matrix): MathJsChain; - - /** - * Bitwise left logical shift of a value x by y number of bits, x << y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - leftShift(y: number|BigNumber): MathJsChain; - - /** - * Bitwise right arithmetic shift of a value x by y number of bits, x >> y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - rightArithShift(y: number|BigNumber): MathJsChain; - - /** - * Bitwise right logical shift of value x by y number of bits, x >>> y. For matrices, the function is evaluated element wise. For units, the function is evaluated on the best prefix base. - * @param x Value to be shifted - * @param y Amount of shifts - */ - rightLogShift(y: number): MathJsChain; - - /** - * The Bell Numbers count the number of partitions of a set. - * A partition is a pairwise disjoint subset of S whose union is S. - * bellNumbers only takes integer arguments. The following condition must be enforced: n >= 0 - * @param n Total number of objects in the set - */ - bellNumbers(): MathJsChain; - - /** - * The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0 - * @param n nth Catalan number - */ - catalan(): MathJsChain; - - /** - * The composition counts of n into k parts. Composition only takes integer arguments. The following condition must be enforced: k <= n. - * @param n Total number of objects in the set - * @param k Number of objects in the subset - * @returns Returns the composition counts of n into k parts. - */ - composition(k: number|BigNumber): MathJsChain; - - /** - * The Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. - * stirlingS2 only takes integer arguments. The following condition must be enforced: k <= n. - * If n = k or k = 1, then s(n,k) = 1 - * @param n Total number of objects in the set - * @param k Number of objects in the subset - */ - stirlingS2(k: number|BigNumber): MathJsChain; - - /** - * Compute the argument of a complex value. For a complex number a + bi, the argument is computed as atan2(b, a). For matrices, the function is evaluated element wise. - * @param x A complex number or array with complex numbers - */ - arg(): MathJsChain; - - /** - * Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate of x is a - bi. For matrices, the function is evaluated element wise. - * @param x A complex number or array with complex numbers - */ - conj(): MathJsChain; - - /** - * Get the imaginary part of a complex number. For a complex number a + bi, the function returns b. - * For matrices, the function is evaluated element wise. - */ - im(): MathJsChain; - - /** - * Get the real part of a complex number. For a complex number a + bi, the function returns a. - * For matrices, the function is evaluated element wise. - */ - re(): MathJsChain; - - /** - * Calculates: The eucledian distance between two points in 2 and 3 dimensional spaces. Distance between point - * and a line in 2 and 3 dimensional spaces. Pairwise distance between a set of 2D or 3D points NOTE: When - * substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c For parametric - * equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c) - */ - distance(y: MathType): MathJsChain; - - /** - * Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in - * three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions - * return null if the lines do not meet. - * Note: Fill the plane coefficients as x + y + z = c and not as x + y + z + c = 0. - * @param w Co-ordinates of first end-point of first line - * @param x Co-ordinates of second end-point of first line - * @param y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation - * @param z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane - * @returns Returns the point of intersection of lines/lines-planes - */ - intersect(x: MathArray|Matrix, y: MathArray|Matrix, z: MathArray|Matrix): MathJsChain; - - /** - * Logical and. Test whether two values are both defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - and(y: number|BigNumber|Complex|Unit|MathArray|Matrix): MathJsChain; - - /** - * Logical not. Flips boolean value of a given parameter. For matrices, the function is evaluated element wise. - */ - not(): MathJsChain; - - /** - * Logical or. Test if at least one value is defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - or(y: number|BigNumber|Complex|Unit|MathArray|Matrix): MathJsChain; - - /** - * Logical xor. Test whether one and only one value is defined with a nonzero/nonempty value. For matrices, the function is evaluated element wise. - */ - xor(y: number|BigNumber|Complex|Unit|MathArray|Matrix): MathJsChain; - - /** - * Calculate the cross product for two vectors in three dimensional space. The cross product of A = [a1, a2, a3] - * and B =[b1, b2, b3] is defined as: - * cross(A, B) = [ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 ] - */ - cross(y: MathArray|Matrix): MathJsChain; - - /** - * Calculate the determinant of a matrix. - */ - det(): MathJsChain; - - /** - * Resize a matrix - * @param x Matrix to be resized - * @param size One dimensional array with numbers - * @param defaultValue Zero by default, except in case of a string, in that case defaultValue = ' ' Default value: 0. - */ - resize(size: MathArray|Matrix, defaultValue?: number|string): MathJsChain; - - /** - * Calculate the size of a matrix or scalar. - */ - size(): MathJsChain; - - /** - * Squeeze a matrix, remove inner and outer singleton dimensions from a matrix. - */ - squeeze(): MathJsChain; - - /** - * Get or set a subset of a matrix or string. - * @param value An array, matrix, or string - * @param index An index containing ranges for each dimension - * @param replacement An array, matrix, or scalar. If provided, the subset is replaced with replacement. If not provided, the subset is returned - * @param defaultValue Default value, filled in on new entries when the matrix is resized. If not provided, math.matrix elements will be left undefined. Default value: undefined. - */ - subset(index: Index, replacement?: any, defaultValue?: any): MathJsChain; - - /** - * Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix. - */ - trace(): MathJsChain; - - /** - * Transpose a matrix. All values of the matrix are reflected over its main diagonal. Only two dimensional matrices are supported. - */ - transpose(): MathJsChain; - - /** - * Random pick a value from a one dimensional array. Array element is picked using a random function with uniform distribution. - */ - pickRandom(): MathJsChain; - - /** - * Return a random number larger or equal to min and smaller than max using a uniform distribution. - */ - random(min?: number, max?: number): MathJsChain; - - /** - * Return a random integer number larger or equal to min and smaller than max using a uniform distribution. - */ - randomInt(min?: number, max?: number): MathJsChain; - - /** - * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y. - * x and y are considered equal when the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - compare(y: MathType): MathJsChain; - - /** - * Test element wise whether two matrices are equal. The function accepts both matrices and scalar values. - */ - deepEqual(y: MathType): MathJsChain; - - /** - * Test whether two values are equal. - * The function tests whether the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. In case of complex numbers, x.re must equal y.re, and x.im must equal y.im. - * Values null and undefined are compared strictly, thus null is only equal to null and nothing else, and undefined is only equal to undefined and nothing else. - */ - equal(y: MathType): MathJsChain; - - /** - * Test whether value x is larger than y. - * The function returns true when x is larger than y and the relative difference between x and y is larger than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - larger(y: MathType): MathJsChain; - - /** - * Test whether value x is larger or equal to y. - * The function returns true when x is larger than y or the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - largerEq(y: MathType): MathJsChain; - - /** - * Test whether value x is smaller than y. - * The function returns true when x is smaller than y and the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. - */ - smaller(MathJsChainy: MathType): MathJsChain; - - /** - * Test whether value x is smaller or equal to y. - * The function returns true when x is smaller than y or the relative difference between x and y is smaller than the configured epsilon. - * The function cannot be used to compare values smaller than approximately 2.22e-16. For matrices, the function is evaluated element wise. - */ - smallerEq(MathJsChainy: MathType): MathJsChain; - - /** - * Test whether two values are unequal. - * The function tests whether the relative difference between x and y is larger than the configured epsilon. The function cannot - * be used to compare values smaller than approximately 2.22e-16. - * For matrices, the function is evaluated element wise. In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im. - * Values null and undefined are compared strictly, thus null is unequal with everything except null, and undefined is unequal with - * everything except undefined. - */ - unequal(MathJsChainy: MathType): MathJsChain; - - /** - * Compute the maximum value of a matrix or a list with values. In case of a multi dimensional array, the maximum of the flattened - * array will be calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - max(dim?: number): MathJsChain; - - /** - * Compute the mean value of matrix or a list with values. In case of a multi dimensional array, the mean of the flattened array will be - * calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - mean(dim?: number): MathJsChain; - - /** - * Compute the median of a matrix or a list with values. The values are sorted and the middle value is returned. In case of an - * even number of values, the average of the two middle values is returned. Supported types of values are: Number, BigNumber, Unit - * In case of a (multi dimensional) array or matrix, the median of all elements will be calculated. - */ - median(): MathJsChain; - - /** - * Compute the maximum value of a matrix or a list of values. In case of a multi dimensional array, the maximum of the flattened - * array will be calculated. When dim is provided, the maximum over the selected dimension will be calculated. Parameter dim is zero-based. - */ - min(dim?: number): MathJsChain; - - /** - * Computes the mode of a set of numbers or a list with values(numbers or characters). If there are more than one modes, it returns a list of those values. - */ - mode(): MathJsChain; - - /** - * Compute the product of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the sum of all elements will be calculated. - */ - prod(): MathJsChain; - - /** - * Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. - * Supported types of sequence values are: Number, BigNumber, Unit Supported types of probability are: Number, BigNumber - * In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated. - */ - quantileSeq(prob: number|BigNumber|MathArray, sorted?: boolean): MathJsChain; - - /** - * Compute the standard deviation of a matrix or a list with values. The standard deviations is defined as the square root of the - * variance: std(A) = sqrt(var(A)). In case of a (multi dimensional) array or matrix, the standard deviation over all elements will - * be calculated. - * Optionally, the type of normalization can be specified as second parameter. The parameter normalization can be one of the following - * values: - * 'unbiased' (default) The sum of squared errors is divided by (n - 1) - * 'uncorrected' The sum of squared errors is divided by n - * 'biased' The sum of squared errors is divided by (n + 1) - */ - std(normalization?: string): MathJsChain; - - /** - * Compute the sum of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the sum of all elements will be calculated. - */ - sum(): MathJsChain; - - /** - * Compute the variance of a matrix or a list with values. In case of a (multi dimensional) array or matrix, the variance over all - * elements will be calculated. - * Optionally, the type of normalization can be specified as second parameter. The parameter normalization can be one of the - * following values: - * 'unbiased' (default) The sum of squared errors is divided by (n - 1) - * 'uncorrected' The sum of squared errors is divided by n - * 'biased' The sum of squared errors is divided by (n + 1) - * Note that older browser may not like the variable name var. In that case, the function can be called as math['var'](...) - * instead of math.var(...). - */ - var(normalization?: string): MathJsChain; - - /** - * Calculate the inverse cosine of a value. For matrices, the function is evaluated element wise. - */ - acos(): MathJsChain; - - /** - * Calculate the hyperbolic arccos of a value, defined as acosh(x) = ln(sqrt(x^2 - 1) + x). - * For matrices, the function is evaluated element wise. - */ - acosh(): MathJsChain; - - /** - * Calculate the inverse cotangent of a value. For matrices, the function is evaluated element wise. - */ - acot(): MathJsChain; - - /** - * Calculate the hyperbolic arccotangent of a value, defined as acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2. - * For matrices, the function is evaluated element wise. - */ - acoth(): MathJsChain; - - /** - * Calculate the inverse cosecant of a value. For matrices, the function is evaluated element wise. - */ - acsc(): MathJsChain; - - /** - * Calculate the hyperbolic arccosecant of a value, defined as acsch(x) = ln(1/x + sqrt(1/x^2 + 1)). - * For matrices, the function is evaluated element wise. - */ - acsch(): MathJsChain; - - /** - * Calculate the inverse secant of a value. For matrices, the function is evaluated element wise. - */ - asec(): MathJsChain; - - /** - * Calculate the hyperbolic arcsecant of a value, defined as asech(x) = ln(sqrt(1/x^2 - 1) + 1/x). For matrices, the function is evaluated element wise. - */ - asech(): MathJsChain; - - /** - * Calculate the inverse sine of a value. For matrices, the function is evaluated element wise. - */ - asin(): MathJsChain; - - /** - * Calculate the hyperbolic arcsine of a value, defined as asinh(x) = ln(x + sqrt(x^2 + 1)). For matrices, the function is evaluated element wise. - */ - asinh(): MathJsChain; - - /** - * Calculate the inverse tangent of a value. For matrices, the function is evaluated element wise. - */ - atan(): MathJsChain; - - /** - * Calculate the inverse tangent function with two arguments, y/x. By providing two arguments, the right quadrant of the - * computed angle can be determined. - * For matrices, the function is evaluated element wise. - */ - atan2(x: number|MathArray|Matrix): MathJsChain; - - /** - * Calculate the hyperbolic arctangent of a value, defined as atanh(x) = ln((1 + x)/(1 - x)) / 2. - * For matrices, the function is evaluated element wise. - */ - atanh(): MathJsChain; - - /** - * Calculate the cosine of a value. For matrices, the function is evaluated element wise. - */ - asin(): MathJsChain; // tslint:disable-line adjacent-overload-signatures - - /** - * Calculate the hyperbolic cosine of a value, defined as cosh(x) = 1/2 * (exp(x) + exp(-x)). For matrices, the function is evaluated element wise. - */ - cosh(): MathJsChain; - - /** - * Calculate the cotangent of a value. cot(x) is defined as 1 / tan(x). For matrices, the function is evaluated element wise. - */ - cot(): MathJsChain; - - /** - * Calculate the hyperbolic cotangent of a value, defined as coth(x) = 1 / tanh(x). For matrices, the function is evaluated element wise. - */ - coth(): MathJsChain; - - /** - * Calculate the cosecant of a value, defined as csc(x) = 1/sin(x). For matrices, the function is evaluated element wise. - */ - csc(): MathJsChain; - - /** - * Calculate the hyperbolic cosecant of a value, defined as csch(x) = 1 / sinh(x). For matrices, the function is evaluated element wise. - */ - csch(): MathJsChain; - - /** - * Calculate the secant of a value, defined as sec(x) = 1/cos(x). For matrices, the function is evaluated element wise. - */ - sec(): MathJsChain; - - /** - * Calculate the hyperbolic secant of a value, defined as sech(x) = 1 / cosh(x). For matrices, the function is evaluated element wise. - */ - sech(): MathJsChain; - - /** - * Calculate the sine of a value. For matrices, the function is evaluated element wise. - */ - sin(): MathJsChain; - - /** - * Calculate the hyperbolic sine of a value, defined as sinh(x) = 1/2 * (exp(x) - exp(-x)). For matrices, the function is evaluated element wise. - */ - sinh(): MathJsChain; - - /** - * Calculate the tangent of a value. tan(x) is equal to sin(x) / cos(x). For matrices, the function is evaluated element wise. - */ - tan(): MathJsChain; - - /** - * Calculate the hyperbolic tangent of a value, defined as tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1). For matrices, the function is evaluated element wise. - */ - tanh(): MathJsChain; - - /** - * Change the unit of a value. For matrices, the function is evaluated element wise. - * @param x The unit to be converted. - * @param unit New unit. Can be a string like "cm" or a unit without value. - */ - to(unit: Unit|string): MathJsChain; - - /** - * Clone an object. - */ - clone(): MathJsChain; - - /** - * Filter the items in an array or one dimensional matrix. - * @param x A one dimensional matrix or array to filter - * @param test - */ - filter(test: RegExp|((item: any) => boolean)): MathJsChain; - - /** - * Format a value of any type into a string. - */ - format(options?: FormatOptions|number|((item: any) => string)): MathJsChain; - - /** - * Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array. - * @param callback The callback method is invoked with three parameters: the value of the element, the index of the element, and the matrix being traversed. - */ - map(callback: (item: any) => any): MathJsChain; - - /** - * Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect. - * @param k The kth smallest value to be retrieved; zero-based index - * @param compare An optional comparator function. The function is called as compare(a, b), and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. - * @returns Returns the kth lowest value. - */ - partitionSelect(k: number, compare?: string|((a: any, b: any) => number)): MathJsChain; - - /** - * Sort the items in a matrix. - * @param compare An optional comparator function. The function is called as compare(a, b), and must return 1 when a > b, -1 when a < b, and 0 when a == b. Default value: 'asc'. - */ - sort(compare?: string|((a: any, b: any) => number)): MathJsChain; - - done(): any; - valueOf(): any; - toString(): string; - } + kron(y: Matrix | MathArray): MathJsChain; + + /** + * Iterate over all elements of a matrix/array, and executes the given + * callback function. + * @param callback The callback function is invoked with three + * parameters: the value of the element, the index of the element, and + * the Matrix/array being traversed. + */ + map(callback: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)): MathJsChain; + + /** + * Create a matrix filled with ones. The created matrix can have one or + * multiple dimensions. + * @param format The matrix storage format + */ + ones(format?: string): MathJsChain; + /** + * @param format The matrix storage format + */ + ones(n: number, format?: string): MathJsChain; + /** + * Partition-based selection of an array or 1D matrix. Will find the kth + * smallest value, and mutates the input array. Uses Quickselect. + * @param k The kth smallest value to be retrieved; zero-based index + * @param compare An optional comparator function. The function is + * called as compare(a, b), and must return 1 when a > b, -1 when a < b, + * and 0 when a == b. Default value: 'asc'. + */ + partitionSelect( + k: number, + compare?: "asc" | "desc" | ((a: any, b: any) => number) + ): MathJsChain; + + /** + * Create an array from a range. By default, the range end is excluded. + * This can be customized by providing an extra parameter includeEnd. + * @param end End of the range, excluded by default, included when + * parameter includeEnd=true + * @param step Step size. Default value is 1. + * @param includeEnd: Option to specify whether to include the end or + * not. False by default + */ + range(includeEnd?: boolean): Matrix; + range(end: number | BigNumber, includeEnd?: boolean): MathJsChain; + range( + end: number | BigNumber, + step: number | BigNumber, + includeEnd?: boolean + ): MathJsChain; + + /** + * Reshape a multi dimensional array to fit the specified dimensions + * @param sizes One dimensional array with integral sizes for each + * dimension + */ + reshape(sizes: number[]): MathJsChain; + + /** + * Resize a matrix + * @param size One dimensional array with numbers + * @param defaultValue Zero by default, except in case of a string, in + * that case defaultValue = ' ' Default value: 0. + */ + resize( + size: MathArray | Matrix, + defaultValue?: number | string + ): MathJsChain; + + /** + * Calculate the size of a matrix or scalar. + */ + size(): MathJsChain; + + /** + * Sort the items in a matrix + * @param compare An optional _comparator function or name. The function + * is called as compare(a, b), and must return 1 when a > b, -1 when a < + * b, and 0 when a == b. Default value: ‘asc’ + */ + sort(compare: ((a: any, b: any) => number) | "asc" | "desc" | "natural"): MathJsChain; + + /** + * Calculate the principal square root of a square matrix. The principal + * square root matrix X of another matrix A is such that X * X = A. + */ + sqrtm(): MathJsChain; + + /** + * Squeeze a matrix, remove inner and outer singleton dimensions from a + * matrix. + */ + squeeze(): MathJsChain; + + /** + * Get or set a subset of a matrix or string. + * @param index An index containing ranges for each dimension + * @param replacement An array, matrix, or scalar. If provided, the + * subset is replaced with replacement. If not provided, the subset is + * returned + * @param defaultValue Default value, filled in on new entries when the + * matrix is resized. If not provided, math.matrix elements will be left + * undefined. Default value: undefined. + */ + subset( + index: Index, + replacement?: any, + defaultValue?: any + ): MathJsChain; + + /** + * Calculate the trace of a matrix: the sum of the elements on the main + * diagonal of a square matrix. + */ + trace(): MathJsChain; + + /** + * Transpose a matrix. All values of the matrix are reflected over its + * main diagonal. Only two dimensional matrices are supported. + */ + transpose(): MathJsChain; + + /** + * Create a matrix filled with zeros. The created matrix can have one or + * multiple dimensions. + * @param format The matrix storage format + * @returns A matrix filled with zeros + */ + zeros(format?: string): MathJsChain; + /** + * @param n The y dimension of the matrix + * @param format The matrix storage format + */ + zeros(n: number, format?: string): MathJsChain; + + /************************************************************************* + * Probability functions + ************************************************************************/ + + /** + * Compute the number of ways of picking k unordered outcomes from n + * possibilities. Combinations only takes integer arguments. The + * following condition must be enforced: k <= n. + * @param k Number of objects in the subset + */ + combinations(k: number | BigNumber): MathJsChain; + + /** + * Compute the factorial of a value Factorial only supports an integer + * value as argument. For matrices, the function is evaluated element + * wise. + */ + factorial(): MathJsChain; + + /** + * Compute the gamma function of a value using Lanczos approximation for + * small values, and an extended Stirling approximation for large + * values. For matrices, the function is evaluated element wise. + */ + gamma(): MathJsChain; + + /** + * Calculate the Kullback-Leibler (KL) divergence between two + * distributions + * @param p Second vector + */ + kldivergence(p: MathArray | Matrix): MathJsChain; + + /** + * Multinomial Coefficients compute the number of ways of picking a1, + * a2, ..., ai unordered outcomes from n possibilities. multinomial + * takes one array of integers as an argument. The following condition + * must be enforced: every ai <= 0 + */ + multinomial(): MathJsChain; + + /** + * Compute the number of ways of obtaining an ordered subset of k + * elements from a set of n elements. Permutations only takes integer + * arguments. The following condition must be enforced: k <= n. + * @param k The number of objects in the subset + */ + permutations(k?: number | BigNumber): MathJsChain; + + /** + * Random pick a value from a one dimensional array. Array element is + * picked using a random function with uniform distribution. + * @param number An int or float + * @param weights An array of ints or floats + */ + pickRandom(number?: number, weights?: number[]): MathJsChain; + + /** + * Return a random number larger or equal to min and smaller than max + * using a uniform distribution. + * @param min Minimum boundary for the random value, included + * @param max Maximum boundary for the random value, excluded + */ + // tslint:disable-next-line unified-signatures + random(max?: number): MathJsChain; + // tslint:disable-next-line unified-signatures + random(min: number, max: number): MathJsChain; + + /** + * Return a random integer number larger or equal to min and smaller + * than max using a uniform distribution. + * @param min Minimum boundary for the random value, included + * @param max Maximum boundary for the random value, excluded + */ + // tslint:disable-next-line unified-signatures + randomInt(max?: number): MathJsChain; + // tslint:disable-next-line unified-signatures + randomInt(min: number, max: number): MathJsChain; + + /************************************************************************* + * Relational functions + ************************************************************************/ + + /** + * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x + * == y. x and y are considered equal when the relative difference + * between x and y is smaller than the configured epsilon. The function + * cannot be used to compare values smaller than approximately 2.22e-16. + * For matrices, the function is evaluated element wise. + * @param y Second value to compare + */ + compare(y: MathType | string): MathJsChain; + + /** + * Compare two values of any type in a deterministic, natural way. For + * numeric values, the function works the same as math.compare. For + * types of values that can’t be compared mathematically, the function + * compares in a natural way. + * @param y Second value to compare + */ + compareNatural(y: any): MathJsChain; + + /** + * Compare two strings lexically. Comparison is case sensitive. Returns + * 1 when x > y, -1 when x < y, and 0 when x == y. For matrices, the + * function is evaluated element wise. + * @param y Second string to compare + */ + compareText(y: string | MathArray | Matrix): MathJsChain; + + /** + * Test element wise whether two matrices are equal. The function + * accepts both matrices and scalar values. + * @param y Second amtrix to compare + */ + deepEqual(y: MathType): MathJsChain; + + /** + * Test whether two values are equal. + * + * The function tests whether the relative difference between x and y is + * smaller than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. For matrices, the + * function is evaluated element wise. In case of complex numbers, x.re + * must equal y.re, and x.im must equal y.im. Values null and undefined + * are compared strictly, thus null is only equal to null and nothing + * else, and undefined is only equal to undefined and nothing else. + * @param y Second value to compare + */ + equal(y: MathType | string): MathJsChain; + + /** + * Check equality of two strings. Comparison is case sensitive. For + * matrices, the function is evaluated element wise. + * @param y Second string to compare + */ + equalText(y: string | MathArray | Matrix): MathJsChain; + + /** + * Test whether value x is larger than y. The function returns true when + * x is larger than y and the relative difference between x and y is + * larger than the configured epsilon. The function cannot be used to + * compare values smaller than approximately 2.22e-16. For matrices, the + * function is evaluated element wise. + * @param y Second value to compare + */ + larger(y: MathType | string): MathJsChain; + + /** + * Test whether value x is larger or equal to y. The function returns + * true when x is larger than y or the relative difference between x and + * y is smaller than the configured epsilon. The function cannot be used + * to compare values smaller than approximately 2.22e-16. For matrices, + * the function is evaluated element wise. + * @param y Second value to vcompare + */ + largerEq(y: MathType | string): MathJsChain; + + /** + * Test whether value x is smaller than y. The function returns true + * when x is smaller than y and the relative difference between x and y + * is smaller than the configured epsilon. The function cannot be used + * to compare values smaller than approximately 2.22e-16. For matrices, + * the function is evaluated element wise. + * @param y Second value to vcompare + */ + smaller(y: MathType | string): MathJsChain; + + /** + * Test whether value x is smaller or equal to y. The function returns + * true when x is smaller than y or the relative difference between x + * and y is smaller than the configured epsilon. The function cannot be + * used to compare values smaller than approximately 2.22e-16. For + * matrices, the function is evaluated element wise. + * @param y Second value to compare + */ + smallerEq(y: MathType | string): MathJsChain; + + /** + * Test whether two values are unequal. The function tests whether the + * relative difference between x and y is larger than the configured + * epsilon. The function cannot be used to compare values smaller than + * approximately 2.22e-16. For matrices, the function is evaluated + * element wise. In case of complex numbers, x.re must unequal y.re, or + * x.im must unequal y.im. Values null and undefined are compared + * strictly, thus null is unequal with everything except null, and + * undefined is unequal with everything except undefined. + * @param y Second value to vcompare + */ + unequal(y: MathType | string): MathJsChain; + + /************************************************************************* + * Set functions + ************************************************************************/ + + /** + * Create the cartesian product of two (multi)sets. Multi-dimension + * arrays will be converted to single-dimension arrays before the + * operation. + * @param a2 A (multi)set + */ + setCartesian(a2: MathArray | Matrix): MathJsChain; + + /** + * Create the difference of two (multi)sets: every element of set1, that + * is not the element of set2. Multi-dimension arrays will be converted + * to single-dimension arrays before the operation + * @param a2 A (multi)set + */ + setDifference(a2: MathArray | Matrix): MathJsChain; + + /** + * Collect the distinct elements of a multiset. A multi-dimension array + * will be converted to a single-dimension array before the operation. + */ + setDistinct(): MathJsChain; + + /** + * Create the intersection of two (multi)sets. Multi-dimension arrays + * will be converted to single-dimension arrays before the operation. + * @param a2 A (multi)set + */ + setIntersect(a2: MathArray | Matrix): MathJsChain; + + /** + * Check whether a (multi)set is a subset of another (multi)set. (Every + * element of set1 is the element of set2.) Multi-dimension arrays will + * be converted to single-dimension arrays before the operation. + * @param a2 A (multi)set + */ + setIsSubset(a2: MathArray | Matrix): MathJsChain; + + /** + * Count the multiplicity of an element in a multiset. A multi-dimension + * array will be converted to a single-dimension array before the + * operation. + * @param a A multiset + */ + setMultiplicity(a: MathArray | Matrix): MathJsChain; + + /** + * Create the powerset of a (multi)set. (The powerset contains very + * possible subsets of a (multi)set.) A multi-dimension array will be + * converted to a single-dimension array before the operation. + */ + setPowerset(): MathJsChain; + + /** + * Count the number of elements of a (multi)set. When a second parameter + * is ‘true’, count only the unique values. A multi-dimension array will + * be converted to a single-dimension array before the operation. + */ + setSize(): MathJsChain; + + /** + * Create the symmetric difference of two (multi)sets. Multi-dimension + * arrays will be converted to single-dimension arrays before the + * operation. + * @param a2 A (multi)set + */ + setSymDifference(a2: MathArray | Matrix): MathJsChain; + + /** + * Create the union of two (multi)sets. Multi-dimension arrays will be + * converted to single-dimension arrays before the operation. + * @param a2 A (multi)set + */ + setUnion(a2: MathArray | Matrix): MathJsChain; + + /************************************************************************* + * Special functions + ************************************************************************/ + + /** + * Compute the erf function of a value using a rational Chebyshev + * approximations for different intervals of x. + */ + erf(): MathJsChain; + + /************************************************************************* + * Statistics functions + ************************************************************************/ + + /** + * Compute the median absolute deviation of a matrix or a list with + * values. The median absolute deviation is defined as the median of the + * absolute deviations from the median. + */ + mad(): MathJsChain; + + /** + * Compute the maximum value of a matrix or a list with values. In case + * of a multi dimensional array, the maximum of the flattened array will + * be calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param dim The maximum over the selected dimension + */ + max(dim?: number): MathJsChain; + + /** + * Compute the mean value of matrix or a list with values. In case of a + * multi dimensional array, the mean of the flattened array will be + * calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param dim The mean over the selected dimension + */ + mean(dim?: number): MathJsChain; + + /** + * Compute the median of a matrix or a list with values. The values are + * sorted and the middle value is returned. In case of an even number of + * values, the average of the two middle values is returned. Supported + * types of values are: Number, BigNumber, Unit In case of a (multi + * dimensional) array or matrix, the median of all elements will be + * calculated. + */ + median(): MathJsChain; + + /** + * Compute the maximum value of a matrix or a list of values. In case of + * a multi dimensional array, the maximum of the flattened array will be + * calculated. When dim is provided, the maximum over the selected + * dimension will be calculated. Parameter dim is zero-based. + * @param dim The minimum over the selected dimension + */ + min(dim?: number): MathJsChain; + + /** + * Computes the mode of a set of numbers or a list with values(numbers + * or characters). If there are more than one modes, it returns a list + * of those values. + */ + mode(): MathJsChain; + + /** + * Compute the product of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the sum of all elements will be + * calculated. + */ + prod(): MathJsChain; + + /** + * Compute the prob order quantile of a matrix or a list with values. + * The sequence is sorted and the middle value is returned. Supported + * types of sequence values are: Number, BigNumber, Unit Supported types + * of probability are: Number, BigNumber In case of a (multi + * dimensional) array or matrix, the prob order quantile of all elements + * will be calculated. + * @param probOrN prob is the order of the quantile, while N is the + * amount of evenly distributed steps of probabilities; only one of + * these options can be provided + * @param sorted =false is data sorted in ascending order + */ + quantileSeq( + prob: number | BigNumber | MathArray, + sorted?: boolean + ): MathJsChain; + + /** + * Compute the standard deviation of a matrix or a list with values. The + * standard deviations is defined as the square root of the variance: + * std(A) = sqrt(var(A)). In case of a (multi dimensional) array or + * matrix, the standard deviation over all elements will be calculated. + * Optionally, the type of normalization can be specified as second + * parameter. The parameter normalization can be one of the following + * values: 'unbiased' (default) The sum of squared errors is divided by + * (n - 1) 'uncorrected' The sum of squared errors is divided by n + * 'biased' The sum of squared errors is divided by (n + 1) + * @param array A single matrix or multiple scalar values + * @param normalization Determines how to normalize the variance. Choose + * ‘unbiased’ (default), ‘uncorrected’, or ‘biased’. Default value: + * ‘unbiased’. + * @returns The standard deviation + */ + std( + normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased" + ): MathJsChain; + + /** + * Compute the sum of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the sum of all elements will be + * calculated. + */ + sum(): MathJsChain; + + /** + * Compute the variance of a matrix or a list with values. In case of a + * (multi dimensional) array or matrix, the variance over all elements + * will be calculated. Optionally, the type of normalization can be + * specified as second parameter. The parameter normalization can be one + * of the following values: 'unbiased' (default) The sum of squared + * errors is divided by (n - 1) 'uncorrected' The sum of squared errors + * is divided by n 'biased' The sum of squared errors is divided by (n + + * 1) Note that older browser may not like the variable name var. In + * that case, the function can be called as math['var'](...) instead of + * math.var(...). + * @param normalization normalization Determines how to normalize the + * variance. Choose ‘unbiased’ (default), ‘uncorrected’, or ‘biased’. + * Default value: ‘unbiased’. + * @returns The variance + */ + var( + normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased" + ): MathJsChain; + + /************************************************************************* + * String functions + ************************************************************************/ + + /** + * Format a value of any type into a string. + * @param options An object with formatting options. + * @param callback A custom formatting function, invoked for all numeric + * elements in value, for example all elements of a matrix, or the real + * and imaginary parts of a complex number. This callback can be used to + * override the built-in numeric notation with any type of formatting. + * Function callback is called with value as parameter and must return a + * string. + * @see http://mathjs.org/docs/reference/functions/format.html + */ + format( + value: any, + options?: FormatOptions | number | ((item: any) => string), + callback?: ((value: any) => string) + ): MathJsChain; + + /** + * Interpolate values into a string template. + * @param values An object containing variables which will be filled in + * in the template. + * @param precision Number of digits to format numbers. If not provided, + * the value will not be rounded. + * @param options Formatting options, or the number of digits to format + * numbers. See function math.format for a description of all options. + */ + print( + values: any, + precision?: number, + options?: number | object + ): MathJsChain; + + /************************************************************************* + * Trigonometry functions + ************************************************************************/ + + /** + * Calculate the inverse cosine of a value. For matrices, the function + * is evaluated element wise. + */ + acos(): MathJsChain; + + /** + * Calculate the hyperbolic arccos of a value, defined as acosh(x) = + * ln(sqrt(x^2 - 1) + x). For matrices, the function is evaluated + * element wise. + */ + acosh(): MathJsChain; + + /** + * Calculate the inverse cotangent of a value. For matrices, the + * function is evaluated element wise. + */ + acot(): MathJsChain; + + /** + * Calculate the hyperbolic arccotangent of a value, defined as acoth(x) + * = (ln((x+1)/x) + ln(x/(x-1))) / 2. For matrices, the function is + * evaluated element wise. + */ + acoth(): MathJsChain; + + /** + * Calculate the inverse cosecant of a value. For matrices, the function + * is evaluated element wise. + */ + acsc(): MathJsChain; + + /** + * Calculate the hyperbolic arccosecant of a value, defined as acsch(x) + * = ln(1/x + sqrt(1/x^2 + 1)). For matrices, the function is evaluated + * element wise. + */ + acsch(): MathJsChain; + + /** + * Calculate the inverse secant of a value. For matrices, the function + * is evaluated element wise. + */ + asec(): MathJsChain; + + /** + * Calculate the hyperbolic arcsecant of a value, defined as asech(x) = + * ln(sqrt(1/x^2 - 1) + 1/x). For matrices, the function is evaluated + * element wise. + */ + asech(): MathJsChain; + + /** + * Calculate the inverse sine of a value. For matrices, the function is + * evaluated element wise. + */ + asin(): MathJsChain; + + /** + * Calculate the hyperbolic arcsine of a value, defined as asinh(x) = + * ln(x + sqrt(x^2 + 1)). For matrices, the function is evaluated + * element wise. + */ + asinh(): MathJsChain; + + /** + * Calculate the inverse tangent of a value. For matrices, the function + * is evaluated element wise. + */ + atan(): MathJsChain; + + /** + * Calculate the inverse tangent function with two arguments, y/x. By + * providing two arguments, the right quadrant of the computed angle can + * be determined. For matrices, the function is evaluated element wise. + */ + atan2(): MathJsChain; + + /** + * Calculate the hyperbolic arctangent of a value, defined as atanh(x) = + * ln((1 + x)/(1 - x)) / 2. For matrices, the function is evaluated + * element wise. + */ + atanh(): MathJsChain; + + /** + * Calculate the cosine of a value. For matrices, the function is + * evaluated element wise. + */ + cos(): MathJsChain; + + /** + * Calculate the hyperbolic cosine of a value, defined as cosh(x) = 1/2 + * * (exp(x) + exp(-x)). For matrices, the function is evaluated element + * wise. + */ + cosh(): MathJsChain; + + /** + * Calculate the cotangent of a value. cot(x) is defined as 1 / tan(x). + * For matrices, the function is evaluated element wise. + */ + cot(): MathJsChain; + + /** + * Calculate the hyperbolic cotangent of a value, defined as coth(x) = 1 + * / tanh(x). For matrices, the function is evaluated element wise. + */ + coth(): MathJsChain; + + /** + * Calculate the cosecant of a value, defined as csc(x) = 1/sin(x). For + * matrices, the function is evaluated element wise. + */ + csc(): MathJsChain; + + /** + * Calculate the hyperbolic cosecant of a value, defined as csch(x) = 1 + * / sinh(x). For matrices, the function is evaluated element wise. + */ + csch(): MathJsChain; + + /** + * Calculate the secant of a value, defined as sec(x) = 1/cos(x). For + * matrices, the function is evaluated element wise. + */ + sec(): MathJsChain; + + /** + * Calculate the hyperbolic secant of a value, defined as sech(x) = 1 / + * cosh(x). For matrices, the function is evaluated element wise. + */ + sech(): MathJsChain; + + /** + * Calculate the sine of a value. For matrices, the function is + * evaluated element wise. + */ + sin(): MathJsChain; + + /** + * Calculate the hyperbolic sine of a value, defined as sinh(x) = 1/2 * + * (exp(x) - exp(-x)). For matrices, the function is evaluated element + * wise. + */ + sinh(): MathJsChain; + + /** + * Calculate the tangent of a value. tan(x) is equal to sin(x) / cos(x). + * For matrices, the function is evaluated element wise. + */ + tan(): MathJsChain; + + /** + * Calculate the hyperbolic tangent of a value, defined as tanh(x) = + * (exp(2 * x) - 1) / (exp(2 * x) + 1). For matrices, the function is + * evaluated element wise. + */ + tanh(): MathJsChain; + + /************************************************************************* + * Unit functions + ************************************************************************/ + + /** + * Change the unit of a value. For matrices, the function is evaluated + * element wise. + * @param unit New unit. Can be a string like "cm" or a unit without + * value. + */ + to(unit: Unit | string): MathJsChain; + + /************************************************************************* + * Utils functions + ************************************************************************/ + + /** + * Clone an object. + */ + clone(): MathJsChain; + + /** + * Test whether a value is an integer number. The function supports + * number, BigNumber, and Fraction. The function is evaluated + * element-wise in case of Array or Matrix input. + */ + isInteger(): MathJsChain; + + /** + * Test whether a value is NaN (not a number). The function supports + * types number, BigNumber, Fraction, Unit and Complex. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isNaN(): MathJsChain; + + /** + * Test whether a value is negative: smaller than zero. The function + * supports types number, BigNumber, Fraction, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isNegative(): MathJsChain; + + /** + * Test whether a value is an numeric value. The function is evaluated + * element-wise in case of Array or Matrix input. + */ + isNumeric(): MathJsChain; + + /** + * Test whether a value is positive: larger than zero. The function + * supports types number, BigNumber, Fraction, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isPositive(): MathJsChain; + + /** + * Test whether a value is prime: has no divisors other than itself and + * one. The function supports type number, bignumber. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isPrime(): MathJsChain; + + /** + * Test whether a value is zero. The function can check for zero for + * types number, BigNumber, Fraction, Complex, and Unit. The function is + * evaluated element-wise in case of Array or Matrix input. + */ + isZero(): MathJsChain; + + /** + * Determine the type of a variable. + */ + typeof(): MathJsChain; + } } diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 6cf43dc698..c1e32a7d9a 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -33,7 +33,7 @@ Bignumbers examples { // configure the default type of numbers as BigNumbers math.config({ - number: 'bignumber', + number: 'BigNumber', precision: 20, }); @@ -108,16 +108,13 @@ Complex numbers examples // create a complex number from polar coordinates { - const p: math.PolarCoordinates = { r: math.sqrt(2), phi: math.pi / 4 }; - const c: math.Complex = math - .complex(p); + const p: math.PolarCoordinates = { r: math.sqrt(2), phi: math.pi / 4 }; + const c: math.Complex = math.complex(p); } // get polar coordinates of a complex number { - const p: math.PolarCoordinates = math - .complex(3, 4) - .toPolar(); + const p: math.PolarCoordinates = math.complex(3, 4).toPolar(); } } @@ -175,6 +172,11 @@ Expressions examples // get and set variables and functions { + parser.eval('x = 7 / 2'); // 3.5 + parser.eval('x + 3'); // 6.5 + parser.eval('f(x, y) = x^y'); // f(x, y) + parser.eval('f(2, 3)'); // 8 + const x = parser.get('x'); const f = parser.get('f'); const g = f(3, 3); @@ -193,7 +195,7 @@ Fractions examples { // configure the default type of numbers as Fractions math.config({ - number: 'fraction', + number: 'Fraction', }); const x = math.fraction(0.125); @@ -205,9 +207,6 @@ Fractions examples // output formatting const a = math.fraction('2/3'); - console.log(math.format(a)); - console.log(math.format(a, {fraction: 'ratio'})); - console.log(math.format(a, {fraction: 'decimal'})); } /* @@ -237,7 +236,8 @@ Matrices examples b.subset(math.index(1, [0, 1]), [[7, 8]]); const c = math.multiply(a, b); - const d: math.Matrix = c.subset(math.index(1, 0)); + const f: math.Matrix = math.matrix([1, 0]); + const d: math.Matrix = f.subset(math.index(1, 0)); } // get a sub matrix @@ -282,8 +282,9 @@ Sparse matrices examples // do operations with a sparse matrix const b = math.multiply(a, a); const c = math.multiply(b, math.complex(2, 2)); - const d = math.transpose(c); - const e = math.multiply(d, a); + const d = math.matrix([0, 1]); + const e = math.transpose(d); + const f = math.multiply(e, a); } /* @@ -299,8 +300,8 @@ Units examples math.createUnit('foo'); math.createUnit('furlong', '220 yards'); math.createUnit('furlong', '220 yards', {override: true}); - math.createUnit('fahrenheit', {definition: '0.555556 kelvin', offset: 459.67}); - math.createUnit('fahrenheit', {definition: '0.555556 kelvin', offset: 459.67}, {override: true}); + math.createUnit('testunit', {definition: '0.555556 kelvin', offset: 459.67}); + math.createUnit('testunit', {definition: '0.555556 kelvin', offset: 459.67}, {override: true}); math.createUnit('knot', {definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts']}); math.createUnit('knot', {definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts']}, {override: true}); math.createUnit('knot', { @@ -309,7 +310,7 @@ Units examples prefixes: 'long' }, {override: true}); math.createUnit({ - foo: { + foo_2: { prefixes: 'long' }, bar: '40 foo', @@ -365,3 +366,15 @@ Expression tree examples } }); } + +/* +JSON serialization/deserialization +*/ +{ + const data = { + bigNumber: math.bignumber('1.5') + }; + const stringified = JSON.stringify(data); + const parsed = JSON.parse(stringified, math.json.reviver); + parsed.bigNumber === math.bignumber('1.5'); // true +} diff --git a/types/maxmind/index.d.ts b/types/maxmind/index.d.ts index da45eb907b..c93c59a72a 100644 --- a/types/maxmind/index.d.ts +++ b/types/maxmind/index.d.ts @@ -68,6 +68,11 @@ export declare interface Response { readonly names: Translations; }; readonly postal?: { code: string }; + readonly isp?: { + readonly isp: string; + readonly autonomous_system_number: number; + }; + readonly connection?: { connection_type: string }; } export declare interface Translations { diff --git a/types/meteor/meteor-tests.ts b/types/meteor/meteor-tests.ts index f9cf039c84..a321e4a409 100644 --- a/types/meteor/meteor-tests.ts +++ b/types/meteor/meteor-tests.ts @@ -781,3 +781,8 @@ DDPRateLimiter.addRule({ userId: 'foo' }, 5, 1000); DDPRateLimiter.addRule({ userId: userId => userId == 'foo' }, 5, 1000); Template.instance().autorun(() => { }).stop(); + +// Mongo Collection without connection (local collection) +const collectionWithoutConnection = new Mongo.Collection("monkey", { + connection: null +}); diff --git a/types/meteor/mongo.d.ts b/types/meteor/mongo.d.ts index 248f5a22af..771d24edc1 100644 --- a/types/meteor/mongo.d.ts +++ b/types/meteor/mongo.d.ts @@ -124,7 +124,7 @@ declare module Mongo { var Collection: CollectionStatic; interface CollectionStatic { new (name: string, options?: { - connection?: Object; + connection?: Object | null; idGeneration?: string; transform?: Function; }): Collection; @@ -348,7 +348,7 @@ declare module "meteor/mongo" { var Collection: CollectionStatic; interface CollectionStatic { new (name: string, options?: { - connection?: Object; + connection?: Object | null; idGeneration?: string; transform?: Function; }): Collection; diff --git a/types/moment-duration-format/index.d.ts b/types/moment-duration-format/index.d.ts index 4506311ab6..1716d55d83 100644 --- a/types/moment-duration-format/index.d.ts +++ b/types/moment-duration-format/index.d.ts @@ -80,12 +80,12 @@ declare module "moment" { } interface LocaleSpecification { - durationLabelsLong: DurationLabelDef; - durationLabelsStandard: DurationLabelDef; - durationLabelsShort: DurationLabelDef; - durationTimeTemplates: DurationTimeDef; - durationLabelTypes: DurationLabelTypeDef[]; - durationPluralKey: (token: string, integerValue: number, decimalValue: number) => string; + durationLabelsLong?: DurationLabelDef; + durationLabelsStandard?: DurationLabelDef; + durationLabelsShort?: DurationLabelDef; + durationTimeTemplates?: DurationTimeDef; + durationLabelTypes?: DurationLabelTypeDef[]; + durationPluralKey?: (token: string, integerValue: number, decimalValue: number) => string; } type TemplateFunction = ((this: DurationFormatSettings) => string); diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 98aa2daca8..273a0716b2 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1252,7 +1252,7 @@ export class Cursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.0/api/Cursor.html#limit */ limit(value: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Cursor.html#map */ - map(transform: Function): Cursor; + map(transform: (T) => U): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Cursor.html#max */ max(max: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Cursor.html#maxAwaitTimeMS */ diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 59a5c95989..a94f3a691d 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -103,7 +103,10 @@ declare module "mongoose" { export function createConnection(): Connection; export function createConnection(uri: string, options?: ConnectionOptions - ): Connection; + ): Connection & { + then: Promise["then"]; + catch: Promise["catch"]; + }; /** * Disconnects all connections. @@ -201,7 +204,7 @@ declare module "mongoose" { */ open(connection_string: string, database?: string, port?: number, options?: ConnectionOpenOptions, callback?: (err: any) => void): any; - + /** * Opens the connection to MongoDB. * @param mongodb://uri or the host to which you are connecting @@ -451,9 +454,6 @@ declare module "mongoose" { /** Expose the possible connection states. */ static STATES: any; - - then: Promise["then"]; - catch: Promise["catch"]; } /* @@ -2727,9 +2727,9 @@ declare module "mongoose" { * This function does not trigger save middleware. * @param docs Documents to insert. * @param options Optional settings. - * @param options.ordered if true, will fail fast on the first error encountered. + * @param options.ordered if true, will fail fast on the first error encountered. * If false, will insert all the documents it can and report errors later. - * @param options.rawResult if false, the returned promise resolves to the documents that passed mongoose document validation. + * @param options.rawResult if false, the returned promise resolves to the documents that passed mongoose document validation. * If `false`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) * with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. */ diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 90b6fc2561..90259483f2 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -161,6 +161,13 @@ mongoose.Connection.STATES.hasOwnProperty(''); conn1.on('data', cb); conn1.addListener('close', cb); +// The connection returned by useDb is *not* thenable. +// From https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26057#issuecomment-396150819 +const getDB = async (tenant: string)=> { + return conn1.useDb(tenant); +}; + + /* * section error/validation.js * http://mongoosejs.com/docs/api.html#error-validation-js diff --git a/types/multer/index.d.ts b/types/multer/index.d.ts index d019b9fdcb..7d2bfefc26 100644 --- a/types/multer/index.d.ts +++ b/types/multer/index.d.ts @@ -71,6 +71,8 @@ declare namespace multer { fields(fields: Field[]): express.RequestHandler; /** Accepts all files that comes over the wire. An array of files will be stored in req.files. */ any(): express.RequestHandler; + /** Accept only text fields. If any file upload is made, error with code “LIMIT_UNEXPECTED_FILE” will be issued. This is the same as doing upload.fields([]). */ + none(): express.RequestHandler; } } diff --git a/types/next/app.d.ts b/types/next/app.d.ts new file mode 100644 index 0000000000..18bca653cf --- /dev/null +++ b/types/next/app.d.ts @@ -0,0 +1,18 @@ +import * as React from "react"; +import { NextContext } from "."; +import { SingletonRouter } from "./router"; + +export interface AppComponentProps { + Component: React.ComponentType; + pageProps: any; +} + +export interface AppComponentContext { + Component: React.ComponentType; + router: SingletonRouter; + ctx: NextContext; +} + +export class Container extends React.Component {} + +export default class App extends React.Component {} diff --git a/types/next/document.d.ts b/types/next/document.d.ts index b8ae0864ba..38e20e00c0 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -1,30 +1,5 @@ import * as React from "react"; -import * as http from "http"; - -export interface Context { - err?: Error; - req: http.IncomingMessage; - res: http.ServerResponse; - pathname: string; - query?: { - [key: string]: - | boolean - | boolean[] - | number - | number[] - | string - | string[]; - }; - asPath: string; - - renderPage( - enhancer?: (page: React.Component) => React.ComponentType - ): { - html?: string; - head: Array>; - errorHtml: string; - }; -} +import { NextContext } from "."; export interface DocumentProps { __NEXT_DATA__?: any; @@ -38,9 +13,21 @@ export interface DocumentProps { [key: string]: any; } +/** + * Context object used inside `Document` + */ +export interface NextDocumentContext extends NextContext { + /** A callback that executes the actual React rendering logic (synchronously) */ + renderPage( + cb?: (enhancer: () => JSX.Element) => React.ComponentType + ): { + [key: string]: any + }; +} + export class Head extends React.Component {} export class Main extends React.Component {} export class NextScript extends React.Component {} export default class extends React.Component { - static getInitialProps(ctx: Context): DocumentProps; + static getInitialProps(ctx: NextContext): DocumentProps; } diff --git a/types/next/index.d.ts b/types/next/index.d.ts index fe44537f5f..95395bc2b8 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for next 2.4 +// Type definitions for next 6.0 // Project: https://github.com/zeit/next.js // Definitions by: Drew Hays // Brice BERNARD +// James Hegedus +// Resi Respati // Scott Jones // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -11,7 +13,44 @@ import * as http from "http"; import * as url from "url"; +import { Response as NodeResponse } from "node-fetch"; + declare namespace next { + /** + * Context object used in methods like `getInitialProps()` + * <> + */ + interface NextContext { + /** path section of URL */ + pathname: string; + /** query string section of URL parsed as an object */ + query: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }; + /** String of the actual path (including the query) shows in the browser */ + asPath: string; + /** HTTP request object (server only) */ + req?: http.IncomingMessage; + /** HTTP response object (server only) */ + res?: http.ServerResponse; + /** Fetch Response object (client only) - from https://developer.mozilla.org/en-US/docs/Web/API/Response */ + jsonPageRes?: NodeResponse; + /** Error object if any error is encountered during the rendering */ + err?: Error; + } + + type NextSFC = NextStatelessComponent; + interface NextStatelessComponent + extends React.StatelessComponent { + getInitialProps?: (ctx: NextContext) => Promise; + } + type UrlLike = url.UrlObject | url.Url; interface ServerConfig { @@ -41,12 +80,12 @@ declare namespace next { handleRequest( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; getRequestHandler(): ( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ) => Promise; prepare(): Promise; close(): Promise; @@ -55,7 +94,7 @@ declare namespace next { run( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; render( @@ -71,7 +110,7 @@ declare namespace next { | string | string[]; }, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; renderError( err: any, @@ -86,12 +125,12 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; render404( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; renderToHTML( req: http.IncomingMessage, @@ -105,7 +144,7 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; renderErrorToHTML( err: any, @@ -120,13 +159,13 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; serveStatic( req: http.IncomingMessage, res: http.ServerResponse, - path: string, + path: string ): Promise; isServeableUrl(path: string): boolean; isInternalUrl(req: http.IncomingMessage): boolean; @@ -135,12 +174,12 @@ declare namespace next { getCompilationError( page: string, req: http.IncomingMessage, - res: http.ServerResponse, + res: http.ServerResponse ): Promise; handleBuildHash( filename: string, hash: string, - res: http.ServerResponse, + res: http.ServerResponse ): void; send404(res: http.ServerResponse): void; } diff --git a/types/next/test/next-app-tests.tsx b/types/next/test/next-app-tests.tsx new file mode 100644 index 0000000000..3e7c56f87c --- /dev/null +++ b/types/next/test/next-app-tests.tsx @@ -0,0 +1,27 @@ +import * as React from "react"; +import App, { Container } from "next/app"; + +interface NextComponentProps { + example: string; +} + +class TestApp extends App { + static async getInitialProps({ Component, router, ctx }: any) { + let pageProps = {}; + + if (Component.getInitialProps) { + pageProps = await Component.getInitialProps(ctx); + } + + return { pageProps }; + } + + render() { + const { Component, pageProps } = this.props; + return ( + + + + ); + } +} diff --git a/types/next/test/next-component-tests.tsx b/types/next/test/next-component-tests.tsx new file mode 100644 index 0000000000..55173fd25c --- /dev/null +++ b/types/next/test/next-component-tests.tsx @@ -0,0 +1,28 @@ +import * as React from "react"; +import { NextStatelessComponent, NextContext } from "next"; + +interface NextComponentProps { + example: string; +} + +class ClassNext extends React.Component { + static async getInitialProps(ctx: NextContext) { + const { example } = ctx.query; + return { example }; + } + + render() { + return ( +

I'm a class component! {this.props.example}
+ ); + } +} + +const StatelessNext: NextStatelessComponent = ({ example }) => ( +
I'm a stateless component! {example}
+); + +StatelessNext.getInitialProps = async ({ query }: NextContext) => { + const { example } = query; + return { example: example as string }; +}; diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 0177d1d451..2b3257cd25 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -1,12 +1,40 @@ -import Document, * as document from "next/document"; +import Document, { Head, Main, NextScript, NextDocumentContext } from 'next/document'; import * as React from "react"; const results = ( - + - - - + +
+ ); + +const Wrapper: React.SFC = ({ children }) => {children}; + +export default class MyDocument extends Document { + static async getInitialProps({ renderPage }: NextDocumentContext) { + // Without callback + const page = renderPage(); + // With callback + const differentPage = renderPage(App => props => ); + const style = {}; + return { ...page, style }; + } + + render() { + return ( + + + My page +