From c77275b10cdf02ce276bbdf16b83127d6d70d81e Mon Sep 17 00:00:00 2001 From: Flosch Date: Fri, 11 May 2018 18:03:30 +0200 Subject: [PATCH 01/37] [reactstrap] Add Typings for CustomInput --- types/reactstrap/index.d.ts | 3 + types/reactstrap/lib/CustomInput.d.ts | 22 +++++++ types/reactstrap/reactstrap-tests.tsx | 89 +++++++++++++++++++++++++++ 3 files changed, 114 insertions(+) create mode 100644 types/reactstrap/lib/CustomInput.d.ts diff --git a/types/reactstrap/index.d.ts b/types/reactstrap/index.d.ts index b7c408183b..a42e7b6723 100644 --- a/types/reactstrap/index.d.ts +++ b/types/reactstrap/index.d.ts @@ -101,6 +101,9 @@ export { CollapseProps } from './lib/Collapse'; import { default as Container_ } from './lib/Container'; export class Container extends Container_ {} export { ContainerProps } from './lib/Container'; +export { default as CustomInput_ } from './lib/CustomInput'; +export class CustomerInput extends CustomInput_ {}; +export { CustomInputProps } from './lib/CustomInput'; import { default as Dropdown_ } from './lib/Dropdown'; export class Dropdown extends Dropdown_ {} export { DropdownProps } from './lib/Dropdown'; diff --git a/types/reactstrap/lib/CustomInput.d.ts b/types/reactstrap/lib/CustomInput.d.ts new file mode 100644 index 0000000000..ff1d196667 --- /dev/null +++ b/types/reactstrap/lib/CustomInput.d.ts @@ -0,0 +1,22 @@ +import * as React from 'react'; +import { CSSModule } from '../index'; + +export type CustomInputType = + | 'select' + | 'file' + | 'radio' + | 'checkbox'; + +export type CustomInputProps = React.InputHTMLAttributes & { + type: CustomInputType; + label?: string; + inline?: boolean; + bsSize?: 'lg' | 'sm'; + valid?: boolean; + invalid?: boolean; + className?: string; + cssModule?: CSSModule; +} & T; + +declare class CustomInput extends React.Component> {} +export default CustomInput; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 550a1242a8..290e2657e1 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -35,6 +35,7 @@ import { Col, Container, Collapse, + CustomInput, Fade, Form, FormFeedback, @@ -4051,3 +4052,91 @@ function GenericPropExample() { ); } + +class Example118 extends React.Component { + render() { + return ( +
+ + +
+ + + +
+
+ + +
+ + + +
+
+ + +
+ + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ ); + } +} From ccbd12e286f14d5e55d37b3bfcd5cc4270a1ed40 Mon Sep 17 00:00:00 2001 From: Flosch Date: Fri, 11 May 2018 18:08:10 +0200 Subject: [PATCH 02/37] [reactstrap] Add borderless type to Table --- types/reactstrap/lib/Table.d.ts | 1 + types/reactstrap/reactstrap-tests.tsx | 39 ++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/types/reactstrap/lib/Table.d.ts b/types/reactstrap/lib/Table.d.ts index 394a1f3f40..8e59b6a13e 100644 --- a/types/reactstrap/lib/Table.d.ts +++ b/types/reactstrap/lib/Table.d.ts @@ -6,6 +6,7 @@ export type TableProps = React.HTMLAttributes & { cssModule?: CSSModule; size?: string; bordered?: boolean; + borderless?: boolean; striped?: boolean; inverse?: boolean; hover?: boolean; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 290e2657e1..61bee46edc 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -4053,7 +4053,7 @@ function GenericPropExample() { ); } -class Example118 extends React.Component { +class Example119 extends React.Component { render() { return (
@@ -4140,3 +4140,40 @@ class Example118 extends React.Component { ); } } + +class Example120 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#First NameLast NameUsername
1MarkOtto@mdo
2JacobThornton@fat
3Larrythe Bird@twitter
+ ); + } +} From 7ea7631815deea1f94f9517364a4efc8a8bae2b9 Mon Sep 17 00:00:00 2001 From: Flosch Date: Fri, 11 May 2018 18:43:48 +0200 Subject: [PATCH 03/37] [reactstrap] Add setActiveFromChild prop --- types/reactstrap/lib/Dropdown.d.ts | 3 +++ types/reactstrap/reactstrap-tests.tsx | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/types/reactstrap/lib/Dropdown.d.ts b/types/reactstrap/lib/Dropdown.d.ts index 59f827744e..12d001accd 100644 --- a/types/reactstrap/lib/Dropdown.d.ts +++ b/types/reactstrap/lib/Dropdown.d.ts @@ -14,7 +14,9 @@ export type UncontrolledProps = React.HTMLAttributes & { cssModule?: CSSModule; nav?: boolean; inNavbar?: boolean; + setActiveFromChild?: boolean; } & T; + export type UncontrolledDropdownProps = UncontrolledProps; export type Props = UncontrolledProps & { @@ -25,6 +27,7 @@ export type Props = UncontrolledProps & { tag?: React.ReactType; addonType?: boolean | 'prepend' | 'append'; }; + export type DropdownProps = Props; declare class Dropdown extends React.Component> {} diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 61bee46edc..b59ffa377d 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -4177,3 +4177,22 @@ class Example120 extends React.Component { ); } } + +class Example120 extends React.Component { + render() { + return ( + + + Dropdown + + + Header + Action + Another Action + + Another Action + + + ); + } +} From 98ba0b7e2e9000246dab8abb9e04328a14ad1a6e Mon Sep 17 00:00:00 2001 From: Flosch Date: Fri, 11 May 2018 18:44:47 +0200 Subject: [PATCH 04/37] [reactstrap] Add DropdownMenu persist and modifiers props --- types/reactstrap/lib/DropdownMenu.d.ts | 3 +++ types/reactstrap/reactstrap-tests.tsx | 34 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/types/reactstrap/lib/DropdownMenu.d.ts b/types/reactstrap/lib/DropdownMenu.d.ts index e485fad076..814771e87f 100644 --- a/types/reactstrap/lib/DropdownMenu.d.ts +++ b/types/reactstrap/lib/DropdownMenu.d.ts @@ -1,5 +1,6 @@ import * as React from 'react'; import { CSSModule } from '../index'; +import { Popper } from './Popper'; export type DropdownMenuProps = React.HTMLAttributes & { tag?: React.ReactType; @@ -7,6 +8,8 @@ export type DropdownMenuProps = React.HTMLAttributes & { className?: string; cssModule?: CSSModule; flip?: boolean; + modifiers?: Popper.Modifiers; + persist?: boolean; } & T; declare class DropdownMenu extends React.Component> {} diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index b59ffa377d..05974e77d6 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -4196,3 +4196,37 @@ class Example120 extends React.Component { ); } } + +class Example121 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + dropdownOpen: false + }; + } + + toggle() { + this.setState({ + dropdownOpen: !this.state.dropdownOpen + }); + } + + render() { + return ( + + + Dropdown + + + Header + Action + Another Action + + Another Action + + + ); + } +} From 14dc64eac5270e797e1bbb5eb7223a3cf568375c Mon Sep 17 00:00:00 2001 From: Flosch Date: Sat, 12 May 2018 18:00:01 +0200 Subject: [PATCH 05/37] [reactstrap] Bump to 6.0 --- types/reactstrap/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/reactstrap/index.d.ts b/types/reactstrap/index.d.ts index a42e7b6723..355ed59841 100644 --- a/types/reactstrap/index.d.ts +++ b/types/reactstrap/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for reactstrap 5.0 +// Type definitions for reactstrap 6.0 // Project: https://github.com/reactstrap/reactstrap#readme // Definitions by: Ali Hammad Baig // Marco Falkenberg From 9afbbb00fb842f7f8cc54eacac9cf4b9e50b9ce9 Mon Sep 17 00:00:00 2001 From: Flosch Date: Wed, 6 Jun 2018 16:26:42 +0200 Subject: [PATCH 06/37] Correct tests --- types/reactstrap/reactstrap-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 05974e77d6..2167922704 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -4178,7 +4178,7 @@ class Example120 extends React.Component { } } -class Example120 extends React.Component { +class Example121 extends React.Component { render() { return ( @@ -4197,7 +4197,7 @@ class Example120 extends React.Component { } } -class Example121 extends React.Component { +class Example122 extends React.Component { constructor(props: any) { super(props); From 83315b7319034ff1a5a3ae9d4e50c327e5718e9d Mon Sep 17 00:00:00 2001 From: Flosch Date: Wed, 6 Jun 2018 16:33:31 +0200 Subject: [PATCH 07/37] Fix CustomInput export typo --- types/reactstrap/index.d.ts | 4 ++-- types/reactstrap/lib/CustomInput.d.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/reactstrap/index.d.ts b/types/reactstrap/index.d.ts index 355ed59841..45f885b172 100644 --- a/types/reactstrap/index.d.ts +++ b/types/reactstrap/index.d.ts @@ -101,8 +101,8 @@ export { CollapseProps } from './lib/Collapse'; import { default as Container_ } from './lib/Container'; export class Container extends Container_ {} export { ContainerProps } from './lib/Container'; -export { default as CustomInput_ } from './lib/CustomInput'; -export class CustomerInput extends CustomInput_ {}; +import { default as CustomInput_ } from './lib/CustomInput'; +export class CustomInput extends CustomInput_ {} export { CustomInputProps } from './lib/CustomInput'; import { default as Dropdown_ } from './lib/Dropdown'; export class Dropdown extends Dropdown_ {} diff --git a/types/reactstrap/lib/CustomInput.d.ts b/types/reactstrap/lib/CustomInput.d.ts index ff1d196667..f2629a8da3 100644 --- a/types/reactstrap/lib/CustomInput.d.ts +++ b/types/reactstrap/lib/CustomInput.d.ts @@ -18,5 +18,5 @@ export type CustomInputProps = React.InputHTMLAttributes extends React.Component> {} +declare class CustomInput extends React.Component> {} export default CustomInput; From 3d26b490c53a41596cb2bcf86d6d752c7b3cb97d Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Wed, 6 Jun 2018 16:57:10 -0700 Subject: [PATCH 08/37] Event class documentation --- types/office-js/index.d.ts | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 5af6916816..4d06e7b764 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -523,7 +523,7 @@ declare namespace Office { */ name: string; } - export namespace AddinCommands { + namespace AddinCommands { /** * The event object is passed as a parameter to add-in functions invoked by UI-less command buttons. The object allows the add-in to identify which button was clicked and to signal the host that it has completed its processing. * @@ -539,8 +539,13 @@ declare namespace Office { * * Applicable Outlook mode: Compose or Read */ - export interface Event { + interface Event { + /** + * Information about the control that triggered calling this function + */ + source:Source; + /** * Indicates that the add-in has completed processing that was triggered by an add-in command button or event handler. * @@ -561,6 +566,17 @@ declare namespace Office { */ completed(options?: any): void; } + + /** + * Encapsulates source data for add-in events. + */ + interface Source { + + /** + * The id of the control that triggered calling this function. The id comes from the manifest and is the unique ID of your Office Add-in as a GUID. + */ + id: string; + } } /** * Provides objects and methods that you can use to create and manipulate UI components, such as dialog boxes, in your Office Add-ins. From 405abf22d4e3f3d05e487144717154f9f8c236cb Mon Sep 17 00:00:00 2001 From: Flosch Date: Thu, 7 Jun 2018 19:04:58 +0200 Subject: [PATCH 09/37] Add CustomInput to AnyPropsExample and GenericPropsExample tests --- types/reactstrap/reactstrap-tests.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 2167922704..4516db6329 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -3753,6 +3753,7 @@ import { default as CarouselCaption_ } from './lib/CarouselCaption'; /* tslint:d import { default as Col_ } from './lib/Col'; /* tslint:disable-line: no-relative-import-in-test */ import { default as Collapse_ } from './lib/Collapse'; /* tslint:disable-line: no-relative-import-in-test */ import { default as Container_ } from './lib/Container'; /* tslint:disable-line: no-relative-import-in-test */ +import { default as CustomInput_ } from './lib/CustomInput'; /* tslint:disable-line: no-relative-import-in-test */ import { default as Dropdown_ } from './lib/Dropdown'; /* tslint:disable-line: no-relative-import-in-test */ import { default as DropdownItem_ } from './lib/DropdownItem'; /* tslint:disable-line: no-relative-import-in-test */ import { default as DropdownMenu_ } from './lib/DropdownMenu'; /* tslint:disable-line: no-relative-import-in-test */ @@ -3834,6 +3835,7 @@ function AnyPropExample() { + @@ -3920,6 +3922,7 @@ class CarouselCaptionGeneric extends CarouselCaption {} class ColGeneric extends Col {} class CollapseGeneric extends Collapse {} class ContainerGeneric extends Container {} +class CustomInputGeneric extends CustomInput {} class DropdownGeneric extends Dropdown {} class DropdownItemGeneric extends DropdownItem {} class DropdownMenuGeneric extends DropdownMenu {} @@ -4001,6 +4004,7 @@ function GenericPropExample() { + From 03041459989ac55f3031e9bef0492482a5575f91 Mon Sep 17 00:00:00 2001 From: Flosch Date: Thu, 7 Jun 2018 22:49:21 +0200 Subject: [PATCH 10/37] Replace local Popper typings by popper.js dependency --- types/reactstrap/lib/DropdownMenu.d.ts | 2 +- types/reactstrap/lib/Popover.d.ts | 2 +- types/reactstrap/lib/Popper.d.ts | 134 ------------------------- types/reactstrap/lib/Tooltip.d.ts | 2 +- types/reactstrap/package.json | 6 ++ 5 files changed, 9 insertions(+), 137 deletions(-) delete mode 100644 types/reactstrap/lib/Popper.d.ts create mode 100644 types/reactstrap/package.json diff --git a/types/reactstrap/lib/DropdownMenu.d.ts b/types/reactstrap/lib/DropdownMenu.d.ts index 814771e87f..fedb12f4c3 100644 --- a/types/reactstrap/lib/DropdownMenu.d.ts +++ b/types/reactstrap/lib/DropdownMenu.d.ts @@ -1,6 +1,6 @@ import * as React from 'react'; +import * as Popper from 'popper.js'; import { CSSModule } from '../index'; -import { Popper } from './Popper'; export type DropdownMenuProps = React.HTMLAttributes & { tag?: React.ReactType; diff --git a/types/reactstrap/lib/Popover.d.ts b/types/reactstrap/lib/Popover.d.ts index d1a0d56127..2af1a3bed9 100644 --- a/types/reactstrap/lib/Popover.d.ts +++ b/types/reactstrap/lib/Popover.d.ts @@ -1,6 +1,6 @@ import * as React from 'react'; +import * as Popper from 'popper.js'; import { CSSModule } from '../index'; -import { Popper } from './Popper'; export type PopoverProps = React.HTMLAttributes & { isOpen?: boolean; diff --git a/types/reactstrap/lib/Popper.d.ts b/types/reactstrap/lib/Popper.d.ts deleted file mode 100644 index b28c61bd30..0000000000 --- a/types/reactstrap/lib/Popper.d.ts +++ /dev/null @@ -1,134 +0,0 @@ -// Type definitions for popper.js 1.10 -// Project: https://github.com/FezVrasta/popper.js/ -// Definitions by: edcarroll , ggray , rhysd , joscha , seckardt , marcfallows - -// This file only declares the public portions of the API. -// It should not define internal pieces such as utils or modifier details. -// It has been copied from: https://raw.githubusercontent.com/FezVrasta/popper.js/master/packages/popper/index.d.ts - -export as namespace Popper; - -export type Position = "top" | "right" | "bottom" | "left"; - -export type Placement = - | "auto-start" - | "auto" - | "auto-end" - | "top-start" - | "top" - | "top-end" - | "right-start" - | "right" - | "right-end" - | "bottom-end" - | "bottom" - | "bottom-start" - | "left-end" - | "left" - | "left-start"; - -export type Boundary = "scrollParent" | "viewport" | "window"; - -export type ModifierFn = (data: Data, options: Object) => Data; - -export interface BaseModifier { - order?: number; - enabled?: boolean; - fn?: ModifierFn; -} - -export interface Modifiers { - shift?: BaseModifier; - offset?: BaseModifier & { - offset?: number | string; - }; - preventOverflow?: BaseModifier & { - priority?: Position[]; - padding?: number; - boundariesElement?: Boundary | Element; - escapeWithReference?: boolean; - }; - keepTogether?: BaseModifier; - arrow?: BaseModifier & { - element?: string | Element; - }; - flip?: BaseModifier & { - behavior?: "flip" | "clockwise" | "counterclockwise" | Position[]; - padding?: number; - boundariesElement?: Boundary | Element; - }; - inner?: BaseModifier; - hide?: BaseModifier; - applyStyle?: BaseModifier & { - onLoad?: Function; - gpuAcceleration?: boolean; - }; - computeStyle?: BaseModifier & { - gpuAcceleration?: boolean; - x?: "bottom" | "top"; - y?: "left" | "right"; - }; - [name: string]: (BaseModifier & Record) | undefined; -} - -export interface Offset { - top: number; - left: number; - width: number; - height: number; -} - -export interface Data { - instance: Popper; - placement: Placement; - originalPlacement: Placement; - flipped: boolean; - hide: boolean; - arrowElement: Element; - styles: CSSStyleDeclaration; - boundaries: Object; - offsets: { - popper: Offset; - reference: Offset; - arrow: { - top: number; - left: number; - }; - }; -} - -export interface PopperOptions { - placement?: Placement; - positionFixed: boolean; - eventsEnabled?: boolean; - modifiers?: Modifiers; - removeOnDestroy?: boolean; - onCreate?(data: Data): void; - onUpdate?(data: Data): void; -} - -export interface ReferenceObject { - clientHeight: number; - clientWidth: number; - getBoundingClientRect(): ClientRect; -} - -export class Popper { - static modifiers: (Popper.BaseModifier & { name: string })[]; - static placements: Popper.Placement[]; - static Defaults: Popper.PopperOptions; - - options: Popper.PopperOptions; - - constructor( - reference: Element | Popper.ReferenceObject, - popper: Element, - options?: Popper.PopperOptions - ); - - destroy(): void; - update(): void; - scheduleUpdate(): void; - enableEventListeners(): void; - disableEventListeners(): void; -} diff --git a/types/reactstrap/lib/Tooltip.d.ts b/types/reactstrap/lib/Tooltip.d.ts index 5cfcfcab1e..5ec05fa72f 100644 --- a/types/reactstrap/lib/Tooltip.d.ts +++ b/types/reactstrap/lib/Tooltip.d.ts @@ -1,6 +1,6 @@ import * as React from 'react'; +import * as Popper from 'popper.js'; import { CSSModule } from '../index'; -import {Popper} from './Popper'; export type UncontrolledProps = React.HTMLAttributes & { target: string | HTMLElement; diff --git a/types/reactstrap/package.json b/types/reactstrap/package.json new file mode 100644 index 0000000000..245f69cd2c --- /dev/null +++ b/types/reactstrap/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "popper.js": "^1.14.1" + } +} From 195e2da1e5205bd8726ad74dc612a97128703f81 Mon Sep 17 00:00:00 2001 From: CrossR Date: Fri, 8 Jun 2018 22:59:47 +0100 Subject: [PATCH 11/37] Update MarkedOptions for 0.4. Alphabetised options to bring in line with package docs. Also updated tests to pass, and be a bit clearer. --- types/marked/index.d.ts | 87 ++++++++++++++++++++---------------- types/marked/marked-tests.ts | 24 +++++----- 2 files changed, 62 insertions(+), 49 deletions(-) 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..8a80f2966c 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)); From 10dc3c49b11574f13962b1a1f2604b3e943c9190 Mon Sep 17 00:00:00 2001 From: CrossR Date: Sat, 9 Jun 2018 09:40:59 +0100 Subject: [PATCH 12/37] Fix lint error. --- types/marked/marked-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/marked/marked-tests.ts b/types/marked/marked-tests.ts index 8a80f2966c..e1cb63042c 100644 --- a/types/marked/marked-tests.ts +++ b/types/marked/marked-tests.ts @@ -19,7 +19,7 @@ const options: marked.MarkedOptions = { function callback(err: string, markdown: string) { console.log("Callback called!"); - return markdown + return markdown; } const myOldMarked: typeof marked = marked.setOptions(options); From d5c2d6a0e3ffb17b59ce9787907e97003739d213 Mon Sep 17 00:00:00 2001 From: Christopher Deutsch Date: Sat, 9 Jun 2018 13:03:58 -0500 Subject: [PATCH 13/37] Add `type` property for `
    ` https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement --- types/react/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 27a76a9a08..b4fb9415d3 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -1545,6 +1545,7 @@ declare namespace React { interface OlHTMLAttributes extends HTMLAttributes { reversed?: boolean; start?: number; + type?: '1' | 'a' | 'A' | 'i' | 'I'; } interface OptgroupHTMLAttributes extends HTMLAttributes { From ecf8cf915c33151b769d7b3ada256252127cf741 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1F3J099\\Brad" Date: Sun, 10 Jun 2018 15:39:09 -0400 Subject: [PATCH 14/37] Update mathjs type definitions to 4.4.2 release (from 3.2.1) --- types/mathjs/index.d.ts | 6655 +++++++++++++++++++++++----------- types/mathjs/mathjs-tests.ts | 27 +- 2 files changed, 4496 insertions(+), 2186 deletions(-) diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index cdecc3e1b4..3fa5455fe5 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -1,2252 +1,4561 @@ -// Type definitions for mathjs 3.21 -// Project: http://mathjs.org/ -// Definitions by: Ilya Shestakov , -// Andy Patterson -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// Type definitions for mathjs 4.4.2 Project: http://mathjs.org/ Definitions by: +// Ilya Shestakov , Andy Patterson +// , Brad Besserman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped TypeScript +// Version: 2.8.1 -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 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 { + // 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; - 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; - 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: object) => object; + /** + * 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: object) => 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 + | 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 (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( + 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: any | MathArray | Matrix | 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: Function | string | object): 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?: object + ): 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: boolean + ): object | 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?: ({ 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 | any, + sizes: number[] + ): any | 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): 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 { + 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 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. + */ + complex(): MathJsChain; + /** + * @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?: object): 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?: ({ 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: Unit): MathJsChain; + divide(y: number): MathJsChain; + 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): MathJsChain; + lcm(b: BigNumber): MathJsChain; + lcm(b: MathArray): MathJsChain; + lcm(b: 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; + log1p(base?: number | BigNumber | Complex): MathJsChain; + log1p(base?: number | BigNumber | Complex): MathJsChain; + log1p(base?: number | BigNumber | Complex): MathJsChain; + 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; + multiply(y: Unit): MathJsChain; + multiply(y: number): MathJsChain; + 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): MathJsChain; + bitOr(y: BigNumber): MathJsChain; + bitOr(y: MathArray): MathJsChain; + bitOr(y: 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 + */ + random(max?: number): number; + 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 + */ + randomInt(max?: number): MathJsChain; + 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. + */ + max(): MathJsChain; + /** + * @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. + */ + mean(): MathJsChain; + /** + * @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. + */ + min(): MathJsChain; + /** + * @param dim The minimum over the selected dimension + * @returns The minimum value + */ + 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(...). + * @returns The variance + */ + var(): MathJsChain; + /** + * @param normalization normalization Determines how to normalize the + * variance. Choose ‘unbiased’ (default), ‘uncorrected’, or ‘biased’. + * Default value: ‘unbiased’. + */ + 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..221365e1df 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,9 +108,8 @@ 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 @@ -175,6 +174,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 +197,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 +209,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 +238,7 @@ 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 d: math.Matrix = (c).subset(math.index(1, 0)); } // get a sub matrix @@ -282,7 +283,7 @@ 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 d = math.transpose((c)); const e = math.multiply(d, a); } @@ -296,11 +297,11 @@ Units examples const b = math.unit('0.1m'); // 100 mm // creating units - math.createUnit('foo'); + math.createUnit('foo', '12 meters'); 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', { From fb1af8608b3db6abed222846c29b2bad4691d14e Mon Sep 17 00:00:00 2001 From: "DESKTOP-1F3J099\\Brad" Date: Sun, 10 Jun 2018 18:03:10 -0400 Subject: [PATCH 15/37] Fixes based on PR comments --- types/mathjs/index.d.ts | 43 +++++++++++++++++++++--------------- types/mathjs/mathjs-tests.ts | 13 +++++------ 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index 3fa5455fe5..a2e2cb8b6b 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -1,17 +1,18 @@ -// Type definitions for mathjs 4.4.2 Project: http://mathjs.org/ Definitions by: -// Ilya Shestakov , Andy Patterson -// , Brad Besserman -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped TypeScript -// Version: 2.8.1 +// Type definitions for mathjs 4.4.2 +// Project: http://mathjs.org/ Definitions by: +// Ilya Shestakov , +// Andy Patterson , +// Brad Besserman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8.1 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 @@ -62,7 +63,7 @@ declare namespace math { * randomly seed. * @returns Returns the current configuration */ - config: (options: object) => object; + config: (options: ConfigOptions) => ConfigOptions; /** * Create a typed-function which checks the types of the arguments and * can match them against multiple provided signatures. The @@ -73,7 +74,7 @@ declare namespace math { * @param signatures Object with one or multiple function signatures * @returns The created typed-function. */ - typed: (name: string, signatures: object) => any; + typed: (name: string, signatures: Record) => Function; /************************************************************************* * Construction functions @@ -163,13 +164,7 @@ declare namespace math { /** * Create a user-defined unit and register it with the Unit type. * @param units Definition of the unit - * @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. + * @param options * @returns The new unit */ createUnit( @@ -2674,6 +2669,9 @@ declare namespace math { } interface CreateUnitOptions { + prefixes?: "none" | "short" | "long" | "binary_short" | "binary_long"; + aliases?: string[]; + offset?: number; override?: boolean; } @@ -2937,6 +2935,15 @@ declare namespace math { toJSON(): string; } + interface ConfigOptions { + epsilon?: number; + matrix?: string; + number?: string; + precision?: number; + parenthesis?: string; + randomSeed?: string; + } + interface MathJsChain { done(): any; diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 221365e1df..455b1fdaee 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -114,9 +114,7 @@ Complex numbers examples // 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,7 +173,7 @@ Expressions examples // get and set variables and functions { parser.eval('x = 7 / 2'); // 3.5 - parser.eval('x + 3'); // 6.5 + parser.eval('x + 3'); // 6.5 parser.eval('f(x, y) = x^y'); // f(x, y) parser.eval('f(2, 3)'); // 8 @@ -238,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)); + let f: math.Matrix; + const d: math.Matrix = f.subset(math.index(1, 0)); } // get a sub matrix @@ -297,7 +296,7 @@ Units examples const b = math.unit('0.1m'); // 100 mm // creating units - math.createUnit('foo', '12 meters'); + math.createUnit('foo'); math.createUnit('furlong', '220 yards'); math.createUnit('furlong', '220 yards', {override: true}); math.createUnit('testunit', {definition: '0.555556 kelvin', offset: 459.67}); @@ -310,7 +309,7 @@ Units examples prefixes: 'long' }, {override: true}); math.createUnit({ - foo: { + foo_2: { prefixes: 'long' }, bar: '40 foo', From 230bb5bec8137d9cd85c404fdddba87e1c29bb16 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1F3J099\\Brad" Date: Sun, 10 Jun 2018 18:08:38 -0400 Subject: [PATCH 16/37] Fix header --- types/mathjs/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index a2e2cb8b6b..9e3d14d372 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for mathjs 4.4.2 -// Project: http://mathjs.org/ Definitions by: -// Ilya Shestakov , +// Project: http://mathjs.org/ +// Definitions by: Ilya Shestakov , // Andy Patterson , // Brad Besserman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 42dd2665ea9f281f10d8161e95319cacde2f4287 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1F3J099\\Brad" Date: Sun, 10 Jun 2018 18:15:36 -0400 Subject: [PATCH 17/37] Update Typescript version in header --- types/mathjs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index 9e3d14d372..28bc0cc65a 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -4,7 +4,7 @@ // Andy Patterson , // Brad Besserman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8.1 +// TypeScript Version: 2.2 import { Decimal } from "decimal.js"; From bbd338282523ada426469735e890a04cef906d0c Mon Sep 17 00:00:00 2001 From: "DESKTOP-1F3J099\\Brad" Date: Sun, 10 Jun 2018 18:19:21 -0400 Subject: [PATCH 18/37] Update rationalize definition --- types/mathjs/index.d.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index 28bc0cc65a..fd9c92b686 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -435,11 +435,8 @@ declare namespace math { * expression node (default) * @returns The rational polynomial of expr */ - rationalize( - expr: MathNode | string, - optional: object | boolean, - detailed: boolean - ): object | MathNode; + 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. From 21d6b26b9aefa23b3c43dd1a9da7e44239061b5c Mon Sep 17 00:00:00 2001 From: "DESKTOP-1F3J099\\Brad" Date: Sun, 10 Jun 2018 18:38:37 -0400 Subject: [PATCH 19/37] Fix Travis CI Build Failures --- types/mathjs/index.d.ts | 43 ++++++++++++----------------------------- 1 file changed, 12 insertions(+), 31 deletions(-) diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index fd9c92b686..8a4e9c628b 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -275,7 +275,7 @@ declare namespace math { * @returns The created string */ string( - value: any | MathArray | Matrix | null + value: MathType | null ): string | MathArray | Matrix; /** @@ -450,7 +450,7 @@ declare namespace math { */ simplify( expr: MathNode | string, - rules?: ({ l: string; r: string } | string | ((node: MathNode) => MathNode))[], + rules?: Array<({ l: string; r: string } | string | ((node: MathNode) => MathNode))>, scope?: object ): MathNode; @@ -1112,8 +1112,8 @@ declare namespace math { * @returns Returns the distance from two/three points */ distance( - x: MathArray | Matrix | Object, - y: MathArray | Matrix | Object + x: MathArray | Matrix | object, + y: MathArray | Matrix | object ): number | BigNumber; /** @@ -1411,9 +1411,9 @@ declare namespace math { * @returns A reshaped clone of matrix x */ reshape( - x: MathArray | Matrix | any, + x: MathArray | Matrix, sizes: number[] - ): any | MathArray | Matrix; + ): MathArray | Matrix; /** * Resize a matrix @@ -2965,13 +2965,10 @@ declare namespace math { /** * Create a complex value or convert a value to a complex value. - */ - complex(): MathJsChain; - /** * @param im Argument specifying the imaginary part of the complex * number */ - complex(im: number): MathJsChain; + complex(im?: number): MathJsChain; /** * Create a user-defined unit and register it with the Unit type. @@ -3169,7 +3166,7 @@ declare namespace math { * @param scope Scope to variables */ simplify( - rules?: ({ l: string; r: string } | string | ((node: MathNode) => MathNode))[], + rules?: Array<({ l: string; r: string } | string | ((node: MathNode) => MathNode))>, scope?: object ): MathJsChain; @@ -3241,9 +3238,7 @@ declare namespace math { * the inverse of y: x * inv(y). * @param y Denominator */ - divide(y: Unit): MathJsChain; - divide(y: number): MathJsChain; - divide(y: MathType): MathJsChain; + divide(y: Unit | Number | MathType): MathJsChain; /** * Divide two matrices element wise. The function accepts both matrices @@ -3309,10 +3304,7 @@ declare namespace math { * the function is evaluated element wise. * @param b An integer number */ - lcm(b: number): MathJsChain; - lcm(b: BigNumber): MathJsChain; - lcm(b: MathArray): MathJsChain; - lcm(b: Matrix): MathJsChain; + lcm(b: number | BigNumber | MathArray | Matrix): MathJsChain; /** * Calculate the logarithm of a value. For matrices, the function is @@ -3333,11 +3325,6 @@ declare namespace math { * evaluated element wise. */ log1p(base?: number | BigNumber | Complex): MathJsChain; - log1p(base?: number | BigNumber | Complex): MathJsChain; - log1p(base?: number | BigNumber | Complex): MathJsChain; - log1p(base?: number | BigNumber | Complex): MathJsChain; - 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. @@ -3358,9 +3345,6 @@ declare namespace math { * @param y The second value to multiply */ multiply(y: MathType): MathJsChain; - multiply(y: Unit): MathJsChain; - multiply(y: number): MathJsChain; - multiply(y: MathType): MathJsChain; /** * Calculate the norm of a number, vector or matrix. The second @@ -3467,10 +3451,7 @@ declare namespace math { * print base. * @param y Second value to or */ - bitOr(y: number): MathJsChain; - bitOr(y: BigNumber): MathJsChain; - bitOr(y: MathArray): MathJsChain; - bitOr(y: Matrix): MathJsChain; + bitOr(y: number | BigNumber | MathArray | Matrix): MathJsChain; /** * Bitwise XOR two values, x ^ y. For matrices, the function is @@ -3585,7 +3566,7 @@ declare namespace math { * c) * @param y Coordinates of the second point */ - distance(y: MathArray | Matrix | Object): MathJsChain; + distance(y: MathArray | Matrix | object): MathJsChain; /** * Calculates the point of intersection of two lines in two or three From 4d4c9a47d755466172d791f40b32ad7d5fd12e26 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1F3J099\\Brad" Date: Sun, 10 Jun 2018 19:32:09 -0400 Subject: [PATCH 20/37] Fix Travis CI Build Failure Pt. 2 --- types/mathjs/index.d.ts | 63 ++++++++++++++++-------------------- types/mathjs/mathjs-tests.ts | 7 ++-- 2 files changed, 31 insertions(+), 39 deletions(-) diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index 8a4e9c628b..a09b23bae9 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for mathjs 4.4.2 +// Type definitions for mathjs 4.4 // Project: http://mathjs.org/ // Definitions by: Ilya Shestakov , // Andy Patterson , @@ -74,7 +74,7 @@ declare namespace math { * @param signatures Object with one or multiple function signatures * @returns The created typed-function. */ - typed: (name: string, signatures: Record) => Function; + typed: (name: string, signatures: Record any>) => ((...args: any[]) => any); /************************************************************************* * Construction functions @@ -327,7 +327,7 @@ declare namespace math { * @param search A function or function name for which to get help * @returns A help object */ - help(search: Function | string | object): Help; + help(search: () => any): Help; /** * Parse an expression. Returns a node tree, which can be evaluated by @@ -364,7 +364,7 @@ declare namespace math { derivative( expr: MathNode | string, variable: MathNode | string, - options?: object + options?: {simplify: boolean} ): MathNode; /** @@ -1297,7 +1297,7 @@ declare namespace math { */ filter( x: Matrix | MathArray, - test: ((value:any, index: any, matrix: Matrix | MathArray)=>Matrix | MathArray) | RegExp + test: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray) | RegExp ): Matrix | MathArray; /** @@ -1315,7 +1315,7 @@ declare namespace math { * 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; + forEach(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => void)): void; /** * Calculate the inverse of a square matrix. @@ -1343,7 +1343,7 @@ declare namespace math { * 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; + 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 @@ -1448,7 +1448,7 @@ declare namespace math { */ sort( x: Matrix | MathArray, - compare: ((a:any, b:any)=>number) | "asc" | "desc" | "natural" + compare: ((a: any, b: any) => number) | "asc" | "desc" | "natural" ): Matrix | MathArray; /** @@ -2129,7 +2129,7 @@ declare namespace math { format( value: any, options?: FormatOptions | number | ((item: any) => string), - callback?: ((value:any)=>string) + callback?: ((value: any) => string) ): string; /** @@ -2518,7 +2518,7 @@ declare namespace math { * boolean. Returns false for other types. Throws an error in case of * unknown types. */ - isNumeric(x: any): boolean; + isNumeric(x: any): x is number | BigNumber | Fraction | boolean; /** * Test whether a value is positive: larger than zero. The function @@ -2600,7 +2600,7 @@ declare namespace math { ): void; toArray(): MathArray | Matrix; valueOff(): MathArray | Matrix; - format(options?: FormatOptions | number | ((value:any)=>string)): string; + format(options?: FormatOptions | number | ((value: any) => string)): string; toString(): string; toJSON(): any; diagonal(k?: number | BigNumber): any[]; @@ -3107,7 +3107,7 @@ declare namespace math { * @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?: object): MathJsChain; + derivative(variable: MathNode | string, options?: {simplify: boolean}): MathJsChain; /** * Solves the linear equation system by forwards substitution. Matrix @@ -3155,7 +3155,7 @@ declare namespace math { * @param detailed optional True if return an object, false if return * expression node (default) */ - rationalize(optional: object | boolean, detailed: boolean): MathJsChain; + rationalize(optional?: object | boolean, detailed?: boolean): MathJsChain; /** * Simplify an expression tree. @@ -3238,7 +3238,7 @@ declare namespace math { * the inverse of y: x * inv(y). * @param y Denominator */ - divide(y: Unit | Number | MathType): MathJsChain; + divide(y: MathType): MathJsChain; /** * Divide two matrices element wise. The function accepts both matrices @@ -3698,7 +3698,7 @@ declare namespace math { /** * Filter the items in an array or one dimensional matrix. */ - filter(test: ((value:any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)| RegExp): MathJsChain; + filter(test: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)| RegExp): MathJsChain; /** * Flatten a multi dimensional matrix into a single dimensional matrix. @@ -3709,7 +3709,7 @@ declare namespace math { * 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; + forEach(callback: ((value: any, index: any, matrix: Matrix | MathArray) => void)): MathJsChain; /** * Calculate the inverse of a square matrix. @@ -3729,7 +3729,7 @@ declare namespace math { * 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; + 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 @@ -3800,7 +3800,7 @@ declare namespace math { * 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; + sort(compare: ((a: any, b: any) => number) | "asc" | "desc" | "natural"): MathJsChain; /** * Calculate the principal square root of a square matrix. The principal @@ -3918,8 +3918,10 @@ declare namespace math { * @param min Minimum boundary for the random value, included * @param max Maximum boundary for the random value, excluded */ - random(max?: number): number; - random(min?: number, max?: number): MathJsChain; + // 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 @@ -3927,8 +3929,10 @@ declare namespace math { * @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; - randomInt(min?: number, max?: number): MathJsChain; + // tslint:disable-next-line unified-signatures + randomInt(min: number, max: number): MathJsChain; /************************************************************************* * Relational functions @@ -4146,9 +4150,6 @@ declare namespace math { * 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(): MathJsChain; - /** * @param dim The maximum over the selected dimension */ max(dim?: number): MathJsChain; @@ -4158,9 +4159,6 @@ declare namespace math { * 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(): MathJsChain; - /** * @param dim The mean over the selected dimension */ mean(dim?: number): MathJsChain; @@ -4180,11 +4178,7 @@ declare namespace math { * 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(): MathJsChain; - /** * @param dim The minimum over the selected dimension - * @returns The minimum value */ min(dim?: number): MathJsChain; @@ -4257,13 +4251,10 @@ declare namespace math { * 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(...). - * @returns The variance - */ - var(): MathJsChain; - /** * @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" @@ -4287,7 +4278,7 @@ declare namespace math { format( value: any, options?: FormatOptions | number | ((item: any) => string), - callback?: ((value:any)=>string) + callback?: ((value: any) => string) ): MathJsChain; /** diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 455b1fdaee..4db5261f9f 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -236,7 +236,7 @@ Matrices examples b.subset(math.index(1, [0, 1]), [[7, 8]]); const c = math.multiply(a, b); - let f: math.Matrix; + const f: math.Matrix = math.matrix([1, 0]); const d: math.Matrix = f.subset(math.index(1, 0)); } @@ -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); } /* From d419bddbce227a24126bce0581728d1f70643479 Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Mon, 11 Jun 2018 15:57:22 -0700 Subject: [PATCH 21/37] Office function descriptions --- types/office-js/index.d.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 4d06e7b764..d9a54c2331 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -240,8 +240,20 @@ declare namespace Office { */ var context: Context; /** - * This method is called after the Office API was loaded. - * @param reason Indicates how the app was initialized + * Occurs when the runtime environment is loaded and the add-in is ready to start interacting with the application and hosted document. + * + * The reason parameter of the initialize event listener function returns an `InitializationReason` enumeration value that specifies how initialization occurred. A task pane or content add-in can be initialized in two ways: + * + * - The user just inserted it from Recently Used Add-ins section of the Add-in drop-down list on the Insert tab of the ribbon in the Office host application, or from Insert add-in dialog box. + * + * - The user opened a document that already contains the add-in. + * + * *Note*: The reason parameter of the initialize event listener function only returns an `InitializationReason` enumeration value for task pane and content add-ins. It does not return a value for Outlook add-ins. + * + * @remarks + * Hosts: Access, Excel, Outlook, PowerPoint, Project, Word + * + * @param reason Indicates how the app was initialized. */ function initialize(reason: InitializationReason): void; /** @@ -252,8 +264,9 @@ declare namespace Office { */ function onReady(callback?: (info: { host: HostType, platform: PlatformType }) => any): Promise<{ host: HostType, platform: PlatformType }>; /** - * Indicates if the large namespace for objects will be used or not. - * @param useShortNamespace Indicates if 'true' that the short namespace will be used + * Toggles on and off the `Office` alias for the full `Microsoft.Office.WebExtension` namespace. + * + * @param useShortNamespace True to use the shortcut alias; otherwise false to disable it. The default is true. */ function useShortNamespace(useShortNamespace: boolean): void; // Enumerations From caf2c31222ccc68c405b0a5f566d7b5cdbb875c9 Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Mon, 11 Jun 2018 15:59:34 -0700 Subject: [PATCH 22/37] Office function descriptions --- types/office-js/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index d9a54c2331..17bb3dcb55 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -266,6 +266,9 @@ declare namespace Office { /** * Toggles on and off the `Office` alias for the full `Microsoft.Office.WebExtension` namespace. * + * @remarks + * Hosts: Access, Excel, Outlook, PowerPoint, Project, Word + * * @param useShortNamespace True to use the shortcut alias; otherwise false to disable it. The default is true. */ function useShortNamespace(useShortNamespace: boolean): void; From ba196342a208dfbae5e04ec4d24db0b2205ffc9d Mon Sep 17 00:00:00 2001 From: Joshua Goldberg Date: Tue, 12 Jun 2018 01:43:42 -0700 Subject: [PATCH 23/37] Cleaned up & partially expanded Jest's jest-tests.ts The old file was a mix of pure types tests and copied real-world behavior examples. It was quite confusing. This organizes the contents into what is mostly a superset of the existing tests. --- types/jest/jest-tests.ts | 1623 +++++++++++++++++++++----------------- 1 file changed, 898 insertions(+), 725 deletions(-) diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index e154561c86..bfaaec6259 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -1,762 +1,935 @@ -// 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 workTestFramework = async (testFramework: jest.TestFramework): Promise => { + return testFramework( + { + 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, + }, + { + 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"], + }, + { + 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 {}; + }, + }, + {}, + "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); - - 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"); -}); +matchersUtil2 = matchersUtil1; From 79c3a025a30bc24824a22d9175f05eb550c25a3f Mon Sep 17 00:00:00 2001 From: Dobes Vandermeer Date: Tue, 12 Jun 2018 17:14:34 -0700 Subject: [PATCH 24/37] Update generic type of map to reflect variable output type The output type of the contents of the Cursor should match the return type of the mapping function. See also https://github.com/DefinitelyTyped/DefinitelyTyped/issues/15991 --- types/mongodb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 98aa2daca8..1ca0c2a8b8 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 */ From cc01b622739263f8871de60503be4a5c83a941ae Mon Sep 17 00:00:00 2001 From: Jose Colella Date: Wed, 13 Jun 2018 10:58:35 -0400 Subject: [PATCH 25/37] Add optional family type to CoreOptions. References issue https://github.com/request/request-promise-native/issues/6 --- types/request/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index 71f41ff794..f9ee41842b 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -139,6 +139,7 @@ declare namespace request { method?: string; headers?: Headers; body?: any; + family?: number; followRedirect?: boolean | ((response: http.IncomingMessage) => boolean); followAllRedirects?: boolean; followOriginalHttpMethod?: boolean; From 6ee3480792a0df733e2e4bc28a1729c7738a6140 Mon Sep 17 00:00:00 2001 From: Jose Colella Date: Wed, 13 Jun 2018 11:22:18 -0400 Subject: [PATCH 26/37] Add name and github link to definitionsby --- types/request/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index f9ee41842b..51cb7919a7 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -7,6 +7,7 @@ // Christopher Currens , // Jon Stevens , // Matt R. Wilson +// Jose Colella // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From fbc13e7029c8217353ae1b03754bb7b3c2de9022 Mon Sep 17 00:00:00 2001 From: Rafael Tavares Date: Wed, 6 Jun 2018 18:03:05 -0300 Subject: [PATCH 27/37] Updates reCAPTCHA v2 definitions according to the docs --- types/grecaptcha/grecaptcha-tests.ts | 3 +++ types/grecaptcha/index.d.ts | 37 +++++++++++++++++++++------- 2 files changed, 31 insertions(+), 9 deletions(-) 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; } } From f3ac309bad9b6df22f5b4f92deb57319b088d0f7 Mon Sep 17 00:00:00 2001 From: jafaircl Date: Wed, 13 Jun 2018 16:29:52 -0400 Subject: [PATCH 28/37] Fix getStatsFor type getStatsFor is not a DayOfWeek string it is a DateRange string --- types/google-adwords-scripts/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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; } From 0fe7605dcf3277c14634d4a97da9a6982109ba1d Mon Sep 17 00:00:00 2001 From: "DESKTOP-1F3J099\\Brad" Date: Wed, 13 Jun 2018 17:11:07 -0400 Subject: [PATCH 29/37] Fix merge conflicts --- types/mathjs/index.d.ts | 9 +++++++++ types/mathjs/mathjs-tests.ts | 12 ++++++++++++ 2 files changed, 21 insertions(+) diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index a09b23bae9..eda68ade10 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -44,6 +44,7 @@ declare namespace math { version: string; expression: MathNode; + json: MathJsJson; /************************************************************************* * Core functions @@ -96,6 +97,7 @@ declare namespace math { | MathArray | Matrix | boolean + | Fraction | null ): BigNumber; @@ -2941,6 +2943,13 @@ declare namespace math { 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 { done(): any; diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 4db5261f9f..c1e32a7d9a 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -366,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 +} From 5c62309e20701f3f33321921c69255dd79cce37b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Piotr=20=C5=81uczak?= Date: Wed, 13 Jun 2018 23:33:08 +0200 Subject: [PATCH 30/37] [express-socket.io-session] Added "session" and "sessionID" to SocketIO.Socket.handshake --- .../express-socket.io-session-tests.ts | 16 ++++ types/express-socket.io-session/index.d.ts | 7 ++ types/socket.io/index.d.ts | 89 ++++++++++--------- 3 files changed, 68 insertions(+), 44 deletions(-) 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/socket.io/index.d.ts b/types/socket.io/index.d.ts index 6f7c0ef321..4d6adc529c 100644 --- a/types/socket.io/index.d.ts +++ b/types/socket.io/index.d.ts @@ -553,49 +553,7 @@ declare namespace SocketIO { /** * The object used when negociating the handshake */ - handshake: { - /** - * The headers passed along with the request. e.g. 'host', - * 'connection', 'accept', 'referer', 'cookie' - */ - headers: any; - - /** - * The current time, as a string - */ - time: string; - - /** - * The remote address of the connection request - */ - address: string; - - /** - * Is this a cross-domain request? - */ - xdomain: boolean; - - /** - * Is this a secure request? - */ - secure: boolean; - - /** - * The timestamp for when this was issued - */ - issued: number; - - /** - * The request url - */ - url: string; - - /** - * Any query string parameters in the request url - */ - query: any; - }; - + handshake: Handshake; /** * Sets the 'json' flag when emitting an event */ @@ -629,7 +587,7 @@ declare namespace SocketIO { /** * Registers a middleware, which is a function that gets executed for every incoming Packet and receives as parameter the packet and a function to optionally defer execution to the next registered middleware. - * + * * Errors passed to middleware callbacks are sent as special error packets to clients. */ use( fn: ( packet: Packet, next: (err?: any) => void ) => void ): Socket; @@ -690,6 +648,49 @@ declare namespace SocketIO { compress( compress: boolean ): Socket; } + interface Handshake { + /** + * The headers passed along with the request. e.g. 'host', + * 'connection', 'accept', 'referer', 'cookie' + */ + headers: any; + + /** + * The current time, as a string + */ + time: string; + + /** + * The remote address of the connection request + */ + address: string; + + /** + * Is this a cross-domain request? + */ + xdomain: boolean; + + /** + * Is this a secure request? + */ + secure: boolean; + + /** + * The timestamp for when this was issued + */ + issued: number; + + /** + * The request url + */ + url: string; + + /** + * Any query string parameters in the request url + */ + query: any; + } + /** * The interface used when dealing with rooms etc */ From bdc48075dce41a2bf857068430a6f5885f431bca Mon Sep 17 00:00:00 2001 From: Joshua Goldberg Date: Wed, 13 Jun 2018 14:42:30 -0700 Subject: [PATCH 31/37] Added tests for YouTube typings --- types/youtube/tsconfig.json | 3 +- types/youtube/youtube-tests.ts | 282 +++++++++++++++++++++++++++++++++ 2 files changed, 284 insertions(+), 1 deletion(-) create mode 100644 types/youtube/youtube-tests.ts diff --git a/types/youtube/tsconfig.json b/types/youtube/tsconfig.json index 82e6284376..e263b7845c 100644 --- a/types/youtube/tsconfig.json +++ b/types/youtube/tsconfig.json @@ -18,6 +18,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "youtube-tests.ts" ] } \ No newline at end of file diff --git a/types/youtube/youtube-tests.ts b/types/youtube/youtube-tests.ts new file mode 100644 index 0000000000..6452d720db --- /dev/null +++ b/types/youtube/youtube-tests.ts @@ -0,0 +1,282 @@ +const players: YT.Player[] = [ + new YT.Player(document.body, {}), + new YT.Player(document.body, { + width: 100, + height: 100, + }), + new YT.Player("id", { + width: "100%", + height: "100%", + videoId: "videoId", + playerVars: {}, + events: {}, + }), + new YT.Player("id", { + playerVars: { + autohide: YT.AutoHide.AlwaysVisible, + autoplay: YT.AutoPlay.AutoPlay, + cc_load_policy: YT.ClosedCaptionsLoadPolicy.ForceOn, + color: "red", + controls: YT.Controls.Hide, + disablekb: YT.KeyboardControls.Disable, + enablejsapi: YT.JsApi.Disable, + end: 9001, + fs: YT.FullscreenButton.Hide, + hl: "en-us", + iv_load_policy: YT.IvLoadPolicy.Hide, + list: "my query", + listType: "search", + loop: YT.Loop.Loop, + modestbranding: YT.ModestBranding.Full, + origin: "localhost", + playlist: "1,2", + playsinline: YT.PlaysInline.Fullscreen, + rel: YT.RelatedVideos.Hide, + showinfo: YT.ShowInfo.Hide, + start: 0, + }, + }), + new YT.Player("id", { + events: { + onReady(event: YT.PlayerEvent) { + const targetPlayer: YT.Player = event.target; + }, + onStateChange(event: YT.OnStateChangeEvent) { + const targetPlayer: YT.Player = event.target; + const playerData: YT.PlayerState = event.data; + }, + onPlaybackQualityChange(event: YT.OnPlaybackQualityChangeEvent) { + const targetPlayer: YT.Player = event.target; + const newQuality: string = event.data; + }, + onPlaybackRateChange(event: YT.OnPlaybackRateChangeEvent) { + const targetPlayer: YT.Player = event.target; + const newRate: number = event.data; + }, + onError(event: YT.OnErrorEvent) { + const targetPlayer: YT.Player = event.target; + const error: YT.PlayerError = event.data; + }, + onApiChange(event: YT.PlayerEvent) { + const targetPlayer: YT.Player = event.target; + }, + } + }), +]; + +const ensureNumeric = () => {}; + +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); +ensureNumeric(); + +const ensureString = () => {} + +ensureString(); +ensureString(); +ensureString(); +ensureString(); +ensureString(); +ensureString(); + +const player = new YT.Player("", {}); + +player.cueVideoById("id"); +player.cueVideoById("id", 0); +player.cueVideoById("id", 9001, "default"); +player.cueVideoById("id", 9001, "small"); + +player.cueVideoById({ + videoId: "id", +}); + +player.cueVideoById({ + startSeconds: 0, + endSeconds: 9001, + suggestedQuality: "highres", + videoId: "id", +}); + +player.loadVideoById("id"); +player.loadVideoById("id", 0); +player.loadVideoById("id", 0, "medium"); +player.loadVideoById("id", 0, "large"); + +player.loadVideoById({ + videoId: "id", +}); + +player.loadVideoById({ + endSeconds: 9001, + startSeconds: 0, + suggestedQuality: "hd720", + videoId: "id", +}); + +player.cueVideoByUrl("url"); +player.cueVideoByUrl("url", 0); +player.cueVideoByUrl("url", 0, "hd1080"); +player.cueVideoByUrl("url", 0, "highres"); + +player.cueVideoByUrl({ + mediaContentUrl: "url", +}); + +player.cueVideoByUrl({ + endSeconds: 9001, + mediaContentUrl: "url", + startSeconds: 0, + suggestedQuality: "hd720", +}); + +player.loadVideoByUrl("url"); +player.loadVideoByUrl("url", 0); +player.loadVideoByUrl("url", 0, "hd1080"); +player.loadVideoByUrl("url", 0, "highres"); + +player.loadVideoByUrl({ + mediaContentUrl: "url", +}); + +player.loadVideoByUrl({ + endSeconds: 9001, + mediaContentUrl: "url", + startSeconds: 0, + suggestedQuality: "hd720", +}); + +player.cuePlaylist(["play", "list"]); +player.cuePlaylist(["play", "list"], 7); +player.cuePlaylist(["play", "list"], 7, 0); +player.cuePlaylist(["play", "list"], 7, 0, "default"); + +player.cuePlaylist({ + list: "playlist", + listType: "player", +}); + +player.cuePlaylist({ + index: 7, + list: "playlist", + listType: "search", +}); + +player.cuePlaylist({ + endSeconds: 9001, + index: 7, + list: "playlist", + listType: "search", + startSeconds: 0, + suggestedQuality: "hd720", +}); + +player.loadPlaylist(["play", "list"]); +player.loadPlaylist(["play", "list"], 7); +player.loadPlaylist(["play", "list"], 7, 0); +player.loadPlaylist(["play", "list"], 7, 0, "default"); + +player.loadPlaylist({ + list: "playlist", + listType: "player", +}); + +player.loadPlaylist({ + index: 7, + listType: "search", + list: "playlist", +}); + +player.loadPlaylist({ + endSeconds: 9001, + index: 7, + listType: "search", + list: "playlist", + startSeconds: 0, + suggestedQuality: "hd720", +}); + +player.playVideo(); + +player.pauseVideo(); + +player.stopVideo(); + +player.seekTo(9001, true); + +player.nextVideo(); + +player.previousVideo(); + +player.playVideoAt(0); + +player.mute(); + +player.unMute(); + +const muted: boolean = player.isMuted(); + +player.setVolume(49); + +const volume: number = player.getVolume(); + +player.setSize(350, 490); + +const playbackRate: number = player.getPlaybackRate(); + +player.setPlaybackRate(2); + +const playbackRates: number[] = player.getAvailablePlaybackRates(); + +player.setLoop(true); + +player.setShuffle(false); + +const fraction: number = player.getVideoLoadedFraction(); + +const state: YT.PlayerState = player.getPlayerState(); + +const time: number = player.getCurrentTime(); + +const quality: YT.SuggestedVideoQuality = player.getPlaybackQuality(); + +player.setPlaybackQuality(quality); +player.setPlaybackQuality("medium"); + +const qualities: YT.SuggestedVideoQuality[] = player.getAvailableQualityLevels(); + +for (const quality of player.getAvailableQualityLevels()) { + player.setPlaybackQuality(quality) +} + +const duration: number = player.getDuration(); + +const videoUrl: string = player.getVideoUrl(); + +const videoEmbed: string = player.getVideoEmbedCode(); + +const playlist: string[] = player.getPlaylist(); + +const playlistIndex: number = player.getPlaylistIndex(); + +player.addEventListener("onReady", (event: YT.PlayerEvent) => {}); +player.addEventListener("onStateChange", (event: YT.OnStateChangeEvent) => {}); +player.addEventListener("onPlaybackQualityChange", (event: YT.OnPlaybackQualityChangeEvent) => {}); +player.addEventListener("onPlaybackRateChange", (event: YT.OnPlaybackRateChangeEvent) => {}); +player.addEventListener("onError", (event: YT.OnErrorEvent) => {}); +player.addEventListener("onApiChange", (event: YT.PlayerEvent) => {}); + +const frame: HTMLIFrameElement = player.getIframe(); + +player.destroy(); From 42b5630be7becf7239d85cde8d594875d49f5894 Mon Sep 17 00:00:00 2001 From: Dobes Vandermeer Date: Wed, 13 Jun 2018 16:10:19 -0700 Subject: [PATCH 32/37] Remove extra whitespace --- types/mongodb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 1ca0c2a8b8..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: (T) => U ): 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 */ From ba5a3703e808997d4ed9d3e5379aa4b8fda6d666 Mon Sep 17 00:00:00 2001 From: Tina Roh Date: Wed, 13 Jun 2018 17:53:55 -0700 Subject: [PATCH 33/37] Fix Expo v27 Constants --- types/expo/index.d.ts | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 048d7b884d..d20b5ec87b 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -8,6 +8,7 @@ // Umidbek Karimov // Moshe Feuchtwanger // Michael Prokopchuk +// Tina Roh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -789,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; From a6c21fe750011de5bc2cdd96a36fd69e9e07b991 Mon Sep 17 00:00:00 2001 From: Tina Roh Date: Wed, 13 Jun 2018 17:55:07 -0700 Subject: [PATCH 34/37] Fix Expo v26 Constants --- types/expo/v26/index.d.ts | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/types/expo/v26/index.d.ts b/types/expo/v26/index.d.ts index 4e7a0ebdb3..b436d5987a 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; From c18f3fb50055c71dfd3af01e91648af5b8d441d6 Mon Sep 17 00:00:00 2001 From: Tina Roh Date: Wed, 13 Jun 2018 18:01:12 -0700 Subject: [PATCH 35/37] Fix typo lignt -> light --- types/expo/index.d.ts | 2 +- types/expo/v26/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index d20b5ec87b..952cd4a086 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -900,7 +900,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/expo/v26/index.d.ts b/types/expo/v26/index.d.ts index b436d5987a..f1641ea643 100644 --- a/types/expo/v26/index.d.ts +++ b/types/expo/v26/index.d.ts @@ -898,7 +898,7 @@ export namespace Constants { }; appKey?: string; androidStatusBar?: { - barStyle?: 'lignt-content' | 'dark-content', + barStyle?: 'light-content' | 'dark-content', backgroundColor?: string }; androidShowExponentNotificationInShellApp?: boolean; From a51018316fabe2535d860584cbabf0b2ad97c2bd Mon Sep 17 00:00:00 2001 From: Jose Colella Date: Thu, 14 Jun 2018 08:22:34 -0400 Subject: [PATCH 36/37] Restrict optional family value to 4 or 6. References IPv4 and IPv6 --- types/request/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index 51cb7919a7..60e24b7692 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -140,7 +140,7 @@ declare namespace request { method?: string; headers?: Headers; body?: any; - family?: number; + family?: 4 | 6; followRedirect?: boolean | ((response: http.IncomingMessage) => boolean); followAllRedirects?: boolean; followOriginalHttpMethod?: boolean; From 4220af6d67a0363145b22dd88c07b7b05e07efd7 Mon Sep 17 00:00:00 2001 From: denkpark <26546651+denkpark@users.noreply.github.com> Date: Thu, 14 Jun 2018 17:00:53 +0200 Subject: [PATCH 37/37] Middleware properties optional; req.brute - properties in `ExpressBrute.Middleware` are optional - added`req.brute.reset()` to express.Request --- types/express-brute/index.d.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) 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;