From bc0ecd2c61698592e8754f7aeb7493f6b67c31f9 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 28 Jul 2016 11:08:36 +0900 Subject: [PATCH 01/56] Sleep --- sleep/sleep-tests.ts | 6 ++++++ sleep/sleep.d.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 sleep/sleep-tests.ts create mode 100644 sleep/sleep.d.ts diff --git a/sleep/sleep-tests.ts b/sleep/sleep-tests.ts new file mode 100644 index 0000000000..2d2c05c2ff --- /dev/null +++ b/sleep/sleep-tests.ts @@ -0,0 +1,6 @@ +/// + +import sleep = require("sleep"); + +sleep.sleep(1); +sleep.usleep(5000); \ No newline at end of file diff --git a/sleep/sleep.d.ts b/sleep/sleep.d.ts new file mode 100644 index 0000000000..5173e4b4ef --- /dev/null +++ b/sleep/sleep.d.ts @@ -0,0 +1,26 @@ +// Type definitions for node-scanf +// Project: https://github.com/ErikDubbelboer/node-sleep +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace __node_sleep +{ + /** + * Sleep for n seconds. + * + * @param n Number of seconds to sleep. + */ + function sleep(n: number): void; + + /** + * Sleep for n microseconds. + * + * @param n Number of microseconds to sleep; 1 second is 1,000,000 microseconds. + */ + function usleep(n: number): void; +} + +declare module "sleep" +{ + export = __node_sleep; +} \ No newline at end of file From 0bb3ec00dd31d85a43695aca33b72ff69c444ee5 Mon Sep 17 00:00:00 2001 From: Diullei Date: Fri, 8 Jul 2016 00:44:30 -0300 Subject: [PATCH 02/56] improved - blessedjs typings --- blessed/blessed-tests.ts | 773 ++++++++ blessed/blessed.d.ts | 4059 ++++++++++++++++++++++++++------------ 2 files changed, 3585 insertions(+), 1247 deletions(-) create mode 100644 blessed/blessed-tests.ts diff --git a/blessed/blessed-tests.ts b/blessed/blessed-tests.ts new file mode 100644 index 0000000000..4e7f7002e6 --- /dev/null +++ b/blessed/blessed-tests.ts @@ -0,0 +1,773 @@ +/// + +import * as blessed from 'blessed'; + +let screen: blessed.Widgets.Screen = null; + +// https://github.com/chjj/blessed/blob/master/test/widget-autopad.js + +screen = blessed.screen({ + dump: __dirname + '/logs/autopad.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var box1 = blessed.box({ + parent: screen, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line' +}); + +var box2 = blessed.box({ + parent: box1, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line' +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js + +screen = blessed.screen({ + dump: __dirname + '/logs/bigtext.log', + smartCSR: true, + warnings: true +}); + +var box = blessed.bigtext({ + parent: screen, + content: 'Hello', + shrink: true, + width: '80%', + // height: '80%', + height: 'shrink', + // width: 'shrink', + border: 'line', + fch: ' ', + ch: '\u2592', + style: { + fg: 'red', + bg: 'blue', + bold: false + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-csr.js + +screen = blessed.screen({ + dump: __dirname + '/logs/csr.log', + smartCSR: true, + warnings: true +}); + +var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8'); + +var cleanSides = screen.cleanSides; +function expectClean(value: any) { + screen.cleanSides = function(el: blessed.widget.Element) { + var ret = cleanSides.apply(this, arguments); + if (ret !== value) { + throw new Error('Failed. Expected ' + + value + ' from cleanSides. Got ' + + ret + '.'); + } + return ret; + }; +} +var btext = blessed.box({ + parent: screen, + left: 'center', + top: 'center', + width: '80%', + height: '80%', + style: { + bg: 'green' + }, + border: 'line', + content: 'CSR should still work.' +}); +let _oscroll = btext.scroll; +btext.scroll = function(offset, always) { + expectClean(true); + return _oscroll(offset, always); +}; + +var text = blessed.scrollabletext({ + parent: screen, + content: lorem, + border: 'line', + left: 'center', + top: 'center', + draggable: true, + width: '50%', + height: '50%', + mouse: true, + keys: true, + vi: true +}); + +_oscroll = text.scroll; +text.scroll = function(offset, always) { + var el = this; + var value = true; + if (el.left < 0) value = true; + if (el.top < 0) value = false; + if (el.left + el.width > screen.width) value = true; + if (el.top + el.height > screen.height) value = false; + expectClean(value); + return _oscroll(offset, always); +}; + +text.focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js + +screen = blessed.screen({ + dump: __dirname + '/logs/dock.log', + smartCSR: true, + dockBorders: true, + warnings: true +}); + +blessed.box({ + parent: screen, + left: -1, + top: -1, + width: '50%+1', + height: '50%+1', + border: 'line', + content: 'Foo' +}); + +blessed.box({ + parent: screen, + left: '50%-1', + top: -1, + width: '50%+3', + height: '50%+1', + content: 'Bar', + border: 'line' +}); + +blessed.box({ + parent: screen, + left: -1, + top: '50%-1', + width: '50%+1', + height: '50%+3', + border: 'line', + content: 'Foo' +}); + +blessed.listtable({ + parent: screen, + left: '50%-1', + top: '50%-1', + width: '50%+3', + height: '50%+3', + border: 'line', + align: 'center', + tags: true, + keys: true, + vi: true, + mouse: true, + style: { + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta', + selected: { + bg: 'blue' + } + } + }, + data: [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] + ] +}).focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js + +var form = blessed.form({ + parent: screen, + keys: true, + left: 0, + top: 0, + width: 30, + height: 4, + bg: 'green', + content: 'Submit or cancel?' +}); + +var submit = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 10, + top: 2, + shrink: true, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +var cancel = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 20, + top: 2, + shrink: true, + name: 'cancel', + content: 'cancel', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +// https://github.com/chjj/blessed/blob/master/test/widget-layout.js + +screen = blessed.screen({ + dump: __dirname + '/logs/layout.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var layout = blessed.layout({ + parent: screen, + top: 'center', + left: 'center', + width: '50%', + height: '50%', + border: 'line', + layout: process.argv[2] === 'grid' ? 'grid' : 'inline', + style: { + bg: 'red', + border: { + fg: 'blue' + } + } +}); + +var box1 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '1' +}); + +var box2 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '2' +}); + +var box3 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '3' +}); + +var box4 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '4' +}); + +var box5 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '5' +}); + +var box6 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '6' +}); + +var box7 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '7' +}); + +var box8 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '8' +}); + +var box9 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '9' +}); + +var box10 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '10' +}); + +var box11 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '11' +}); + +var box12 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '12' +}); + +if (process.argv[2] !== 'grid') { + for (var i = 0; i < 10; i++) { + blessed.box({ + parent: layout, + // width: i % 2 === 0 ? 10 : 20, + // height: i % 2 === 0 ? 5 : 10, + width: Math.random() > 0.5 ? 10 : 20, + height: Math.random() > 0.5 ? 5 : 10, + border: 'line', + content: (i + 1 + 12) + '' + }); + } +} + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-form.js + +screen = blessed.screen({ + dump: __dirname + '/logs/form.log', + warnings: true +}); + +type FormData = { + radio1: boolean; + radio2: boolean; + text: string; + check: boolean; +}; + +var form2 = blessed.form({ + parent: screen, + mouse: true, + keys: true, + vi: true, + left: 0, + top: 0, + width: '100%', + //height: 12, + style: { + bg: 'green', + border: { + inverse: true + }, + scrollbar: { + inverse: true + } + }, + content: 'foobar', + scrollable: true, + scrollbar: { + ch: ' ' + } + //alwaysScroll: true +}); + +form2.on('submit', (data) => { + output.setContent(JSON.stringify(data, null, 2)); + screen.render(); +}); + +form2.key('d', function() { + form2.scroll(1, true); + screen.render(); +}); + +form2.key('u', function() { + form2.scroll(-1, true); + screen.render(); +}); + +var set = blessed.radioset({ + parent: form2, + left: 1, + top: 1, + shrink: true, + //padding: 1, + //content: 'f', + style: { + bg: 'magenta' + } +}); + +var radio1 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 0, + top: 0, + name: 'radio1', + content: 'radio1' +}); + +var radio2 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 15, + top: 0, + name: 'radio2', + content: 'radio2' +}); + +var text2 = blessed.textbox({ + parent: form2, + mouse: true, + keys: true, + style: { + bg: 'blue' + }, + height: 1, + width: 20, + left: 1, + top: 3, + name: 'text' +}); + +text2.on('focus', function() { + text2.readInput(); +}); + +var check = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 1, + name: 'check', + content: 'check' +}); + +var check2 = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 14, + name: 'foooooooo2', + content: 'foooooooo2' +}); + +var submit = blessed.button({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + padding: { + left: 1, + right: 1 + }, + left: 29, + top: 3, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + } + } +}); + +submit.on('press', function() { + form2.submit(); +}); + +var box1 = blessed.box({ + parent: form2, + left: 1, + top: 10, + height: 10, + width: 10, + content: 'one', + style: { + bg: 'cyan' + } +}); + +var box2 = blessed.box({ + parent: box1, + left: 1, + top: 2, + height: 8, + width: 9, + content: 'two', + style: { + bg: 'magenta' + } +}); + +var box3 = blessed.box({ + parent: box2, + left: 1, + top: 2, + height: 6, + width: 8, + content: 'three', + style: { + bg: 'yellow' + } +}); + +var box4 = blessed.box({ + parent: box3, + left: 1, + top: 2, + height: 4, + width: 7, + content: 'four', + style: { + bg: 'blue' + } +}); + +var output = blessed.scrollabletext({ + parent: form2, + mouse: true, + keys: true, + left: 0, + top: 20, + height: 5, + right: 0, + style: { + bg: 'red' + }, + content: 'foobar' +}); + +var bottom = blessed.line({ + parent: form2, + type: 'line', + orientation: 'horizontal', + left: 0, + right: 0, + top: 50, + style: { + fg: 'blue' + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +form2.focus(); + +form2.submit(); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-table.js + +screen = blessed.screen({ + dump: __dirname + '/logs/table.log', + autoPadding: false, + fullUnicode: true, + warnings: true +}); + +var DU = '杜'; +var JUAN = '鹃'; + +var table = blessed.table({ + //parent: screen, + top: 'center', + left: 'center', + data: null, + border: 'line', + align: 'center', + tags: true, + //width: '80%', + width: 'shrink', + style: { + border: { + fg: 'red' + }, + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta' + } + } +}); + +var data1 = [ + [ 'Animals', 'Foods', 'Times' ], + [ 'Elephant', 'Apple', '1:00am' ], + [ 'Bird', 'Orange', '2:15pm' ], + [ 'T-Rex', 'Taco', '8:45am' ], + [ 'Mouse', 'Cheese', '9:05am' ] +]; + +data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}'; +data1[2][0] += ' (' + DU + JUAN + ')'; + +var data2 = [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] +]; + +data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}'; +data2[2][0] += ' (' + DU + JUAN + ')'; + +screen.key('q', function() { + return screen.destroy(); +}); + +table.setData(data2); +screen.append(table); +screen.render(); + +setTimeout(function() { + table.setData(data1); + screen.render(); +}, 3000); diff --git a/blessed/blessed.d.ts b/blessed/blessed.d.ts index 6746afe5f5..cb9bd393ed 100644 --- a/blessed/blessed.d.ts +++ b/blessed/blessed.d.ts @@ -1,1256 +1,155 @@ -// Type definitions for blessed 0.1.5 +// Type definitions for blessed 0.1.81 // Project: https://github.com/chjj/blessed -// Definitions by: bryn austin bellomy +// Definitions by: bryn austin bellomy , Diullei Gomes // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// -declare module "blessed" -{ - import events = require('events'); - import buffer = require('buffer'); - import child_process = require('child_process'); +declare module "blessed" { + import {EventEmitter} from 'events'; + import * as stream from "stream" + import * as child_process from "child_process"; - module Blessed - { - export var colors: Colors; + export class BlessedProgram { + hideCursor: () => void; + move: any; + showCursor: any; + } - export interface GenericCallback { - (...args:any[]): void; + export module Widgets { + + export module Types { + + export type TTopLeft = string | number | "center"; + + export type TPosition = string | number; + + export type TMouseAction = "mousedown" | "mouseup" | "mousemove"; + + export type TStyle = { + type?: string; + bg?: string; + fg?: string; + ch?: string; + bold?: boolean; + underline?: boolean; + blink?: boolean; + inverse?: boolean; + invisible?: boolean; + transparent?: boolean; + border?: "line" | "bg" | TBorder; + hover?: boolean; + focus?: boolean; + label?: string; + track?: {bg?: string; fg?: string;}; + scrollbar?: {bg?: string; fg?: string;}; + } + + export type TBorder = { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export type TCursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } + + export type TAlign = "left" | "center" | "right"; + + export type ListbarCommand = { + key: string; + callback: () => void; + }; + + export type TImage = { + /** + * Pixel width. + */ + width: number; + /** + * Pixel height. + */ + height: number; + /** + * Image bitmap. + * */ + bmp: any; + /** + * Image cellmap (bitmap scaled down to cell size). + */ + cellmap: any; + }; + + export type Cursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } } - export interface ColorPair { - /** background, must be number (-1 for default). */ - bg?: number; - /** foreground, must be number (-1 for default). */ - fg?: number; - } - - export interface Style extends ColorPair { - bold?: boolean; - underline?: boolean; - border: Border; - hover: ColorPair; - } - - export interface Border extends ColorPair { - /** type of border ('line' or 'bg'). */ - type?: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch?: string; - } - - export interface Padding { - top?:number; - right?:number; - bottom?:number; - left?:number; - } - - export interface Position { - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - top?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - right?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - bottom?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - left?:number|string; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?:number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?:number|string; - } - - export interface KeyCode { - name: string; - ctrl: boolean; - meta: boolean; - shift: boolean; - sequence: string; - full: string; - } - - export class Program - { - /** - Wrap the given text in terminal formatting codes corresponding to the given attribute - name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 - integer color number. - */ - text (text:string, attr:string): string; - } - - export interface Colors { - /** Either pass a hex string, an array of 3 numbers, or three separate numbers representing an RGB value. This returns the 0-255 color number for that color. */ - match (r:string|number[]|number, g?:number, b?:number): number; - - /** An array of the 255 colors as hex strings. */ - colors: string[]; - } - - export interface NodeOptions - { - screen?: Screen; - parent?: Node; - children?: Node[]; - } - - export class Node extends events.EventEmitter - { - constructor(options?:NodeOptions); - - type : string; - options : NodeOptions; - parent : Node; - screen : Screen; - children : Node[]; - data : any; - _ : any; - $ : any; - index : number; - - // on(event:string, callback:() => void); - // on(event:'adopt', callback:() => void); - // on(event:'remove', callback:() => void); - // on(event:'reparent', callback:() => void); - // on(event:'attach', callback:() => void); - // on(event:'detach', callback:() => void); - - prepend(node:Node): void; - append(node:Node): void; - remove(node:Node): void; - insert(node:Node, index:number): void; - insertBefore(node:Node, refNode:Node): void; - insertAfter(node:Node, refNode:Node): void; - detach(): void; - // emitDescendants(): void; - // get(key:string): any; - // get(key:string, default:any): any; - // set(key:string, value:any): void; - } - - export interface ScreenOptions extends NodeOptions - { - /** the blessed Program to be associated with. will be automatically instantiated if none is provided. */ - program?: any; - /** attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with uniform cells to their sides). this is known to cause flickering with elements that are not full-width, however, it is more optimal for terminal rendering. */ - smartCSR?: boolean; - /** do CSR on any element within 20 cols of the screen edge on either side. faster than smartCSR, but may cause flickering depending on what is on each side of the element. */ - fastCSR?: boolean; - /** attempt to perform back_color_erase optimizations for terminals that support it. it will also work with terminals that don't support it, but only on lines with the default background color. as it stands with the current implementation, it's uncertain how much terminal performance this adds at the cost of overhead within node. */ - useBCE?: boolean; - /** amount of time (in ms) to redraw the screen after the terminal is resized (default: 300). */ - resizeTimeout?: number; - /** the width of tabs within an element's content. */ - tabSize?: number; - /** automatically position child elements with border and padding in mind. */ - autoPadding?: boolean; - /** the name of the logfile to use. if specified but the file does not exist, it will be created. see log method. */ - log?: string; - /** dump all output and input to desired file. can be used together with log option if set as a boolean. */ - dump?: any; - /** debug mode. enables usage of the `debug` method. also creates a debug console which will display when pressing F12. it will display all log and debug messages. */ - debug?: boolean; - /** Array of keys in their full format (e.g. C-c) to ignore when keys are locked. Useful for creating a key that will always exit no matter whether the keys are locked. */ - ignoreLocked?: string[]; - - /** Do not clear the screen, only scroll down enough to make room for the elements on the screen. do not use the alternate screenbuffer. useful for writing a CLI tool or some kind of prompt (experimental - see test/widget-noalt.js) */ - noAlt?: boolean; - - /** Options for the cursor. */ - cursor?: CursorOptions; - } - - export interface CursorOptions { - /** have blessed draw a custom cursor and hide the terminal cursor (experimental). */ - artificial?: boolean; - /** shape of the artificial cursor. can be: block, underline, or line. */ - shape?: string; //'block'|'underline'|'line'; - /** whether the artificial cursor blinks. */ - blink?: boolean; - /** color of the artificial cursor. accepts any valid color value (null is default). */ - color?: string; - } - - export interface ScreenEventCallback { - (character:string, keyCode:KeyCode): void; - } - - export class Screen extends Node - { - constructor(options?:ScreenOptions); - - /** the blessed Program object. */ - program: any; - /** the blessed Tput object (only available if you passed tput: true to the Program constructor.) */ - tput: any; - /** top of the focus history stack. */ - focused: any; - /** width of the screen (same as program.cols). */ - width: number; - /** height of the screen (same as program.rows). */ - height: number; - /** same as screen.width. */ - cols: number; - /** same as screen.height. */ - rows: number; - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** whether the focused element grabs all keypresses. */ - grabKeys: boolean; - /** prevent keypresses from being received by any element. */ - lockKeys: boolean; - /** the currently hovered element. only set if mouse events are bound. */ - hover: Element; - /** set or get window title. */ - title: string; - - /** write string to the log file if one was created. */ - log(...msg:any[]): void; - /** same as the log method, but only gets called if the debug option was set. */ - debug(...msg:string[]): void; - /** allocate a new pending screen buffer and a new output screen buffer. */ - alloc(): void; - /** draw the screen based on the contents of the screen buffer. */ - draw(start:number, end:number): void; - /** render all child elements, writing all data to the screen buffer and drawing the screen. */ - render(): void; - /** clear any region on the screen. */ - clearRegion(x1:number, x2:number, y1:number, y2:number): void; - /** fill any region with a character of a certain attribute. */ - fillRegion(attr:number, ch:string, x1:number, x2:number, y1:number, y2:number): void; - /** focus element by offset of focusable elements. */ - focusOffset(offset:number): void; - /** focus previous element in the index. */ - focusPrevious(): void; - /** focus next element in the index. */ - focusNext(): void; - /** push element on the focus stack (equivalent to screen.focused = el). */ - focusPush(element:Element): void; - /** pop element off the focus stack. */ - focusPop(): void; - /** save the focused element. */ - saveFocus(): void; - /** restore the saved focused element. */ - restoreFocus(): void; - /** "rewind" focus to the last visible and attached element. */ - rewindFocus(): void; - /** bind a keypress listener for a specific key. */ - key(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** bind a keypress listener for a specific key once. */ - onceKey(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:ScreenEventCallback): void; - /** spawn a process in the foreground, return to blessed app after exit. */ - spawn(file:string, args:string[], options:NodeChildProcessExecOptions): child_process.ChildProcess; - /** spawn a process in the foreground, return to blessed app after exit. executes callback on error or exit. */ - exec(file:string, args:string[], options:NodeChildProcessExecOptions, callback:GenericCallback): child_process.ChildProcess; - /** read data from text editor. */ - readEditor(options:{}, callback:GenericCallback): void; - /** set effects based on two events and attributes. */ - setEffects(el:Element, fel:Element, over:string, out:string, effects:Style, temp?:string): void; - /** insert a line into the screen (using csr: this bypasses the output buffer). */ - insertLine(n:number, y:number, top:number, bottom:number): void; - /** delete a line from the screen (using csr: this bypasses the output buffer). */ - deleteLine(n:number, y:number, top:number, bottom:number): void; - /** insert a line at the bottom of the screen. */ - insertBottom(top:number, bottom:number): void; - /** insert a line at the top of the screen. */ - insertTop(top:number, bottom:number): void; - /** delete a line at the bottom of the screen. */ - deleteBottom(top:number, bottom:number): void; - /** delete a line at the top of the screen. */ - deleteTop(top:number, bottom:number): void; - - /** enable mouse events for the screen and optionally an element (automatically called when a form of on('mouse') is bound). */ - enableMouse(el?:Element): void; - /** enable keypress events for the screen and optionally an element (automatically called when a form of on('keypress') is bound). */ - enableKeys(el?:Element): void; - /** enable key and mouse events. calls bot enableMouse and enableKeys. */ - enableInput(el?:Element): void; - - /** attempt to copy text to clipboard using iTerm2's propriety sequence. returns true if successful. */ - copyToClipboard(text:string): boolean; - /** attempt to change cursor shape. will not work in all terminals (see artificial cursors for a solution to this). returns true if successful. */ - cursorShape(shape:string, blink:boolean): boolean; - /** attempt to change cursor color. returns true if successful. */ - cursorColor(color: string): boolean; - /** attempt to reset cursor. returns true if successful. */ - cursorReset(): boolean; - - } - - export interface ElementOptions extends NodeOptions - { - fg?: string; - bg?: string; - scrollbar?: ColorPair; - focus?: Style; - hover?: Style; - - /** border object, see below. */ - border?: Border; - /** positioning options. */ - position?: Position; - /** amount of padding on the inside of the element. can be a number or an object containing the properties: left, right, top, and bottom. */ - padding?: number|Padding; - /** element's text content. */ - content?: string; - /** element is clickable. */ - clickable?: boolean; - /** element is focusable and can receive key input. */ - input?: boolean; - /** element is focused. */ - focused?: boolean; - /** whether the element is hidden. */ - hidden?: boolean; - /** a simple text label for the element. */ - label?: string; - /** a floating text label for the element which appears on mouseover. */ - hoverText?: string; - /** text alignment: left, center, or right. */ - align?: string; - /** vertical text alignment: top, middle, or bottom. */ - valign?: string; - /** shrink/flex/grow to content and child elements. width/height during render. */ - shrink?: any; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?: number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?: number|string; - /** whether the element is scrollable or not. */ - scrollable?: boolean; - /** background character (default is whitespace ). */ - ch?: string; - /** allow the element to be dragged with the mouse. */ - draggable?: boolean; - } - - export class Element extends Node - { - constructor(options?:ElementOptions); - - /** name of the element. useful for form submission. */ - name: string; - /** border object. */ - border: Border; - /** contains attributes (e.g. fg/bg/underline). see above. */ - style: Style; - /** raw width, height, and offsets. */ - position: Position; - /** type of border (line or bg). bg by default. */ - type: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch: string; - /** raw text content. */ - content: string; - /** whether the element is hidden or not. */ - hidden: boolean; - /** whether the element is visible or not. */ - visible: boolean; - /** whether the element is attached to a screen in its ancestry somewhere. */ - detached: boolean; - /** calculated width. */ - width: number; - /** calculated height. */ - height: number; - /** whether the element is draggable. set to true to allow dragging. */ - draggable: boolean; - - - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** write content and children to the screen buffer. */ - render(): void; - /** hide element. */ - hide(): void; - /** show element. */ - show(): void; - /** toggle hidden/shown. */ - toggle(): void; - /** focus element. */ - focus(): void; - /** bind a keypress listener for a specific key. */ - key(name:string|string[], listener:(character?:any, keyCode?:any) => void): void; - /** bind a keypress listener for a specific key once. */ - onceKey(name:string, listener:() => void): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:() => void): void; - /** same as el.on('screen', ...) except this will automatically cleanup listeners after the element is detached. */ - onScreenEvent(event:string, listener:(...args:any[]) => void): void; - /** set the z-index of the element (changes rendering order). */ - setIndex(z:number): void; - /** put the element in front of its siblings. */ - setFront(): void; - /** put the element in back of its siblings. */ - setBack(): void; - /** set the label text for the top-left corner. example options: {text:'foo',side:'left'} */ - setLabel(textOrOptions:string|{}): void; - /** remove the label completely. */ - removeLabel(): void; - /** set the hover text for the bottom-right corner. example options: {text:'foo'} */ - setHover(textOrOptions:string|{}): void; - /** remove the hover label completely. */ - removeHover(): void; - /** set the content. note: when text is input, it will be stripped of all non-SGR escape codes, tabs will be replaced with 8 spaces, and tags will be replaced with SGR codes (if enabled). */ - setContent(text:string): void; - /** return content, slightly different from el.content. assume the above formatting. */ - getContent(): void; - /** similar to setContent, but ignore tags and remove escape codes. */ - setText(text:string): void; - /** similar to getContent, but return content with tags and escape codes removed. */ - getText(): void; - /** insert a line into the box's content. */ - insertLine(index:number, lines:string|string[]): void; - /** delete a line from the box's content. */ - deleteLine(index:number, numLines:number): void; - /** get a line from the box's content. */ - getLine(index:number): void; - /** get a line from the box's content from the visible top. */ - getBaseLine(index:number): void; - /** set a line in the box's content. */ - setLine(index:number, line:string): void; - /** set a line in the box's content from the visible top. */ - setBaseLine(index:number, line:string): void; - /** clear a line from the box's content. */ - clearLine(index:number): void; - /** clear a line from the box's content from the visible top. */ - clearBaseLine(index:number): void; - /** insert a line at the top of the box. */ - insertTop(lines:string|string[]): void; - /** insert a line at the bottom of the box. */ - insertBottom(lines:string|string[]): void; - /** delete a line at the top of the box. */ - deleteTop(): void; - /** delete a line at the bottom of the box. */ - deleteBottom(): void; - /** unshift a line onto the top of the content. */ - unshiftLine(lines:string|string[]): void; - /** shift a line off the top of the content. */ - shiftLine(index:number): void; - /** push a line onto the bottom of the content. */ - pushLine(lines:string|string[]): void; - /** pop a line off the bottom of the content. */ - popLine(index:number): void; - /** an array containing the content lines. */ - getLines(): void; - /** an array containing the lines as they are displayed on the screen. */ - getScreenLines(): void; - /** get a string's real length, taking into account tags. */ - textLength(text:string): number; - - /** enable dragging of the element. */ - enableDrag(): void; - /** disable dragging of the element. */ - disableDrag(): void; - } - - - // - // Box - // - - export interface BoxOptions extends ElementOptions { - // intentionally empty - } - - export class Box extends Element { - constructor(options?:BoxOptions); - // intentionally empty - } - - - // - // ScrollableBox - // - - export interface ScrollableBoxOptions extends BoxOptions { - /** a limit to the childBase. default is `Infinity`. */ - baseLimit: number; - /** a option which causes the ignoring of `childOffset`. this in turn causes the childBase to change every time the element is scrolled. */ - alwaysScroll: boolean; - /** object enabling a scrollbar. */ - scrollbar: ScrollBar; - } - - /** A box with scrollable content. */ - export class ScrollableBox extends Box { - constructor(options?:ScrollableBoxOptions); - - /** the offset of the top of the scroll content. */ - childBase: number; - /** the offset of the chosen item/line. */ - childOffset: number; - /** scroll the content by a relative offset. */ - scroll(offset:number): void; - /** scroll the content to an absolute index. */ - scrollTo(index:number): void; - /** same as `scrollTo`. */ - setScroll(index:number): void; - /** set the current scroll index in percentage (0-100). */ - setScrollPerc(perc:number): void; - /** get the current scroll index in lines. */ - getScroll(): number; - /** get the actual height of the scrolling area. */ - getScrollHeight(): number; - /** get the current scroll index in percentage. */ - getScrollPerc(): number; - /** reset the scroll index to its initial state. */ - resetScroll(): void; - - } - - export interface ScrollBar { - /** style of the scrollbar. */ - style: Style; - /** style of the scrollbar track if present (takes regular style options). */ - track: Style; - } - - - // - // ScrollableText - // - - export interface ScrollableTextOptions extends ScrollableBoxOptions { - /** whether to enable automatic mouse support for this element. */ - mouse: boolean; - /** use predefined keys for navigating the text. */ - keys: boolean; - /** use vi keys with the `keys` option. */ - vi: boolean; - } - - /** __DEPRECATED__ - Use Box with the `scrollable` and `alwaysScroll` options instead. A scrollable text box which can display and scroll text, as well as handle pre-existing newlines and escape codes. */ - export class ScrollableText extends ScrollableBox { - constructor(options?:ScrollableTextOptions); - } - - - - // - // Text - // - - export interface TextOptions extends ElementOptions { - align?: string; //'left'|'center'|'right'; - } - - export class Text extends Element { - constructor(options?:TextOptions); - // intentionally empty - } - - - // - // Line - // - - export interface LineOptions extends BoxOptions { - orientation?: string; //'vertical'|'horizontal'; - style?: Style; - } - - export class Line extends Box { - constructor(options?:LineOptions); - // intentionally empty - } - - - // - // List - // - - export interface ListStyle extends Style { - selected?: Style; - item?: Style; - } - - export interface ListOptions extends BoxOptions - { - style?: ListStyle; - - /** whether to automatically enable mouse support for this list (allows clicking items). */ - mouse?: boolean; - /** use predefined keys for navigating the list. */ - keys?: any; - /** use vi keys with the keys option. */ - vi?: boolean; - /** an array of strings which become the list's items. */ - items?: string[]; - /** a function that is called when vi mode is enabled and the key / is pressed. This function accepts a callback function which should be called with the search string. The search string is then used to jump to an item that is found in items. */ - search?: (callback:(searchString:string) => void) => void; - /** whether the list is interactive and can have items selected (default: true). */ - interactive?: boolean; - } - - export class List extends Box - { - constructor(options?:ListOptions); - - /** The text of the currently selected item. */ - value:string; - /** The items in the list. */ - items:string[]; - /** The items in the list. */ - ritems:string[]; - /** The index of the current selection. */ - selected:number; - - /** add an item based on a string. */ - addItem(text:string): void; - /** returns the item index from the list. child can be an element, index, or string. */ - getItemIndex(child:Element|number|string): void; - /** returns the item element. child can be an element, index, or string. */ - getItem(child:Element|number|string): void; - /** removes an item from the list. child can be an element, index, or string. */ - removeItem(child:Element|number|string): void; - /** clears all items from the list. */ - clearItems(): void; - /** sets the list items to multiple strings. */ - setItems(items:string[]): void; - /** Sets the current selection by absolute index. */ - select(index:number): void; - /** Changes the current selection based on current offset. */ - move(offset:number): void; - /** select item above selected. */ - up(amount:number): void; - /** select item below selected. */ - down(amount:number): void; - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(cwd:string, callback:(err:any, file:string) => void): void; - - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(callback:(err:any, file:string) => void): void; - } - - // - // Input - // - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - export class Input extends Box { - constructor(options?:InputOptions); - // intentionally empty - } - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - // - // Textarea - // - - export interface TextareaOptions extends InputOptions - { - /** use pre-defined keys (`i` or `enter` for insert, `e` for editor, `C-e` for editor while inserting). */ - keys?: boolean; - /** use pre-defined mouse events (right-click for editor). */ - mouse?: boolean; - /** call `readInput()` when the element is focused. automatically unfocus. */ - inputOnFocus?: boolean; - } - - /** A box which allows multiline text input. */ - export class Textarea extends Input - { - constructor(options?:TextareaOptions); - - /** the input text. __read-only__. */ - value: string; - - /** submit the textarea (emits `submit`). */ - submit(): void; - /** cancel the textarea (emits `cancel`). */ - cancel(): void; - /** grab key events and start reading text from the keyboard. takes a callback which receives the final value. */ - readInput(callback:GenericCallback): void; - /** open text editor in `$EDITOR`, read the output from the resulting file. takes a callback which receives the final value. */ - readEditor(callback:GenericCallback): void; - /** the same as `this.value`, for now. */ - getValue(): string; - /** clear input. */ - clearValue(): void; - /** set value. */ - setValue(text:string): void; - } - - - // - // Textbox - // - - export interface TextboxOptions extends TextareaOptions { - /** completely hide text. */ - secret?: boolean; - /** replace text with asterisks (`*`). */ - censor?: boolean; - } - - /** A box which allows text input. */ - export class Textbox extends Textarea { - constructor(options?:TextboxOptions); - - /** completely hide text. */ - secret: boolean; - /** replace text with asterisks (`*`). */ - censor: boolean; - } - - - // - // Button - // - - export interface ButtonOptions extends InputOptions { - } - - /** A button which can be focused and allows key and mouse input. */ - export class Button extends Input { - constructor(options?:ButtonOptions); - - // on(event:string, callback:() => void): void; - // on(event:'press', callback:() => void); - - /** press button. emits 'press'. */ - press(): void; - } - - - // - // ProgressBar - // - - export interface ProgressBarOptions extends InputOptions { - /** can be `horizontal` or `vertical`. */ - orientation: string; - /** the character to fill the bar with (default is space). */ - pch: string; - /** the amount filled (0 - 100). */ - filled: number; - /** same as `filled`. */ - value: number; - /** enable key support. */ - keys: boolean; - /** enable mouse support. */ - mouse: boolean; - - /** contains the extra key 'bar', which defines the style of the bar contents itself. */ - style: ProgressBarStyle; - } - - export interface ProgressBarStyle extends Style { - /** style of the bar contents itself. */ - bar: Style; - } - - - export class ProgressBar extends Input { - constructor(options?:ProgressBarOptions); - - /** progress the bar by a fill amount. */ - progress(amount:number): void; - /** set progress to specific amount. */ - setProgress(amount:number): void; - /** reset the bar. */ - reset(): void; - } - - // - // Checkbox - // - - export interface CheckboxOptions extends InputOptions { - /** whether the element is checked or not. */ - checked: boolean; - /** enable mouse support. */ - mouse: boolean; + export module Events { + + export interface IMouseEventArg { + x: number; + y: number; + action: Types.TMouseAction; + } + + export interface IKeyEventArg { + full: string; + name: string; + shift: boolean; + ctrl: boolean; + meta: boolean; + sequence: string; + } } - - /** A checkbox which can be used in a form element. */ - export class Checkbox extends Input - { - constructor(options?:CheckboxOptions); - - /** the text next to the checkbox (do not use setcontent, use `check.text = ''`). */ - text: string; - /** whether the element is checked or not. */ - checked: boolean; - /** same as `checked`. */ - value: boolean; - - /** check the element. */ - check(): void; - /** uncheck the element. */ - uncheck(): void; - /** toggle checked state. */ - toggle(): void; - } - - - // - // RadioSet - // - - export interface RadioSetOptions extends BoxOptions { - } - - - export class RadioSet extends Box { - constructor(options?:RadioSetOptions); - } - - - // - // RadioButton - // - - export interface RadioButtonOptions extends CheckboxOptions { - } - - - /** A radio button which can be used in a form element. */ - export class RadioButton extends Checkbox { - constructor(options?:RadioButtonOptions); - } - - - - // - // Prompt - // - - export interface PromptOptions extends BoxOptions { - } - - - /** A prompt box containing a text input, okay, and cancel buttons (automatically hidden). */ - export class Prompt extends Box - { - constructor(options?:PromptOptions); - - /** show the prompt and wait for the result of the textbox. set text and initial value */ - input(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - setInput(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - readInput(text:string, value:any, callback:(val:any) => void): void; - } - - - // - // Question - // - - export interface QuestionOptions extends BoxOptions { - } - - - /** A question box containing okay and cancel buttons (automatically hidden). */ - export class Question extends Box - { - constructor(options?:QuestionOptions); - - /** ask a `question`. `callback` will yield the result. */ - ask(question:string, callback:(result:any) => void): void; - } - - - // - // Message - // - - export interface MessageOptions extends BoxOptions { - } - - - /** A box containing a message to be displayed (automatically hidden). */ - export class Message extends Box - { - constructor(options?:MessageOptions); - - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - log(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - display(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display an error in the same way. */ - error(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - } - - export interface MessageCallback { - (): void; - } - - - // - // Loading - // - - export interface LoadingOptions extends BoxOptions { - } - - /** A box with a spinning line to denote loading (automatically hidden). */ - export class Loading extends Box - { - constructor(options?:LoadingOptions); - - /** display the loading box with a message. will lock keys until `stop` is called. */ - load(text:string): void; - /** hide loading box. unlock keys. */ - stop(): void; - } - - - // - // Listbar - // - - export interface ListbarOptions extends BoxOptions - { - /** Listbar's `style` object includes sub-styles for `selected` and `item`. */ - style?: ListbarStyle; - - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - items?: ListbarItemSet; - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - commands?: ListbarItemSet; - /** automatically bind list buttons to keys 0-9. */ - autoCommandKeys?: boolean; - } - - export interface ListbarItemSet { - [name: string]: ListbarItem; - } - - export interface ListbarItem { - keys: string[]; - callback: GenericCallback; - } - - export interface ListbarStyle extends Style - { - /** style for a selected item. */ - selected: Style; - /** style for an unselected item. */ - item: Style; - } - - /** A horizontal list. Useful for a main menu bar. */ - export class Listbar extends Box - { - constructor(options?:ListbarOptions); - - /** append an item to the bar. */ - add(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - addItem(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - appendItem(item:ListbarItem, callback:GenericCallback): void; - - /** select button and execute its callback. */ - selectTab(index: number): void; - - /** set commands (see `commands` option above). */ - setItems(commands: ListbarItemSet): void; - /** select an item on the bar. */ - select(offset: number): void; - /** remove item from the bar. */ - removeItem(child:ListbarItem): void; - /** move focus relatively across the bar. */ - move(offset: number): void; - /** move focus left relatively across the bar. */ - moveLeft(offset: number): void; - /** move focus right relatively across the bar. */ - moveRight(offset: number): void; - } - - - // - // Log - // - - export interface LogOptions extends ScrollableTextOptions { - /** amount of scrollback allowed. default: Infinity. */ - scrollback?: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput?: boolean; - } - - - /** A log permanently scrolled to the bottom. */ - export class Log extends ScrollableText - { - constructor(options?:LogOptions); - - /** amount of scrollback allowed. default: Infinity. */ - scrollback: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput: boolean; - - /** add a log line. */ - log(text:string): void; - /** add a log line. */ - add(text:string): void; - } - - - // - // Table - // - - export interface TableOptions extends BoxOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - /** do not draw inner cells. */ - noCellBorders?: boolean; - /** fill cell borders with the adjacent background color. */ - fillCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface TableStyle extends Style { - /** header style. */ - header: Style; - /** cell style. */ - cell: Style; - } - - /** A stylized table of text elements. */ - export class Table extends Box - { - /** includes `header` and `cell` substyles. */ - style: TableStyle; - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - - // - // ListTable - // - - export interface ListTableOptions extends ListOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - - /** do not draw inner cells. */ - noCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface ListTableStyle extends TableStyle { - } - - - /** A stylized table of text elements with a list. */ - export class ListTable extends List - { - constructor(options?:ListTableOptions); - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - // - // Image - // - - export interface ImageOptions extends BoxOptions { - /** path to image. */ - file: string; - /** path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. */ - w3m: string; - } - - - /** Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. */ - export class Image extends Box - { - constructor(options?:ImageOptions); - - /** set the image in the box to a new path. */ - setImage (img:string, callback:GenericCallback): void; - /** clear the current image. */ - clearImage (callback:GenericCallback): void; - /** get the size of an image file in pixels. */ - imageSize (img:string, callback:GenericCallback): void; - /** get the size of the terminal in pixels. */ - termSize (callback:GenericCallback): void; - /** get the pixel to cell ratio for the terminal. */ - getPixelRatio (callback:GenericCallback): void; - } - - - // - // Form - // - - export interface FormOptions extends BoxOptions { - /** allow default keys (tab, vi keys, enter). */ - keys?:boolean; - /** allow vi keys. */ - vi?:boolean; - } - - export class Form extends Box - { - constructor(options?:FormOptions); - - /** last submitted data. */ - submission: any; - - // on(event:string, callback:() => void): void; - // on(event:'submit', callback:(data) => void): void; - // on(event:'cancel', callback:() => void): void; - // on(event:'reset', callback:() => void): void; - - next(): void; - previous(): void; - - resetSelected(): void; - /** focus first form element. */ - focusFirst(): void; - /** focus last form element. */ - focusLast(): void; - /** focus next form element. */ - focusNext(): void; - /** focus previous form element. */ - focusPrevious(): void; - /** submit the form. */ - submit(): void; - /** discard the form. */ - cancel(): void; - /** clear the form. */ - reset(): void; - } - - - // - // FileManager - // - - export interface FileManagerOptions extends ListOptions { - cwd?: string; - } - - export interface DirectoryEntry { - name: string; - text: string; - dir: boolean; - symlink: boolean; - } - - export class FileManager extends List - { - constructor(options?:FileManagerOptions); - - cwd: string; - - useFormatter (formatterFn:(entry:DirectoryEntry) => DirectoryEntry): void; - - /** refresh the file list (perform a readdir on cwd and update the list items). */ - refresh (cwd?:string, callback?:() => void): void; - - /** refresh the file list. */ - refresh (callback?:() => void): void; - - /** reset back to original cwd. */ - reset (cwd?:string, callback?:() => void): void; - } - - - // - // Terminal - // - - export interface TerminalOptions extends BoxOptions - { - /** handler for input data. */ - handler?: (userInput:Buffer) => void; - /** name of shell. $SHELL by default. */ - shell?:string; - /** args for shell. */ - args?:any; - /** can be line, underline, and block. */ - cursor?:string; //'line'|'underline'|'block'; - } - - export class Terminal extends Box - { - /** reference to the headless term.js terminal. */ - term: any; - /** reference to the pty.js pseudo terminal. */ - pty: any; - - /** write data to the terminal. */ - write(data:string): void; - - /** nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. */ - screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; - } - - - export interface NodeChildProcessExecOptions - { + export interface NodeChildProcessExecOptions { cwd?: string; stdio?: any; customFds?: any; @@ -1260,10 +159,2676 @@ declare module "blessed" maxBuffer?: number; killSignal?: string; } + + export interface IDestroyable { + destroy(): void; + } + + export interface IOptions { + } + + export interface IHasOptions { + options: T; + } + + export interface TputsOptions extends IOptions { + terminal?: string; + extended?: boolean; + debug?: boolean; + termcap?: string; + terminfoFile?: string; + terminfoPrefix?: string; + termcapFile?: string; + } + + export class Tput implements IHasOptions { + constructor(opts: TputsOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: TputsOptions; + + debug: boolean; + padding: boolean; + extended: boolean; + printf: boolean; + termcap: string; + terminfoPrefix: string; + terminfoFile: string; + termcapFile: string; + error: Error; + terminal: string; + + setup(): void; + term(is: any): boolean; + readTerminfo(term: string): string; + parseTerminfo(data: any, file: string): { + header: { + dataSize: number; + headerSize: number; + magicNumber: boolean; + namesSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + extended: { + dataSize: number; + headerSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + lastStrTableOffset: number; + } + } + name: string; + names: string[]; + desc: string; + bools: Object; + numbers: Object; + strings: Object; + }; + } + + export interface IDestroyable { + destroy(): void; + } + + export interface INodeOptions extends IOptions { + name?: string; + screen?: Screen; + parent?: Node; + children?: Node[]; + focusable?: boolean; + } + + export abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { + constructor(options: INodeOptions); + + // ** properties ** // + + focusable: boolean; + + /** + * Original options object. + */ + options: INodeOptions; + + /** + * An object for any miscellanous user data. + */ + data: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + _: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + $: {[index: string]: any;}; + /** + * Type of the node (e.g. box). + */ + type: string; + /** + * Render index (document order index) of the last render call. + */ + index: number; + /** + * Parent screen. + */ + screen: Screen; + /** + * Parent node. + */ + parent: Node; + /** + * Array of node's children. + */ + children: Node[]; + + // ** methods ** // + + /** + * Prepend a node to this node's children. + */ + prepend(node: Node): void; + /** + * Append a node to this node's children. + */ + append(node: Node): void; + /** + * Remove child node from node. + */ + remove(node: Node): void; + /** + * Insert a node to this node's children at index i. + */ + insert(node: Node, index: number): void; + /** + * Insert a node to this node's children before the reference node. + */ + insertBefore(node: Node, refNode: Node): void; + /** + * Insert a node from node after the reference node. + */ + insertAfter(node: Node, refNode: Node): void; + /** + * Remove node from its parent. + */ + detach(): void; + /** + * Remove node from its parent. + */ + free(): void; + /** + * Remove node from its parent. + */ + forDescendants(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + forAncestors(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + collectDescendants(s: any): void; + /** + * Remove node from its parent. + */ + collectAncestors(s: any): void; + /** + * Remove node from its parent. + */ + emitDescendants(): void; + /** + * Remove node from its parent. + */ + emitAncestors(): void; + /** + * Remove node from its parent. + */ + hasDescendant(target: Node): void; + /** + * Remove node from its parent. + */ + hasAncestor(target: Node): boolean; + /** + * Remove node from its parent. + */ + destroy(): void; + /** + * Emit event for element, and recursively emit same event for all descendants. + */ + emitDescendants(type: string, ...args: any[]): void; + /** + * Get user property with a potential default value. + */ + get(name: string, def: T): T; + /** + * Set user property to value. + */ + set(name: string, value: T): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when node is added to a parent. + */ + on(event: "adopt", callback: (arg: Node) => void): this; + /** + * Received when node is removed from it's current parent. + */ + on(event: "remove", callback: (arg: Node) => void): this; + /** + * Received when node gains a new parent. + */ + on(event: "reparent", callback: (arg: Node) => void): this; + /** + * Received when node is attached to the screen directly or somewhere in its ancestry. + */ + on(event: "attach", callback: (arg: Node) => void): this; + /** + * Received when node is detached from the screen directly or somewhere in its ancestry. + */ + on(event: "detach", callback: (arg: Node) => void): this; + } + + export class NodeWithEvents extends Node { + // ** methods ** // + + /** + * Bind a keypress listener for a specific key. + */ + key(name: string | string[], listener: Function): void; + /** + * Bind a keypress listener for a specific key once. + */ + onceKey(name: string, listener: Function): void; + /** + * Remove a keypress listener for a specific key. + */ + unkey(name: string, listener: Function): void; + removeKey(name: string, listener: Function): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received on screen resize. + */ + on(event: "resize", callback: () => void): this; + /** + * Received on mouse events. + */ + on(event: "mouse", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseout", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseover", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousedown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousewheel", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheeldown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheelup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousemove", callback: (arg: Events.IMouseEventArg) => void): this; + /** + * Received on key events. + */ + on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; + /** + * Global events received for all elements. + */ + on(event: "element click", callback: (arg: Screen) => void): this; + on(event: "element mouseover", callback: (arg: Screen) => void): this; + on(event: "element mouseout", callback: (arg: Screen) => void): this; + on(event: "element mouseup", callback: (arg: Screen) => void): this; + /** + * Received on key event for [name]. + */ + //on(event: "key", callback: (arg: BlessedScreen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "focus", callback: (arg: Screen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "blur", callback: (arg: Screen) => void): this; + /** + * Received before render. + */ + on(event: "prerender", callback: () => void): this; + /** + * Received on render. + */ + on(event: "render", callback: () => void): this; + /** + * Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). + */ + on(event: "warning", callback: (text: string) => void): this; + /** + * Received when the screen is destroyed (only useful when using multiple screens). + */ + on(event: "destroy", callback: () => void): this; + /** + * Received when the element is moved. + */ + on(event: "move", callback: () => void): this; + /** + * Element was clicked (slightly smarter than mouseup). + */ + on(event: "click", callback: (arg: Screen) => void): this; + /** + * Received when element is shown. + */ + on(event: "show", callback: () => void): this; + /** + * Received when element becomes hidden. + */ + on(event: "hide", callback: () => void): this; + + on(event: "set content", callback: () => void): this; + on(event: "parsed content", callback: () => void): this; + } + + export interface IScreenOptions extends INodeOptions { + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program?: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR?: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR?: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE?: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout?: number; + /** + * The width of tabs within an element's content. + */ + tabSize?: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding?: boolean; + + cursor?: Types.TCursor; + + /** + * Create a log file. See log method. + */ + log?: (...msg: any[]) => void; + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump?: string; + /** + * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when + * pressing F12. It will display all log and debug messages. + */ + debug?: (...msg: string[]) => void; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked?: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders?: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast?: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode?: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus?: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings?: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode?: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input?: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output?: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput?: Tput; + /** + * Top of the focus history stack. + */ + focused?: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width?: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height?: Types.TPosition; + /** + * Same as screen.width. + */ + cols?: number; + /** + * Same as screen.height. + */ + rows?: number; + /** + * Relative top offset, always zero. + */ + top?: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left?: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right?: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom?: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop?: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft?: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright?: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom?: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys?: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys?: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover?: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal?: string; + /** + * Set or get window title. + */ + title?: string; + } + + export class Screen extends NodeWithEvents implements IHasOptions { + constructor(opts: IScreenOptions); + + // ** properties ** // + cleanSides: any; + + /** + * Original options object. + */ + options: IScreenOptions; + + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout: number; + /** + * The width of tabs within an element's content. + */ + tabSize: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding: boolean; + + cursor: Types.TCursor; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump: string; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput: Tput; + /** + * Top of the focus history stack. + */ + focused: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height: Types.TPosition; + /** + * Same as screen.width. + */ + cols: number; + /** + * Same as screen.height. + */ + rows: number; + /** + * Relative top offset, always zero. + */ + top: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal: string; + /** + * Set or get window title. + */ + title: string; + + // ** methods ** // + + /** + * Write string to the log file if one was created. + */ + log(...msg: any[]): void; + /** + * Same as the log method, but only gets called if the debug option was set. + */ + debug(...msg: string[]): void; + /** + * Allocate a new pending screen buffer and a new output screen buffer. + */ + alloc(): void; + /** + * Reallocate the screen buffers and clear the screen. + */ + realloc(): void; + /** + * Draw the screen based on the contents of the screen buffer. + */ + draw(start: number, end: number): void; + /** + * Render all child elements, writing all data to the screen buffer and drawing the screen. + */ + render(): void; + /** + * Clear any region on the screen. + */ + clearRegion(x1: number, x2: number, y1: number, y2: number): void; + /** + * Fill any region with a character of a certain attribute. + */ + fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; + /** + * Focus element by offset of focusable elements. + */ + focusOffset(offset: number): any; + /** + * Focus previous element in the index. + */ + focusPrevious(): void; + /** + * Focus next element in the index. + */ + focusNext(): void; + /** + * Push element on the focus stack (equivalent to screen.focused = el). + */ + focusPush(element: BlessedElement): void; + /** + * Pop element off the focus stack. + */ + focusPop(): BlessedElement; + /** + * Save the focused element. + */ + saveFocus(): BlessedElement; + /** + * Restore the saved focused element. + */ + restoreFocus(): BlessedElement; + /** + * "Rewind" focus to the last visible and attached element. + */ + rewindFocus(): BlessedElement; + /** + * Spawn a process in the foreground, return to blessed app after exit. + */ + spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + /** + * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. + */ + exec(file: string, args: string[], options: NodeChildProcessExecOptions, callback: Function): child_process.ChildProcess; + /** + * Read data from text editor. + */ + readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /** + * Set effects based on two events and attributes. + */ + setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; + /** + * Insert a line into the screen (using csr: this bypasses the output buffer). + */ + insertLine(n: number, y: number, top: number, bottom: number): void; + /** + * Delete a line from the screen (using csr: this bypasses the output buffer). + */ + deleteLine(n: number, y: number, top: number, bottom: number): void; + /** + * Insert a line at the bottom of the screen. + */ + insertBottom(top: number, bottom: number): void; + /** + * Insert a line at the top of the screen. + */ + insertTop(top: number, bottom: number): void; + /** + * Delete a line at the bottom of the screen. + */ + deleteBottom(top: number, bottom: number): void; + /** + * Delete a line at the top of the screen. + */ + deleteTop(top: number, bottom: number): void; + /** + * Enable mouse events for the screen and optionally an element (automatically called when a form of + * on('mouse') is bound). + */ + enableMouse(el: BlessedElement): void; + enableMouse(): void; + /** + * Enable keypress events for the screen and optionally an element (automatically called when a form of + * on('keypress') is bound). + */ + enableKeys(el: BlessedElement): void; + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(el: BlessedElement): void; + enableInput(): void; + /** + * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. + */ + copyToClipboard(text: string): void; + /** + * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution + * to this). Returns true if successful. + */ + cursorShape(shape: boolean, blink: boolean): any; + /** + * Attempt to change cursor color. Returns true if successful. + */ + cursorColor(color: string): void; + /** + * Attempt to reset cursor. Returns true if successful. + */ + cursorReset(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + /** + * Destroy the screen object and remove it from the global list. Also remove all global events relevant + * to the screen object. If all screen objects are destroyed, the node process is essentially reset + * to its initial state. + */ + destroy(): void; + /** + * Reset the terminal to term. Reloads terminfo. + */ + setTerminal(term: string): void; + } + + export interface Padding { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + + export class PositionCoords { + xi: number; + xl: number; + yi: number; + yl: number; + } + + export interface Position { + left: number | string; + right: number | string; + top: number | string; + bottom: number | string; + } + + export interface Border { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export interface ElementOptions extends INodeOptions { + tags?: boolean; + + fg?: string; + bg?: string; + bold?: string; + underline?: string; + + style?: any; + /** + * Border object, see below. + */ + border?: Border | "line" | "bg"; + /** + * Element's text content. + */ + content?: string; + /** + * Element is clickable. + */ + clickable?: boolean; + /** + * Element is focusable and can receive key input. + */ + input?: boolean; + keyable?: boolean; + /** + * Element is focused. + */ + focused?: BlessedElement; + /** + * Whether the element is hidden. + */ + hidden?: boolean; + /** + * A simple text label for the element. + */ + label?: string; + /** + * A floating text label for the element which appears on mouseover. + */ + hoverText?: string; + /** + * Text alignment: left, center, or right. + */ + align?: "left" | "center" | "right"; + /** + * Vertical text alignment: top, middle, or bottom. + */ + valign?: "top" | "middle" | "bottom"; + /** + * Shrink/flex/grow to content and child elements. Width/height during render. + */ + shrink?: boolean; + /** + * Amount of padding on the inside of the element. Can be a number or an object containing + * the properties: left, right, top, and bottom. + */ + padding?: number | Padding; + + top?: Types.TTopLeft; + left?: Types.TTopLeft; + right?: Types.TPosition; + bottom?: Types.TPosition; + + /** + * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). + * Percentages can also have offsets (50%+1, 50%-1). + */ + width?: number | string; + /** + * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or + * keyword (center). right and bottom do not accept keywords. Percentages can also have + * offsets (50%+1, 50%-1). + */ + height?: number | string; + /** + * Can contain the above options. + */ + position?: Position; + /** + * Whether the element is scrollable or not. + */ + scrollable?: boolean; + /** + * Background character (default is whitespace ). + */ + ch?: string; + /** + * Allow the element to be dragged with the mouse. + */ + draggable?: boolean; + /** + * Draw a translucent offset shadow behind the element. + */ + shadow?: boolean; + } + + export interface Coords { + xl: number; + xi: number; + yl: number; + yi: number; + base: number; + _contentEnd: {x: number; y: number;}; + notop: Types.TTopLeft; + noleft: Types.TTopLeft; + noright: Types.TPosition; + nobot: Types.TPosition; + } + + export interface LabelOptions { + text: string; + side: Types.TAlign; + } + + // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. + export abstract class BlessedElement extends NodeWithEvents implements IHasOptions { + constructor(opts: ElementOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: ElementOptions; + /** + * Name of the element. Useful for form submission. + */ + name: string; + /** + * Border object. + */ + border: Border; + + style: any; + position: Position; + content: string; + hidden: boolean; + visible: boolean; + detached: boolean; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg: number; + fg: number; + /** + * Border attributes. + */ + bold: string; + underline: string; + /** + * Calculated width. + */ + width: number | string; + /** + * Calculated height. + */ + height: number | string; + /** + * Calculated relative top offset.*/ + top: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + left: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + right: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + bottom: Types.TPosition; + /** + * Calculated absolute top offset. + */ + atop: Types.TTopLeft; + /** + * Calculated absolute left offset. + */ + aleft: Types.TTopLeft; + /** + * Calculated absolute right offset. + */ + aright: Types.TPosition; + /** + * Calculated absolute bottom offset. + */ + abottom: Types.TPosition; + + /** + * Whether the element is draggable. Set to true to allow dragging. + */ + draggable: boolean; + + itop: Types.TTopLeft; + ileft: Types.TTopLeft; + iheight: Types.TPosition; + iwidth: Types.TPosition; + + /** + * Calculated relative top offset. + */ + rtop: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + rleft: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + rright: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + rbottom: Types.TPosition; + + lpos: PositionCoords; + + // ** methods ** // + + /** + * Write content and children to the screen buffer. + */ + render(): Coords; + /** + * Hide element.*/ + hide(): void; + /** + * Show element. + */ + show(): void; + /** + * Toggle hidden/shown. + */ + toggle(): void; + /** + * Focus element. + */ + focus(): void; + /** + * Same asel.on('screen', ...) except this will automatically keep track of which listeners + * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). + */ + onScreenEvent(type: string, handler: Function): void; + /** + * Same asel.removeListener('screen', ...) except this will automatically keep track of which + * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). + */ + removeScreenEvent(type: string, handler: Function): void; + /** + * Free up the element. Automatically unbind all events that may have been bound to the screen + * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), + * and destroy(). + */ + free(): void; + /** + * Same as the detach() method, except this will automatically call free() and unbind any screen + * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). + */ + destroy(): void; + /** + * Set the z-index of the element (changes rendering order). + */ + setIndex(z: number): void; + /** + * Put the element in front of its siblings.*/ + setFront(): void; + /** + * Put the element in back of its siblings. + */ + setBack(): void; + /** + * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} + */ + setLabel(arg: string | LabelOptions): void; + /** + * Remove the label completely. + */ + removeLabel(): any; + /** + * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute + * in the browser. Example options: {text:'foo'} + */ + setHover(arg: string | LabelOptions): void; + /** + * Remove the hover label completely. + */ + removeHover(): void; + /** + * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). + */ + enableMouse(): void; + /** + * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). + */ + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(): void; + /** + * Enable dragging of the element. + */ + enableDrag(): void; + /** + * Disable dragging of the element. + */ + disableDrag(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /* + Content Methods + + Methods for dealing with text content, line by line. Useful for writing a text editor, + irc client, etc. + + Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() + on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending + on how long the original line was. + + The lines parameter can be a string or an array of strings. The line parameter must + be a string. + */ + + /** + * Set the content. Note: When text is input, it will be stripped of all non-SGR + * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced + * with SGR codes (if enabled). + */ + setContent(text: string): void; + /** + * Return content, slightly different from el.content. Assume the above formatting. + */ + getContent(): string; + /** + * Similar to setContent, but ignore tags and remove escape codes. + */ + setText(text: string): void; + /** + * Similar to getContent, but return content with tags and escape codes removed. + */ + getText(): string; + /** + * Insert a line into the box's content. + */ + insertLine(i: number, lines: string | string[]): void; + /** + * Delete a line from the box's content. + */ + deleteLine(i: number): void; + /** + * Get a line from the box's content. + */ + getLine(i: number): string; + /** + * Get a line from the box's content from the visible top. + */ + getBaseLine(i: number): string; + /** + * Set a line in the box's content. + */ + setLine(i: number, line: string | string[]): void; + /** + * Set a line in the box's content from the visible top. + */ + setBaseLine(i: number, line: string | string[]): void; + /** + * Clear a line from the box's content. + */ + clearLine(i: number): void; + /** + * Clear a line from the box's content from the visible top. + */ + clearBaseLine(i: number): void; + /** + * Insert a line at the top of the box. + */ + insertTop(lines: string | string[]): void; + /** + * Insert a line at the bottom of the box. + */ + insertBottom(lines: string | string[]): void; + /** + * Delete a line at the top of the box. + */ + deleteTop(): void; + /** + * Delete a line at the bottom of the box. + */ + deleteBottom(): void; + /** + * Unshift a line onto the top of the content. + */ + unshiftLine(lines: string | string[]): void; + /** + * Shift a line off the top of the content. + */ + shiftLine(i: number): void; + /** + * Push a line onto the bottom of the content. + */ + pushLine(lines: string | string[]): void; + /** + * Pop a line off the bottom of the content. + */ + popLine(i: number): string; + /** + * An array containing the content lines. + */ + getLines(): string[]; + /** + * An array containing the lines as they are displayed on the screen. + */ + getScreenLines(): string[]; + /** + * Get a string's displayed width, taking into account double-width, surrogate pairs, + * combining characters, tags, and SGR escape codes. + */ + strWidth(text: string): string; + + // ** events ** // + } + + export interface ScrollableBoxOptions extends ElementOptions { + /** + * A limit to the childBase. Default is Infinity. + */ + baseLimit?: number; + /** + * A option which causes the ignoring of childOffset. This in turn causes the + * childBase to change every time the element is scrolled. + */ + alwaysScroll?: boolean; + /** + * Object enabling a scrollbar. + * Style of the scrollbar track if present (takes regular style options). + */ + scrollbar?: { style?: any; track?: any; ch?: string; } + } + + export interface ScrollableTextOptions extends ScrollableBoxOptions { + /** + * Whether to enable automatic mouse support for this element. + * Use pre-defined mouse events (right-click for editor). + */ + mouse?: boolean | (() => void); + /** + * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). + */ + keys?: string | string[] | boolean; + /** + * Use vi keys with the keys option. + */ + vi?: boolean; + } + + export interface BoxOptions extends ScrollableTextOptions { + bindings?: any; + } + + /** + * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. + */ + export class ScrollableBoxElement extends BlessedElement { + /** + * The offset of the top of the scroll content. + */ + childBase: number; + /** + * The offset of the chosen item/line. + */ + childOffset: number; + + /** + * Scroll the content by a relative offset. + */ + scroll(offset: number, always?: boolean): void; + /** + * Scroll the content to an absolute index. + */ + scrollTo(index: number): void; + /** + * Same as scrollTo. + */ + setScroll(index: number): void; + /** + * Set the current scroll index in percentage (0-100). + */ + setScrollPerc(perc: number): void; + /** + * Get the current scroll index in lines. + */ + getScroll(): void; + /** + * Get the actual height of the scrolling area. + */ + getScrollHeight(): void; + /** + * Get the current scroll index in percentage. + */ + getScrollPerc(): void; + /** + * Reset the scroll index to its initial state. + */ + resetScroll(): void; + + on(event: string, listener: Function): this; + /** + * Received when the element is scrolled. + */ + on(event: "scroll", callback: () => void): this; + } + + /** + * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. + * A scrollable text box which can display and scroll text, as well as handle + * pre-existing newlines and escape codes. + */ + export class ScrollableTextElement extends ScrollableBoxElement { + } + + /** + * A box element which draws a simple box containing content or other elements. + */ + export class BoxElement extends ScrollableTextElement implements IHasOptions { + constructor(opts: BoxOptions); + + /** + * Original options object. + */ + options: BoxOptions; + } + + export interface TextOptions extends ElementOptions { + /** + * Fill the entire line with chosen bg until parent bg ends, even if there + * is not enough text to fill the entire width. + */ + fill?: boolean; + /** + * Text alignment: left, center, or right. + */ + align?: Types.TAlign; + } + + /** + * An element similar to Box, but geared towards rendering simple text elements. + */ + export class TextElement extends BlessedElement implements IHasOptions { + constructor(opts: TextOptions); + + /** + * Original options object. + */ + options: TextOptions; + } + + /** + * A simple line which can be line or bg styled. + */ + export interface LineOptions extends BoxOptions { + /** + * Can be vertical or horizontal. + */ + orientation?: "vertical" | "horizontal"; + /** + * Treated the same as a border object. (attributes can be contained in style). + */ + type?: string; + bg?: string; + fg?: string; + ch?: string; + } + + /** + * A simple line which can be line or bg styled. + */ + export class LineElement extends BoxElement implements IHasOptions { + constructor(opts: LineOptions); + + /** + * Original options object. + */ + options: LineOptions; + } + + export interface BigTextOptions extends BoxOptions { + /** + * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + font?: string; + /** + * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + fontBold?: string; + /** + * foreground character. (default: ' ') + */ + fch?: string; + } + + /** + * A box which can render content drawn as 8x14 cell characters using the terminus font. + */ + export class BigTextElement extends BoxElement implements IHasOptions { + constructor(opts: BigTextOptions); + + /** + * Original options object. + */ + options: BigTextOptions; + } + + export interface ListElementStyle { + selected?: any; + item?: any; + } + + export interface ListOptions extends BoxOptions { + /** + * Style for a selected item. Style for an unselected item. + */ + style?: TStyle; + /** + * An array of strings which become the list's items. + */ + items?: string[]; + /** + * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a + * callback function which should be called with the search string. The search string is then used to + * jump to an item that is found in items. + */ + search?: () => void; + /** + * Whether the list is interactive and can have items selected (Default: true). + */ + interactive?: boolean; + /** + * Whether to automatically override tags and invert fg of item when selected (Default: true). + */ + invertSelected?: boolean; + } + + export class ListElement extends BoxElement implements IHasOptions> { + constructor(opts: ListOptions); + + /** + * Original options object. + */ + options: ListOptions; + + /** + * Add an item based on a string. + */ + add(text: string): void; + /** + * Add an item based on a string. + */ + addItem(text: string): void; + /** + * Removes an item from the list. Child can be an element, index, or string. + */ + removeItem(child: BlessedElement): BlessedElement; + /** + * Push an item onto the list. + * */ + pushItem(child: BlessedElement): number; + /** + * Pop an item off the list. + * */ + popItem(): BlessedElement; + /** + * Unshift an item onto the list. + */ + unshiftItem(child: BlessedElement): number; + /** + * Shift an item off the list. + * */ + shiftItem(): BlessedElement; + /** + * Inserts an item to the list. Child can be an element, index, or string. + */ + insertItem(i: number, child: BlessedElement): void; + /** + * Returns the item element. Child can be an element, index, or string. + */ + getItem(child: BlessedElement): BlessedElement; + /** + * Set item to content. + */ + setItem(child: BlessedElement, content: BlessedElement | string): void; + /** + * Remove and insert items to the list. + * */ + spliceItem(i: number, n: number, ...items: BlessedElement[]): void; + /** + * Clears all items from the list. + * */ + clearItems(): void; + /** + * Sets the list items to multiple strings. + */ + setItems(items: BlessedElement[]): void; + /** + * Returns the item index from the list. Child can be an element, index, or string. + */ + getItemIndex(child: BlessedElement): number; + /** + * Select an index of an item. + * */ + select(index: number): void; + /** + * Select item based on current offset. + * */ + move(offset: number): void; + /** + * Select item above selected. + * */ + up(amount: number): void; + /** + * Select item below selected. + */ + down(amount: number): void; + /** + * Show/focus list and pick an item. The callback is executed with the result. + */ + pick(callback: () => void): void; + /** + * Find an item based on its text content. + */ + fuzzyFind(arg: string | RegExp | (() => void)): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "select", callback: (item: BoxElement, index: number) => void): this; + /** + * List was canceled (when esc is pressed with the keys option). + */ + on(event: "cancel", callback: () => void): this; + /** + * Either a select or a cancel event was received. + */ + on(event: "action", callback: () => void): this; + + on(event: "create item", callback: () => void): this; + on(event: "add item", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "insert item", callback: () => void): this; + on(event: "set items", callback: () => void): this; + on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; + } + + export interface FileManagerOptions extends ListOptions { + /** + * Current working directory. + */ + cwd?: string; + } + + export class FileManagerElement extends ListElement implements IHasOptions { + constructor(opts: FileManagerOptions); + + /** + * Original options object. + */ + options: FileManagerOptions; + /** + * Current working directory. + */ + cwd: string; + + /** + * Refresh the file list (perform a readdir on cwd and update the list items). + */ + refresh(cwd:string, callback: () => void): void; + refresh(callback: () => void): void; + refresh(): void; + /** + * Pick a single file and return the path in the callback. + */ + pick(cwd:string, callback: () => void): void; + pick(callback: () => void): void; + /** + * Reset back to original cwd. + */ + reset(cwd:string, callback: () => void): void; + reset(callback: () => void): void; + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "cd", callback: (file: string, cwd: string) => void): this; + /** + * Received when an item is selected. + */ + on(event: "file", callback: (file: string) => void): this; + + on(event: "error", callback: (err: any, file: string) => void): this; + on(event: "refresh", callback: () => void): this; + } + + export interface StyleListTable extends ListElementStyle { + /** + * Header style. + */ + header?: any; + /** + * Cell style. + */ + cell?: any; + } + + export interface ListTableOptions extends ListOptions { + /** + * Array of array of strings representing rows. + */ + rows?: string[]; + data?: string[][]; + /** + * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side + * (only useful if the width is shrunken). + */ + pad?: number; + /** + * Do not draw inner cells. + */ + noCellBorders?: boolean; + + style?: StyleListTable; + } + + export class ListTableElement extends ListElement implements IHasOptions { + constructor(opts: ListTableOptions); + + /** + * Original options object. + */ + options: ListTableOptions; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setRows(rows: string[][]): void; + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setData(rows: string[][]): void; + } + + export interface ListbarOptions extends BoxOptions { + style?: ListElementStyle; + /** + * Set buttons using an object with keys as titles of buttons, containing of objects + * containing keys of keys and callback. + */ + commands: Types.ListbarCommand[]; + items: Types.ListbarCommand[]; + /** + * Automatically bind list buttons to keys 0-9. + */ + autoCommandKeys: boolean; + } + + export class ListbarElement extends BoxElement implements IHasOptions { + constructor(opts: ListbarOptions); + + /** + * Original options object. + */ + options: ListbarOptions; + + /** + * Set commands (see commands option above). + */ + setItems(commands: Types.ListbarCommand[]): void; + /** + * Append an item to the bar. + */ + add(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + addItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + appendItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Select an item on the bar. + */ + select(offset: number): void; + /** + * Remove item from the bar. + */ + removeItem(child: BlessedElement): void; + /** + * Move relatively across the bar. + */ + move(offset: number): void; + /** + * Move left relatively across the bar. + */ + moveLeft(offset: number): void; + /** + * Move right relatively across the bar. + */ + moveRight(offset: number): void; + /** + * Select button and execute its callback. + */ + selectTab(index: number): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "set items", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "select tab", callback: () => void): this; + } + + export interface FormOptions extends BoxOptions { + /** + * Allow default keys (tab, vi keys, enter). + */ + keys?: any; + /** + * Allow vi keys. + */ + vi?: boolean; + } + + export class FormElement extends BoxElement implements IHasOptions { + constructor(opts: FormOptions); + + /** + * Original options object. + */ + options: FormOptions; + /** + * Last submitted data. + */ + submission: TFormData; + + /** + * Focus next form element. + */ + focusNext(): void; + /** + * Focus previous form element. + */ + focusPrevious(): void; + /** + * Submit the form. + */ + submit(): void; + /** + * Discard the form. + */ + cancel(): void; + /** + * Clear the form. + */ + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Form is submitted. Receives a data object. + */ + on(event: "submit", callback: (out: TFormData) => void): this; + /** + * Form is discarded. + */ + on(event: "cancel", callback: () => void): this; + /** + * Form is cleared. + */ + on(event: "reset", callback: () => void): this; + } + + export interface InputOptions extends BoxOptions { } + + export abstract class InputElement extends BoxElement { + constructor(opts: InputOptions); + } + + /** + * A box which allows multiline text input. + */ + export interface TextareaOptions extends InputOptions { + /** + * Call readInput() when the element is focused. Automatically unfocus. + */ + inputOnFocus?: boolean; + } + + export class TextareaElement extends InputElement implements IHasOptions { + constructor(opts: TextareaOptions); + + /** + * Original options object. + */ + options: TextareaOptions; + + /** + * The input text. read-only. + */ + value: string; + + /** + * Submit the textarea (emits submit). + */ + submit(): void; + /** + * Cancel the textarea (emits cancel). + */ + cancel(): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + readInput(callback?: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + input(callback: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + setInput(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + readEditor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + editor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + setEditor(callback: (err: any, value?: string) => void): void; + /** + * The same as this.value, for now. + */ + getValue(): string; + /** + * Clear input. + */ + clearValue(): void; + /** + * Set value. + */ + setValue(text: string): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "error", callback: (err: any) => void): this; + + /** + * Value is submitted (enter). + */ + on(event: "submit", callback: (value: any) => void): this; + /** + * Value is discared (escape). + */ + on(event: "cancel", callback: (value: any) => void): this; + /** + * Either submit or cancel. + */ + on(event: "action", callback: (value: any) => void): this; + } + + export interface TextboxOptions extends TextareaOptions { + /** + * Completely hide text. + */ + secret?: boolean; + /** + * Replace text with asterisks (*). + */ + censor?: boolean; + } + + export class TextboxElement extends TextareaElement implements IHasOptions { + constructor(opts: TextboxOptions); + + /** + * Original options object. + */ + options: TextboxOptions; + + /** + * Completely hide text. + */ + secret: boolean; + /** + * Replace text with asterisks (*). + */ + censor: boolean; + } + + export interface ButtonOptions extends BoxOptions { } + + export class ButtonElement extends InputElement implements IHasOptions { + constructor(opts: ButtonOptions); + + /** + * Original options object. + */ + options: ButtonOptions; + + /** + * Press button. Emits press. + */ + press(): void; + + on(event: string, listener: Function): this; + + on(event: "press", callback: () => void): this; + } + + export interface CheckboxOptions extends BoxOptions { + /** + * whether the element is checked or not. + * */ + checked?: boolean; + /** + * enable mouse support. + * */ + mouse?: boolean; + } + + /** + * A checkbox which can be used in a form element. + * */ + export class CheckboxElement extends InputElement implements IHasOptions { + constructor(options?: CheckboxOptions); + + /** + * Original options object. + */ + options: CheckboxOptions; + + /** + * the text next to the checkbox (do not use setcontent, use `check.text = ''`). + * */ + text: string; + /** + * whether the element is checked or not. + * */ + checked: boolean; + /** + * same as `checked`. + * */ + value: boolean; + + /** + * check the element. + * */ + check(): void; + /** + * uncheck the element. + * */ + uncheck(): void; + /** + * toggle checked state. + * */ + toggle(): void; + } + + export interface RadioSetOptions extends BoxOptions { } + + /** + * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive + * with each other. + * */ + export abstract class RadioSetElement extends BoxElement { + constructor(opts: RadioSetOptions); + } + + export interface RadioButtonOptions extends BoxOptions { } + + /** + * A radio button which can be used in a form element. + */ + export abstract class RadioButtonElement extends CheckboxElement { + constructor(opts: RadioButtonOptions); + } + + export interface PromptOptions extends BoxOptions { } + + /** + * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). + */ + export class PromptElement extends BoxElement implements IHasOptions { + constructor(opts: PromptOptions); + + options: PromptOptions; + + /** + * Show the prompt and wait for the result of the textbox. Set text and initial value. + */ + input(text: string, value: string, callback: (err: any, value: string) => void): void; + setInput(text: string, value: string, callback: (err: any, value: string) => void): void; + readInput(text: string, value: string, callback: (err: any, value: string) => void): void; + } + + export interface QuestionOptions extends BoxOptions { } + + /** + * A question box containing okay and cancel buttons (automatically hidden). + */ + export class QuestionElement extends BoxElement implements IHasOptions { + constructor(opts: QuestionOptions); + + options: QuestionOptions; + + /** + * Ask a question. callback will yield the result. + */ + ask(question: string, callback: (err: any, value: string) => void): void; + } + + export interface MessageOptions extends BoxOptions { } + + /** + * A box containing a message to be displayed (automatically hidden). + */ + export class MessageElement extends BoxElement implements IHasOptions { + constructor(opts: MessageOptions); + + options: MessageOptions; + + /** + * Display a message for a time (default is 3 seconds). Set time to 0 for a perpetual message that is dismissed on keypress. + */ + log(text: string, time: number, callback: (err: any) => void): void; + log(text: string, callback: (err: any) => void): void; + display(text: string, time: number, callback: (err: any) => void): void; + display(text: string, callback: (err: any) => void): void; + + /** + * Display an error in the same way. + */ + error(text: string, time: number, callback: () => void): void; + error(text: string, callback: () => void): void; + } + + export interface LoadingOptions extends BoxOptions { } + + /** + * A box with a spinning line to denote loading (automatically hidden). + */ + export class LoadingElement extends BoxElement implements IHasOptions { + constructor(opts: LoadingOptions); + + options: LoadingOptions; + + /** + * Display the loading box with a message. Will lock keys until stop is called. + */ + load(text: string): void; + /** + * Hide loading box. Unlock keys. + */ + stop(): void; + } + + export interface ProgressBarOptions extends BoxOptions { + /** + * can be `horizontal` or `vertical`. + * */ + orientation: string; + /** + * the character to fill the bar with (default is space). + * */ + pch: string; + /** + * the amount filled (0 - 100). + * */ + filled: number; + /** + * same as `filled`. + * */ + value: number; + /** + * enable key support. + * */ + keys: boolean; + /** + * enable mouse support. + * */ + mouse: boolean; + } + + /** + * A progress bar allowing various styles. This can also be used as a form input. + */ + export class ProgressBarElement extends InputElement implements IHasOptions { + constructor(options?: ProgressBarOptions); + + options: ProgressBarOptions; + + /** + * progress the bar by a fill amount. + * */ + progress(amount:number): void; + /** + * set progress to specific amount. + * */ + setProgress(amount:number): void; + /** + * reset the bar. + * */ + reset(): void; + + on(event: string, listener: Function): this; + /** + * Bar was reset. + */ + on(event: "reset", callback: () => void): this; + /** + * Bar has completely filled. + */ + on(event: "complete", callback: () => void): this; + } + + export interface LogOptions extends ScrollableTextOptions { + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback?: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput?: boolean; + } + + /** + * A log permanently scrolled to the bottom. + * */ + export class Log extends ScrollableTextElement implements IHasOptions { + constructor(options?: LogOptions); + + options: LogOptions; + + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput: boolean; + + /** + * add a log line. + * */ + log(text:string): void; + /** + * add a log line. + * */ + add(text:string): void; + } + + export interface TableOptions extends BoxOptions { + /** + * array of array of strings representing rows (same as `data`). + * */ + rows?: string[][]; + /** + * array of array of strings representing rows (same as `rows`). + * */ + data?: string[][]; + /** + * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). + * */ + pad?: number; + /** + * do not draw inner cells. + * */ + noCellBorders?: boolean; + /** + * fill cell borders with the adjacent background color. + * */ + fillCellBorders?: boolean; + } + + /** + * A stylized table of text elements. + * */ + export class TableElement extends BoxElement implements IHasOptions { + constructor(opts: TableOptions); + + options: TableOptions; + + /** + * set rows in table. array of arrays of strings. + * */ + setData(rows: string[][]): void; + /** + * set rows in table. array of arrays of strings. + * */ + setRows(rows: string[][]): void; + } + + export interface TerminalOptions extends BoxOptions { + /** + * handler for input data. + * */ + handler?: (userInput:Buffer) => void; + /** + * name of shell. $SHELL by default. + * */ + shell?:string; + /** + * args for shell. + * */ + args?:any; + /** + * can be line, underline, and block. + * */ + cursor?: 'line'|'underline'|'block'; + + terminal?: string; + + /** + * Object for process env. + */ + env?: any; + } + + export class TerminalElement extends BoxElement implements IHasOptions { + constructor(opts: TerminalOptions); + + options: TerminalOptions; + + /** + * reference to the headless term.js terminal. + * */ + term: any; + /** + * reference to the pty.js pseudo terminal. + * */ + pty: any; + + /** + * write data to the terminal. + * */ + write(data:string): void; + + /** + * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. + * */ + screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; + } + + export interface ImageOptions extends BoxOptions { + /** + * path to image. + * */ + file: string; + /** + * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + * */ + type: "ansi" | "overlay" | "w3m"; + } + + /** + * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. + * */ + export class ImageElement extends BoxElement implements IHasOptions { + constructor(options?: ImageOptions); + + options: ImageOptions; + } + + export interface ANSIImageOptions extends BoxOptions { + /** + * URL or path to PNG/GIF file. Can also be a buffer. + * */ + file: string; + /** + * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). + * */ + scale: number; + + /** + * This differs from other element's width or height in that only one of them is needed: blessed will maintain the aspect ratio of the image as it scales down to the proper number of cells. NOTE: PNG/GIF's are always automatically shrunken to size (based on scale) if a width or height is not given. + * */ + width: number | string; + height: number | string; + + /** + * Add various "density" ASCII characters over the rendering to give the image more detail, similar to libcaca/libcucul (the library mplayer uses to display videos in the terminal). + */ + ascii: string; + + /** + * Whether to animate if the image is an APNG/animating GIF. If false, only display the first frame or IDAT (Default: true). + */ + animate: boolean; + + /** + * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) + */ + speed: number; + + /** + * mem or cpu. If optimizing for memory, animation frames will be rendered to bitmaps as the animation plays, using less memory. Optimizing for cpu will precompile all bitmaps beforehand, which may be faster, but might also OOM the process on large images. (Default: mem). + */ + optimization: "mem" | "cpu"; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class ANSIImageElement extends BoxElement implements IHasOptions { + constructor(options?:ANSIImageOptions); + + options: ANSIImageOptions; + + /** + * Image object from the png reader. + */ + img: Types.TImage; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * Play animation if it has been paused or stopped. + */ + play(): void; + /** + * Pause animation. + */ + pause(): void; + /** + * Stop animation. + */ + stop(): void; + } + + export interface OverlayImageOptions extends BoxOptions { + /** + * Path to image. + */ + file: string; + /** + * Render the file as ANSI art instead of using w3m to overlay Internally uses the ANSIImage element. See the ANSIImage element for more information/options. (Default: true). + */ + ansi: boolean; + /** + * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + */ + w3m: string; + /** + * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). + */ + search: string; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class OverlayImageElement extends BoxElement implements IHasOptions { + constructor(options?: OverlayImageOptions); + + options: OverlayImageOptions; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * get the size of an image file in pixels. + * */ + imageSize(img:string, callback: () => void): void; + /** + * get the size of the terminal in pixels. + * */ + termSize(callback: () => void): void; + /** + * get the pixel to cell ratio for the terminal. + * */ + getPixelRatio(callback: () => void): void; + } + + export interface VideoOptions extends BoxOptions { + /** + * Video to play. + */ + file: string; + /** + * Start time in seconds. + */ + start: number; + } + + export class VideoElement extends BoxElement implements IHasOptions { + constructor(options?: VideoOptions); + + options: VideoOptions; + + /** + * The terminal element running mplayer or mpv. + */ + tty: any; + } + + export interface LayoutOptions extends ElementOptions { + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer?: () => void; + + /** + * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render + * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' + * width and height are always determined by the largest children in the layout. + */ + layout: "inline" | "inline-block" | "grid"; + } + + export class LayoutElement extends BlessedElement implements IHasOptions { + constructor(options?: LayoutOptions); + + options: LayoutOptions; + + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer(coords: PositionCoords): void; + /** + * Check to see if a previous child element has been rendered and is visible on screen. This is only useful + * for checking child elements that have already been attempted to be rendered! see the example below. + */ + isRendered(el: BlessedElement): boolean; + /** + * Get the last rendered and visible child element based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. + */ + getLast(i: number): Element; + /** + * Get the last rendered and visible child element coords based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. See the example below. + */ + getLastCoords(i: number): PositionCoords; + } + + export class Program { + /** + Wrap the given text in terminal formatting codes corresponding to the given attribute + name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 + integer color number. + */ + text (text:string, attr:string): string; + } } - export = Blessed; + export module widget { + export class Element extends Widgets.BlessedElement { } + export class Node extends Widgets.Node { } + export class Screen extends Widgets.Screen { } + + export class Box extends Widgets.BoxElement { } + export class ScrollableBox extends Widgets.ScrollableBoxElement { } + export class ScrollableText extends Widgets.ScrollableTextElement { } + export class Text extends Widgets.BoxElement { } + export class Line extends Widgets.LineElement { } + export class BigText extends Widgets.BigTextElement { } + export class List extends Widgets.ListElement { } + export class FileManager extends Widgets.FileManagerElement { } + export class ListTable extends Widgets.ListTableElement { } + export class ListBar extends Widgets.ListbarElement { } + export class Form extends Widgets.FormElement { } + export class Textarea extends Widgets.TextareaElement { } + export class Button extends Widgets.ButtonElement { } + export class Checkbox extends Widgets.CheckboxElement { } + export class RadioSet extends Widgets.RadioSetElement { } + export class RadioButton extends Widgets.RadioButtonElement { } + + export class Prompt extends Widgets.PromptElement { } + export class question extends Widgets.QuestionElement { } + export class Message extends Widgets.MessageElement { } + export class Loading extends Widgets.LoadingElement { } + + export class ProgressBar extends Widgets.ProgressBarElement { } + export class Terminal extends Widgets.TerminalElement { } + } + + export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; + + export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function text(options?: Widgets.TextOptions): Widgets.TextElement; + export function line(options?: Widgets.LineOptions): Widgets.LineElement; + export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; + export function list(options?: Widgets.ListOptions): Widgets.ListElement; + export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; + export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; + export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; + export function form(options?: Widgets.FormOptions): Widgets.FormElement; + export function input(options?: Widgets.InputOptions): Widgets.InputElement; + export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; + export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; + export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; + export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; + export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; + export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; + + export function table(options?: Widgets.TableOptions): Widgets.TableElement; + + export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; + export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; + export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; + export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; + + export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; + export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; + + export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; + + export function escape(item: any): any; + export const colors: { + match: (hexColor: string) => string + } } - - - From 3e18cac5fc60ccb0091bce3115e64890865253d9 Mon Sep 17 00:00:00 2001 From: Garth Kidd Date: Wed, 10 Aug 2016 10:28:40 +1000 Subject: [PATCH 03/56] Add new type definition for xmlpoke --- xmlpoke/xmlpoke-tests.ts | 83 ++++++++++++++++++++++++++++++++++++++++ xmlpoke/xmlpoke.d.ts | 45 ++++++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 xmlpoke/xmlpoke-tests.ts create mode 100644 xmlpoke/xmlpoke.d.ts diff --git a/xmlpoke/xmlpoke-tests.ts b/xmlpoke/xmlpoke-tests.ts new file mode 100644 index 0000000000..b77463f164 --- /dev/null +++ b/xmlpoke/xmlpoke-tests.ts @@ -0,0 +1,83 @@ +/// +/// + +// tsc xmlpoke-tests.ts && node xmlpoke-tests.js + +import * as xmlpoke from 'xmlpoke'; +import * as assert from 'assert'; + +let result: string; + +// add with xpath, value +result = xmlpoke('', xml => xml.add('/a/b', 'c')); +assert.equal(result, 'c'); + +// add with xpath, Transform +const addfn: XmlPoke.Transform = (node, value) => 'c'; +result = xmlpoke('', xml => xml.add('/a/b', addfn)); +assert.equal(result, 'c'); + +// add with xpath, CDataValue +const cdataval: XmlPoke.CDataValue = new xmlpoke.CDataValue('c'); +result = xmlpoke('', xml => xml.add('/a/b', cdataval)); +assert.equal(result, ''); + +// add with xpath, XMLVal +const xmlval = new xmlpoke.XmlString(''); +result = xmlpoke('', xml => xml.add('/a/b', xmlval)); +assert.equal(result, ''); + +// add with map +result = xmlpoke('', xml => xml.add({ + '/a/b': 'c' +})); +assert.equal(result, 'c'); + +// set with xpath, value +result = xmlpoke('b', xml => xml.set('/a', 'c')); +assert.equal(result, 'c'); + +// set with map +result = xmlpoke('b', xml => xml.set({ + '/a': 'c' +})); +assert.equal(result, 'c'); + +// set with xpath that doesn't exist (no-op) +result = xmlpoke('bval', xml => xml.set('/a/c', 'cval')); +assert.equal(result, 'bval'); + +// setOrAdd with xpath, value +result = xmlpoke('', xml => xml.setOrAdd('/a/b', 'c')); +assert.equal(result, 'c'); + +// setOrAdd with map +result = xmlpoke('', xml => xml.setOrAdd({ + '/a/b': 'c' +})); +assert.equal(result, 'c'); + +// setOrAdd with xpath that doesn't exist: add +result = xmlpoke('bval', xml => xml.setOrAdd('/a/c', 'cval')); +assert.equal(result, 'bvalcval'); + +// remove +result = xmlpoke('', xml => xml.remove('//b')); +assert.equal(result, ''); + +// clear +result = xmlpoke('', xml => xml.clear('/a')); +assert.equal(result, ''); + +// withBasePath, addNamespace, errorOnNoMatches +result = xmlpoke('', xml => + xml.withBasePath('/test') + .addNamespace('x', 'http://example.com/x') + .errorOnNoMatches() + .set('/x', (node, value) => { + assert.equal(typeof node, 'object'); + assert.equal((node.constructor as any).name, 'Element'); + assert.equal(value, 'hello'); + return 'y'; + })); +assert.equal(result, 'y'); diff --git a/xmlpoke/xmlpoke.d.ts b/xmlpoke/xmlpoke.d.ts new file mode 100644 index 0000000000..4b8868be98 --- /dev/null +++ b/xmlpoke/xmlpoke.d.ts @@ -0,0 +1,45 @@ +// Type definitions for xmlpoke 0.1.12 +// Project: https://github.com/mikeobrien/node-xmlpoke +// Definitions by: Garth Kidd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module XmlPoke { // ghost module + interface Transform { + (node: Node, value: string): Value; + } + type Value = string | boolean | number | XmlValue | CDataValue | PathToValueMap | Transform; + type PathToValueMap = { + [xpath: string]: Value; + } + interface API { + add(xpath: string, value: Value): API; + add(map: PathToValueMap): API; + set(xpath: string, value: Value): API; + set(map: PathToValueMap): API; + setOrAdd(xpath: string, value: Value): API; + setOrAdd(map: PathToValueMap): API; + remove(xpath: string): API; + clear(xpath: string): API; + withBasePath(xpath: string): API; + addNamespace(prefix: string, uri: string): API; + errorOnNoMatches(): API; + } + interface CDataValue { + value: string; + } + interface XmlValue { + value: string; + } +} + +declare module 'xmlpoke' { + const xmlpoke: { + (xml: string, modify: (api: XmlPoke.API) => void): string; + CDataValue: new (value: string) => XmlPoke.CDataValue; + XmlString: new (value: string) => XmlPoke.XmlValue; + }; + namespace xmlpoke {} + export = xmlpoke; +} From 0ebac1ef817e65b965d67b1255df7283f46d4001 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 11 Aug 2016 16:35:40 +0900 Subject: [PATCH 04/56] TypeScript-STL & Samchon Framework --- samchon-framework/samchon-framework.d.ts | 4554 +++++++++++++++++----- typescript-stl/typescript-stl-tests.ts | 2 +- typescript-stl/typescript-stl.d.ts | 1357 +++---- 3 files changed, 4371 insertions(+), 1542 deletions(-) diff --git a/samchon-framework/samchon-framework.d.ts b/samchon-framework/samchon-framework.d.ts index c81a9d1e5b..a6d03758dd 100644 --- a/samchon-framework/samchon-framework.d.ts +++ b/samchon-framework/samchon-framework.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Samchon Framework v1.2.0 +// Type definitions for Samchon Framework v2.0.0-beta.1 // Project: https://github.com/samchon/framework // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -11,28 +11,59 @@ declare module "samchon-framework" } /** - * Samchon Framework, A SDN framework. + *

Samchon-Framework

* + *

+ *

+ * + *

Samchon, a SDN (Software Defined Network) framework.

+ * + *

With Samchon Framework, you can implement distributed processing system within framework of OOD like + * handling S/W objects (classes). You can realize cloud and distributed system very easily with provided + * system templates and even integration with C++ is possible.

+ * + *

The goal, ultimate utilization model of Samchon Framework is, building cloud system with NodeJS and + * takING heavy works to C++ distributed systems with provided modules (those are system templates).

+ * + * @git https://github.com/samchon/framework * @author Jeongho Nam */ declare namespace samchon { -} -declare namespace samchon.library { -} -declare namespace samchon.collection { -} -declare namespace samchon.protocol { -} -declare namespace samchon.protocol.service { -} -declare namespace samchon.protocol.master { -} -declare namespace samchon.protocol.slave { + /** + *

Running on Node.

+ * + *

Test whether the JavaScript is running on Node.

+ * + * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser + */ + function is_node(): boolean; } declare namespace samchon.collection { /** * A {@link Vector} who can detect element I/O events. * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
    • {@link push_back}
    • + *
    • {@link unshift}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
    • {@link pop_back}
    • + *
    • {@link shift}
    • + *
    • {@link pop}
    • + *
    • {@link splice}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link sort}
    • + *
  • + *
+ * * @author Jeongho Nam */ class ArrayCollection extends std.Vector implements ICollection { @@ -80,38 +111,46 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.VectorIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.VectorIterator, last: std.VectorIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ @@ -132,12 +171,9 @@ declare namespace samchon.collection { } declare namespace samchon.library { /** - * An event class. - * - *
    - *
  • Comments from - https://developer.mozilla.org/en-US/docs/Web/API/Event/
  • - *
+ * A basic event class of Samchon Framework. * + * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event * @author Jeongho Nam */ class BasicEvent implements Event { @@ -231,51 +267,78 @@ declare namespace samchon.library { } declare namespace samchon.collection { /** - * Type of function pointer for {@link CollectionEvent CollectionEvents}. + * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. */ interface CollectionEventListener extends EventListener { (event: CollectionEvent): void; } +} +declare namespace samchon.collection { /** - * + * @author Jeongho Nam */ class CollectionEvent extends library.BasicEvent { - static INSERT: string; - static ERASE: string; /** - * + * @hidden */ private first_; /** - * + * @hidden */ private last_; /** + * Initialization Constructor. * - * - * @param type + * @param type Type of collection event. * @param first * @param last */ constructor(type: string, first: std.Iterator, last: std.Iterator); + constructor(type: "insert", first: std.Iterator, last: std.Iterator); + constructor(type: "erase", first: std.Iterator, last: std.Iterator); + constructor(type: "refresh", first: std.Iterator, last: std.Iterator); /** - * + * Get associative container. */ container: ICollection; /** - * + * Get range of the first. */ first: std.Iterator; /** - * + * Get range of the last. */ last: std.Iterator; } } +declare namespace samchon.collection.CollectionEvent { + const INSERT: string; + const ERASE: string; + const REFRESH: string; +} declare namespace samchon.collection { /** * A {@link Deque} who can detect element I/O events. * + *

Below are list of methods who are dispatching {@link CollectionEvent}:

+ * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
    • {@link push_front}
    • + *
    • {@link push_back}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
    • {@link pop_front}
    • + *
    • {@link pop_back}
    • + *
  • + *
+ * * @author Jeongho Nam */ class DequeCollection extends std.Deque implements ICollection { @@ -323,44 +386,72 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.DequeIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.DequeIterator, last: std.DequeIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { /** * A {@link HashMap} who can detect element I/O events. * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
    • {@link set}
    • + *
    • {@link insert_or_assign}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
    • {@link extract}
    • + *
  • + *
  • refresh typed events:
      + *
    • {@link set}
    • + *
    • {@link insert_or_assign}
    • + *
  • + *
+ * * @author Jeongho Nam */ class HashMapCollection extends std.HashMap implements ICollection> { @@ -384,42 +475,65 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener>): void; + addEventListener(type: "erase", listener: CollectionEventListener>): void; + addEventListener(type: "refresh", listener: CollectionEventListener>): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener>): void; + removeEventListener(type: "erase", listener: CollectionEventListener>): void; + removeEventListener(type: "refresh", listener: CollectionEventListener>): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; } +} +declare namespace samchon.collection { /** * A {@link HashMultiMap} who can detect element I/O events. * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
  • + *
+ * * @author Jeongho Nam */ class HashMultiMapCollection extends std.HashMap implements ICollection> { @@ -443,47 +557,143 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener>): void; + addEventListener(type: "erase", listener: CollectionEventListener>): void; + addEventListener(type: "refresh", listener: CollectionEventListener>): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener>): void; + removeEventListener(type: "erase", listener: CollectionEventListener>): void; + removeEventListener(type: "refresh", listener: CollectionEventListener>): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + } +} +declare namespace samchon.collection { + /** + * A {@link HashMultiSet} who can detect element I/O events. + * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
  • + *
+ * + * @author Jeongho Nam + */ + class HashMultiSetCollection extends std.HashMultiSet implements ICollection { + /** + * A chain object taking responsibility of dispatching events. + */ + private event_dispatcher_; /** * @inheritdoc */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + hasEventListener(type: string): boolean; /** * @inheritdoc */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { /** * A {@link HashSet} who can detect element I/O events. * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
    • {@link extract}
    • + *
  • + *
+ * * @author Jeongho Nam */ - class HashSetCollection extends std.TreeSet implements ICollection { + class HashSetCollection extends std.HashSet implements ICollection { /** * A chain object taking responsibility of dispatching events. */ @@ -507,216 +717,175 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + refresh(): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + refresh(it: std.SetIterator): void; /** * @inheritdoc */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: EventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - } - class HashMultiSetCollection extends std.TreeMultiSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: Event): boolean; + refresh(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { /** * An interface for {@link IContainer containers} who can detect element I/O events. * + *

Below are list of methods who are dispatching {@link CollectionEvent}:

+ * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
  • + * * @author Jeongho Nam */ interface ICollection extends std.base.IContainer, library.IEventDispatcher { + /** + *

    Dispatch a {@link CollectionEvent} with refresh typed.

    + * + *

    {@link ICollection} dispatches {@link CollectionEvent} typed insert or erase whenever + * elements I/O has occured. However, unlike those elements I/O events, content change in element level can't be + * detected. There's no way to detect those events automatically by {@link IContainer}.

    + * + *

    If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch refresh typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * refresh typed will be dispatched.

    + * + *

    If you don't specify any iterator, then the range of the refresh event will be all elements in this + * {@link ICollection collection}; {@link begin begin()} to {@link end end()}.

    + */ + refresh(): void; + /** + *

    Dispatch a {@link CollectionEvent} with refresh typed.

    + * + *

    {@link ICollection} dispatches {@link CollectionEvent} typed insert or erase whenever + * elements I/O has occured. However, unlike those elements I/O events, content change in element level can't be + * detected. There's no way to detect those events automatically by {@link IContainer}.

    + * + *

    If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch refresh typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * refresh typed will be dispatched.

    + * + * @param it An iterator targeting the content changed element. + */ + refresh(it: std.Iterator): void; + /** + *

    Dispatch a {@link CollectionEvent} with refresh typed.

    + * + *

    {@link ICollection} dispatches {@link CollectionEvent} typed insert or erase whenever + * elements I/O has occured. However, unlike those elements I/O events, content change in element level can't be + * detected. There's no way to detect those events automatically by {@link IContainer}.

    + * + *

    If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch refresh typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * refresh typed will be dispatched.

    + * + * @param first An Iterator to the initial position in a sequence of the content changed elmeents. + * @param last An {@link Iterator} to the final position in a sequence of the content changed elements. The range + * used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by + * last. + */ + refresh(first: std.Iterator, last: std.Iterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - *

    Registers an event listener object with an EventDispatcher object so that the listener - * receives notification of an event. You can register event listeners on all nodes in the display - * list for a specific type of event, phase, and priority. - * - *

    After you successfully register an event listener, you cannot change its priority through - * additional calls to addEventListener(). To change a listener's priority, you must first call - * removeEventListener(). Then you can register the listener again with the new priority level.

    - * - *

    Keep in mind that after the listener is registered, subsequent calls to addEventListener() - * with a different type or useCapture value result in the creation of a separate listener - * registration. For example, if you first register a listener with useCapture set to true, - * it listens only during the capture phase. If you call addEventListener() again using the same - * listener object, but with useCapture set to false, you have two separate listeners: one that - * listens during the capture phase and another that listens during the target and bubbling phases.

    - * - *

    You cannot register an event listener for only the target phase or the bubbling phase. - * Those phases are coupled during registration because bubbling applies only to the ancestors of - * the target node.

    - * - *

    If you no longer need an event listener, remove it by calling removeEventListener(), or - * memory problems could result. Event listeners are not automatically removed from memory because - * the garbage collector does not remove the listener as long as the dispatching object exists - * (unless the useWeakReference parameter is set to true).

    - * - *

    Copying an EventDispatcher instance does not copy the event listeners attached to it. (If - * your newly created node needs an event listener, you must attach the listener after creating - * the node.) However, if you move an EventDispatcher instance, the event listeners attached to - * it move along with it.

    - * - *

    If the event listener is being registered on a node while an event is also being processed - * on this node, the event listener is not triggered during the current phase but may be triggered - * during a later phase in the event flow, such as the bubbling phase.

    - * - *

    If an event listener is removed from a node while an event is being processed on the node, - * it is still triggered by the current actions. After it is removed, the event listener is never - * invoked again (unless it is registered again for future processing).

    - * - * @param event The type of event; {@link CollectionEvent.INSERT} or {@link CollectionEvent.ERASE}. - * @param listener The listener function that processes the event. - * This function must accept an Event object as its only parameter and must return - * nothing. - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - *

    Registers an event listener object with an EventDispatcher object so that the listener - * receives notification of an event. You can register event listeners on all nodes in the display - * list for a specific type of event, phase, and priority. - * - *

    After you successfully register an event listener, you cannot change its priority through - * additional calls to addEventListener(). To change a listener's priority, you must first call - * removeEventListener(). Then you can register the listener again with the new priority level.

    - * - *

    Keep in mind that after the listener is registered, subsequent calls to addEventListener() - * with a different type or useCapture value result in the creation of a separate listener - * registration. For example, if you first register a listener with useCapture set to true, - * it listens only during the capture phase. If you call addEventListener() again using the same - * listener object, but with useCapture set to false, you have two separate listeners: one that - * listens during the capture phase and another that listens during the target and bubbling phases.

    - * - *

    You cannot register an event listener for only the target phase or the bubbling phase. - * Those phases are coupled during registration because bubbling applies only to the ancestors of - * the target node.

    - * - *

    If you no longer need an event listener, remove it by calling removeEventListener(), or - * memory problems could result. Event listeners are not automatically removed from memory because - * the garbage collector does not remove the listener as long as the dispatching object exists - * (unless the useWeakReference parameter is set to true).

    - * - *

    Copying an EventDispatcher instance does not copy the event listeners attached to it. (If - * your newly created node needs an event listener, you must attach the listener after creating - * the node.) However, if you move an EventDispatcher instance, the event listeners attached to - * it move along with it.

    - * - *

    If the event listener is being registered on a node while an event is also being processed - * on this node, the event listener is not triggered during the current phase but may be triggered - * during a later phase in the event flow, such as the bubbling phase.

    - * - *

    If an event listener is removed from a node while an event is being processed on the node, - * it is still triggered by the current actions. After it is removed, the event listener is never - * invoked again (unless it is registered again for future processing).

    - * - * @param event The type of event; {@link CollectionEvent.INSERT} or {@link CollectionEvent.ERASE}. - * @param listener The listener function that processes the event. - * This function must accept an Event object as its only parameter and must return - * nothing. - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * Removes a listener from the EventDispatcher object. If there is no matching listener registered - * with the EventDispatcher object, a call to this method has no effect. - * - * @param type The type of event; {@link CollectionEvent.INSERT} or {@link CollectionEvent.ERASE}. - * @param listener The listener object to remove. - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * Removes a listener from the EventDispatcher object. If there is no matching listener registered - * with the EventDispatcher object, a call to this method has no effect. - * - * @param type The type of event; {@link CollectionEvent.INSERT} or {@link CollectionEvent.ERASE}. - * @param listener The listener object to remove. - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { /** * A {@link List} who can detect element I/O events. * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
      • {@link push_front}
      • + *
      • {@link push_back}
      • + *
      • {@link merge}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
      • {@link pop_front}
      • + *
      • {@link pop_back}
      • + *
      • {@link unique}
      • + *
      • {@link remove}
      • + *
      • {@link remove_if}
      • + *
      • {@link splice}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link sort}
      • + *
    • + *
    + * * @author Jeongho Nam */ class ListCollection extends std.List implements ICollection { @@ -772,47 +941,75 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.ListIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.ListIterator, last: std.ListIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { /** * A {@link TreeMap} who can detect element I/O events. * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
      • {@link set}
      • + *
      • {@link insert_or_assign}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
      • {@link extract}
      • + *
    • + *
    • refresh typed events:
        + *
      • {@link set}
      • + *
      • {@link insert_or_assign}
      • + *
    • + *
    + * * @author Jeongho Nam */ - class TreeMapCollection extends std.HashMap implements ICollection> { + class TreeMapCollection extends std.TreeMap implements ICollection> { /** * A chain object taking responsibility of dispatching events. */ @@ -833,45 +1030,68 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener>): void; + addEventListener(type: "erase", listener: CollectionEventListener>): void; + addEventListener(type: "refresh", listener: CollectionEventListener>): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener>): void; + removeEventListener(type: "erase", listener: CollectionEventListener>): void; + removeEventListener(type: "refresh", listener: CollectionEventListener>): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; } +} +declare namespace samchon.collection { /** * A {@link TreeMultiMap} who can detect element I/O events. * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
    • + *
    + * * @author Jeongho Nam */ - class TreeMultiMapCollection extends std.HashMap implements ICollection> { + class TreeMultiMapCollection extends std.TreeMultiMap implements ICollection> { /** * A chain object taking responsibility of dispatching events. */ @@ -892,95 +1112,65 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener>): void; + addEventListener(type: "erase", listener: CollectionEventListener>): void; + addEventListener(type: "refresh", listener: CollectionEventListener>): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener>): void; + removeEventListener(type: "erase", listener: CollectionEventListener>): void; + removeEventListener(type: "refresh", listener: CollectionEventListener>): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; } } declare namespace samchon.collection { - /** - * A {@link TreeMap} who can detect element I/O events. - * - * @author Jeongho Nam - */ - class TreeSetCollection extends std.TreeSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: Event): boolean; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: EventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: EventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - } /** * A {@link TreeMultiSet} who can detect element I/O events. * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
    • + *
    + * * @author Jeongho Nam */ class TreeMultiSetCollection extends std.TreeMultiSet implements ICollection { @@ -1004,38 +1194,121 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collection { + /** + * A {@link TreeMap} who can detect element I/O events. + * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
      • {@link extract}
      • + *
    • + *
    + * + * @author Jeongho Nam + */ + class TreeSetCollection extends std.TreeSet implements ICollection { + /** + * A chain object taking responsibility of dispatching events. + */ + private event_dispatcher_; /** * @inheritdoc */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + hasEventListener(type: string): boolean; /** * @inheritdoc */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } } declare namespace samchon.library { @@ -1373,7 +1646,7 @@ declare namespace samchon.library { * * @author Jeongho Nam */ - class XMLList extends std.Vector { + class XMLList extends std.Deque { getTag(): string; /** *

    Convert XMLList to string.

    @@ -1390,6 +1663,30 @@ declare namespace samchon.library { } } declare namespace samchon.collection { + /** + * An {@link XMLList} who can detect element I/O events. + * + *

    Below are list of methods who are dispatching {@link CollectionEvent}:

    + * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
      • {@link push_front}
      • + *
      • {@link push_back}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
      • {@link pop_front}
      • + *
      • {@link pop_back}
      • + *
    • + *
    + * + * @author Jeongho Nam + */ class XMLListCollection extends library.XMLList implements ICollection { /** * A chain object taking responsibility of dispatching events. @@ -1406,11 +1703,11 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.VectorIterator, n: number, val: library.XML): std.VectorIterator; + protected insert_by_repeating_val(position: std.DequeIterator, n: number, val: library.XML): std.DequeIterator; /** * @hidden */ - protected insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; + protected insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; /** * @inheritdoc */ @@ -1418,7 +1715,7 @@ declare namespace samchon.collection { /** * @hidden */ - protected erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; + protected erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; /** * @hidden */ @@ -1435,71 +1732,57 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.DequeIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.DequeIterator, last: std.DequeIterator): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - unshift(...items: U[]): number; - /** - * @inheritdoc - */ - pop(): library.XML; - /** - * @inheritdoc - */ - splice(start: number): library.XML[]; - /** - * @inheritdoc - */ - splice(start: number, deleteCount: number, ...items: library.XML[]): library.XML[]; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } } -declare namespace samchon.example { - function test_file_reference(): void; -} -declare namespace samchon.example { - function test_web_client(): void; -} declare namespace samchon.library { /** *

    Case generator.

    * - *

    CaseGenerator is an abstract case generator using like a matrix.

    + *

    {@link CaseGenerator} is an abstract case generator being used like a matrix.

    *
      - *
    • nTTr(n^r) -> CombinedPermutationGenerator
    • - *
    • nPr -> PermutationGenerator
    • - *
    • n! -> FactorialGenerator
    • + *
    • n��r(n^r) -> {@link CombinedPermutationGenerator}
    • + *
    • nPr -> {@link PermutationGenerator}
    • + *
    • n! -> {@link FactorialGenerator}
    • *
    * * @author Jeongho Nam @@ -1544,13 +1827,13 @@ declare namespace samchon.library { * @param index Index number * @return The row of the index'th in combined permuation case */ - abstract at(index: number): Array; + abstract at(index: number): number[]; } /** *

    A combined-permutation case generator.

    - *

    nTTr

    * - * @inheritdoc + *

    n��r

    + * * @author Jeongho Nam */ class CombinedPermutationGenerator extends CaseGenerator { @@ -1565,14 +1848,14 @@ declare namespace samchon.library { * @param r Size of elements of each case. */ constructor(n: number, r: number); - at(index: number): Array; + at(index: number): number[]; } /** *

    A permutation case generator.

    - *

    nPr

    + * + *

    nPr

    * * @author Jeongho Nam - * @inheritdoc */ class PermuationGenerator extends CaseGenerator { /** @@ -1585,8 +1868,15 @@ declare namespace samchon.library { /** * @inheritdoc */ - at(index: number): Array; + at(index: number): number[]; } + /** + *

    Factorial case generator.

    + * + *

    n! = nPn

    + * + * @author Jeongho Nam + */ class FactorialGenerator extends PermuationGenerator { /** * Construct from factorial size N. @@ -1602,8 +1892,8 @@ declare namespace samchon.library { * whether specific types of event listeners are registered, and dispatches events.

    * *

    Event targets are an important part of the Flash�� Player and Adobe AIR event model. The event - * target serves as the focal point for how events flow through the display list hierarchy. When an - * event such as a mouse click or a keypress occurs, an event object is dispatched into the event flow + * target serves as the local point for how events flow through the display list hierarchy. When an + * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow * from the root of the display list. The event object makes a round-trip journey to the event target, * which is conceptually divided into three phases: the capture phase includes the journey from the * root to the last node before the event target's node; the target phase includes only the event @@ -1728,6 +2018,7 @@ declare namespace samchon.library { * @param listener The listener function that processes the event. * This function must accept an Event object as its only parameter and must return * nothing. + * @param thisArg The object to be used as the this object. */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; /** @@ -1744,6 +2035,7 @@ declare namespace samchon.library { * * @param type The type of event. * @param listener The listener object to remove. + * @param thisArg The object to be used as the this object. */ removeEventListener(type: string, listener: EventListener, thisArg: Object): void; } @@ -1795,11 +2087,11 @@ declare namespace samchon.library { /** * The origin object who issuing events. */ - protected target: IEventDispatcher; + protected event_dispatcher_: IEventDispatcher; /** * Container of listeners. */ - protected listeners: std.HashMap>>; + protected event_listeners_: std.HashMap>>; /** * Default Constructor. */ @@ -1807,9 +2099,9 @@ declare namespace samchon.library { /** * Construct from the origin event dispatcher. * - * @param target The origin object who issuing events. + * @param dispatcher The origin object who issuing events. */ - constructor(target: IEventDispatcher); + constructor(dispatcher: IEventDispatcher); /** * @inheritdoc */ @@ -2011,6 +2303,31 @@ declare namespace samchon.library { * @param fileName File name to be saved. */ save(data: string, fileName: string): void; + /** + *

    Save a file to local filesystem.

    + * + *

    {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. + * However, the plan, future's {@link FileReference} will follow such rule:

    + * + *

    Opens a dialog box that lets the user save a file to the local filesystem.

    + * + *

    The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a + * filename and select a location on the local computer to save the file. When the user selects a location and + * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events + * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box + * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, + * open, progress, and complete.

    + * + *

    When the file is saved successfully, the properties of the {@link FileReference} object are populated with + * the properties of the local file. The complete event is dispatched if the save is successful.

    + * + *

    Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one + * dialog box can be invoked at a time).

    + * + * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. + * @param fileName File name to be saved. + */ + static save(data: string, fileName: string): void; } /** *

    The {@link FileReferenceList} class provides a means to let users select one or more files for @@ -2081,10 +2398,251 @@ declare namespace samchon.library { browse(...typeFilter: string[]): void; } } +declare namespace samchon.library { + /** + *

    A genetic algorithm class.

    + * + * @details + *

    In the field of artificial intelligence, a genetic algorithm (GA) is a search heuristic that mimics the + * process of natural selection. This heuristic (also sometimes called a metaheuristic) is routinely used to generate + * useful solutions to optimization and search problems.

    + * + *

    Genetic algorithms belong to the larger class of evolutionary algorithms (EA), which generate solutions to + * optimization problems using techniques inspired by natural evolution, such as inheritance, {@link mutate mutation}, + * {@link selection}, and {@link crossover}.

    + * + * @reference https://en.wikipedia.org/wiki/Genetic_algorithm + * @author Jeongho Nam + */ + class GeneticAlgorithm { + /** + * Whether each element (Gene) is unique in their GeneArray. + */ + private unique; + /** + * Rate of mutation. + * + * The {@link mutation_rate} determines the percentage of occurence of mutation in GeneArray. + * + *
      + *
    • When {@link mutation_rate} is too high, it is hard to ancitipate studying on genetic algorithm.
    • + *
    • + * When {@link mutation_rate} is too low and initial set of genes (GeneArray) is far away from optimal, the + * evolution tends to wandering outside of he optimal. + *
    • + *
    + */ + private mutation_rate; + /** + * Number of tournaments in selection. + */ + private tournament; + /** + * Initialization Constructor. + * + * @param unique Whether each Gene is unique in their GeneArray. + * @param mutation_rate Rate of mutation. + * @param tournament Number of tournaments in selection. + */ + constructor(unique?: boolean, mutation_rate?: number, tournament?: number); + /** + *

    Evolove GeneArray.

    + * + *

    Convenient method accessing to {@link evolvePopulation evolvePopulation()}.

    + * + * @param individual An initial set of genes; sequence listing. + * @param population Size of population in a generation. + * @param generation Size of generation in evolution. + * @param compare A comparison function returns whether left gene is more optimal. + * + * @return An evolved GeneArray, optimally. + * + * @see {@link GAPopulation.compare} + */ + evolveGeneArray>(individual: GeneArray, population: number, generation: number, compare?: (left: T, right: T) => boolean): GeneArray; + /** + * Evolve population, a mass of GeneArraies. + * + * @param population An initial population. + * @param compare A comparison function returns whether left gene is more optimal. + * + * @return An evolved population. + * + * @see {@link GAPopulation.compare} + */ + evolvePopulation>(population: GAPopulation, compare?: (left: T, right: T) => boolean): GAPopulation; + /** + *

    Select the best GeneArray in population from tournament.

    + * + *

    {@link selection Selection} is the stage of a genetic algorithm in which individual genomes are chosen + * from a population for later breeding (using {@linlk crossover} operator). A generic {@link selection} + * procedure may be implemented as follows:

    + * + *
      + *
    1. + * The fitness function is evaluated for each individual, providing fitness values, which are then + * normalized. ization means dividing the fitness value of each individual by the sum of all fitness + * values, so that the sum of all resulting fitness values equals 1. + *
    2. + *
    3. The population is sorted by descending fitness values.
    4. + *
    5. + * Accumulated normalized fitness values are computed (the accumulated fitness value of an individual is the + * sum of its own fitness value plus the fitness values of all the previous individuals). The accumulated + * fitness of the last individual should be 1 (otherwise something went wrong in the normalization step). + *
    6. + *
    7. A random number R between 0 and 1 is chosen.
    8. + *
    9. The selected individual is the first one whose accumulated normalized value is greater than R.
    10. + *
    + * + * @param population The target of tournament. + * @return The best genes derived by the tournament. + * + * @reference https://en.wikipedia.org/wiki/Selection_(genetic_algorithm) + */ + private selection(population); + /** + *

    Create a new GeneArray by crossing over two GeneArray(s).

    + * + *

    {@link crossover} is a genetic operator used to vary the programming of a chromosome or chromosomes from + * one generation to the next. It is analogous to reproduction and biological crossover, upon which genetic + * algorithms are based.

    + * + *

    {@link crossover Cross over} is a process of taking more than one parent solutions and producing a child + * solution from them. There are methods for selection of the chromosomes.

    + * + * @param parent1 A parent sequence listing + * @param parent2 A parent sequence listing + * + * @reference https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm) + */ + private crossover(parent1, parent2); + /** + *

    Cause a mutation on the GeneArray.

    + * + *

    {@link mutate Mutation} is a genetic operator used to maintain genetic diversity from one generation of a + * population of genetic algorithm chromosomes to the next. It is analogous to biological mutation.

    + * + *

    {@link mutate Mutation} alters one or more gene values in a chromosome from its initial state. In + * {@link mutate mutation}, the solution may change entirely from the previous solution. Hence GA can come to + * better solution by using {@link mutate mutation}.

    + * + *

    {@link mutate Mutation} occurs during evolution according to a user-definable mutation probability. This + * probability should be set low. If it is set too high, the search will turn into a primitive random search.

    + * + *

    Note

    + *

    Muttion is pursuing diversity. Mutation is useful for avoiding the following problem.

    + * + *

    When initial set of genes(GeneArray) is far away from optimail, without mutation (only with selection and + * crossover), the genetic algorithm has a tend to wandering outside of the optimal.

    + * + *

    Genes in the GeneArray will be swapped following percentage of the {@link mutation_rate}.

    + * + * @param individual A container of genes to mutate + * + * @reference https://en.wikipedia.org/wiki/Mutation_(genetic_algorithm) + * @see {@link mutation_rate} + */ + private mutate(individual); + } + /** + *

    A population in a generation.

    + * + *

    {@link GAPopulation} is a class representing population of candidate genes (sequence listing) having an array + * of GeneArray as a member. {@link GAPopulation} also manages initial set of genes and handles fitting test direclty + * by the method {@link fitTest fitTest()}.

    + * + *

    The success of evolution of genetic algorithm is depend on the {@link GAPopulation}'s initial set and fitting + * test. (GeneArray and {@link compare}.)

    + * + *

    Warning

    + *

    Be careful for the mistakes of direction or position of the {@link compare}.

    + *

    Most of logical errors failed to access optimal solution are occured from those mistakes.

    + * + * @param Type of gene elements. + * @param An array containing genes as elments; sequnce listing. + * + * @author Jeongho Nam + */ + class GAPopulation> { + /** + * Genes representing the population. + */ + private children; + /** + *

    A comparison function returns whether left gene is more optimal, greater.

    + * + *

    Default value of this {@link compare} is {@link std.greater}. It means to compare two array + * (GeneArray must be a type of {@link std.base.IArrayContainer}). Thus, you've to keep follwing rule.

    + * + *
      + *
    • GeneArray is implemented from {@link std.base.IArrayContainer}.
    • + *
        + *
      • {@link std.Vector}
      • + *
      • {@link std.Deque}
      • + *
      + *
    • GeneArray has custom public less(obj: T): boolean; function.
    • + *
    + * + *

    If you don't want to follow the rule or want a custom comparison function, you have to realize a + * comparison function.

    + */ + private compare; + /** + *

    Private constructor with population.

    + * + *

    Private constructor of GAPopulation does not create {@link children}. (candidate genes) but only assigns + * null repeatedly following the population size.

    + * + *

    This private constructor is designed only for {@link GeneticAlgorithm}. Don't create {@link GAPopulation} + * with this constructor, by yourself.

    + * + * @param size Size of the population. + */ + constructor(size: number); + /** + *

    Construct from a {@link GeneArray} and size of the population.

    + * + *

    This public constructor creates GeneArray(s) as population (size) having shuffled genes which are + * came from the initial set of genes (geneArray). It uses {@link std.greater} as default comparison function. + *

    + * + * @param geneArray An initial sequence listing. + * @param size The size of population to have as children. + */ + constructor(geneArray: GeneArray, size: number); + /** + *

    Constructor from a GeneArray, size of the poluation and custom comparison function.

    + * + *

    This public constructor creates GeneArray(s) as population (size) having shuffled genes which are + * came from the initial set of genes (geneArray). The compare is used for comparison function. + *

    + * + * @param geneArray An initial sequence listing. + * @param size The size of population to have as children. + * @param compare A comparison function returns whether left gene is more optimal. + */ + constructor(geneArray: GeneArray, size: number, compare: (left: GeneArray, right: GeneArray) => boolean); + /** + * Test fitness of each GeneArray in the {@link population}. + * + * @return The best GeneArray in the {@link population}. + */ + fitTest(): GeneArray; + /** + * @hidden + */ + private clone(obj); + } +} declare namespace samchon.library { /** *

    A utility class supporting static methods of string.

    * + *

    The {@link StringUtil} utility class is an all-static class with methods for working with string objects within + * Samchon Framework. You do not create instances of {@link StringUtil}; instead you call methods such as the + * StringUtil.substitute() method.

    + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/StringUtil.html * @author Jeongho Nam */ class StringUtil { @@ -2105,11 +2663,11 @@ declare namespace samchon.library { *
  • If start and end are all omitted, returns str, itself.
  • *
* - * @param str Target string to be applied between - * @param start A string for separating substring at the front - * @param end A string for separating substring at the end + * @param str Target string to be applied between. + * @param start A string for separating substring at the front. + * @param end A string for separating substring at the end. * - * @return substring by specified terms + * @return substring by specified terms. */ static between(str: string, start?: string, end?: string): string; /** @@ -2124,12 +2682,12 @@ declare namespace samchon.library { *
  • If startStr and endStar are all omitted, returns str.
  • * * - * @param str Target string to split by between + * @param str Target string to split by between. * @param start A string for separating substring at the front. - * If omitted, it's same with split(end) not having last item + * If omitted, it's same with split(end) not having last item. * @param end A string for separating substring at the end. - * If omitted, it's same with split(start) not having first item - * @return An array of substrings + * If omitted, it's same with split(start) not having first item. + * @return An array of substrings. */ static betweens(str: string, start?: string, end?: string): Array; /** @@ -2195,20 +2753,74 @@ declare namespace samchon.library { * @return A string specified words are replaced */ static replaceAll(str: string, ...pairs: std.Pair[]): string; - /** - *

    Get a tabbed string by specified size.

    - */ - static tab(size: number): string; - /** - *

    Get a tabbed HTLM string by specified size.

    - */ - static htmlTab(size: number): string; /** * Replace all HTML spaces to a literal space. * * @param str Target string to replace. */ static removeHTMLSpaces(str: string): string; + /** + *

    Repeat a string.

    + * + *

    Returns a string consisting of a specified string concatenated with itself a specified number of times.

    + * + * @param str The string to be repeated. + * @param n The repeat count. + * + * @return The repeated string. + */ + static repeat(str: string, n: number): string; + /** + *

    Number to formatted string with "," sign.

    + * + *

    Returns a string converted from the number rounded off from specified precision with "," symbols.

    + * + * @param val A number wants to convert to string. + * @param precision Target precision of round off. + * + * @return A string who represents the number with roundoff and "," symbols. + */ + static numberFormat(val: number, precision?: number): string; + static percentFormat(val: number, precision?: number): string; + } +} +declare namespace samchon.library { + /** + *

    URLVariables class is for representing variables of HTTP.

    + * + *

    URLVariables class allows you to transfer variables between an application and server. + * When transfering, URLVariables will be converted to a URI string.

    + * + *
      + *
    • URI: Uniform Resource Identifier
    • + *
    + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html + * @author Migrated by Jeongho Nam + */ + class URLVariables extends std.HashMap { + /** + * Default Constructor. + */ + constructor(); + /** + *

    Construct from a URL-encoded string.

    + * + *

    The {@link decode decode()} method is automatically called to convert the string to properties of the {@link URLVariables} object.

    + * + * @param str A URL-encoded string containing name/value pairs. + */ + constructor(str: string); + /** + * Converts the variable string to properties of the specified URLVariables object. + * + * @param str A URL-encoded query string containing name/value pairs. + */ + decode(str: string): void; + /** + * Returns a string containing all enumerable variables, in the MIME content encoding application/x-www-form-urlencoded. + */ + toString(): string; } } declare namespace samchon.protocol { @@ -2247,20 +2859,31 @@ declare namespace samchon.protocol { * * @param xml An xml used to contruct data of entity. */ - construct(xml: library.XML): any; + construct(xml: library.XML): void; /** *

    Get a key that can identify the Entity uniquely.

    * - *

    If identifier of the Entity is not atomic value, returns a string or paired object + *

    If identifier of the Entity is not atomic value, returns a paired or tuple object * that can represents the composite identifier.

    + * + * + * class Point extends Entity + * { + * private x: number; + * private y: number; + * + * public key(): std.Pair + * { + * return std.make_pair(this.x, this.y); + * } + * } + * */ key(): any; /** *

    A tag name when represented by XML.

    * - *
      - *
    • - *
    + * */ TAG(): string; /** @@ -2345,6 +2968,593 @@ declare namespace samchon.protocol { toXML(): library.XML; } } +declare namespace samchon.protocol { + /** + *

    An interface taking full charge of network communication.

    + * + *

    {@link ICommunicator} is an interface for communicator classes who take full charge of network communication + * with external system, without reference to whether the external system is a server or a client.

    + * + *

    Whenever a replied message comes from the external system, the message will be converted to an + * {@link Invoke} class and will be shifted to the {@link WebCommunicator.listener listener}'s + * {@link IProtocol.replyData replyData()} method.

    + * + * + interface ICommmunicator + { + private socket: SomeSocketClass; + + // LISTENER LISTENS INVOKE MESSAGE BY IT'S IProtocol.replyData() METHOD + protected listener: IProtocol; + + // YOU CAN DETECT DISCONNECTION BY ENROLLING FUNCTION POINTER TO HERE. + public onClose: Function; + + public sendData(invoke: Invoke): void + { + this.socket.write(invoke); + } + public replyData(invoke: Invoke): void + { + // WHENEVER COMMUNICATOR GETS MESSAGE, THEN SHIFT IT TO LISTENER'S replyData() METHOD. + this.listener.replyData(invoke); + } + } + * + * + *

    + * + *

    + * + * + *

    Basic Components

    + *

    What Basic Components are

    + *

    Basic Components are the smallest unit of network communication in this Samchon Framework. With + * Basic Components, you can construct any type of network system, even how the network system is enormously + * scaled and complicated, by just combinating the Basic Components.

    + * + *

    All the system templates in this framework are also being implemented by utilization of the + * Basic Compoonents.

    + * + *
      + *
    • {@link service Service} + *
    • {@link external External System} + *
    • {@link parallel Parallel System} + *
    • {@link distributed Distributed System} + *
    + * + *

    Note that, whatever the network system what you've to construct is, just concentrate on role of each system + * and attach matched Basic Components to the role, within framework of the Object-Oriented Design. + * Then construction of the network system will be much easier.

    + * + *
      + *
    • A system is a server, then use {@link IServer} or {@link IServerBase}.
    • + *
    • A server wants to handle a client has connected, then use {@link IClientDriver}.
    • + *
    • A system is a client connecting to an external server, then use {@link IServerConnector}.
    • + *
    • + *
    + * + *

    Example - System Templates

    + *

    Learning and understanding Basic Components of Samchon Framework, reading source codes and design of + * System Templates' modules will be very helpful.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Name Source API Documents
    Cloud Service protocol/service {@link protocol.service}
    External System protocol/external {@link protocol.external}
    Parallel System protocol/parallel {@link protocol.parallel}
    Distributed System protocol/distributed {@link protocol.distributed}
    Slave System protocol/slave {@link protocol.slave}
    + * + *

    Example - Projects

    + * + * + * @see {@link IClientDriver}, {@link IServerConnector} + * @handbook Basic Components - ICommunicator + * @author Jeongho Nam + */ + interface ICommunicator extends IProtocol { + /** + * Callback function for connection closed. + */ + onClose: Function; + /** + * Close connection. + */ + close(): any; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol { + abstract class CommunicatorBase implements ICommunicator { + /** + * @hidden + */ + protected listener: IProtocol; + /** + * @inheritdoc + */ + onClose: Function; + /** + * @hidden + */ + private binary_invoke; + /** + * @hidden + */ + private binary_parameters; + /** + * @hidden + */ + private unhandled_invokes; + /** + * Default Constructor. + */ + constructor(); + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + abstract close(): void; + protected is_binary_invoke(): boolean; + abstract sendData(invoke: Invoke): void; + replyData(invoke: Invoke): void; + protected handle_string(str: string): void; + protected handle_binary(binary: Uint8Array): void; + } +} +declare namespace samchon.protocol { + class Communicator extends CommunicatorBase { + /** + * @hidden + */ + protected socket: socket.socket; + /** + * @hidden + */ + private header_bytes; + /** + * @hidden + */ + private data; + /** + * @hidden + */ + private data_index; + /** + * @hidden + */ + private listening; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + protected start_listen(): void; + /** + * @hidden + */ + private handle_error(); + /** + * @hidden + */ + private handle_close(); + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + private listen_piece(piece); + /** + * @hidden + */ + private listen_header(piece, piece_index); + /** + * @hidden + */ + private listen_data(piece, piece_index); + } +} +declare namespace samchon.protocol { + /** + *

    Base class for web-communicator, {@link WebClientDriver} and {@link WebServerConnector}.

    + * + *

    This class {@link WebCommunicatorBase} subrogates network communication for web-communicator classes, + * {@link WebClinetDriver} and {@link WebServerConnector}. The web-communicator and this class + * {@link WebCommunicatorBase} share same interface {@link IProtocol} and have a chain of responsibily + * relationship.

    + * + *

    When an {@link Invoke} message was delivered from the connected remote system, then this class calls + * web-communicator's {@link WebServerConnector.replyData replyData()} method. Also, when called web-communicator's + * {@link WebClientDriver.sendData sendData()}, then {@link sendData sendData()} of this class will be caleed.

    + * + *
      + *
    • this.replyData() -> communicator.replyData()
    • + *
    • communicator.sendData() -> this.sendData()
    • + *
    + * + * @author Jeongho Nam + */ + class WebCommunicator extends CommunicatorBase { + /** + * Connection driver, a socket for web-socket. + */ + protected connection: websocket.connection; + /** + * Close the connection. + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + *

    Handle raw-data received from the remote system.

    + * + *

    Queries raw-data received from the remote system. When the raw-data represents an formal {@link Invoke} + * message, then it will be sent to the {@link replyData}.

    + * + * @param message A raw-data received from the remote system. + */ + protected handle_message(message: websocket.IMessage): void; + protected handle_close(): void; + } +} +declare namespace samchon.protocol { + class SharedWorkerCommunicator extends CommunicatorBase { + protected port: MessagePort; + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + protected handle_message(event: MessageEvent): void; + } +} +declare namespace samchon.protocol { + /** + *

    An interface for communicator with connected client.

    + * + *

    {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with connected client + * in a server. It takes full charge of network communication with the connected client.

    + * + *

    {@link IClientDriver} is created in {@link IServer} and delivered via + * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being + * created by matched {@link IServer} object.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Derived Type Created By
    {@link ClientDrvier} {@link Server}
    {@link WebClientDrvier} {@link WebServer}
    {@link SharedWorkerClientDrvier} {@link SharedWorkerServer}
    + * + *

    + * + *

    + * + *

    When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then + * specify {@link CommunicatorBase.listener listener} with {@link IClient.listen IClient.listen()}. Below codes are + * an example specifying and managing the {@link CommunicatorBase.listener listener} objects.

    + * + * + /// + /// + + // IMPORTS + import std = require("typescript-stl"); + import samchon = require("samchon-framework"); + + // SHORTCUTS + import library = samchon.library; + import protocol = samchon.protocol; + + class CalculatorServer extends protocol.Server + { + private clients: std.HashSet; + + // WHEN A CLIENT HAS CONNECTED + public addClient(driver: IClientDriver): void + { + let client: CalculatorClient = new CalculatorClient(this, driver); + this.clients.insert(client); + } + } + + class CalculatorClient extends protocol.IProtocol + { + // PARENT SERVER INSTANCE + private server: CalculatorServer; + + // COMMUNICATOR, SENDS AND RECEIVES NETWORK MESSAGE WITH CONNECTED CLIENT + private driver: protocol.IClientDriver; + + ///// + // CONSTRUCTORS + ///// + public constructor(server: CalculatorServer, driver: protocol.IClientDriver) + { + this.server = server; + this.driver = driver; + + // START LISTENING AND RESPOND CLOSING EVENT + this.driver.listen(this); // INVOKE MESSAGE WILL COME TO HERE + this.driver.onClose = this.destructor.bind(this); // DISCONNECTED HANDLER + } + public destructor(): void + { + // WHEN DISCONNECTED, THEN ERASE THIS OBJECT FROM CalculatorServer.clients. + this.server["clients"].erase(this); + } + + ///// + // INVOKE MESSAGE CHAIN + ///// + public sendData(invoke: protocol.Invoke): void + { + // CALL ICommunicator.sendData(), WHO PHYSICALLY SEND NETWORK MESSAGE + this.driver.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + // FIND MATCHED MEMBER FUNCTION NAMED EQUAL TO THE invoke.getListener() + invoke.apply(this); + } + } + * + * + * + *

    Basic Components

    + *

    What Basic Components are

    + *

    Basic Components are the smallest unit of network communication in this Samchon Framework. With + * Basic Components, you can construct any type of network system, even how the network system is enormously + * scaled and complicated, by just combinating the Basic Components.

    + * + *

    All the system templates in this framework are also being implemented by utilization of the + * Basic Compoonents.

    + * + *
      + *
    • {@link service Service} + *
    • {@link external External System} + *
    • {@link parallel Parallel System} + *
    • {@link distributed Distributed System} + *
    + * + *

    Note that, whatever the network system what you've to construct is, just concentrate on role of each system + * and attach matched Basic Components to the role, within framework of the Object-Oriented Design. + * Then construction of the network system will be much easier.

    + * + *
      + *
    • A system is a server, then use {@link IServer} or {@link IServerBase}.
    • + *
    • A server wants to handle a client has connected, then use {@link IClientDriver}.
    • + *
    • A system is a client connecting to an external server, then use {@link IServerConnector}.
    • + *
    • + *
    + * + *

    Example - System Templates

    + *

    Learning and understanding Basic Components of Samchon Framework, reading source codes and design of + * System Templates' modules will be very helpful.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Name Source API Documents
    Cloud Service protocol/service {@link protocol.service}
    External System protocol/external {@link protocol.external}
    Parallel System protocol/parallel {@link protocol.parallel}
    Distributed System protocol/distributed {@link protocol.distributed}
    Slave System protocol/slave {@link protocol.slave}
    + * + *

    Example - Projects

    + * + * + * @see {@link IServer} + * @handbook Basic Components - IClientDriver + * @author Jeongho Nam + */ + interface IClientDriver extends ICommunicator { + /** + *

    Listen message from the newly connected client.

    + * + *

    Starts listening message from the newly connected client. Replied message from the connected client will + * be converted to {@link Invoke} classes and shifted to the listener's + * {@link IProtocol.replyData replyData()} method.

    + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} message. + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + class ClientDriver extends Communicator implements IClientDriver { + constructor(socket: socket.socket); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + class WebClientDriver extends WebCommunicator implements IClientDriver { + /** + * Requested path. + */ + private path; + /** + * Session ID, an identifier of the remote client. + */ + private session_id; + private listening; + /** + * Initialization Constructor. + * + * @param connection Connection driver, a socket for web-socket. + * @param path Requested path. + * @param session_id Session ID, an identifier of the remote client. + */ + constructor(connection: websocket.connection, path: string, session_id: string); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + /** + * Get requested path. + */ + getPath(): string; + /** + * Get session ID, an identifier of the remote client. + */ + getSessionID(): string; + } +} +declare namespace samchon.protocol { + class SharedWorkerClientDriver extends SharedWorkerCommunicator implements IClientDriver { + private listening; + constructor(port: MessagePort); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + abstract class DedicatedWorker implements IProtocol { + private communicator_; + /** + * Default Constructor. + */ + constructor(); + abstract replyData(invoke: protocol.Invoke): void; + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + class DedicatedWorkerConnector extends CommunicatorBase implements IServerConnector { + private worker; + /** + * @inheritdoc + */ + onConnect: Function; + /** + * @inheritdoc + */ + onClose: Function; + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(jsFile: string): void; + /** + * @inheritdoc + */ + close(): void; + sendData(invoke: Invoke): void; + replyData(invoke: Invoke): void; + private handle_message(event); + } +} declare namespace samchon.protocol { interface IEntityGroup extends IEntity, std.base.IContainer { /** @@ -2368,7 +3578,6 @@ declare namespace samchon.protocol { * * @return A new child Entity belongs to EntityArray. */ - createChild(xml: library.XML): T; /** *

    Get iterator to element.

    * @@ -2444,9 +3653,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    Factory method of a child Entity.

    + * + *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged + * to the EntityArray. This method is called by EntityArray::construct(). The children construction + * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    + * + * @return A new child Entity belongs to EntityArray. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2488,9 +3703,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    Factory method of a child Entity.

    + * + *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged + * to the EntityArray. This method is called by EntityArray::construct(). The children construction + * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    + * + * @return A new child Entity belongs to EntityArray. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2532,9 +3753,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    Factory method of a child Entity.

    + * + *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged + * to the EntityArray. This method is called by EntityArray::construct(). The children construction + * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    + * + * @return A new child Entity belongs to EntityArray. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2583,9 +3810,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    Factory method of a child Entity.

    + * + *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged + * to the EntityArray. This method is called by EntityArray::construct(). The children construction + * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    + * + * @return A new child Entity belongs to EntityArray. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2627,9 +3860,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    Factory method of a child Entity.

    + * + *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged + * to the EntityArray. This method is called by EntityArray::construct(). The children construction + * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    + * + * @return A new child Entity belongs to EntityArray. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2671,9 +3910,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    Factory method of a child Entity.

    + * + *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged + * to the EntityArray. This method is called by EntityArray::construct(). The children construction + * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    + * + * @return A new child Entity belongs to EntityArray. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2709,203 +3954,238 @@ declare namespace samchon.protocol { } declare namespace samchon.protocol { /** - *

    A network driver for an external system.

    + *

    An interface for {@link Invoke} message chain.

    * - *

    ExternalSystem is a boundary class interacting with an external system by network communication. - * Also, ExternalSystem is an abstract class that a network role, which one is server and which one is - * client, is not determined yet.

    + *

    {@link IProtocol} is an interface for {@link Invoke} message, which is standard message of network I/O in + * Samchon Framework, chain. The {@link IProtocol} interface is used to network drivers and some classes + * which are in a relationship of Chain of Responsibility Pattern with those network drivers.

    * - *

    The ExternalSystem has ExternalSystemRole(s) groupped methods, handling Invoke message - * interacting with the external system, by subject or unit of a moudle. The ExternalSystemRole is - * categorized in a 'control'.

    + *

    Implements {@link IProtocol} if the class sends and handles {@link Invoke} message. Looking around source + * codes of Samchon Framework, especially System Templates, you can find out that all the classes and + * modules handling {@link Invoke} messages are always implementing this {@link IProtocol} . Yes, {@link IProtocol}, + * this is the main role you've to follow in this Samchon Framework.

    * - *

    Note

    - *

    The ExternalSystem class takes a role of interaction with external system in network level. - * However, within a framework of Samchon Framework, a boundary class like the ExternalSystem is - * not such important. You can find some evidence in a relationship between ExternalSystemArray, - * ExternalSystem and ExternalSystemRole.

    + *

    + * + *

    * - *

    Of course, the ExternalSystemRole is belonged to an ExternalSystem. However, if you - * access an ExternalSystemRole from an ExternalSystemArray directly, not passing by a belonged - * ExternalSystem, and send an Invoke message even you're not knowing which ExternalSystem is - * related in, it's called "Proxy pattern". * - *

    Like the explanation of "Proxy pattern", you can utilize an ExternalSystemRole as a proxy - * of an ExternalSystem. With the pattern, you can only concentrate on ExternalSystemRole itself, - * what to do with Invoke message, irrespective of the ExternalSystemRole is belonged to which - * ExternalSystem.

    - * - * @author Jeongho Nam - */ - abstract class ExternalSystem extends EntityArray implements IProtocol { - /** - *

    A driver for interacting with (real, physical) external system.

    - */ - protected driver: ServerConnector; - /** - *

    A name can identify an external system.

    - * - *

    The name must be unique in ExternalSystemArray.

    - */ - protected name: string; - /** - *

    An ip address of an external system.

    - */ - protected ip: string; - /** - *

    A port number of an external system.

    - */ - protected port: number; - /** - *

    Default Constructor.

    - */ - constructor(); - /** - *

    Start interaction.

    - *

    An abstract method starting interaction with an external system.

    - * - *

    If an external systems are a server, starts connection and listening Inovoke message, - * else clients, just starts listening only. You also can addict your own procudures of starting - * the driver, but if you directly override method of abstract ExternalSystem, be careful about - * virtual inheritance.

    - */ - start(): void; - key(): any; - /** - *

    Get name.

    - */ - getName(): string; - /** - *

    Get ip address of the external system.

    - */ - getIP(): string; - /** - *

    Get port number of the external system.

    - */ - getPort(): number; - sendData(invoke: Invoke): void; - replyData(invoke: Invoke): void; - TAG(): string; - CHILD_TAG(): string; - } -} -declare namespace samchon.protocol { - /** - *

    An array of ExternalSystem(s).

    - * - *

    ExternalSystemArray is an abstract class containing and managing external system drivers.

    - * - *

    Also, ExternalSystemArray can access to ExternalSystemRole(s) directly. With the method, you - * can use an ExternalSystemRole as "logical proxy" of an ExternalSystem. Of course, the - * ExternalSystemRole is belonged to an ExternalSystem. However, if you access an ExternalSystemRole - * from an ExternalSystemArray directly, not passing by a belonged ExternalSystem, and send an Invoke - * message even you're not knowing which ExternalSystem is related in, the ExternalSystemRole acted - * a role of proxy.

    - * - *

    It's called as "Proxy pattern". With the pattern, you can only concentrate on - * ExternalSystemRole itself, what to do with Invoke message, irrespective of the ExternalSystemRole - * is belonged to which ExternalSystem.

    + *

    Utilization Case

    + *

    Below pseudo code and class diagram represents {@link service Service Module}, who can build a cloud server. + * All the classes in the pseudo code are implementing the {@link IProtocol} because all of them are handling + * {@link Invoke} message.

    * *
      - *
    • ExternalSystemArray::getRole("something")->sendData(invoke);
    • + *
    • Server: Represents a server literally
    • + *
    • User: Represents an user being identified by its session id. User contains multiple Client objects.
    • + *
        + *
      • In browser, an user can open multiple windows. + *
          + *
        • User: A browser (like IE, Chrome and Safari). + *
        • Client: An internet browser window + *
        + *
      • + *
      + *
    • Client: Represents a browser window and it takes role of network communication with it.
    • + *
    • Service: Represents a service, domain logic.
    • *
    * - * @author Jeongho Nam - */ - abstract class ExternalSystemArray extends EntityArray implements IProtocol { - /** - * Default Constructor. - */ - constructor(); - /** - *

    Start interaction.

    - *

    An abstract method starting interaction with external systems.

    - * - *

    If external systems are servers, starts connection to them, else clients, opens a server - * and accepts the external systems. You can addict your own procudures of starting drivers, but - * if you directly override method of abstract ExternalSystemArray, be careful about virtual - * inheritance.

    - */ - start(): void; - /** - *

    Test whether has a role.

    - * - * @param name Name of an ExternalSystemRole. - * @return Whether has or not. - */ - hasRole(key: string): boolean; - /** - *

    Get a role.

    - * - * @param name Name of an ExternalSystemRole - * @return A shared pointer of specialized role - */ - getRole(key: string): ExternalSystemRole; - sendData(invoke: Invoke): void; - replyData(invoke: Invoke): void; - TAG(): string; - CHILD_TAG(): string; + *

    + * + *

    + * + * + /// + /// + + // IMPORTS + import std = require("typescript-stl"); + import samchon = require("samchon-framework"); + + // SHORTCUTS + import library = samchon.library; + import collection = samchon.collection; + import protocol = samchon.protocol; + + namespace service + { + export class Server extends protocol.WebServer implements IProtocol + { + // SERVER HAS MULTIPLE USER OBJECTS + private session_map: std.HashMap; + + //------------------------ + // MESSAGE CHAIN + //------------------------ + public sendData(invoke: protocol.Invoke): void + { + // SEND INVOKE MESSAGE TO ALL USER OBJECTS + for (let it = this.session_map.begin(); !it.equal_to(this.session_map.end()); it = it.next()) + it.second.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + invoke.apply(this); // HANDLE INVOKE MESSAGE BY ITSELF + } + } + + export class User extends + collection.HashMapCollection // USER HAS MULTIPLE CLIENT OBJECTS + implements IProtocol + { + private server: Server; // USER REFRES SERVER + + //------------------------ + // MESSAGE CHAIN + //------------------------ + public sendData(invoke: protocol.Invoke): void + { + // SEND INVOKE MESSAGE TO ALL CLIENT OBJECTS + for (let it = this.begin(); !it.equal_to(this.end()); it = it.next()) + it.second.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + invoke.apply(this); // HANDLE INOVKE MESSAGE BY ITSELF + this.server.replyData(invoke); // OR VIA SERVER + } + } + + export class Client implements IProtocol + { + private user: User; // CLIENT REFERS USER + private service: Service; // CLIENT HAS A SERVICE OBJECT + + private driver: WebClientDriver; + + //------------------------ + // MESSAGE CHAIN + //------------------------ + public sendData(invoke: protocol.Invoke): void + { + // SEND INVOKE MESSAGE VIA driver: WebClientDriver + this.driver.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + invoke.apply(this); // HANDLE INOVKE MEESAGE BY ITSELF + this.user.replyData(invoke); // OR VIA USER + + if (this.service != null) // OR VIA SERVICE + this.service.replyData(invoke); + } + } + + export class Service implements IProtocol + { + private client: Client; // SERVICE REFRES CLIENT + + //------------------------ + // MESSAGE CHAIN + //------------------------ + public sendData(invoke: protocol.Invoke): void + { + // SEND INVOKE MESSAGE VIA CLIENT + return this.client.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + invoke.apply(this); // HANDLE INVOKE MESSAGE BY ITSELF + } + } } -} -declare namespace samchon.protocol { - /** - *

    A role belongs to an external system.

    + *
    * - *

    ExternalSystemRole is a 'control' class groupping methods, handling Invoke messages - * interacting with an external system that the ExternalSystemRole is belonged to, by a subject or - * unit of a module.

    * - *

    ExternalSystemRole can be a "logical proxy" for an ExternalSystem which is containing the - * ExternalSystemRole. Of course, the ExternalSystemRole is belonged to an ExternalSystem. However, - * if you access an ExternalSystemRole from an ExternalSystemArray directly, not passing by a - * belonged ExternalSystem, and send an Invoke message even you're not knowing which ExternalSystem - * is related in, the ExternalSystemRole acted a role of proxy.

    + *

    Basic Components

    + *

    What Basic Components are

    + *

    Basic Components are the smallest unit of network communication in this Samchon Framework. With + * Basic Components, you can construct any type of network system, even how the network system is enormously + * scaled and complicated, by just combinating the Basic Components.

    * - *

    It's called as "Proxy pattern". With the pattern, you can only concentrate on - * ExternalSystemRole itself, what to do with Invoke message, irrespective of the ExternalSystemRole - * is belonged to which ExternalSystem.

    + *

    All the system templates in this framework are also being implemented by utilization of the + * Basic Compoonents.

    * - * @author Jeongho Nam - */ - class ExternalSystemRole extends Entity implements IProtocol { - /** - *

    A driver of external system containing the ExternalSystemRole.

    - */ - protected system: ExternalSystem; - /** - *

    A name representing the role.

    - */ - protected name: string; - protected sendListeners: std.HashSet; - /** - *

    Construct from external system driver.

    - * - * @param system A driver of external system the ExternalSystemRole is belonged to. - */ - constructor(system: ExternalSystem); - construct(xml: library.XML): void; - getName(): string; - hasSendListener(key: string): boolean; - sendData(invoke: Invoke): void; - replyData(invoke: Invoke): void; - TAG(): string; - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - *

    An interface for Invoke message chain.

    + *
      + *
    • {@link service Service} + *
    • {@link external External System} + *
    • {@link parallel Parallel System} + *
    • {@link distributed Distributed System} + *
    * - *

    IProtocol is an interface for Invoke message, which is standard message of network I/O - * in Samchon Framework, chain. The IProtocol interface is used to network drivers and some - * classes which are in a relationship of chain of responsibility with those network drivers.

    + *

    Note that, whatever the network system what you've to construct is, just concentrate on role of each system + * and attach matched Basic Components to the role, within framework of the Object-Oriented Design. + * Then construction of the network system will be much easier.

    * - *

    In Samchon Framework, server side, IProtocol is one of the basic 3 + 1 components that - * can make any type of network system in Samchon Framework with IServer and IClient. Following - * the "chain of responsibility" pa1ttern, looking around classes in Samchon Framework, you - * can see all related classes with network I/O are implemented from the IProtocol.

    + *
      + *
    • A system is a server, then use {@link IServer} or {@link IServerBase}.
    • + *
    • A server wants to handle a client has connected, then use {@link IClientDriver}.
    • + *
    • A system is a client connecting to an external server, then use {@link IServerConnector}.
    • + *
    • + *
    * - * @see Invoke + *

    Example - System Templates

    + *

    Learning and understanding Basic Components of Samchon Framework, reading source codes and design of + * System Templates' modules will be very helpful.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Name Source API Documents
    Cloud Service protocol/service {@link protocol.service}
    External System protocol/external {@link protocol.external}
    Parallel System protocol/parallel {@link protocol.parallel}
    Distributed System protocol/distributed {@link protocol.distributed}
    Slave System protocol/slave {@link protocol.slave}
    + * + *

    Example - Projects

    + * + * + * @see {@link Invoke} + * @handbook Basic Components - IProtocol * @author Jeongho Nam */ interface IProtocol { @@ -2920,7 +4200,7 @@ declare namespace samchon.protocol { *

    Handling replied message.

    *

    Handles replied message or shifts the responsibility to chain.

    * - * @param invoke Replied invoke message + * @param invoke An {@link Invoke} message has received. */ sendData(invoke: Invoke): void; } @@ -2928,7 +4208,8 @@ declare namespace samchon.protocol { declare namespace samchon.protocol { /** *

    Standard message of network I/O.

    - *

    Invoke is a class used in network I/O in protocol package of Samchon Framework.

    + * + *

    {@link Invoke} is a class used in network I/O in protocol package of Samchon Framework.

    * *

    The Invoke message has an XML structure like the result screen of provided example in below. * We can enjoy lots of benefits by the normalized and standardized message structure used in @@ -2940,8 +4221,8 @@ declare namespace samchon.protocol { * like a object (class) in OOD. And those relationships can be easily designed by using design * pattern.

    * - *

    In Samchon Framework, you can make any type of network system with basic 3 + 1 componenets - * (IProtocol, IServer and IClient + ServerConnector), by implemens or inherits them, like designing + *

    In Samchon Framework, you can make any type of network system with basic componenets + * (IProtocol, IServer and ICommunicator) by implemens or inherits them, like designing * classes of S/W architecture.

    * * @see IProtocol @@ -2952,6 +4233,10 @@ declare namespace samchon.protocol { *

    Listener, represent function's name.

    */ protected listener: string; + /** + * Default Constructor. + */ + constructor(); constructor(listener: string); /** * Copy Constructor. @@ -2959,13 +4244,17 @@ declare namespace samchon.protocol { * @param invoke */ constructor(invoke: Invoke); - constructor(xml: library.XML); - constructor(listener: string, begin: std.VectorIterator, end: std.VectorIterator); - constructor(listener: string, ...parameters: any[]); + /** + * Construct from listener and parametric values. + * + * @param listener + * @param parameters + */ + constructor(listener: string, ...parameters: Array); /** * @inheritdoc */ - createChild(xml: library.XML): InvokeParameter; + protected createChild(xml: library.XML): InvokeParameter; /** * Get listener. */ @@ -2990,93 +4279,10 @@ declare namespace samchon.protocol { CHILD_TAG(): string; } } -declare namespace samchon.protocol { - /** - *

    A history of an Invoke message.

    - * - *

    InvokeHistory is a class for reporting history log of an Invoke message with elapsed time - * from a slave to its master.

    - * - *

    With the elapsed time, consumed time for a process of handling the Invoke message, - * InvokeHistory is reported to the master. The master utilizies the elapsed time to estimating - * performances of each slave system. With the estimated performan index, master retrives the - * optimal solution of distributing processes.

    - * - * @author Jeongho Nam - */ - class InvokeHistory extends Entity { - /** - *

    An identifier.

    - */ - protected uid: number; - /** - *

    A listener of the Invoke message.

    - * - *

    InvokeHistory does not archive entire data of an Invoke message. InvokeHistory only - * archives its listener. The first, formal reason is to save space, avoid wasting spaces.

    - * - *

    The second, complicate reason is on an aspect of which systems are using the - * InvokeHistory class. InvokeHistory is designed to let slave reports to master elapsed time - * of a process used to handling the Invoke message. If you want to archive entire history log - * of Invoke messages, then the subject should be master, not the slave using InvokeHistory - * classes.

    - */ - protected listener: string; - /** - *

    Start time of the history.

    - * - *

    Means start time of a process handling the Invoke message. The start time not only - * has ordinary arguments represented Datetime (year to seconds), but also has very precise - * values under seconds, which is expressed as nano seconds (10^-9).

    - * - *

    The precise start time will be used to calculate elapsed time with end time.

    - */ - protected startTime: Date; - /** - *

    End time of the history.

    - * - * @details - *

    Means end time of a process handling the Invoke message. The end time not only - * has ordinary arguments represented Datetime (year to seconds), but also has very precise - * values under seconds, which is expressed as nano seconds (10^-9).

    - * - *

    The precise end time will be used to calculate elapsed time with start time.

    - */ - protected endTime: Date; - /** - *

    Construct from an Invoke message.

    - * - *

    InvokeHistory does not archive entire Invoke message, only archives its listener.

    - * - * @param invoke A message to archive its history log - */ - constructor(invoke: Invoke); - /** - *

    Notify end of the process.

    - * - *

    Notifies end of a process handling the matched Invoke message to InvokeHistory.

    - *

    InvokeHistory archives the end datetime and calculates elapsed time as nanoseconds.

    - */ - notifyEnd(): void; - TAG(): string; - toXML(): library.XML; - /** - *

    Get an Invoke message.

    - * - *

    Returns an Invoke message to report to a master that how much time was elapsed on a - * process handling the Invoke message. In master, those reports are used to estimate - * performance of each slave system.

    - * - * @return An Invoke message to report master. - */ - toInvoke(): Invoke; - } -} declare namespace samchon.protocol { /** * A parameter belongs to an Invoke. * - * @see Invoke * @author Jeongho Nam */ class InvokeParameter extends Entity { @@ -3093,31 +4299,33 @@ declare namespace samchon.protocol { /** *

    Value of the parameter.

    */ - protected value: any; + protected value: string | number | library.XML | Uint8Array; /** * Default Constructor. */ constructor(); + constructor(val: number); + constructor(val: string); + constructor(val: library.XML); + constructor(val: Uint8Array); /** - * Initialization Constructor without type specification. + * Construct from variable name and number value. * * @param name * @param val */ - constructor(name: string, val: any); - /** - * Initialization Constructor. - * - * @param name - * @param type - * @param val - */ - constructor(name: string, type: string, val: any); + constructor(name: string, val: number); + constructor(name: string, val: string); + constructor(name: string, val: library.XML); + constructor(name: string, val: Uint8Array); /** * @inheritdoc */ construct(xml: library.XML): void; - setValue(value: any): void; + setValue(value: number): any; + setValue(value: string): any; + setValue(value: library.XML): any; + setValue(value: Uint8Array): any; /** * @inheritdoc */ @@ -3145,193 +4353,1781 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { - /** - *

    A server connector for a physical client.

    - * - *

    ServerConnector is a class for a physical client connecting a server. If you want to connect - * to a server, then implements this ServerConnector and just override some methods like - * getIP(), getPort() and replyData(). That's all.

    - * - *

    In Samchon Framework, package protocol, There are basic 3 + 1 components that can make any - * type of network system in Samchon Framework. The basic 3 components are IProtocol, IServer and - * IClient. The last, surplus one is the ServerConnector. Looking around classes in - * Samchon Framework, especially module master and slave which are designed for realizing - * distributed processing systems and parallel processing systems, physical client classes are all - * derived from this ServerConnector.

    - * - * - * - * @author Jeongho Nam - */ - class ServerConnector implements IProtocol { + class InvokeHistory extends Entity { /** - *

    A parent object who listens and sends Invoke message.

    * - *
      - *
    • ServerConnector.replyData(Invoke) -> parent.replyData(Invoke)
    • - *
    */ - private parent; + private uid; /** - *

    A socket for network I/O.

    + * @see {@link Invoke.listener} */ - private socket; - private binary_invoke; + private listener; /** - *

    An open-event listener.

    - */ - onopen: Function; - /** - *

    Constructor with parent.

    - */ - constructor(parent: IProtocol); - /** - *

    Connects to a cloud server with specified host and port.

    * - *

    If the connection fails immediately, either an event is dispatched or an exception is thrown: - * an error event is dispatched if a host was specified, and an exception is thrown if no host - * was specified. Otherwise, the status of the connection is reported by an event. - * If the socket is already connected, the existing connection is closed first.

    + */ + private startTime; + /** * - * @param ip - * The name or IP address of the host to connect to. - * If no host is specified, the host that is contacted is the host where the calling - * file resides. If you do not specify a host, use an event listener to determine whether - * the connection was successful. - * @param port - * The port number to connect to. - * - * @throws IOError - * No host was specified and the connection failed. - * @throws SecurityError - * This error occurs in SWF content for the following reasons: - * Local untrusted SWF files may not communicate with the Internet. You can work around - * this limitation by reclassifying the file as local-with-networking or as trusted. */ - connect(ip: string, port: number, path?: string): void; + private endTime; /** - *

    Send data to the server.

    + * Default Constructor. */ - sendData(invoke: Invoke): void; - /** - *

    Shift responsiblity of handling message to parent.

    - */ - replyData(invoke: Invoke): void; - private handleConnect(event); - /** - *

    Handling replied message.

    - */ - private handleReply(event); + constructor(); + constructor(invoke: Invoke); + construct(xml: library.XML): void; + notifyEnd(): void; + key(): number; + getUID(): number; + getListener(): string; + getStartTime(): Date; + getEndTime(): Date; + computeElapsedTime(): number; + TAG(): string; + toXML(): library.XML; + toInvoke(): Invoke; } } -declare namespace samchon.protocol.service { +declare namespace samchon.protocol { /** - *

    An application, the top class in JS-UI.

    + *

    An interface for a physical server.

    + * + *

    {@link IServer} provides methods for opening a server. Extends one of them who are derived from this + * {@link IServer} and open the server with method {@link open IServer.open()}. Override + * {@link addClient IServer.addClient()} who accepts a newly connected client with {@link IClientDriver}. + * If you're embarrased because your class already extended another one, then use {@link IServerBase}.

    * - *

    The Application is separated to three part, TopMenu, Movie and ServerConnector.

    *
      - *
    • TopMenu: Menu on the top. It's not an essential component.
    • - *
    • Movie: Correspond with Service in Server. Movie has domain UI components(Movie) for the matched Service.
    • - *
    • ServerConnector: The socket connecting to the Server.
    • + *
    • {@link Server}
    • + *
    • {@link WebServer}
    • + *
    • {@link SharedWorkerServer}
    • *
    * - *

    The Application and its UI-layout is not fixed, essential component for Samchon Framework in Flex, - * so it's okay to do not use the provided Application and make your custom Application. - * But the custom Application, your own, has to contain the Movie and keep the construction routine.

    + *

    + * + *

    * - *

    + *

    Basic Components

    + *

    What Basic Components are

    + *

    Basic Components are the smallest unit of network communication in this Samchon Framework. With + * Basic Components, you can construct any type of network system, even how the network system is enormously + * scaled and complicated, by just combinating the Basic Components.

    + * + *

    All the system templates in this framework are also being implemented by utilization of the + * Basic Compoonents.

    * - *

    THE CONSTRUCTION ROUTINE

    *
      - *
    • Socket Connection
    • - *
        - *
      • Connect to the CPP-Server
      • - *
      - *
    • Fetch authority
    • - *
        - *
      • Send a request to fetching authority
      • - *
      • The window can be navigated to other page by the authority
      • - *
      - *
    • Construct Movie
    • - *
        - *
      • Determine a Movie by URLVariables::movie and construct it
      • - *
      - *
    • All the routines are done
    • + *
    • {@link service Service} + *
    • {@link external External System} + *
    • {@link parallel Parallel System} + *
    • {@link distributed Distributed System} *
    * + *

    Note that, whatever the network system what you've to construct is, just concentrate on role of each system + * and attach matched Basic Components to the role, within framework of the Object-Oriented Design. + * Then construction of the network system will be much easier.

    + * + *
      + *
    • A system is a server, then use {@link IServer} or {@link IServerBase}.
    • + *
    • A server wants to handle a client has connected, then use {@link IClientDriver}.
    • + *
    • A system is a client connecting to an external server, then use {@link IServerConnector}.
    • + *
    • + *
    + * + *

    Example - System Templates

    + *

    Learning and understanding Basic Components of Samchon Framework, reading source codes and design of + * System Templates' modules will be very helpful.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Name Source API Documents
    Cloud Service protocol/service {@link protocol.service}
    External System protocol/external {@link protocol.external}
    Parallel System protocol/parallel {@link protocol.parallel}
    Distributed System protocol/distributed {@link protocol.distributed}
    Slave System protocol/slave {@link protocol.slave}
    + * + *

    Example - Projects

    + * + * + * @see {@link IClientDriver} + * @handbook Basic Components - IServer * @author Jeongho Nam */ - class Application implements IProtocol { - /** - *

    Invoke Socket.

    - */ - protected socket: ServerConnector; - /** - *

    A movie.

    - */ - protected movie: Movie; - /** - *

    Construct from arguments.

    - * - * @param movie A movie represents a service. - * @param ip An ip address of cloud server to connect. - * @param port A port number of cloud server to connect. - */ - constructor(movie: Movie, ip: string, port: number); - private handleConnect(event); - /** - *

    Handle replied message or shift the responsibility.

    - */ - replyData(invoke: Invoke): void; - /** - *

    Send a data to server.

    - */ - sendData(invoke: Invoke): void; + interface IServer { + open(port: number): void; + close(): void; + addClient(clientDriver: IClientDriver): void; } } -declare namespace samchon.protocol.service { - /** - * A movie belonged to an Application. - */ - class Movie implements IProtocol { +declare namespace samchon.protocol { + abstract class Server implements IServer { + private server; /** - *

    An application the movie is belonged to + * @inheritdoc */ - protected application: Application; + abstract addClient(driver: ClientDriver): void; /** - * Handle replied data. + * @inheritdoc */ - replyData(invoke: Invoke): void; + open(port: number): void; /** - * Send data to server. + * @inheritdoc */ - sendData(invoke: Invoke): void; + close(): void; + private handle_connect(socket); } } -declare namespace samchon.protocol.service { -} -declare namespace samchon.protocol.slave { - /** - * @brief A slave system. - * - * @details - *

    SlaveSystem, literally, means a slave system belongs to a maste system.

    - * - *

    The SlaveSystem class is used in opposite side system of master::DistributedSystem - * and master::ParallelSystem and reports elapsed time of each commmand (by Invoke message) - * for estimation of its performance.

    - * - * @inheritdoc - * @author Jeongho Nam - */ - abstract class SlaveSystem extends ExternalSystem { +declare namespace samchon.protocol { + abstract class WebServer implements IServer { /** - *

    Default Constructor.

    + * A server handler. + */ + private http_server; + /** + * Sequence number for issuing session id. + */ + private sequence; + /** + * @hidden + */ + private my_port; + /** + * Default Constructor. */ constructor(); /** * @inheritdoc */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + abstract addClient(driver: WebClientDriver): void; + /** + *

    Handle request from a client system.

    + * + *

    This method {@link handle_request} will be called when a client is connected. It will call an abstract + * method method {@link addClient addClient()} who handles an accepted client. If the newly connected client + * doesn't have its own session id, then a new session id will be issued.

    + * + * @param request Requested header. + */ + private handle_request(request); + /** + *

    Get session id from a newly connected.

    + * + *

    Queries ordinary session id from cookies of a newly connected client. If the client has not, a new + * session id will be issued.

    + * + * @param cookies Cookies from the remote client. + */ + private get_session_id(cookies); + /** + * Issue a new session id. + */ + private issue_session_id(); + } +} +declare namespace samchon.protocol { + abstract class SharedWorkerServer implements IServer { + /** + * @inheritdoc + */ + abstract addClient(driver: SharedWorkerClientDriver): void; + /** + * @inheritdoc + */ + open(): void; + /** + * @inheritdoc + */ + close(): void; + private handle_connect(event); + } +} +declare namespace samchon.protocol { + /** + *

    An interface for substitute server classes.

    + * + *

    {@link IServerBase} is an interface for substitue server classes who subrogate server's role.

    + * + *

    The easiest way to defining a server class is to extending one of them, who are derived from the + * {@link IServer}.

    + * + *
      + *
    • {@link Server}
    • + *
    • {@link WebServer}
    • + *
    • {@link SharedWorkerServer}
    • + *
    + * + *

    However, it is impossible (that is, if the class is already extending another class), you can instead implement + * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into the + * aggregated {@link IServerBase}.

    + * + *

    {@link ExternalClientArray} can be a good example using this {@link IServerBase}.

    + *
      + *
    • https://github.com/samchon/framework/blob/master/ts/src/samchon/protocol/external/ExternalClientArray.ts
    • + *
    + * + * + class MyServer extends Something implements IServer + { + private server_base: IServerBase = new WebServerBase(this); + + public addClient(driver: IClientDriver): void + { + // WHAT TO DO WHEN A CLIENT HAS CONNECTED + } + + public open(port: number): void + { + this.server_base.open(); + } + public close(): void + { + this.server_base.close(); + } + } + * + * + * @see {@link IServer} + * @handbook Basic Components - IServerBase + * @author Jeongho Nam + */ + interface IServerBase extends IServer { + } +} +declare namespace samchon.protocol { + /** + *

    A substitute {@link Server}.

    + * + *

    {@link ServerBase} is a substitute class who subrogates {@link Server}'s responsibility.

    + * + *

    The easiest way to defning a server class following normal protocol of Samchon Framework is to extending + * {@link Server}. However, it is impossible (that is, if the class is already extending another class), you can + * instead implement the {@link IServer} interface, create a {@link ServerBase} member, and write simple hooks + * to route calls into the aggregated {@link ServerBase}.

    + * + *

    {@link ExternalClientArray} can be a good example using this {@link IServerBase}.

    + *
      + *
    • https://github.com/samchon/framework/blob/master/ts/src/samchon/protocol/external/ExternalClientArray.ts
    • + *
    + * + * + class MyServer extends Something implements IServer + { + private server_base: ServerBase = new ServerBase(this); + + public addClient(driver: ClientDriver): void + { + // WHAT TO DO WHEN A CLIENT HAS CONNECTED + } + + public open(port: number): void + { + this.server_base.open(); + } + public close(): void + { + this.server_base.close(); + } + } + * + * + * @author Jeongho Nam + */ + class ServerBase extends Server implements IServerBase { + private target; + constructor(target: IServer); + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + *

    A substitute {@link WebServer}.

    + * + *

    {@link WebServerBase} is a substitute class who subrogates {@link WebServer}'s responsibility.

    + * + *

    The easiest way to defning a server class following normal protocol of Samchon Framework is to extending + * {@link WebServer}. However, it is impossible (that is, if the class is already extending another class), you can + * instead implement the {@link IServer} interface, create a {@link WebServerBase} member, and write simple hooks to + * route calls into the aggregated {@link WebServerBase}.

    + * + *

    {@link ExternalClientArray} can be a good example using this {@link IServerBase}.

    + *
      + *
    • https://github.com/samchon/framework/blob/master/ts/src/samchon/protocol/external/ExternalClientArray.ts
    • + *
    + * + * + class MyServer extends Something implements IServer + { + private server_base: WebServerBase = new WebServerBase(this); + + public addClient(driver: WebClientDriver): void + { + // WHAT TO DO WHEN A CLIENT HAS CONNECTED + } + + public open(port: number): void + { + this.server_base.open(); + } + public close(): void + { + this.server_base.close(); + } + } + * + * + * @author Jeongho Nam + */ + class WebServerBase extends WebServer implements IServerBase { + private target; + constructor(target: IServer); + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + *

    A substitute {@link SharedWorkerServer}.

    + * + *

    {@link SharedWorkerServerBase} is a substitute class who subrogates {@link SharedWorkerServer}'s + * responsibility.

    + * + *

    The easiest way to defning a server class following normal protocol of Samchon Framework is to extending + * {@link SharedWorkerServer}. However, it is impossible (that is, if the class is already extending another class), + * you can instead implement the {@link IServer} interface, create a {@link SharedWorkerServerBase} member, and write + * simple hooks to route calls into the aggregated {@link SharedWorkerServerBase}.

    + * + *

    {@link ExternalClientArray} can be a good example using this {@link IServerBase}.

    + *
      + *
    • https://github.com/samchon/framework/blob/master/ts/src/samchon/protocol/external/ExternalClientArray.ts
    • + *
    + * + * + class MyServer extends Something implements IServer + { + private server_base: SharedWorkerServerBase = new SharedWorkerServerBase(this); + + public addClient(driver: SharedWorkerClientDriver): void + { + // WHAT TO DO WHEN A CLIENT HAS CONNECTED + } + + public open(port: number): void + { + this.server_base.open(); + } + public close(): void + { + this.server_base.close(); + } + } + * + * + * @author Jeongho Nam + */ + class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { + private target; + constructor(target: IServer); + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + *

    An interface for server connector.

    + * + *

    {@link IServerConnector} is an interface for server connector classes who ca connect to an external server + * as a client.

    + * + *

    Of course, {@link IServerConnector} is extended from the {@link ICommunicator}, thus, it also takes full + * charge of network communication and delivers replied message to {@link WebCommunicator.listener listener}'s + * {@link IProtocol.replyData replyData()} method.

    + * + * @handbook Basic Components - IServerConnector + * @author Jeongho Nam + */ + interface IServerConnector extends ICommunicator { + /** + * Callback function for connection completed. + */ + onConnect: Function; + /** + *

    Connect to a server.

    + * + *

    Connects to a server with specified host address and port number. After the connection has + * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. + * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to + * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method.

    + * + *

    If the connection fails immediately, either an event is dispatched or an exception is thrown: an error + * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, + * the status of the connection is reported by an event. If the socket is already connected, the existing + * connection is closed first.

    + * + * @param ip The name or IP address of the host to connect to. + * If no host is specified, the host that is contacted is the host where the calling file resides. + * If you do not specify a host, use an event listener to determine whether the connection was + * successful. + * @param port The port number to connect to. + */ + connect(ip: string, port: number): void; + } +} +declare namespace samchon.protocol { + class ServerConnector extends Communicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(ip: string, port: number): void; + private handle_connect(...arg); + } +} +declare namespace samchon.protocol { + /** + *

    A server connector for web-socket protocol.

    + * + * @author Jeongho Nam + */ + class WebServerConnector extends WebCommunicator implements IServerConnector { + /** + *

    A socket for network I/O.

    + * + *

    Note that, {@link socket} is only used in web-browser environment.

    + */ + private browser_socket; + /** + *

    A driver for server connection.

    + * + *

    Note that, {@link node_client} is only used in NodeJS environment.

    + */ + private node_client; + /** + * @inheritdoc + */ + onConnect: Function; + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(ip: string, port: number, path?: string): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + private handle_browser_connect(event); + private handle_browser_message(event); + private handle_node_connect(connection); + } +} +declare namespace samchon.protocol { + class SharedWorkerServerConnector extends SharedWorkerCommunicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + constructor(listener: IProtocol); + connect(jsFile: string): void; + } +} +declare namespace samchon.protocol { + namespace socket { + type socket = any; + type server = any; + type http_server = any; + } + namespace websocket { + type connection = any; + type request = any; + type IMessage = any; + type ICookie = any; + type client = any; + } +} +declare namespace samchon.protocol.external { + /** + *

    An external system driver.

    + * + *

    The {@link ExternalSystem} class represents an external system, connected and interact with this system. + * {@link ExternalSystem} takes full charge of network communication with external system have connected. + * Replied {@link Invoke messages} from the external system is shifted to and processed in, children elements of this + * class, {@link ExternalSystemRole} objects.

    + * + *

    + * + *

    + * + *

    Bridge & Proxy Pattern

    + *

    The {@link ExternalSystem} class can be a bridge for logical proxy. In framework within user, + * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is which can be done.

    + * + *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Bridge Pattern and Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalSystem extends EntityDequeCollection implements IProtocol { + /** + * A network communicator with external system. + */ + /** + * A network communicator with external system. + */ + protected communicator: ICommunicator; + /** + * The name represents external system have connected. + */ + protected name: string; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an IClientDriver object. + * + * @param driver + */ + constructor(driver: IClientDriver); + /** + * Default Destructor. + */ + destructor(): void; + /** + * Identifier of {@link ExternalSystem} is its {@link name}. + */ + key(): string; + /** + * Get {@link name}. + */ + getName(): string; + close(): void; + /** + * Send {@link Invoke} message to external system. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: Invoke): void; + /** + * Handle an {@Invoke} message have received. + * + * @param invoke An {@link Invoke} message have received. + */ + replyData(invoke: Invoke): void; + /** + * Tag name of the {@link ExternalSytem} in {@link XML}. + * + * @return system. + */ + TAG(): string; + /** + * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSytem} in {@link XML}. + * + * @return role. + */ + CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + /** + * @hidden + */ + private communicator_; + /** + * @hidden + */ + private external_system_array_; + /** + * @hidden + */ + private erasing_; + /** + * @hidden + */ + private external_system_array; + /** + * @hidden + */ + private handle_close(); + } +} +declare namespace samchon.protocol.parallel { + /** + *

    An external parallel system driver.

    + * + * + * + * @author Jeongho Nam + */ + abstract class ParallelSystem extends external.ExternalSystem { + /** + * A manager containing this {@link ParallelSystem} object. + */ + private systemArray; + /** + * A list of {@link Invoke} messages on process. + * + * @see {@link performance} + */ + private progress_list; + /** + * A list of {@link Invoke} messages had processed. + * + * @see {@link performance} + */ + private history_list; + /** + *

    Performance index.

    + * + *

    A performance index that indicates how much fast the connected parallel system is.

    + * + *

    If this {@link ParallelSystem parallel system} hasn't any {@link Invoke} message + * {@link history_list had handled}, then the {@link performance performance index} will be 1, which means + * default and average value between all {@link ParallelSystem} instances (belonged to a same + * {@link ParallelSystemArray} object).

    + * + *

    You can specify this {@link performance} by yourself, but notice that, if the + * {@link performance performance index} is higher then other {@link ParallelSystem} objects, then this + * {@link ParallelSystem parallel system} will ordered to handle more processes than other {@link ParallelSystem} + * objects. Otherwise, the {@link performance performance index) is lower than others, of course, less processes + * will be delivered.

    + * + *

    This {@link performance index} is always re-calculated whenever {@link ParallelSystemArray} calls one of + * them below.

    + * + *
      + *
    • {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()}
    • + *
    • {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()}
    • + *
    + * + *

    If this class is a type of {@link DistributedSystem}, a derived class from the {@link ParallelSystem}, + * then {@link DistributedSystemRole.sendData DistributedSystem.sendData()} also cause the re-calculation.

    + * + * @see {@link progress_list}, {@link history_list} + */ + protected performance: number; + /** + * Construct from a {@link ParallelSystemArray}. + * + * @param systemArray A manager containing this {@link ParallelSystem} object. + * @param communicator A communicator who takes full charge of network communication with the external + * parallel system. + */ + constructor(systemArray: ParallelSystemArray, communicator?: ICommunicator); + /** + * Get manager of this object, {@link systemArray}. + * + * @return A manager containing this {@link ParallelSystem} object. + */ + getSystemArray(): ParallelSystemArray; + /** + * Get {@link performant performance index}. + * + * A performance index that indicates how much fast the connected parallel system is. + */ + getPerformance(): number; + /** + * Send an {@link Invoke} message with index of segmentation. + * + * @param invoke An invoke message requesting parallel process. + * @param first Initial piece's index in a section. + * @param last Final piece's index in a section. The ranged used is [first, last), which contains + * all the pieces' indices between first and last, including the piece pointed by index + * first, but not the piece pointed by the index last. + * + * @see {@link ParallelSystemArray.sendPieceData} + */ + private send_piece_data(invoke, first, last); + /** + * + * + * @param xml + * + * @see {@link ParallelSystemArray.notify_end} + */ + private report_invoke_history(xml); + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedSystem extends parallel.ParallelSystem { + } +} +declare namespace samchon.protocol.external { + /** + *

    An array and manager of {@link ExternalSystem external systems}.

    + * + *

    {@link ExternalSystemArray} is an abstract class contains and manages external system drivers, + * {@link ExternalSystem} objects. You can specify this {@link ExternalSystemArray} to be a server accepting + * {@link ExternalSystem external clients} or a client connecting to {@link IExternalServer external servers}. Even + * both of them is also possible.

    + * + *
      + *
    • A server accepting external clients: {@link IExternalClientArray}
    • + *
    • A client connecting to external servers: {@link IExternalServerArray}
    • + *
    • + * Accepts external clients & Connects to external servers at the same time: + * {@link IExternalServerClientArray} + *
    • + *
    + * + *

    + * + *

    + * + *

    Proxy Pattern

    + *

    The {@link ExternalSystemArray} class can use Proxy Pattern. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is which can be done.

    + * + *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalSystemArray extends EntityArrayCollection implements IProtocol { + /** + * Default Constructor. + */ + constructor(); + /** + * @hidden + */ + private handle_system_insert(event); + /** + * @hidden + */ + private handle_system_erase(event); + /** + * @hidden + */ + protected handle_system_close(system: ExternalSystem): void; + /** + * Test whether this system array has the role. + * + * @param name Name, identifier of target {@link ExternalSystemRole role}. + * + * @return Whether the role has or not. + */ + hasRole(name: string): boolean; + /** + * Get a role. + * + * @param name Name, identifier of target {@link ExternalSystemRole role}. + * + * @return The specified role. + */ + getRole(name: string): ExternalSystemRole; + /** + *

    Send an {@link Invoke} message.

    + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: Invoke): void; + /** + *

    Handle an {@Invoke} message have received.

    + * + * @param invoke An {@link Invoke} message have received. + */ + replyData(invoke: Invoke): void; + /** + * Tag name of the {@link ExternalSytemArray} in {@link XML}. + * + * @return systemArray. + */ + TAG(): string; + /** + * Tag name of {@link ExternalSystem children elements} belonged to the {@link ExternalSytemArray} in {@link XML}. + * + * @return system. + */ + CHILD_TAG(): string; + } +} +declare namespace samchon.protocol.parallel { + /** + *

    A manager containing {@link ParallelSystem} objects.

    + * + * + * + * @author Jeongho Nam + */ + abstract class ParallelSystemArray extends external.ExternalSystemArray { + /** + * @see {@link ParallelSystem.progress_list}, {@link ParallelSystem.history_list} + */ + private history_sequence; + /** + * Default Constructor. + */ + constructor(); + /** + * + * @param invoke An invoke message requesting parallel process. + * @param size Number of pieces. + */ + sendSegmentData(invoke: Invoke, size: number): void; + /** + * + * + * @param invoke An invoke message requesting parallel process. + * @param first Initial piece's index in a section. + * @param last Final piece's index in a section. The ranged used is [first, last), which contains + * all the pieces' indices between first and last, including the piece pointed by index + * first, but not the piece pointed by the index last. + */ + sendPieceData(invoke: Invoke, first: number, last: number): void; + /** + * + * @param history + * + * @return Whether the processes with same uid are all fininsed. + * + * @see {@link ParallelSystem.report_invoke_history}, {@link normalize_performance} + */ + protected notify_end(history: PRInvokeHistory): boolean; + /** + * @see {@link ParallelSystem.performance} + */ + private normalize_performance(); + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedSystemArray extends parallel.ParallelSystemArray { + protected roles: std.HashMap; + } +} +declare namespace samchon.protocol.external { + /** + *

    A role of an external system.

    + * + *

    The {@link ExternalSystemRole} class represents a role, what to do in an {@link ExternalSystem}. + * Extends this class and writes some methods related to the role.

    + * + *

    + * + *

    + * + *

    Proxy Pattern

    + *

    The {@link ExternalSystemRole} class can be an logical proxy. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is which can be done.

    + * + *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalSystemRole extends Entity implements IProtocol { + /** + * An {@link ExternalSystem external system} containing this {@link ExternalSystemRole role}. + */ + private system; + /** + *

    A name, represents and identifies this {@link ExternalSystemRole role}.

    + * + *

    This {@link name} is an identifier represents this {@link ExternalSystemRole role}. This {@link name} is + * used in {@link ExternalSystemArray.getRole} and {@link ExternalSystem.get}, as a key elements. Thus, this + * {@link name} should be unique in an {@link ExternalSystemArray}. + */ + private name; + /** + * Constructor from a system. + * + * @param system An external system containing this role. + */ + constructor(system: ExternalSystem); + /** + * Identifier of {@link ExternalSystemRole} is its {@link name}. + */ + key(): string; + /** + * Get external system, this role is belonged to. + */ + getSystem(): ExternalSystem; + /** + * Get name, who represents and identifies this role. + */ + getName(): string; + /** + * Send an {@link Invoke} message to the external system via {@link system}. + * + * @param invoke An {@link Invoke} message to send to the external system. + */ + sendData(invoke: Invoke): void; + /** + *

    Handle replied {@link Invoke message} from the {@link system external system} belonged to.

    + * + *

    This {@link replyData replyData()} will call a member method named following {@link Invoke.listener}. + * in the invoke.

    + * + * @param invoke An {@link Invoke} message received from the {@link system external system}. + */ + replyData(invoke: Invoke): void; + /** + * Tag name of the {@link ExternalSytemRole} in {@link XML}. + * + * @return role. + */ + TAG(): string; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedSystemRole extends external.ExternalSystemRole { + private systems; + } +} +declare namespace samchon.protocol.external { + /** + *

    An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a + * {@link IServer server}.

    + * + *

    The easiest way to defining an {@link ExternalSystemArray} who opens server and accepts + * {@link ExternalSystem external clients} is to extending one of below, who are derived from this interface + * {@link IExternalClientArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or + * client, then make a class (let's name it as BaseSystemArray) extending {@link ExternalSystemArray} and make + * a new class (now, I name it BaseClientArray) extending BaseSystemArray and implementing this + * interface {@link IExternalClientArray}. Define the BaseClientArray following those codes on below: + * + *

    + * + * @author Jeongho Nam + */ + interface IExternalClientArray extends ExternalSystemArray, IServer { + } + /** + *

    An {@link ExternalSystemArray} acceepts {@link ExternalSystem external clients} as a {@link IServer server}.

    + * + *

    {@link ExternalServerArray} is an abstract class contains, manages and accepts external server drivers, + * {@link IExternalServer} objects, as a {@link IServer server}.

    + * + *

    + * + *

    + * + *

    Proxy Pattern

    + *

    The {@link ExternalSystemArray} class can use Proxy Pattern. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is which can be done.

    + * + *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalClientArray extends ExternalSystemArray implements IExternalClientArray { + /** + * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. + */ + private server_base; + /** + * Default Constructor. + */ + constructor(); + /** + *

    Factory method creating {@link IServerBase} object.

    + * + *

    This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol.

    + * + *

    Creates and returns one of them:

    + *
      + *
    • {@link ServerBase}
    • + *
    • {@link WebServerBase}
    • + *
    • {@link SharedWorkerServerBase}
    • + *
    + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + /** + * This method is deprecated. Don't use and override this. + * + * @return null. + */ + protected createChild(xml: library.XML): ExternalSystem; + /** + * Factory method creating {@link ExternalSystem} object. + * + * @param driver A communicator with connected client. + * @return A newly created {@link ExternalSystem} object. + */ + protected abstract createExternalClient(driver: IClientDriver): ExternalSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol.external { + /** + *

    An interface for an external server driver.

    + * + *

    The easiest way to defining an external server driver is to extending one of below, who are derived from this + * interface {@link IExternalServer}. However, if you've to interact with an external system who can be both server + * and client, then make a class (let's name it as BaseSystem) extending {@link ExternalSystem} and make a + * new class (now, I name it BaseServer) extending BaseSystem and implementing this interface + * {@link IExternalServer}. Define the BaseServer following those codes on below: + * + *

    + * + * @author Jeongho Nam + */ + interface IExternalServer extends ExternalSystem { + /** + * Connect to the external system. + */ + connect(): void; + /** + * Get ip address. + */ + getIP(): string; + /** + * Get port number. + */ + getPort(): number; + } + /** + *

    An external server driver.

    + * + *

    The {@link ExternalServer} class represents an external server, connected and interact with this system. + * {@link ExternalServer} takes full charge of network communication with external server have connected. + * Replied {@link Invoke messages} from the external system is shifted to and processed in, children elements of this + * class, {@link ExternalSystemRole} objects.

    + * + *

    + * + *

    + * + *

    Bridge & Proxy Pattern

    + *

    The {@link ExternalSystem} class can be a bridge for logical proxy. In framework within user, + * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is which can be done.

    + * + *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Bridge Pattern and Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalServer extends ExternalSystem implements IExternalServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating server connector. + */ + protected abstract createServerConnector(): IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + /** + * @inheritdoc + */ + getIP(): string; + /** + * @inheritdoc + */ + getPort(): number; + } +} +declare namespace samchon.protocol.external { + /** + *

    An interface for an {@link ExternalSystemArray} connects to {@link IExternalServer external servers} as a + * client.

    + * + *

    The easiest way to defining an {@link ExternalSystemArray} who connects to + * {@link IExternalServer external servers} is to extending one of below, who are derived from this interface + * {@link IExternalServerArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or + * client, then make a class (let's name it as BaseSystemArray) extending {@link ExternalSystemArray} and make + * a new class (now, I name it BaseServerArray) extending BaseSystemArray and implementing this + * interface {@link IExternalServerArray}. Define the BaseServerArray following those codes on below: + * + *

    + * + * @author Jeongho Nam + */ + interface IExternalServerArray extends ExternalSystemArray { + /** + *

    Connect to {@link IExternalServer external servers}.

    + * + *

    This method calls children elements' method {@link IExternalServer.connect} gradually.

    + */ + connect(): void; + } + /** + *

    An {@link ExternalSystemArray} connecting to {@link IExternalServer external servers} as a client.

    + * + *

    {@link ExternalServerArray} is an abstract class contains, manages and connects to external server drivers, + * {@link IExternalServer} objects, as a client.

    + * + *

    + * + *

    + * + *

    Proxy Pattern

    + *

    The {@link ExternalSystemArray} class can use Proxy Pattern. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is which can be done.

    + * + *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalServerArray extends ExternalSystemArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.external { + /** + *

    An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a + * {@link IServer server} and connects to {@link IExternalServer} as client, at the same time.

    + * + *

    The easiest way to defining an {@link IExternalServerClientArray} who opens server, accepts + * {@link ExternalSystem external clients} and connects to {@link IExternalServer external servers} is to extending + * one of below, who are derived from this interface {@link IExternalServerClientArray}. However, if you can't + * specify an {@link ExternalSystemArray} to be whether server or client or even can both them, then make a class + * (let's name it as BaseSystemArray) extending {@link ExternalSystemArray} and make a new class (now, I name + * it BaseServerClientArray) extending BaseSystemArray and implementing this interface + * {@link IExternalServerClientArray}. Define the BaseServerClientArray following those codes on below: + * + *

    + * + * @author Jeongho Nam + */ + interface IExternalServerClientArray extends IExternalServerArray, IExternalClientArray { + } + /** + *

    An {@link ExternalSystemArray} connecting to {@link IExternalServer external servers} as a client and + * accepts {@link ExternalSystem external clients} as a {@link IServer server}.

    + * + *

    {@link ExternalServerArray} is an abstract class contains, manages and connects to external server drivers, + * {@link IExternalServer} objects and accepts external client drivers {@link ExternalSyste} obejcts as a + * client and a {@link IServer server} at the same time.

    + * + *

    + * + *

    + * + *

    Proxy Pattern

    + *

    The {@link ExternalSystemArray} class can use Proxy Pattern. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is which can be done.

    + * + *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalServerClientArray extends ExternalClientArray implements IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + *

    Factory method of a child Entity.

    + * + *

    This method is migrated to {@link createExternalServer createExternalServer()}. Override the + * {@link createExternalServer createExternalServer()}.

    + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + protected createChild(xml: library.XML): ExternalSystem; + /** + * Factory method creating an {@link IExternalServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * + * @return A newly created {@link IExternalServer} object. + */ + protected abstract createExternalServer(xml: library.XML): IExternalServer; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.slave { + abstract class SlaveSystem extends external.ExternalSystem { + /** + * Default Constructor. + */ + constructor(); replyData(invoke: Invoke): void; } } +declare namespace samchon.protocol.external { + abstract class MediatorSystem extends slave.SlaveSystem { + private system_array; + private progress_list; + constructor(systemArray: ExternalSystemArray); + abstract start(): void; + /** + * @hidden + */ + protected createChild(xml: library.XML): ExternalSystemRole; + private notify_end(uid); + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol.external { + class MediatorServer extends MediatorSystem implements IServer { + private server_base; + private port; + constructor(systemArray: ExternalSystemArray, port: number); + protected createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + start(): void; + open(port: number): void; + close(): void; + } + class MediatorWebServer extends MediatorServer { + protected createServerBase(): IServerBase; + } + class MediatorSharedWorkerServer extends MediatorServer { + protected createServerBase(): IServerBase; + } +} +declare namespace samchon.protocol.external { + class MediatorClient extends MediatorSystem implements IExternalServer { + protected ip: string; + protected port: number; + constructor(systemArray: ExternalSystemArray, ip: string, port: number); + protected createServerConnector(): IServerConnector; + getIP(): string; + getPort(): number; + start(): void; + connect(): void; + } + class MediatorWebClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): IServerConnector; + } + class MediatorSharedWorkerClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): IServerConnector; + } +} +declare namespace samchon.protocol.parallel { + class PRInvokeHistory extends InvokeHistory { + /** + * Index number of initial piece. + */ + private first; + /** + * Index number of final piece. + */ + private last; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an Invoke message. + * + * @param invoke + */ + constructor(invoke: Invoke); + getFirst(): number; + getLast(): number; + /** + * Compute number of allocated pieces. + */ + computeSize(): number; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelClientArray extends ParallelSystemArray implements external.IExternalClientArray { + /** + * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. + */ + private server_base; + /** + * Default Constructor. + */ + constructor(); + /** + *

    Factory method creating {@link IServerBase} object.

    + * + *

    This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol.

    + * + *

    Creates and returns one of them:

    + *
      + *
    • {@link ServerBase}
    • + *
    • {@link WebServerBase}
    • + *
    • {@link SharedWorkerServerBase}
    • + *
    + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + protected createChild(xml: library.XML): ParallelSystem; + protected abstract createExternalClient(driver: IClientDriver): ParallelSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelSystemArrayMediator extends ParallelSystemArray { + protected mediator: external.MediatorSystem; + /** + * Default Constructor. + */ + constructor(); + protected abstract createMediator(): external.MediatorSystem; + protected start_mediator(): void; + sendData(invoke: protocol.Invoke): void; + sendPieceData(invoke: protocol.Invoke, first: number, last: number): void; + protected notify_end(history: PRInvokeHistory): boolean; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelClientArrayMediator extends ParallelSystemArrayMediator implements external.IExternalClientArray { + /** + * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. + */ + private server_base; + /** + * Default Constructor. + */ + constructor(); + /** + *

    Factory method creating {@link IServerBase} object.

    + * + *

    This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol.

    + * + *

    Creates and returns one of them:

    + *
      + *
    • {@link ServerBase}
    • + *
    • {@link WebServerBase}
    • + *
    • {@link SharedWorkerServerBase}
    • + *
    + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + protected createChild(xml: library.XML): ParallelSystem; + protected abstract createExternalClient(driver: IClientDriver): ParallelSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol.parallel { + interface IParallelServer extends ParallelSystem, external.IExternalServer { + } + abstract class ParallelServer extends ParallelSystem implements IParallelServer { + protected ip: string; + protected port: number; + constructor(systemArray: ParallelSystemArray); + protected abstract createServerConnector(): IServerConnector; + connect(): void; + getIP(): string; + getPort(): number; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelServerArray extends ParallelSystemArray implements external.IExternalServerArray { + constructor(); + connect(): void; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { + constructor(); + connect(): void; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelServerClientArray extends ParallelClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + protected createChild(xml: library.XML): ParallelSystem; + protected abstract createExternalServer(xml: library.XML): IParallelServer; + connect(): void; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelServerClientArrayMediator extends ParallelClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + protected createChild(xml: library.XML): ParallelSystem; + protected abstract createExternalServer(xml: library.XML): IParallelServer; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.service { + abstract class Client implements protocol.IProtocol { + private user; + private service; + private driver; + private no; + /** + * Construct from an User and WebClientDriver. + */ + constructor(user: User, driver: WebClientDriver); + protected abstract createService(path: string): Service; + close(): void; + getUser(): User; + getService(): Service; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + protected changeService(path: string): void; + } +} +declare namespace samchon.protocol.service { + abstract class Server extends protocol.WebServer implements IProtocol { + private session_map; + private account_map; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link User} object. + * + * @return A newly created {@link User} object. + */ + protected abstract createUser(): User; + has(account: string): boolean; + get(account: string): User; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + addClient(driver: WebClientDriver): void; + private erase_user(user); + } +} +declare namespace samchon.protocol.service { + abstract class Service implements protocol.IProtocol { + private client; + private path; + /** + * Default Constructor. + */ + constructor(client: Client, path: string); + destructor(): void; + /** + * Get client. + */ + getClient(): Client; + /** + * Get path. + */ + getPath(): string; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol.service { + abstract class User extends collection.HashMapCollection implements protocol.IProtocol { + private server; + private session_id; + private sequence; + private account_id; + private authority; + /** + * Construct from a Server. + */ + constructor(server: Server); + protected abstract createClient(driver: WebClientDriver): Client; + private handle_erase_client(event); + getServer(): Server; + getAccountID(): string; + getAuthority(): number; + setAccount(id: string, authority: number): void; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol.slave { + abstract class SlaveClient extends SlaveSystem { + constructor(); + protected abstract createServerConnector(): IServerConnector; + connect(ip: string, port: number): void; + } +} +declare namespace samchon.protocol.slave { + abstract class SlaveServer extends SlaveSystem implements IServer { + private server_base; + constructor(); + protected abstract createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + open(port: number): void; + close(): void; + } +} diff --git a/typescript-stl/typescript-stl-tests.ts b/typescript-stl/typescript-stl-tests.ts index cc684cde7e..d83a9ffc5a 100644 --- a/typescript-stl/typescript-stl-tests.ts +++ b/typescript-stl/typescript-stl-tests.ts @@ -1,4 +1,4 @@ /// import std = require("typescript-stl"); -std.example.test_all(); \ No newline at end of file +console.log(std); \ No newline at end of file diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index a0f92b88b6..9e491ff258 100644 --- a/typescript-stl/typescript-stl.d.ts +++ b/typescript-stl/typescript-stl.d.ts @@ -1,4 +1,4 @@ -// Type definitions for TypeScript-STL v1.0.0-rc.3 +// Type definitions for TypeScript-STL v1.0.0 // Project: https://github.com/samchon/typescript-stl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -117,13 +117,6 @@ declare namespace std { */ declare namespace std.base { } -/** - * Examples for supporting developers who use STL library. - * - * @author Jeongho Nam - */ -declare namespace std.example { -} declare namespace std { /** *

    Apply function to range.

    @@ -2751,8 +2744,8 @@ declare namespace std.base { /** *

    An abstract container.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -2872,8 +2865,8 @@ declare namespace std { *

    There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} * may define its own specific iterator type able to iterate through it and access its elements.

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator @@ -2958,18 +2951,45 @@ declare namespace std { * first element in a range is reversed, the reversed iterator points to the element before the first element (this * would be the past-the-end element of the reversed range).

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator * @author Jeongho Nam */ abstract class ReverseIterator, This extends ReverseIterator> extends Iterator { + /** + * @hidden + */ protected base_: Base; + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: Base); + /** + *

    Return base iterator.

    + * + *

    Return a reference of the base iteraotr.

    + * + *

    The base iterator is an iterator of the same type as the one used to construct the {@link ReverseIterator}, + * but pointing to the element next to the one the {@link ReverseIterator} is currently pointing to + * (a {@link ReverseIterator} has always an offset of -1 with respect to its base iterator). + * + * @return A reference of the base iterator, which iterates in the opposite direction. + */ base(): Base; + /** + * @hidden + */ protected abstract create_neighbor(): This; + /** + *

    Get value of the iterator is pointing.

    + * + * @return A value of the reverse iterator. + */ value: T; /** * @inheritdoc @@ -3194,8 +3214,8 @@ declare namespace std { * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than * {@link List Lists}.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -3217,66 +3237,27 @@ declare namespace std { */ class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { /** - *

    Row size of the {@link matrix_ matrix} which contains elements.

    - * - *

    Note that the {@link ROW} affects on time complexity of accessing and inserting element. - * Accessing element is {@link ROW} times slower than ordinary {@link Vector} and inserting element - * in middle position is {@link ROW} times faster than ordinary {@link Vector}.

    - * - *

    When the {@link ROW} returns 8, time complexity of accessing element is O(8) and inserting - * element in middle position is O(N/8). ({@link Vector}'s time complexity of accessement is O(1) - * and inserting element is O(N)).

    + * @hidden */ private static ROW; /** - *

    Minimum {@link capacity}.

    - * - *

    Although a {@link Deque} has few elements, even no element is belonged to, the {@link Deque} - * keeps the minimum {@link capacity} at least.

    + * @hidden */ private static MIN_CAPACITY; /** - *

    A matrix containing elements.

    - * - *

    This {@link matrix_} is the biggest difference one between {@link Vector} and {@link Deque}. - * Its number of rows follows {@link ROW} and number of columns follows {@link get_col_size} which - * returns divide of {@link capacity} and {@link ROW}.

    - * - * By separating segment of elements (segment: row, elements in a segment: col), {@link Deque} takes - * advantage of time complexity on inserting element in middle position. {@link Deque} is {@link ROW} - * times faster than {@link Vector} when inserting elements in middle position.

    - * - *

    However, separating segment of elements from matrix, {@link Deque} also takes disadvantage of - * time complexity on accessing element. {@link Deque} is {@link ROW} times slower than {@link Vector} - * when accessing element.

    + * @hidden */ private matrix_; /** - * Number of elements in the {@link Deque}. + * @hidden */ private size_; /** - *

    Size of allocated storage capacity.

    - * - *

    The {@link capacity_ capacity} is size of the storage space currently allocated for the - * {@link Deque container}, expressed in terms of elements.

    - * - *

    This {@link capacity_ capacity} is not necessarily equal to the {@link Deque container} - * {@link size}. It can be equal or greater, with the extra space allowing to accommodate for growth - * without the need to reallocate on each insertion.

    - * - *

    Notice that this {@link capacity_ capacity} does not suppose a limit on the {@link size} of - * the {@link Deque container}. When this {@link capacity} is exhausted and more is needed, it is - * automatically expanded by the {@link Deque container} (reallocating it storage space). - * The theoretical limit on the {@link size} of a {@link Deque container} is given by member - * {@link max_size}.

    - * - *

    The {@link capacity_ capacity} of a {@link Deque container} can be explicitly altered by - * calling member {@link Deque.reserve}.

    + * @hidden */ private capacity_; /** - * Get column size; {@link capacity_ capacity} / {@link ROW row}. + * @hidden */ private get_col_size(); /** @@ -3480,8 +3461,8 @@ declare namespace std { /** *

    An iterator of {@link Deque}.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -3509,6 +3490,11 @@ declare namespace std { /** * @inheritdoc */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ value: T; /** * @inheritdoc @@ -3552,8 +3538,8 @@ declare namespace std { /** *

    A reverse-iterator of Deque.

    * - *

    - * + *

    + * *

    * * @param Type of the elements. @@ -3561,13 +3547,20 @@ declare namespace std { * @author Jeongho Nam */ class DequeReverseIterator extends ReverseIterator, DequeReverseIterator> implements base.IArrayIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: DequeIterator); /** - * @inheritdoc + * @hidden */ protected create_neighbor(): DequeReverseIterator; /** - * Set value. + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; /** @@ -3629,8 +3622,8 @@ declare namespace std { *

    All objects thrown by components of the standard library are derived from this class. * Therefore, all standard exceptions can be caught by catching this type by reference.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/exception/exception * @author Jeongho Nam @@ -3678,8 +3671,8 @@ declare namespace std { * *

    It is used as a base class for several logical error exceptions.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/logic_error * @author Jeongho Nam @@ -3704,8 +3697,8 @@ declare namespace std { *

    No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/domain_error * @author Jeongho Nam @@ -3726,8 +3719,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal invalid arguments.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument * @author Jeongho Nam @@ -3748,8 +3741,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library, * such as vector and string also throw exceptions of this type to signal errors resizing.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/length_error * @author Jeongho Nam @@ -3771,8 +3764,8 @@ declare namespace std { * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments * out of range.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range * @author Jeongho Nam @@ -3793,8 +3786,8 @@ declare namespace std { * *

    It is used as a base class for several runtime error exceptions.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error * @author Jeongho Nam @@ -3815,8 +3808,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error * @author Jeongho Nam @@ -3837,8 +3830,8 @@ declare namespace std { *

    No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error * @author Jeongho Nam @@ -3860,8 +3853,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/range_error * @author Jeongho Nam @@ -4422,8 +4415,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -4820,8 +4813,8 @@ declare namespace std { /** *

    An iterator of {@link MapContainer map container}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -4891,13 +4884,21 @@ declare namespace std { /** *

    A reverse-iterator of {@link MapContainer map container}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ class MapReverseIterator extends ReverseIterator, MapIterator, MapReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: MapIterator); + /** + * @hidden + */ protected create_neighbor(): MapReverseIterator; /** * Get first, key element. @@ -4931,8 +4932,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5198,8 +5199,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5311,8 +5312,8 @@ declare namespace std { *

    {@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their * key, although they are generally less efficient for range iteration through a subset of their elements.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -5342,6 +5343,9 @@ declare namespace std { * @author Jeongho Nam */ class HashMap extends base.UniqueMap implements base.IHashMap { + /** + * @hidden + */ private hash_buckets_; /** * @hidden @@ -5473,8 +5477,8 @@ declare namespace std { *

    Elements with equivalent keys are grouped together in the same bucket and in such a way that * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -5505,7 +5509,7 @@ declare namespace std { */ class HashMultiMap extends base.MultiMap { /** - * + * @hidden */ private hash_buckets_; /** @@ -5633,8 +5637,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5910,8 +5914,8 @@ declare namespace std { /** *

    An iterator of a Set.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -5969,146 +5973,26 @@ declare namespace std { /** *

    A reverse-iterator of Set.

    * - *

    - *

    + *

    + *

    * * @param Type of the elements. * * @author Jeongho Nam */ class SetReverseIterator extends ReverseIterator, SetReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: SetIterator); /** - * @inheritdoc + * @hidden */ protected create_neighbor(): SetReverseIterator; } } -declare namespace std.base { - /** - *

    An abstract set.

    - * - *

    {@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

    - * - *

    In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified - * once in the container - they can be inserted and removed, though.

    - * - *

    {@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    - * - *

    - *

    - * - *

    Container properties

    - *
    - *
    Associative
    - *
    - * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
    - * - *
    Set
    - *
    The value of an element is also the key used to identify it.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). - * - * @author Jeongho Nam - */ - abstract class UniqueSet extends SetContainer { - /** - * @inheritdoc - */ - count(key: T): number; - /** - *

    Extract an element.

    - * - *

    Extracts the element pointed to by val and erases it from the {@link UniqueSet}.

    - * - * @param val Value to be extracted. - * - * @return A value. - */ - extract(val: T): T; - /** - *

    Extract an element.

    - * - *

    Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

    - * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. - */ - extract(it: SetIterator): SetIterator; - /** - *

    Extract an element.

    - * - *

    Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

    - * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. - */ - extract(it: SetReverseIterator): SetReverseIterator; - /** - * @hidden - */ - private extract_by_key(val); - /** - * @hidden - */ - private extract_by_iterator(it); - /** - * @hidden - */ - private extract_by_reverse_iterator(it); - /** - *

    Insert an element.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of element inserted (zero or one).

    - * - *

    Because elements in a {@link UniqueSet UniqueSets} are unique, the insertion operation checks whether - * each inserted element is equivalent to an element already in the container, and if so, the element is not - * inserted, returning an iterator to this existing element (if the function returns a value).

    - * - *

    For a similar container allowing for duplicate elements, see {@link MultiSet}.

    - * - * @param key Value to be inserted as an element. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the equivalent element already in the {@link UniqueSet}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent element already existed. - */ - insert(val: T): Pair, boolean>; - /** - * @inheritdoc - */ - insert(hint: SetIterator, val: T): SetIterator; - /** - * @inheritdoc - */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; - /** - * @inheritdoc - */ - insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - swap(obj: UniqueSet): void; - } -} declare namespace std.base { /** *

    An abstract set.

    @@ -6124,8 +6008,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -6177,163 +6061,6 @@ declare namespace std.base { swap(obj: MultiSet): void; } } -declare namespace std.HashSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

    Hashed, unordered set.

    - * - *

    {@link HashSet}s are containers that store unique elements in no particular order, and which - * allow for fast retrieval of individual elements based on their value.

    - * - *

    In an {@link HashSet}, the value of an element is at the same time its key, that - * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be - * modified once in the container - they can be inserted and removed, though.

    - * - *

    Internally, the elements in the {@link HashSet} are not sorted in any particular order, but - * organized into buckets depending on their hash values to allow for fast access to individual elements - * directly by their values (with a constant average time complexity on average).

    - * - *

    {@link HashSet} containers are faster than {@link TreeSet} containers to access individual - * elements by their key, although they are generally less efficient for range iteration through a - * subset of their elements.

    - * - *

    - *

    - * - *

    Container properties

    - *
    - *
    Associative
    - *
    Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
    - * - *
    Hashed
    - *
    Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
    - * - *
    Set
    - *
    The value of an element is also the key used to identify it.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the elements. - * Each element in an {@link HashSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set - * @author Jeongho Nam - */ - class HashSet extends base.UniqueSet { - private hash_buckets_; - /** - * @hidden - */ - protected init(): void; - /** - * @hidden - */ - protected construct_from_array(items: Array): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: T): SetIterator; - /** - * @inheritdoc - */ - begin(): SetIterator; - /** - * @inheritdoc - */ - begin(index: number): SetIterator; - /** - * @inheritdoc - */ - end(): SetIterator; - /** - * @inheritdoc - */ - end(index: number): SetIterator; - /** - * @inheritdoc - */ - rbegin(): SetReverseIterator; - /** - * @inheritdoc - */ - rbegin(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - rend(): SetReverseIterator; - /** - * @inheritdoc - */ - rend(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - bucket_count(): number; - /** - * @inheritdoc - */ - bucket_size(n: number): number; - /** - * @inheritdoc - */ - max_load_factor(): number; - /** - * @inheritdoc - */ - max_load_factor(z: number): void; - /** - * @inheritdoc - */ - bucket(key: T): number; - /** - * @inheritdoc - */ - reserve(n: number): void; - /** - * @inheritdoc - */ - rehash(n: number): void; - /** - * @hidden - */ - protected insert_by_val(val: T): any; - /** - * @hidden - */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected handle_erase(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - swap(obj: base.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); - } -} declare namespace std.HashMultiSet { type iterator = std.SetIterator; type reverse_iterator = std.SetReverseIterator; @@ -6357,8 +6084,8 @@ declare namespace std { *

    Elements with equivalent values are grouped together in the same bucket and in such a way that an * iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -6384,6 +6111,9 @@ declare namespace std { * @author Jeongho Nam */ class HashMultiSet extends base.MultiSet { + /** + * @hidden + */ private hash_buckets_; /** * @hidden @@ -6495,6 +6225,291 @@ declare namespace std { private swap_tree_set(obj); } } +declare namespace std.base { + /** + *

    An abstract set.

    + * + *

    {@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value.

    + * + *

    In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified + * once in the container - they can be inserted and removed, though.

    + * + *

    {@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    + * + *

    + *

    + * + *

    Container properties

    + *
    + *
    Associative
    + *
    + * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
    + * + *
    Set
    + *
    The value of an element is also the key used to identify it.
    + * + *
    Unique keys
    + *
    No two elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam + */ + abstract class UniqueSet extends SetContainer { + /** + * @inheritdoc + */ + count(key: T): number; + /** + *

    Extract an element.

    + * + *

    Extracts the element pointed to by val and erases it from the {@link UniqueSet}.

    + * + * @param val Value to be extracted. + * + * @return A value. + */ + extract(val: T): T; + /** + *

    Extract an element.

    + * + *

    Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

    + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: SetIterator): SetIterator; + /** + *

    Extract an element.

    + * + *

    Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

    + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: SetReverseIterator): SetReverseIterator; + /** + * @hidden + */ + private extract_by_key(val); + /** + * @hidden + */ + private extract_by_iterator(it); + /** + * @hidden + */ + private extract_by_reverse_iterator(it); + /** + *

    Insert an element.

    + * + *

    Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of element inserted (zero or one).

    + * + *

    Because elements in a {@link UniqueSet UniqueSets} are unique, the insertion operation checks whether + * each inserted element is equivalent to an element already in the container, and if so, the element is not + * inserted, returning an iterator to this existing element (if the function returns a value).

    + * + *

    For a similar container allowing for duplicate elements, see {@link MultiSet}.

    + * + * @param key Value to be inserted as an element. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the equivalent element already in the {@link UniqueSet}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent element already existed. + */ + insert(val: T): Pair, boolean>; + /** + * @inheritdoc + */ + insert(hint: SetIterator, val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; + /** + * @inheritdoc + */ + insert>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + swap(obj: UniqueSet): void; + } +} +declare namespace std.HashSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; +} +declare namespace std { + /** + *

    Hashed, unordered set.

    + * + *

    {@link HashSet}s are containers that store unique elements in no particular order, and which + * allow for fast retrieval of individual elements based on their value.

    + * + *

    In an {@link HashSet}, the value of an element is at the same time its key, that + * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be + * modified once in the container - they can be inserted and removed, though.

    + * + *

    Internally, the elements in the {@link HashSet} are not sorted in any particular order, but + * organized into buckets depending on their hash values to allow for fast access to individual elements + * directly by their values (with a constant average time complexity on average).

    + * + *

    {@link HashSet} containers are faster than {@link TreeSet} containers to access individual + * elements by their key, although they are generally less efficient for range iteration through a + * subset of their elements.

    + * + *

    + *

    + * + *

    Container properties

    + *
    + *
    Associative
    + *
    Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
    + * + *
    Hashed
    + *
    Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
    + * + *
    Set
    + *
    The value of an element is also the key used to identify it.
    + * + *
    Unique keys
    + *
    No two elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the elements. + * Each element in an {@link HashSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set + * @author Jeongho Nam + */ + class HashSet extends base.UniqueSet { + /** + * @hidden + */ + private hash_buckets_; + /** + * @hidden + */ + protected init(): void; + /** + * @hidden + */ + protected construct_from_array(items: Array): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: T): SetIterator; + /** + * @inheritdoc + */ + begin(): SetIterator; + /** + * @inheritdoc + */ + begin(index: number): SetIterator; + /** + * @inheritdoc + */ + end(): SetIterator; + /** + * @inheritdoc + */ + end(index: number): SetIterator; + /** + * @inheritdoc + */ + rbegin(): SetReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + rend(): SetReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(n: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc + */ + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: T): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected insert_by_val(val: T): any; + /** + * @hidden + */ + protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.UniqueSet): void; + /** + * @hidden + */ + private swap_tree_set(obj); + } +} declare namespace std.List { type iterator = std.ListIterator; type reverse_iterator = std.ListReverseIterator; @@ -6523,8 +6538,8 @@ declare namespace std { * distance between these. They also consume some extra memory to keep the linking information associated to each * element (which may be an important factor for large lists of small-sized elements).

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -6546,15 +6561,15 @@ declare namespace std { */ class List extends base.Container implements base.IDequeContainer { /** - * An iterator of beginning. + * @hidden */ protected begin_: ListIterator; /** - * An iterator of end. + * @hidden */ protected end_: ListIterator; /** - * Number of elements in the {@link List}. + * @hidden */ protected size_: number; /** @@ -7096,8 +7111,8 @@ declare namespace std { /** *

    An iterator, node of a List.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -7143,6 +7158,11 @@ declare namespace std { /** * @inheritdoc */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ value: T; /** * @inheritdoc @@ -7158,8 +7178,8 @@ declare namespace std { /** *

    A reverse-iterator of List.

    * - *

    - * + *

    + * *

    * * @param Type of the elements. @@ -7167,13 +7187,20 @@ declare namespace std { * @author Jeongho Nam */ class ListReverseIterator extends ReverseIterator, ListReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: ListIterator); /** - * @inheritdoc + * @hidden */ protected create_neighbor(): ListReverseIterator; /** - * @inheritdoc + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; } @@ -7208,8 +7235,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard * container {@link List} is used.

    * - *

    - * + *

    + * *

    * * @param Type of elements. @@ -7540,8 +7567,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard * container {@link List} is used.

    * - *

    - * + *

    + * *

    * * @param Type of elements. @@ -7651,18 +7678,18 @@ declare namespace std.base { * so that they can be interpreted when needed as more abstract (and portable) * {@link ErrorCondition error conditions}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ abstract class ErrorInstance { /** - * A reference to an {@link ErrorCategory} object. + * @hidden */ protected category_: ErrorCategory; /** - * A numerical value identifying an error instance. + * @hidden */ protected value_: number; /** @@ -7761,15 +7788,15 @@ declare namespace std { *

    The class inherits from {@link RuntimeError}, to which it adds an {@link ErrorCode} as * member code (and defines a specialized what member).

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/system_error/system_error * @author Jeongho Nam */ class SystemError extends RuntimeError { /** - * Error code. + * @hidden */ protected code_: ErrorCode; /** @@ -7827,8 +7854,8 @@ declare namespace std { * passed by reference. As such, only one object of each of these types shall exist, each uniquely identifying its own * category: all error codes and conditions of a same category shall return a reference to same object.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/system_error/error_category * @author Jeongho Nam @@ -7955,8 +7982,8 @@ declare namespace std { *

    The {@link ErrorCategory categories} associated with the {@link ErrorCondition} and the * {@link ErrorCode} define the equivalences between them.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/system_error/error_condition * @author Jeongho Nam @@ -7988,8 +8015,8 @@ declare namespace std { *

    Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, so that they * can be interpreted when needed as more abstract (and portable) {@link ErrorCondition error conditions}.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/system_error/error_code * @author Jeongho Nam @@ -8034,8 +8061,8 @@ declare namespace std { * *

    {@link TreeMap}s are typically implemented as binary search trees.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -8063,7 +8090,7 @@ declare namespace std { */ class TreeMap extends base.UniqueMap implements base.ITreeMap { /** - * RB-Tree+ object for implemeting the {@link TreeMap}. + * @hidden */ private tree_; /** @@ -8216,8 +8243,8 @@ declare namespace std { * *

    {@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees.

    * - *

    < - * img src="http://samchon.github.io/typescript-stl/api/assets/images/design/map_containers.png" style="max-width: 100%" />

    + *

    < + * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

    * *

    Container properties

    *
    @@ -8250,6 +8277,9 @@ declare namespace std { * @author Jeongho Nam */ class TreeMultiMap extends base.MultiMap implements base.ITreeMap { + /** + * @hidden + */ private tree_; /** * Default Constructor. @@ -8377,169 +8407,6 @@ declare namespace std { private swap_tree_multimap(obj); } } -declare namespace std.TreeSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

    Tree-structured set, std::set of STL.

    - * - *

    {@link TreeSet}s are containers that store unique elements following a specific order.

    - * - *

    In a {@link TreeSet}, the value of an element also identifies it (the value is itself the - * key, of type T), and each value must be unique. The value of the elements in a - * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they - * can be inserted or removed from the

    - * - *

    Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak - * ordering criterion indicated by its internal comparison method (of {@link less}).

    - * - *

    {@link TreeSet} containers are generally slower than {@link HashSet} containers to access - * individual elements by their key, but they allow the direct iteration on subsets based on their - * order.

    - * - *

    {@link TreeSet}s are typically implemented as binary search trees.

    - * - *

    - *

    - * - *

    Container properties

    - *
    - *
    Associative
    - *
    - * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
    - * - *
    Ordered
    - *
    - * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
    - * - *
    Set
    - *
    The value of an element is also the key used to identify it.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the elements. - * Each element in an {@link TreeSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/set/set - * @author Jeongho Nam - */ - class TreeSet extends base.UniqueSet implements base.ITreeSet { - /** - * RB-Tree+ object for implemeting the {@link TreeSet}. - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: T, y: T) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (x: T, y: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: base.IContainer); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: base.IContainer, compare: (x: T, y: T) => boolean); - /** - * Range Constructor. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Range Constructor with compare. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(val: T): SetIterator; - /** - * @inheritdoc - */ - key_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - lower_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - upper_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - equal_range(val: T): Pair, SetIterator>; - /** - * @hidden - */ - protected insert_by_val(val: T): any; - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected handle_erase(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - swap(obj: base.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); - } -} declare namespace std.TreeMultiSet { type iterator = std.SetIterator; type reverse_iterator = std.SetReverseIterator; @@ -8565,8 +8432,8 @@ declare namespace std { * *

    {@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -8597,7 +8464,7 @@ declare namespace std { */ class TreeMultiSet extends base.MultiSet implements base.ITreeSet { /** - * RB-Tree+ object for implemeting the {@link TreeMultiSet}. + * @hidden */ private tree_; /** @@ -8711,6 +8578,169 @@ declare namespace std { private swap_tree_set(obj); } } +declare namespace std.TreeSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; +} +declare namespace std { + /** + *

    Tree-structured set, std::set of STL.

    + * + *

    {@link TreeSet}s are containers that store unique elements following a specific order.

    + * + *

    In a {@link TreeSet}, the value of an element also identifies it (the value is itself the + * key, of type T), and each value must be unique. The value of the elements in a + * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they + * can be inserted or removed from the

    + * + *

    Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak + * ordering criterion indicated by its internal comparison method (of {@link less}).

    + * + *

    {@link TreeSet} containers are generally slower than {@link HashSet} containers to access + * individual elements by their key, but they allow the direct iteration on subsets based on their + * order.

    + * + *

    {@link TreeSet}s are typically implemented as binary search trees.

    + * + *

    + *

    + * + *

    Container properties

    + *
    + *
    Associative
    + *
    + * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
    + * + *
    Ordered
    + *
    + * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
    + * + *
    Set
    + *
    The value of an element is also the key used to identify it.
    + * + *
    Unique keys
    + *
    No two elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the elements. + * Each element in an {@link TreeSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/set/set + * @author Jeongho Nam + */ + class TreeSet extends base.UniqueSet implements base.ITreeSet { + /** + * @hidden + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (x: T, y: T) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array); + /** + * Contruct from elements with compare. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array, compare: (x: T, y: T) => boolean); + /** + * Copy Constructor. + */ + constructor(container: base.IContainer); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: base.IContainer, compare: (x: T, y: T) => boolean); + /** + * Range Constructor. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * Range Constructor with compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(val: T): SetIterator; + /** + * @inheritdoc + */ + key_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + value_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + lower_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + upper_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + equal_range(val: T): Pair, SetIterator>; + /** + * @hidden + */ + protected insert_by_val(val: T): any; + protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.UniqueSet): void; + /** + * @hidden + */ + private swap_tree_set(obj); + } +} declare namespace std { /** *

    Running on Node.

    @@ -8818,8 +8848,8 @@ declare namespace std { * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. *

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -9200,8 +9230,8 @@ declare namespace std { /** *

    An iterator of Vector.

    * - *

    - * + *

    + * *

    * * @param Type of the elements. @@ -9232,7 +9262,9 @@ declare namespace std { * @inheritdoc */ /** - * Set value. + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; /** @@ -9277,8 +9309,8 @@ declare namespace std { /** *

    A reverse-iterator of Vector.

    * - *

    - * + *

    + * *

    * * @param Type of the elements. @@ -9286,13 +9318,20 @@ declare namespace std { * @author Jeongho Nam */ class VectorReverseIterator extends ReverseIterator, VectorReverseIterator> implements base.IArrayIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: VectorIterator); /** - * @inheritdoc + * @hidden */ protected create_neighbor(): VectorReverseIterator; /** - * Set value. + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; /** @@ -9353,7 +9392,13 @@ declare namespace std.base { * @author Jeongho Nam */ class HashBuckets { + /** + * @hidden + */ private buckets_; + /** + * @hidden + */ private item_size_; /** * Default Constructor. @@ -9400,8 +9445,8 @@ declare namespace std.base { *

    Elements with equivalent keys are grouped together in the same bucket and in such a way that * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -9696,8 +9741,8 @@ declare namespace std.base { /** *

    Hash buckets storing {@link MapIterator MapIterators}.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -9727,8 +9772,8 @@ declare namespace std.base { * elements by their key, although they are generally less efficient for range iteration through a * subset of their elements.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -9951,8 +9996,8 @@ declare namespace std.base { /** *

    Hash buckets storing {@link SetIterator SetIterators}.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -9993,8 +10038,8 @@ declare namespace std.base { * beginning or the end, {@link IArray} objects perform worse and have less consistent iterators and references * than {@link List Lists}

    . * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -10107,8 +10152,8 @@ declare namespace std.base { *

    There is not a single type of {@link IArrayIterator random-access iterator}: Each container may define its * own specific iterator type able to iterate through it and access its elements.

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator @@ -10138,8 +10183,8 @@ declare namespace std.base { *

    {@link IContainer} is an interface designed for sequence containers. Sequence containers of STL * (Standard Template Library) are based on the {@link IContainer}.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -10330,8 +10375,8 @@ declare namespace std.base { /** *

    An interface for deque

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -10360,8 +10405,8 @@ declare namespace std.base { /** *

    An interface for linear containers.

    * - *

    - * + *

    + * *

    * * @author Jeonngho Nam @@ -10522,7 +10567,7 @@ declare namespace std.base { * * * - *

    * *

    These constraints enforce a critical property of red-black trees: the path from the root to the farthest @@ -10717,7 +10762,7 @@ declare namespace std.base { * the only loop, and any rotations occur after this loop, this proves that a constant number of rotations * occur.

    * - *

    * * @param N A node to be inserted or swapped. @@ -10751,7 +10796,7 @@ declare namespace std.base { * node are black) is still violated, but now we can resolve this by * continuing to case 5.

    * - *

    * * @param N A node to be inserted or swapped. @@ -10782,7 +10827,7 @@ declare namespace std.base { * through {@link XTreeNode.parent P}. In each case, this is the only * black node of the three.

    * - *

    * * @param N A node to be inserted or swapped. @@ -10936,7 +10981,7 @@ declare namespace std.base { /** *

    {@link XTreeNode.sibling S} is red.

    * - *

    * *

    In this case we reverse the colors of {@link XTreeNode.parent P} and @@ -10958,7 +11003,7 @@ declare namespace std.base { *

    {@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and {@link XTreeNode.sibling * S}'s children are black.

    * - *

    * *

    In this case, we simply repaint {@link XTreeNode.sibling S} red. The @@ -10982,7 +11027,7 @@ declare namespace std.base { *

    {@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are * black, but {@link XTreeNode.parent P} is red.

    * - *

    * *

    In this case, we simply exchange the colors of {@link XTreeNode.sibling S} and @@ -10999,7 +11044,7 @@ declare namespace std.base { * left child is red, {@link XTreeNode.sibling S}'s right child is * black, and N is the left child of its parent.

    * - *

    * *

    In this case we rotate right at {@link XTreeNode.sibling S}, so that @@ -11038,7 +11083,7 @@ declare namespace std.base { *

    Thus, the paths passing through N pass through one additional * black node.

    * - *

    * *

    Meanwhile, if a path does not go through N, then there are two possibilities:

    @@ -11122,8 +11167,8 @@ declare namespace std.base { * *

    {@link ITreeMap TreeMultiMaps} are typically implemented as binary search trees.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -11257,13 +11302,19 @@ declare namespace std.base { /** *

    A red-black tree storing {@link MapIterator MapIterators}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ class PairTree extends XTree> { + /** + * @hidden + */ private map_; + /** + * @hidden + */ private compare_; /** * Default Constructor. @@ -11409,8 +11460,8 @@ declare namespace std.base { * *

    {@link ITreeSet TreeMultiSets} are typically implemented as binary search trees.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -11551,13 +11602,19 @@ declare namespace std.base { /** *

    A red-black Tree storing {@link SetIterator SetIterators}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ class AtomicTree extends XTree> { + /** + * @hidden + */ private set_; + /** + * @hidden + */ private compare_; /** * Default Constructor. @@ -11738,27 +11795,3 @@ declare namespace std.base { uncle: XTreeNode; } } -declare namespace std.example { - function test_all(): void; -} -declare namespace std.example { - function test_bind(): void; -} -declare namespace std.example { - function test_deque(): void; -} -declare namespace std.example { - function test_for_each(): void; -} -declare namespace std.example { - function test_hash_map(): void; -} -declare namespace std.example { - function test_list(): void; -} -declare namespace std.example { - function sorting(): void; -} -declare namespace std.example { - function tree_set(): void; -} From 98522eee4825682cc8fa73da4a9a8ba5f34aaf18 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Fri, 12 Aug 2016 09:51:01 +0900 Subject: [PATCH 05/56] TypeScript-STL & Samchon Framework --- typescript-stl/typescript-stl.d.ts | 120 ++++++++++++++--------------- 1 file changed, 60 insertions(+), 60 deletions(-) diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index 9e491ff258..5a83a405cd 100644 --- a/typescript-stl/typescript-stl.d.ts +++ b/typescript-stl/typescript-stl.d.ts @@ -2744,8 +2744,8 @@ declare namespace std.base { /** *

    An abstract container.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -2865,8 +2865,8 @@ declare namespace std { *

    There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} * may define its own specific iterator type able to iterate through it and access its elements.

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator @@ -2951,8 +2951,8 @@ declare namespace std { * first element in a range is reversed, the reversed iterator points to the element before the first element (this * would be the past-the-end element of the reversed range).

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator @@ -3622,8 +3622,8 @@ declare namespace std { *

    All objects thrown by components of the standard library are derived from this class. * Therefore, all standard exceptions can be caught by catching this type by reference.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/exception/exception * @author Jeongho Nam @@ -3671,8 +3671,8 @@ declare namespace std { * *

    It is used as a base class for several logical error exceptions.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/logic_error * @author Jeongho Nam @@ -3697,8 +3697,8 @@ declare namespace std { *

    No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/domain_error * @author Jeongho Nam @@ -3719,8 +3719,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal invalid arguments.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument * @author Jeongho Nam @@ -3741,8 +3741,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library, * such as vector and string also throw exceptions of this type to signal errors resizing.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/length_error * @author Jeongho Nam @@ -3764,8 +3764,8 @@ declare namespace std { * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments * out of range.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range * @author Jeongho Nam @@ -3786,8 +3786,8 @@ declare namespace std { * *

    It is used as a base class for several runtime error exceptions.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error * @author Jeongho Nam @@ -3808,8 +3808,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error * @author Jeongho Nam @@ -3830,8 +3830,8 @@ declare namespace std { *

    No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error * @author Jeongho Nam @@ -3853,8 +3853,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/range_error * @author Jeongho Nam @@ -4415,8 +4415,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -4813,8 +4813,8 @@ declare namespace std { /** *

    An iterator of {@link MapContainer map container}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -4884,8 +4884,8 @@ declare namespace std { /** *

    A reverse-iterator of {@link MapContainer map container}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -4932,8 +4932,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5477,8 +5477,8 @@ declare namespace std { *

    Elements with equivalent keys are grouped together in the same bucket and in such a way that * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -5637,8 +5637,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5914,8 +5914,8 @@ declare namespace std { /** *

    An iterator of a Set.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -5973,8 +5973,8 @@ declare namespace std { /** *

    A reverse-iterator of Set.

    * - *

    - *

    + *

    + *

    * * @param Type of the elements. * @@ -6240,8 +6240,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -7235,8 +7235,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard * container {@link List} is used.

    * - *

    - * + *

    + * *

    * * @param Type of elements. @@ -7567,8 +7567,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard * container {@link List} is used.

    * - *

    - * + *

    + * *

    * * @param Type of elements. @@ -9772,8 +9772,8 @@ declare namespace std.base { * elements by their key, although they are generally less efficient for range iteration through a * subset of their elements.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -9996,8 +9996,8 @@ declare namespace std.base { /** *

    Hash buckets storing {@link SetIterator SetIterators}.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -10152,8 +10152,8 @@ declare namespace std.base { *

    There is not a single type of {@link IArrayIterator random-access iterator}: Each container may define its * own specific iterator type able to iterate through it and access its elements.

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator @@ -10183,8 +10183,8 @@ declare namespace std.base { *

    {@link IContainer} is an interface designed for sequence containers. Sequence containers of STL * (Standard Template Library) are based on the {@link IContainer}.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -10375,8 +10375,8 @@ declare namespace std.base { /** *

    An interface for deque

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -10405,8 +10405,8 @@ declare namespace std.base { /** *

    An interface for linear containers.

    * - *

    - * + *

    + * *

    * * @author Jeonngho Nam From d44c56c717ef10b3d9aecb3b59df6dc6e03369a9 Mon Sep 17 00:00:00 2001 From: Michael Zlatkovsky Date: Fri, 12 Aug 2016 18:32:57 -0700 Subject: [PATCH 06/56] Update common runtime and add Excel 1.3 Also strip out filenames that start with _ in Word APIs --- office-js/office-js.d.ts | 1460 ++++++++++++++++++++++++-------------- 1 file changed, 941 insertions(+), 519 deletions(-) diff --git a/office-js/office-js.d.ts b/office-js/office-js.d.ts index f2bebfe3da..4f21022fe5 100644 --- a/office-js/office-js.d.ts +++ b/office-js/office-js.d.ts @@ -53,7 +53,7 @@ declare namespace Office { displayLanguage: string; license: string; touchEnabled: boolean; - ui: UI; + ui: UI; requirements: { /** * Check if the specified requirement set is supported by the host Office application. @@ -67,51 +67,54 @@ declare namespace Office { message: string; name: string; } - export interface UI { - /** - * Displays a dialog to show or collect information from the user or to facilitate Web navigation. - * @param startAddress Accepts the initial HTTPS Url that opens in the dialog. - * @param options Optional. Accepts a DialogOptions object to define dialog behaviors. - * @param callback Optional. Accepts a callback method to handle the dialog creation attempt. - */ - displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; - /** - * When called from an active add-in dialog, asynchronously closes the dialog. - */ - close(): void; - /** - * Synchronously delivers a message from the dialog to its parent add-in. - * @param messageObject Accepts a message from the dialog to deliver to the add-in. - */ - messageParent(messageObject: any): void; + export interface UI { + /** + * Displays a dialog to show or collect information from the user or to facilitate Web navigation. + * @param startAddress Accepts the initial HTTPS Url that opens in the dialog. + * @param options Optional. Accepts a DialogOptions object to define dialog behaviors. + * @param callback Optional. Accepts a callback method to handle the dialog creation attempt. + */ + displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; + /** + * When called from an active add-in dialog, asynchronously closes the dialog. + */ + close(): void; + /** + * Synchronously delivers a message from the dialog to its parent add-in. + * @param messageObject Accepts a message from the dialog to deliver to the add-in. + */ + messageParent(messageObject: any): void; } export interface DialogOptions { /** * Optional. Defines the width of the dialog as a percentage of the current display. Defaults to 99%. 250px minimum. */ - height?: number, + height?: number, /** * Optional. Defines the height of the dialog as a percentage of the current display. Defaults to 99%. 150px minimum. */ - width?: number, + width?: number, /** * Optional. Specifies whether the dialog can only display pages that have HTTPS URLs. */ - requireHTTPS?: boolean, + requireHTTPS?: boolean, /** * Optional. Determines whether the dialog is safe to display within a Web frame. */ xFrameDenySafe?: boolean, } } -declare namespace OfficeExtension { + +declare module OfficeExtension { /** An abstract proxy object that represents an object in an Office document. You create proxy objects from the context (or from other proxy objects), add commands to a queue to act on the object, and then synchronize the proxy object state with the document by calling "context.sync()". */ class ClientObject { /** The request context associated with the object */ context: ClientRequestContext; + /** Returns a boolean value for whether the corresponding object is null. You must call "context.sync()" before reading the isNull property. [Api set: ExcelApi 1.3 (Preview), WordApi 1.3] */ + isNull: boolean; } } -declare namespace OfficeExtension { +declare module OfficeExtension { interface LoadOption { select?: string | string[]; expand?: string | string[]; @@ -127,18 +130,18 @@ declare namespace OfficeExtension { load(object: ClientObject, option?: string | string[] | LoadOption): void; /** Adds a trace message to the queue. If the promise returned by "context.sync()" is rejected due to an error, this adds a ".traceMessages" array to the OfficeExtension.Error object, containing all trace messages that were executed. These messages can help you monitor the program execution sequence and detect the cause of the error. */ trace(message: string): void; - /** Synchronizes the state between JavaScript proxy objects and the Office document, by executing instructions queued on the request context and retrieving properties of loaded Office objects for use in your code.�This method returns a promise, which is resolved when the synchronization is complete. */ + /** Synchronizes the state between JavaScript proxy objects and the Office document, by executing instructions queued on the request context and retrieving properties of loaded Office objects for use in your code. This method returns a promise, which is resolved when the synchronization is complete. */ sync(passThroughValue?: T): IPromise; } } -declare namespace OfficeExtension { +declare module OfficeExtension { /** Contains the result for methods that return primitive types. The object's value property is retrieved from the document after "context.sync()" is invoked. */ class ClientResult { /** The value of the result that is retrieved from the document after "context.sync()" is invoked. */ value: T; } } -declare namespace OfficeExtension { +declare module OfficeExtension { /** The error object returned by "context.sync()", if a promise is rejected due to an error while processing the request. */ class Error { /** Error name: "OfficeExtension.Error".*/ @@ -158,68 +161,186 @@ declare namespace OfficeExtension { }; } } -declare namespace OfficeExtension { +declare module OfficeExtension { class ErrorCodes { static accessDenied: string; static generalException: string; static activityLimitReached: string; + static invalidObjectPath: string; + static propertyNotLoaded: string; + static valueNotLoaded: string; + static invalidRequestContext: string; + static invalidArgument: string; + static runMustReturnPromise: string; + static cannotRegisterEvent: string; } } -declare namespace OfficeExtension { - /** A Promise object that represents a deferred interaction with the host Office application. Promises can be chained via ".then", and errors can be caught via ".catch". Remember to always use a ".catch" on the outer promise, and to return intermediary promises so as not to break the promise chain. */ +declare module OfficeExtension { + /** An IPromise object that represents a deferred interaction with the host Office application. */ interface IPromise { /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => IPromise): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => U): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => void): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => IPromise): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): IPromise; + + /** * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. * @param onRejected function to be called if or when the promise rejects. */ catch(onRejected?: (error: any) => IPromise): IPromise; + /** * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. * @param onRejected function to be called if or when the promise rejects. */ catch(onRejected?: (error: any) => U): IPromise; + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => void): IPromise; + } + + /** An Promise object that represents a deferred interaction with the host Office application. The publically-consumable OfficeExtension.Promise is available starting in ExcelApi 1.2 and WordApi 1.2. Promises can be chained via ".then", and errors can be caught via ".catch". Remember to always use a ".catch" on the outer promise, and to return intermediary promises so as not to break the promise chain. When a "native" Promise implementation is available, OfficeExtension.Promise will switch to use the native Promise instead. */ + export class Promise implements IPromise + { + /** + * Creates a new promise based on a function that accepts resolve and reject handlers. + */ + constructor(func: (resolve, reject) => void); + + /** + * Creates a promise that resolves when all of the child promises resolve. + */ + static all(promises: OfficeExtension.IPromise[]): IPromise; + + /** + * Creates a promise that is resolved. + */ + static resolve(value: U): IPromise; + + /** + * Creates a promise that is rejected. + */ + static reject(error: any): IPromise; + + /* This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => IPromise): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => U): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => void): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => IPromise): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): IPromise; + + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => IPromise): IPromise; + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => U): IPromise; + /** * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. * @param onRejected function to be called if or when the promise rejects. @@ -227,7 +348,8 @@ declare namespace OfficeExtension { catch(onRejected?: (error: any) => void): IPromise; } } -declare namespace OfficeExtension { + +declare module OfficeExtension { /** Collection of tracked objects, contained within a request context. See "context.trackedObjects" for more information. */ class TrackedObjects { /** Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ @@ -241,6 +363,26 @@ declare namespace OfficeExtension { } } +declare module OfficeExtension { + export class EventHandlers { + constructor(context: ClientRequestContext, parentObject: ClientObject, name: string, eventInfo: EventInfo); + add(handler: (args: T) => IPromise): EventHandlerResult; + remove(handler: (args: T) => IPromise): void; + removeAll(): void; + } + + export class EventHandlerResult { + constructor(context: ClientRequestContext, handlers: EventHandlers, handler: (args: T) => IPromise); + remove(): void; + } + + export interface EventInfo { + registerFunc: (callback: (args: any) => void) => IPromise; + unregisterFunc: (callback: (args: any) => void) => IPromise; + eventArgsTransformFunc: (args: any) => IPromise; + } +} + declare namespace Office { /** * Returns a promise of an object described in the expression. Callback is invoked only if method fails. @@ -467,7 +609,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - setDataAsync(data: TableData|any, options?: any, callback?: (result: AsyncResult) => void): void; + setDataAsync(data: TableData | any, options?: any, callback?: (result: AsyncResult) => void): void; } export interface Bindings { document: Document; @@ -743,7 +885,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - goToByIdAsync(id: string|number, goToType: GoToType, options?: any, callback?: (result: AsyncResult) => void): void; + goToByIdAsync(id: string | number, goToType: GoToType, options?: any, callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. * @param eventType The event type. For document can be 'DocumentSelectionChanged' @@ -761,7 +903,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - setSelectedDataAsync(data: string|TableData|any[][], options?: any, callback?: (result: AsyncResult) => void): void; + setSelectedDataAsync(data: string | TableData | any[][], options?: any, callback?: (result: AsyncResult) => void): void; } export interface File { size: number; @@ -853,7 +995,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - addColumnsAsync(tableData: TableData|any[][], options?: any, callback?: (result: AsyncResult) => void): void; + addColumnsAsync(tableData: TableData | any[][], options?: any, callback?: (result: AsyncResult) => void): void; /** * Adds the specified rows to the table * @param rows A 2D array with the rows to add @@ -861,7 +1003,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - addRowsAsync(rows: TableData|any[][], options?: any, callback?: (result: AsyncResult) => void): void; + addRowsAsync(rows: TableData | any[][], options?: any, callback?: (result: AsyncResult) => void): void; /** * Clears the table * @param options Syntax example: {asyncContext:context} @@ -1503,9 +1645,238 @@ declare namespace Office { getWSSUrlAsync(options?: any, callback?: (result: AsyncResult) => void): void; } } - - -declare namespace Excel { +declare module Excel { + interface ThreeArrowsSet { + [index: number]: Icon; + redDownArrow: Icon; + yellowSideArrow: Icon; + greenUpArrow: Icon; + } + interface ThreeArrowsGraySet { + [index: number]: Icon; + grayDownArrow: Icon; + graySideArrow: Icon; + grayUpArrow: Icon; + } + interface ThreeFlagsSet { + [index: number]: Icon; + redFlag: Icon; + yellowFlag: Icon; + greenFlag: Icon; + } + interface ThreeTrafficLights1Set { + [index: number]: Icon; + redCircleWithBorder: Icon; + yellowCircle: Icon; + greenCircle: Icon; + } + interface ThreeTrafficLights2Set { + [index: number]: Icon; + redTrafficLight: Icon; + yellowTrafficLight: Icon; + greenTrafficLight: Icon; + } + interface ThreeSignsSet { + [index: number]: Icon; + redDiamond: Icon; + yellowTriangle: Icon; + greenCircle: Icon; + } + interface ThreeSymbolsSet { + [index: number]: Icon; + redCrossSymbol: Icon; + yellowExclamationSymbol: Icon; + greenCheckSymbol: Icon; + } + interface ThreeSymbols2Set { + [index: number]: Icon; + redCross: Icon; + yellowExclamation: Icon; + greenCheck: Icon; + } + interface FourArrowsSet { + [index: number]: Icon; + redDownArrow: Icon; + yellowDownInclineArrow: Icon; + yellowUpInclineArrow: Icon; + greenUpArrow: Icon; + } + interface FourArrowsGraySet { + [index: number]: Icon; + grayDownArrow: Icon; + grayDownInclineArrow: Icon; + grayUpInclineArrow: Icon; + grayUpArrow: Icon; + } + interface FourRedToBlackSet { + [index: number]: Icon; + blackCircle: Icon; + grayCircle: Icon; + pinkCircle: Icon; + redCircle: Icon; + } + interface FourRatingSet { + [index: number]: Icon; + oneBar: Icon; + twoBars: Icon; + threeBars: Icon; + fourBars: Icon; + } + interface FourTrafficLightsSet { + [index: number]: Icon; + blackCircleWithBorder: Icon; + redCircleWithBorder: Icon; + yellowCircle: Icon; + greenCircle: Icon; + } + interface FiveArrowsSet { + [index: number]: Icon; + redDownArrow: Icon; + yellowDownInclineArrow: Icon; + yellowSideArrow: Icon; + yellowUpInclineArrow: Icon; + greenUpArrow: Icon; + } + interface FiveArrowsGraySet { + [index: number]: Icon; + grayDownArrow: Icon; + grayDownInclineArrow: Icon; + graySideArrow: Icon; + grayUpInclineArrow: Icon; + grayUpArrow: Icon; + } + interface FiveRatingSet { + [index: number]: Icon; + noBars: Icon; + oneBar: Icon; + twoBars: Icon; + threeBars: Icon; + fourBars: Icon; + } + interface FiveQuartersSet { + [index: number]: Icon; + whiteCircleAllWhiteQuarters: Icon; + circleWithThreeWhiteQuarters: Icon; + circleWithTwoWhiteQuarters: Icon; + circleWithOneWhiteQuarter: Icon; + blackCircle: Icon; + } + interface ThreeStarsSet { + [index: number]: Icon; + silverStar: Icon; + halfGoldStar: Icon; + goldStar: Icon; + } + interface ThreeTrianglesSet { + [index: number]: Icon; + redDownTriangle: Icon; + yellowDash: Icon; + greenUpTriangle: Icon; + } + interface FiveBoxesSet { + [index: number]: Icon; + noFilledBoxes: Icon; + oneFilledBox: Icon; + twoFilledBoxes: Icon; + threeFilledBoxes: Icon; + fourFilledBoxes: Icon; + } + interface IconCollections { + threeArrows: ThreeArrowsSet; + threeArrowsGray: ThreeArrowsGraySet; + threeFlags: ThreeFlagsSet; + threeTrafficLights1: ThreeTrafficLights1Set; + threeTrafficLights2: ThreeTrafficLights2Set; + threeSigns: ThreeSignsSet; + threeSymbols: ThreeSymbolsSet; + threeSymbols2: ThreeSymbols2Set; + fourArrows: FourArrowsSet; + fourArrowsGray: FourArrowsGraySet; + fourRedToBlack: FourRedToBlackSet; + fourRating: FourRatingSet; + fourTrafficLights: FourTrafficLightsSet; + fiveArrows: FiveArrowsSet; + fiveArrowsGray: FiveArrowsGraySet; + fiveRating: FiveRatingSet; + fiveQuarters: FiveQuartersSet; + threeStars: ThreeStarsSet; + threeTriangles: ThreeTrianglesSet; + fiveBoxes: FiveBoxesSet; + } + var icons: IconCollections; + /** + * + * Provides information about the binding that raised the SelectionChanged event. + * + * [Api set: ExcelApi 1.2] + */ + interface BindingSelectionChangedEventArgs { + /** + * + * Gets the Binding object that represents the binding that raised the SelectionChanged event. + * + * [Api set: ExcelApi 1.2] + */ + binding: Excel.Binding; + /** + * + * Gets the number of columns selected. + * + * [Api set: ExcelApi 1.2] + */ + columnCount: number; + /** + * + * Gets the number of rows selected. + * + * [Api set: ExcelApi 1.2] + */ + rowCount: number; + /** + * + * Gets the index of the first column of the selection (zero-based). + * + * [Api set: ExcelApi 1.2] + */ + startColumn: number; + /** + * + * Gets the index of the first row of the selection (zero-based). + * + * [Api set: ExcelApi 1.2] + */ + startRow: number; + } + /** + * + * Provides information about the binding that raised the DataChanged event. + * + * [Api set: ExcelApi 1.2] + */ + interface BindingDataChangedEventArgs { + /** + * + * Gets the Binding object that represents the binding that raised the DataChanged event. + * + * [Api set: ExcelApi 1.2] + */ + binding: Excel.Binding; + } + /** + * + * Provides information about the document that raised the SelectionChanged event. + * + * [Api set: ExcelApi 1.2] + */ + interface SelectionChangedEventArgs { + /** + * + * Gets the workbook object that raised the SelectionChanged event. + * + * [Api set: ExcelApi 1.2] + */ + workbook: Excel.Workbook; + } /** * * Represents the Excel application that manages the workbook. @@ -1546,8 +1917,10 @@ declare namespace Excel { private m_bindings; private m_functions; private m_names; + private m_pivotTables; private m_tables; private m_worksheets; + private m_selectionChanged; /** * * Represents Excel application instance that contains this workbook. Read-only. @@ -1576,6 +1949,13 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ names: Excel.NamedItemCollection; + /** + * + * Represents a collection of PivotTables associated with the workbook. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + pivotTables: Excel.PivotTableCollection; /** * * Represents a collection of tables associated with the workbook. Read-only. @@ -1601,6 +1981,13 @@ declare namespace Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Workbook; + /** + * + * Occurs when the selection in the document is changed. + * + * [Api set: ExcelApi 1.2] + */ + onSelectionChanged: OfficeExtension.EventHandlers; } /** * @@ -1612,6 +1999,7 @@ declare namespace Excel { private m_charts; private m_id; private m_name; + private m_pivotTables; private m_position; private m_protection; private m_tables; @@ -1623,6 +2011,13 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ charts: Excel.ChartCollection; + /** + * + * Collection of PivotTables that are part of the worksheet. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + pivotTables: Excel.PivotTableCollection; /** * * Returns sheet protection object for a worksheet. @@ -1702,7 +2097,7 @@ declare namespace Excel { * * The used range is the smallest range that encompasses any cells that have a value or formatting assigned to them. If the worksheet is blank, this function will return the top left cell. * - * @param valuesOnly Considers only cells with values as used cells (ignores formatting). [Parameter available: ExcelApi 1.2] + * @param valuesOnly Considers only cells with values as used cells (ignores formatting). [Api set: ExcelApi 1.2] * * [Api set: ExcelApi 1.1] */ @@ -1747,6 +2142,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItem(key: string): Excel.Worksheet; + /** + * + * Gets a worksheet object using its Name or ID. If the worksheet does not exist, the returned object's isNull property will be true. + * + * @param key The Name or ID of the worksheet. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(key: string): Excel.Worksheet; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -1777,7 +2181,7 @@ declare namespace Excel { protected: boolean; /** * - * Protect a worksheet. It throws if the worksheet has been protected. + * Protects a worksheet. Fails if the worksheet has been protected. * * @param options sheet protection options. * @@ -1786,7 +2190,7 @@ declare namespace Excel { protect(options?: Excel.WorksheetProtectionOptions): void; /** * - * Unprotect a worksheet + * Unprotects a worksheet. * * [Api set: ExcelApi 1.2] */ @@ -1868,7 +2272,7 @@ declare namespace Excel { allowInsertRows?: boolean; /** * - * Represents the worksheet protection option of allowing using pivot table feature. + * Represents the worksheet protection option of allowing using PivotTable feature. * * [Api set: ExcelApi 1.2] */ @@ -1909,6 +2313,8 @@ declare namespace Excel { private m_values; private m_worksheet; private m__ReferenceId; + private _ensureInteger(num, methodName); + private _getAdjacentRange(functionName, count, referenceRange, rowDirection, columnDirection); /** * * Returns a format object, encapsulating the range's font, fill, borders, alignment, and other properties. Read-only. @@ -1916,6 +2322,12 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ format: Excel.RangeFormat; + /** + * + * Represents the range sort of the current range. + * + * [Api set: ExcelApi 1.2] + */ sort: Excel.RangeSort; /** * @@ -2089,6 +2501,24 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getColumn(column: number): Excel.Range; + /** + * + * Gets a certain number of columns to the right of the current Range object. + * + * @param count The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. + * + * [Api set: ExcelApi 1.2] + */ + getColumnsAfter(count?: number): Excel.Range; + /** + * + * Gets a certain number of columns to the left of the current Range object. + * + * @param count The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. + * + * [Api set: ExcelApi 1.2] + */ + getColumnsBefore(count?: number): Excel.Range; /** * * Gets an object that represents the entire column of the range. @@ -2112,6 +2542,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getIntersection(anotherRange: Excel.Range | string): Excel.Range; + /** + * + * Gets the range object that represents the rectangular intersection of the given ranges. If no intersection is found, will return a null object. + * + * @param anotherRange The range object or range address that will be used to determine the intersection of ranges. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getIntersectionOrNull(anotherRange: Excel.Range | string): Excel.Range; /** * * Gets the last cell within the range. For example, the last cell of "B2:D5" is "D5". @@ -2143,6 +2582,16 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getOffsetRange(rowOffset: number, columnOffset: number): Excel.Range; + /** + * + * Gets a Range object similar to the current Range object, but with its bottom-right corner expanded (or contracted) by some number of rows and columns. + * + * @param deltaRows The number of rows by which to expand the bottom-right corner, relative to the current range. Use a positive number to expand the range, or a negative number to decrease it. + * @param deltaColumns The number of columnsby which to expand the bottom-right corner, relative to the current range. Use a positive number to expand the range, or a negative number to decrease it. + * + * [Api set: ExcelApi 1.2] + */ + getResizedRange(deltaRows: number, deltaColumns: number): Excel.Range; /** * * Gets a row contained in the range. @@ -2152,15 +2601,40 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getRow(row: number): Excel.Range; + /** + * + * Gets a certain number of rows above the current Range object. + * + * @param count The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. + * + * [Api set: ExcelApi 1.2] + */ + getRowsAbove(count?: number): Excel.Range; + /** + * + * Gets a certain number of rows below the current Range object. + * + * @param count The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. + * + * [Api set: ExcelApi 1.2] + */ + getRowsBelow(count?: number): Excel.Range; /** * * Returns the used range of the given range object. * - * @param valuesOnly Considers only cells with values as used cells. [Parameter available: ExcelApi 1.2] + * @param valuesOnly Considers only cells with values as used cells. [Api set: ExcelApi 1.2] * * [Api set: ExcelApi 1.1] */ getUsedRange(valuesOnly?: boolean): Excel.Range; + /** + * + * Represents the visible rows of the current range. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getVisibleView(): Excel.RangeView; /** * * Inserts a cell or a range of cells into the worksheet in place of this range, and shifts the other cells to make space. Returns a new Range object at the now blank space. @@ -2207,6 +2681,129 @@ declare namespace Excel { interface RangeReference { address: string; } + /** + * + * RangeView represents a set of visible cells of the parent range. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + class RangeView extends OfficeExtension.ClientObject { + private m_columnCount; + private m_formulas; + private m_formulasLocal; + private m_formulasR1C1; + private m_numberFormat; + private m_rowCount; + private m_rows; + private m_text; + private m_valueTypes; + private m_values; + /** + * + * Represents a collection of range views associated with the range. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + rows: Excel.RangeViewCollection; + /** + * + * Returns the number of visible columns. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + columnCount: number; + /** + * + * Represents the formula in A1-style notation. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + formulas: Array>; + /** + * + * Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + formulasLocal: Array>; + /** + * + * Represents the formula in R1C1-style notation. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + formulasR1C1: Array>; + /** + * + * Represents Excel's number format code for the given cell. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + numberFormat: Array>; + /** + * + * Returns the number of visible rows. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + rowCount: number; + /** + * + * Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + text: Array>; + /** + * + * Represents the type of data of each cell. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + valueTypes: Array>; + /** + * + * Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + values: Array>; + /** + * + * Gets the parent range associated with the current RangeView. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getRange(): Excel.Range; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeView; + } + /** + * + * Represents a collection of worksheet objects that are part of the workbook. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + class RangeViewCollection extends OfficeExtension.ClientObject { + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Gets a RangeView Row via it's index. Zero-Indexed. + * + * @param index Index of the visible row. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItem(index: number): Excel.RangeView; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeViewCollection; + } /** * * A collection of all the nameditem objects that are part of the workbook. @@ -2226,6 +2823,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItem(name: string): Excel.NamedItem; + /** + * + * Gets a nameditem object using its name. If the nameditem object does not exist, the returned object's isNull property will be true. + * + * @param name nameditem name. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(name: string): Excel.NamedItem; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -2292,6 +2898,8 @@ declare namespace Excel { class Binding extends OfficeExtension.ClientObject { private m_id; private m_type; + private m_dataChanged; + private m_selectionChanged; /** * * Represents binding identifier. Read-only. @@ -2331,6 +2939,20 @@ declare namespace Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Binding; + /** + * + * Occurs when data within the binding is changed. + * + * [Api set: ExcelApi 1.2] + */ + onDataChanged: OfficeExtension.EventHandlers; + /** + * + * Occurs when the selection is changed within the binding. + * + * [Api set: ExcelApi 1.2] + */ + onSelectionChanged: OfficeExtension.EventHandlers; } /** * @@ -2350,6 +2972,38 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ count: number; + /** + * + * Add a new binding to a particular Range. + * + * @param range Range to bind the binding to. May be an Excel Range object, or a string. If string, must contain the full address, including the sheet name + * @param bindingType Type of binding. See Excel.BindingType. + * @param id Name of binding. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + add(range: Excel.Range | string, bindingType: string, id: string): Excel.Binding; + /** + * + * Add a new binding based on a named item in the workbook. + * + * @param name Name from which to create binding. + * @param bindingType Type of binding. See Excel.BindingType. + * @param id Name of binding. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + addFromNamedItem(name: string, bindingType: string, id: string): Excel.Binding; + /** + * + * Add a new binding based on the current selection. + * + * @param bindingType Type of binding. See Excel.BindingType. + * @param id Name of binding. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + addFromSelection(bindingType: string, id: string): Excel.Binding; /** * * Gets a binding object by ID. @@ -2368,6 +3022,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.Binding; + /** + * + * Gets a binding object by ID. If the binding object does not exist, the return object's isNull property will be true. + * + * @param id Id of the binding object to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(id: string): Excel.Binding; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -2419,6 +3082,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.Table; + /** + * + * Gets a table by Name or ID. If the table does not exist, the return object's isNull property will be true. + * + * @param key Name or ID of the table to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(key: number | string): Excel.Table; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -2432,9 +3104,14 @@ declare namespace Excel { */ class Table extends OfficeExtension.ClientObject { private m_columns; + private m_highlightFirstColumn; + private m_highlightLastColumn; private m_id; private m_name; private m_rows; + private m_showBandedColumns; + private m_showBandedRows; + private m_showFilterButton; private m_showHeaders; private m_showTotals; private m_sort; @@ -2468,6 +3145,20 @@ declare namespace Excel { * [Api set: ExcelApi 1.2] */ worksheet: Excel.Worksheet; + /** + * + * Indicates whether the first column contains special formatting. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + highlightFirstColumn: boolean; + /** + * + * Indicates whether the last column contains special formatting. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + highlightLastColumn: boolean; /** * * Returns a value that uniquely identifies the table in a given workbook. The value of the identifier remains the same even when the table is renamed. Read-only. @@ -2482,6 +3173,27 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ name: string; + /** + * + * Indicates whether the columns show banded formatting in which odd columns are highlighted differently from even ones to make reading the table easier. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + showBandedColumns: boolean; + /** + * + * Indicates whether the rows show banded formatting in which odd rows are highlighted differently from even ones to make reading the table easier. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + showBandedRows: boolean; + /** + * + * Indicates whether the filter buttons are visible at the top of each column header. Setting this is only allowed if the table contains a header row. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + showFilterButton: boolean; /** * * Indicates whether the header row is visible or not. This value can be set to show or remove the header row. @@ -2610,6 +3322,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.TableColumn; + /** + * + * Gets a column object by Name or ID. If the column does not exist, the returned object's isNull property will be true. + * + * @param key Column Name or ID. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(key: number | string): Excel.TableColumn; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -3131,6 +3852,16 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.Chart; + /** + * + * Gets a chart using its name. If there are multiple charts with the same name, the first one will be returned. + If the chart does not exist, the returned object's isNull property will be true. + * + * @param name Name of the chart to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(name: string): Excel.Chart; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4380,7 +5111,7 @@ declare namespace Excel { * * The first criterion used to filter data. Used as an operator in the case of "custom" filtering. For example ">50" for number greater than 50 or "=*s" for values ending in "s". - + Used as a number in the case of top/bottom items/percents. E.g. "5" for the top 5 items if filterOn is set to "topItems" * * [Api set: ExcelApi 1.2] @@ -4473,10 +5204,85 @@ declare namespace Excel { */ set: string; } + /** + * + * Represents a collection of all the PivotTables that are part of the workbook or worksheet. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + class PivotTableCollection extends OfficeExtension.ClientObject { + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Gets a PivotTable by name. + * + * @param name Name of the PivotTable to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItem(name: string): Excel.PivotTable; + /** + * + * Gets a PivotTable by name. If the PivotTable does not exist, the return object's isNull property will be true. + * + * @param name Name of the PivotTable to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(name: string): Excel.PivotTable; + /** + * + * Refreshes all the PivotTables in the collection. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + refreshAll(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.PivotTableCollection; + } + /** + * + * Represents an Excel PivotTable. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + class PivotTable extends OfficeExtension.ClientObject { + private m_name; + private m_worksheet; + /** + * + * The worksheet containing the current PivotTable. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + worksheet: Excel.Worksheet; + /** + * + * Name of the PivotTable. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + name: string; + /** + * + * Refreshes the PivotTable. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + refresh(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.PivotTable; + } /** * [Api set: ExcelApi 1.1] */ - namespace BindingType { + module BindingType { var range: string; var table: string; var text: string; @@ -4484,7 +5290,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace BorderIndex { + module BorderIndex { var edgeTop: string; var edgeBottom: string; var edgeLeft: string; @@ -4497,7 +5303,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace BorderLineStyle { + module BorderLineStyle { var none: string; var continuous: string; var dash: string; @@ -4510,7 +5316,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace BorderWeight { + module BorderWeight { var hairline: string; var thin: string; var medium: string; @@ -4519,7 +5325,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace CalculationMode { + module CalculationMode { var automatic: string; var automaticExceptTables: string; var manual: string; @@ -4527,7 +5333,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace CalculationType { + module CalculationType { var recalculate: string; var full: string; var fullRebuild: string; @@ -4535,7 +5341,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ClearApplyTo { + module ClearApplyTo { var all: string; var formats: string; var contents: string; @@ -4543,7 +5349,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ChartDataLabelPosition { + module ChartDataLabelPosition { var invalid: string; var none: string; var center: string; @@ -4560,7 +5366,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ChartLegendPosition { + module ChartLegendPosition { var invalid: string; var top: string; var bottom: string; @@ -4570,9 +5376,17 @@ declare namespace Excel { var custom: string; } /** + * + * Specifies whether the series are by rows or by columns. On Desktop, the "auto" option will inspect the source data shape to automatically guess whether the data is by rows or columns; on Excel Online, "auto" will simply default to "columns". + * * [Api set: ExcelApi 1.1] */ - namespace ChartSeriesBy { + module ChartSeriesBy { + /** + * + * On Desktop, the "auto" option will inspect the source data shape to automatically guess whether the data is by rows or columns; on Excel Online, "auto" will simply default to "columns". + * + */ var auto: string; var columns: string; var rows: string; @@ -4580,7 +5394,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ChartType { + module ChartType { var invalid: string; var columnClustered: string; var columnStacked: string; @@ -4659,21 +5473,21 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ChartUnderlineStyle { + module ChartUnderlineStyle { var none: string; var single: string; } /** * [Api set: ExcelApi 1.1] */ - namespace DeleteShiftDirection { + module DeleteShiftDirection { var up: string; var left: string; } /** * [Api set: ExcelApi 1.2] */ - namespace DynamicFilterCriteria { + module DynamicFilterCriteria { var unknown: string; var aboveAverage: string; var allDatesInPeriodApril: string; @@ -4713,7 +5527,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace FilterDatetimeSpecificity { + module FilterDatetimeSpecificity { var year: string; var month: string; var day: string; @@ -4724,7 +5538,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace FilterOn { + module FilterOn { var bottomItems: string; var bottomPercent: string; var cellColor: string; @@ -4739,14 +5553,14 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace FilterOperator { + module FilterOperator { var and: string; var or: string; } /** * [Api set: ExcelApi 1.1] */ - namespace HorizontalAlignment { + module HorizontalAlignment { var general: string; var left: string; var center: string; @@ -4759,7 +5573,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace IconSet { + module IconSet { var invalid: string; var threeArrows: string; var threeArrowsGray: string; @@ -4785,7 +5599,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace ImageFittingMode { + module ImageFittingMode { var fit: string; var fitAndCenter: string; var fill: string; @@ -4793,14 +5607,14 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace InsertShiftDirection { + module InsertShiftDirection { var down: string; var right: string; } /** * [Api set: ExcelApi 1.1] */ - namespace NamedItemType { + module NamedItemType { var string: string; var integer: string; var double: string; @@ -4810,7 +5624,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace RangeUnderlineStyle { + module RangeUnderlineStyle { var none: string; var single: string; var double: string; @@ -4820,7 +5634,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace SheetVisibility { + module SheetVisibility { var visible: string; var hidden: string; var veryHidden: string; @@ -4828,7 +5642,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace RangeValueType { + module RangeValueType { var unknown: string; var empty: string; var string: string; @@ -4840,14 +5654,14 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace SortOrientation { + module SortOrientation { var rows: string; var columns: string; } /** * [Api set: ExcelApi 1.2] */ - namespace SortOn { + module SortOn { var value: string; var cellColor: string; var fontColor: string; @@ -4856,21 +5670,21 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace SortDataOption { + module SortDataOption { var normal: string; var textAsNumber: string; } /** * [Api set: ExcelApi 1.2] */ - namespace SortMethod { + module SortMethod { var pinYin: string; var strokeCount: string; } /** * [Api set: ExcelApi 1.1] */ - namespace VerticalAlignment { + module VerticalAlignment { var top: string; var center: string; var bottom: string; @@ -8229,6 +9043,57 @@ declare namespace Excel { * [Api set: ExcelApi 1.2] */ tbillYield(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pr: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the left-tailed Student's t-distribution. + * + * @param x Is the numeric value at which to evaluate the distribution. + * @param degFreedom Is an integer indicating the number of degrees of freedom that characterize the distribution. + * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE. + * + * [Api set: ExcelApi 1.2] + */ + t_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the two-tailed Student's t-distribution. + * + * @param x Is the numeric value at which to evaluate the distribution. + * @param degFreedom Is an integer indicating the number of degrees of freedom that characterize the distribution. + * + * [Api set: ExcelApi 1.2] + */ + t_Dist_2T(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the right-tailed Student's t-distribution. + * + * @param x Is the numeric value at which to evaluate the distribution. + * @param degFreedom Is an integer indicating the number of degrees of freedom that characterize the distribution. + * + * [Api set: ExcelApi 1.2] + */ + t_Dist_RT(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the left-tailed inverse of the Student's t-distribution. + * + * @param probability Is the probability associated with the two-tailed Student's t-distribution, a number between 0 and 1 inclusive. + * @param degFreedom Is a positive integer indicating the number of degrees of freedom to characterize the distribution. + * + * [Api set: ExcelApi 1.2] + */ + t_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the two-tailed inverse of the Student's t-distribution. + * + * @param probability Is the probability associated with the two-tailed Student's t-distribution, a number between 0 and 1 inclusive. + * @param degFreedom Is a positive integer indicating the number of degrees of freedom to characterize the distribution. + * + * [Api set: ExcelApi 1.2] + */ + t_Inv_2T(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the tangent of an angle. @@ -8598,7 +9463,7 @@ declare namespace Excel { */ z_Test(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, sigma?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; } - namespace ErrorCodes { + module ErrorCodes { var accessDenied: string; var generalException: string; var insertDeleteConflict: string; @@ -8613,7 +9478,7 @@ declare namespace Excel { var unsupportedOperation: string; } } -declare namespace Excel { +declare module Excel { /** * The RequestContext object facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the request context is required to get access to the Excel object model from the add-in. */ @@ -8646,10 +9511,6 @@ declare namespace Word { * [Api set: WordApiDesktop 1.3 Beta] */ createDocument(base64File?: string): Word.Document; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Create a new instance of Word.Application object */ @@ -8751,13 +9612,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ type: string; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the body object. The user can perform the undo operation on the cleared content. @@ -8905,16 +9759,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ select(selectionMode?: string): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Body; - _initReferenceId(value: string): void; } /** * @@ -9100,13 +9948,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ type: string; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the content control. The user can perform the undo operation on the cleared content. @@ -9278,16 +10119,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ split(delimiters: Array, multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ContentControl; - _initReferenceId(value: string): void; } /** * @@ -9308,13 +10143,6 @@ declare namespace Word { first: Word.ContentControl; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Gets a content control by its identifier. @@ -9360,16 +10188,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ getItem(index: number): Word.ContentControl; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ContentControlCollection; - _initReferenceId(value: string): void; } /** * @@ -9411,13 +10233,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ saved: boolean; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Gets the current selection of the document. Multiple selections are not supported. @@ -9439,20 +10254,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ save(): void; - _GetObjectByReferenceId(referenceId: string): OfficeExtension.ClientResult; - _GetObjectTypeNameByReferenceId(referenceId: string): OfficeExtension.ClientResult; - _KeepReference(): void; - _RemoveAllReferences(): void; - _RemoveReference(referenceId: string): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Document; - _initReferenceId(value: string): void; } /** * @@ -9550,23 +10355,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ underline: string; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Font; - _initReferenceId(value: string): void; } /** * @@ -9673,20 +10465,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ width: number; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Deletes the inline picture from the document. @@ -9796,16 +10574,10 @@ declare namespace Word { * [Api set: WordApi 1.2] */ select(selectionMode?: string): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.InlinePicture; - _initReferenceId(value: string): void; } /** * @@ -9826,32 +10598,10 @@ declare namespace Word { first: Word.InlinePicture; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets an inline picture object by its index in the collection. - * - * @param index A number that identifies the index location of an inline picture object. - * - * [Api set: WordApi 1.1] - */ - _GetItem(index: number): Word.InlinePicture; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.InlinePictureCollection; - _initReferenceId(value: string): void; } /** * @@ -9877,7 +10627,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ id: number; - _ReferenceId: string; /** * * Gets the paragraphs in the list. @@ -9897,16 +10646,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.List; - _initReferenceId(value: string): void; } /** * @@ -9927,7 +10670,6 @@ declare namespace Word { first: Word.List; /** Gets the loaded child items in this collection. */ items: Array; - _ReferenceId: string; /** * * Gets a list by its identifier. @@ -9937,25 +10679,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ getById(id: number): Word.List; - /** - * - * Gets a list object by its index in the collection. - * - * @param index A number that identifies the index location of a list object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.List; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ListCollection; - _initReferenceId(value: string): void; } /** * @@ -9973,17 +10700,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ levelTypes: Array; - _ReferenceId: string; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ListFormat; - _initReferenceId(value: string): void; } /** * @@ -10009,7 +10729,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ siblingIndex: number; - _ReferenceId: string; /** * * Gets the list item parent, or the closest ancestor if the parent does not exist. @@ -10028,16 +10747,10 @@ declare namespace Word { * [Api set: WordApiDesktop 1.3 Beta] */ getDescendants(directChildrenOnly?: boolean): Word.ParagraphCollection; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ListItem; - _initReferenceId(value: string): void; } /** * @@ -10248,20 +10961,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ text: string; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the paragraph object. The user can perform the undo operation on the cleared content. @@ -10444,16 +11143,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ startNewList(): Word.List; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Paragraph; - _initReferenceId(value: string): void; } /** * @@ -10482,32 +11175,10 @@ declare namespace Word { last: Word.Paragraph; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a paragraph object by its index in the collection. - * - * @param index A number that identifies the index location of a paragraph object. - * - * [Api set: WordApi 1.1] - */ - _GetItem(index: number): Word.Paragraph; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ParagraphCollection; - _initReferenceId(value: string): void; } /** * @@ -10630,20 +11301,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ text: string; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the range object. The user can perform the undo operation on the cleared content. @@ -10864,16 +11521,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ split(delimiters: Array, multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Range; - _initReferenceId(value: string): void; } /** * @@ -10894,32 +11545,10 @@ declare namespace Word { first: Word.Range; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a range object by its index in the collection. - * - * @param index A number that identifies the index location of a range object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.Range; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.RangeCollection; - _initReferenceId(value: string): void; } /** * @@ -10993,10 +11622,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ matchWildcards: boolean; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11025,32 +11650,10 @@ declare namespace Word { first: Word.Range; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a range object by its index in the collection. - * - * @param index A number that identifies the index location of a range object. - * - * [Api set: WordApi 1.1] - */ - _GetItem(index: number): Word.Range; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.SearchResultCollection; - _initReferenceId(value: string): void; } /** * @@ -11077,20 +11680,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ next: Word.Section; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Gets one of the section's footers. @@ -11109,16 +11698,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ getHeader(type: string): Word.Body; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Section; - _initReferenceId(value: string): void; } /** * @@ -11139,32 +11722,10 @@ declare namespace Word { first: Word.Section; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a section object by its index in the collection. - * - * @param index A number that identifies the index location of a section object. - * - * [Api set: WordApi 1.1] - */ - _GetItem(index: number): Word.Section; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.SectionCollection; - _initReferenceId(value: string): void; } /** * @@ -11399,20 +11960,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ width: number; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Adds columns to the start or end of the table, using the first or last existing column as a template. This is applicable to uniform tables. The string values, if specified, are set in the newly inserted rows. @@ -11594,16 +12141,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ select(selectionMode?: string): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Table; - _initReferenceId(value: string): void; } /** * @@ -11624,32 +12165,10 @@ declare namespace Word { first: Word.Table; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a table object by its index in the collection. - * - * @param index A number that identifies the index location of a table object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.Table; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableCollection; - _initReferenceId(value: string): void; } /** * @@ -11780,20 +12299,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ verticalAlignment: string; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the row. @@ -11863,16 +12368,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ select(selectionMode?: string): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableRow; - _initReferenceId(value: string): void; } /** * @@ -11893,32 +12392,10 @@ declare namespace Word { first: Word.TableRow; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a table row object by its index in the collection. - * - * @param index A number that identifies the index location of a table row object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.TableRow; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableRowCollection; - _initReferenceId(value: string): void; } /** * @@ -12049,20 +12526,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ width: number; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Deletes the column containing this cell. This is applicable to uniform tables. @@ -12118,16 +12581,10 @@ declare namespace Word { * [Api set: WordApiDesktop 1.3 Beta] */ split(rowCount: number, columnCount: number): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableCell; - _initReferenceId(value: string): void; } /** * @@ -12148,32 +12605,10 @@ declare namespace Word { first: Word.TableCell; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a table cell object by its index in the collection. - * - * @param index A number that identifies the index location of a table cell object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.TableCell; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableCellCollection; - _initReferenceId(value: string): void; } /** * @@ -12207,23 +12642,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ width: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableBorderStyle; - _initReferenceId(value: string): void; } /** * From bf341749b4ebbd7242e452ef720ba2580316cf6c Mon Sep 17 00:00:00 2001 From: Erwin Poeze Date: Tue, 16 Aug 2016 08:38:54 +0200 Subject: [PATCH 07/56] ramda typings --- ramda/ramda-tests.ts | 1952 ++++++++++++++++++++++++++++++++++++++++++ ramda/ramda.d.ts | 1807 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 3759 insertions(+) create mode 100644 ramda/ramda-tests.ts create mode 100644 ramda/ramda.d.ts diff --git a/ramda/ramda-tests.ts b/ramda/ramda-tests.ts new file mode 100644 index 0000000000..15ec5eb274 --- /dev/null +++ b/ramda/ramda-tests.ts @@ -0,0 +1,1952 @@ +import * as R from './ramda'; + +var double = function(x: number): number { + return x + x +}; + +var shout = function(x: number): string { + return x >= 10 + ? 'big' + : 'small' +}; + +class F { + x = 'X'; + y = 'Y'; +} +class F2 { + a = 100; + y = 1; + x(){}; + z() {}; +} + +(() => { + var x: boolean; + x = R.isArrayLike('a'); + x = R.isArrayLike([1,2,3]); + x = R.isArrayLike([]); +}); + +(() => { + R.propIs(Number, 'x', {x: 1, y: 2}); //=> true + R.propIs(Number, 'x')({x: 1, y: 2}); //=> true + R.propIs(Number)('x', {x: 1, y: 2}); //=> true + R.propIs(Number)('x')({x: 1, y: 2}); //=> true + R.propIs(Number, 'x', {x: 'foo'}); //=> false + R.propIs(Number, 'x', {}); //=> false +}); + +(() => { + R.type({}); //=> "Object" + R.type(1); //=> "Number" + R.type(false); //=> "Boolean" + R.type('s'); //=> "String" + R.type(null); //=> "Null" + R.type([]); //=> "Array" + R.type(/[A-z]/); //=> "RegExp" +}); + +() => { + var takesNoArg = function() { return true; }; + var takesOneArg = function(a: number) { return [a]; }; + var takesTwoArgs = function(a: number, b: number) { return [a, b]; }; + var takesThreeArgs = function(a: number, b: number, c: number) { return [a, b, c]; }; + + var addFourNumbers = function(a: number, b: number, c: number, d: number): number { + return a + b + c + d; + }; + + var x1: Function = R.curry(addFourNumbers) + // because of the current way of currying, the following call results in a type error + // var x2: Function = R.curry(addFourNumbers)(1,2,4) + var x3: Function = R.curry(addFourNumbers)(1)(2) + var x4: Function = R.curry(addFourNumbers)(1)(2)(3) + var y1: number = R.curry(addFourNumbers)(1)(2)(3)(4) + var y2: number = R.curry(addFourNumbers)(1,2)(3,4) + var y3: number = R.curry(addFourNumbers)(1,2,3)(4) + + R.nAry(0, takesNoArg); + R.nAry(0, takesOneArg); + R.nAry(1, takesTwoArgs); + R.nAry(1, takesThreeArgs); + + var u1: {(a: any): any} = R.unary(takesOneArg); + var u2: {(a: any): any} = R.unary(takesTwoArgs); + var u3: {(a: any): any} = R.unary(takesThreeArgs); + + R.binary(takesTwoArgs); + R.binary(takesThreeArgs); + + var addTwoNumbers = function(a:number, b:number) { return a + b; } + var addTwoNumbersCurried = R.curry(addTwoNumbers); + + var inc = addTwoNumbersCurried(1); + var z1:number = inc(2); + var z2:number = addTwoNumbersCurried(2,3); +} + +() => { + const addFour = (a:number) => (b:number) => (c:number) => (d:number) => a + b + c + d; + const uncurriedAddFour = R.uncurryN(4, addFour); + const res: number = uncurriedAddFour(1, 2, 3, 4); //=> 10 +} + +() => { + // coerceArray :: (a|[a]) -> [a] + const coerceArray = R.unless(R.isArrayLike, R.of); + const a: number[] = coerceArray([1, 2, 3]); //=> [1, 2, 3] + const b: number[] = coerceArray(1); //=> [1] +} + +(() => { + R.nthArg(1)('a', 'b', 'c'); //=> 'b' + R.nthArg(-1)('a', 'b', 'c'); //=> 'c' +}); + +() => { + const fn: (...args: string[])=>string = R.unapply(JSON.stringify); + const res: string = R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]' +} + +() => { + const a: number = R.until(R.flip(R.gt)(100), R.multiply(2))(1) // => 128 +} + +() => { + const truncate = R.when( + R.propSatisfies(R.flip(R.gt)(10), 'length'), + R.pipe(R.take(10), R.append('…'), R.join('')) + ); + const a: string = truncate('12345'); //=> '12345' + const b: string = truncate('0123456789ABC'); //=> '0123456789…' +} + +/* compose */ +() => { + var double = function(x: number): number { + return x + x + } + var limit10 = function(x: number): boolean { + return x >= 10 + } + var func: (x: number) => boolean = R.compose(limit10, double) + var res: boolean = R.compose(limit10, double)(10) + + const f0 = (s: string) => +s; // string -> number + const f1 = (n: number) => n === 1; // number -> boolean + const f2 = R.compose(f1, f0); // string -> boolean + + // akward example that bounces types between number and string + const g0 = (list: number[]) => R.map(R.inc, list); + const g1 = R.dropWhile(R.gt(10)); + const g2 = R.map((i: number) => i > 5 ? 'bigger' : 'smaller'); + const g3 = R.all((i: string) => i === 'smaller'); + const g = R.compose(g3, g2, g1, g0); + const g_res: boolean = g([1, 2, 10, 13]); +} + +/* pipe */ +() => { + var func: (x: number) => string = R.pipe(double, double, shout) + var res: string = R.pipe(double, double, shout)(10); + + const capitalize = (str: string) => R.pipe( + R.split(''), + R.adjust(R.toUpper, 0), + R.join('') + )(str); + + var f = R.pipe(Math.pow, R.negate, R.inc); + var fr: number = f(3, 4); // -(3^4) + 1 +} + +() => { + R.invoker('charAt', String.prototype); + R.invoker('charAt', String.prototype, 1); +} + +(() => { + const range = R.juxt([Math.min, Math.max]); + range(3, 4, 9, -3); //=> [-3, 9] + + const chopped = R.juxt([R.head, R.last]); + chopped('longstring'); // => ["l", "g"] +}); + +var square = function(x: number) { return x * x; }; +var add = function(a: number, b: number) { return a + b; }; +// Adds any number of arguments together +var addAll = function() { + return 0; +}; + +// Basic example +R.useWith(addAll, [ double, square ]); + +(() => { + var printXPlusFive = function(x: number) { console.log(x + 5); }; + R.forEach(printXPlusFive, [1, 2, 3]); + R.clone([{},{},{}]) + R.clone([1,2,3]); +})(); + +// (() => { +// var printXPlusFive = function(x, i) { console.log(i + 5); }; +// R.forEach.idx(printXPlusFive, [{name: 1}, {name: 2}, {name: 3}]); +// })(); + +var i = function(x: number) {return x;}; +R.times(i, 5); + +(() => { + var triple = function(x: number): number { return x * 3; }; + var square = function(x: number): number { return x * x; }; + var squareThenDoubleThenTriple = R.pipe(square, double, triple); + squareThenDoubleThenTriple(5); //=> 150 + + +})(); + +(() => { + var multiply = function(a: number, b: number) { return a * b; }; + var double = R.partial(multiply, 2); + double(2); //=> 4 + + var greet = function(salutation: string, title: string, firstName: string, lastName: string) { + return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; + }; + var sayHello = R.partial(greet, 'Hello'); + var sayHelloToMs = R.partial(sayHello, 'Ms.'); + sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' + + var greetMsJaneJones = R.partialRight(greet, 'Ms.', 'Jane', 'Jones'); + greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' +})(); + +(() => { + var numberOfCalls = 0; + var trackedAdd = function(a: number, b: number) { + numberOfCalls += 1; + return a + b; + }; + var memoTrackedAdd = R.memoize(trackedAdd); + + memoTrackedAdd(1, 2); //=> 3 + numberOfCalls; //=> 1 + memoTrackedAdd(1, 2); //=> 3 + numberOfCalls; //=> 1 + memoTrackedAdd(2, 3); //=> 5 + numberOfCalls; //=> 2 + + // Note that argument order matters + memoTrackedAdd(2, 1); //=> 3 + numberOfCalls; //=> 3 +})(); + +(() => { + var addOneOnce = R.once(function(x: number){ return x + 1; }); + addOneOnce(10); //=> 11 + addOneOnce(addOneOnce(50)); //=> 11 +})(); + +(() => { + var slashify = R.wrap(R.flip(R.add)('/'), function(f: Function, x: string) { + return R.match(/\/$/, x) ? x : f(x); + }); + + slashify('a'); //=> 'a/' + slashify('a/'); //=> 'a/' +})(); + + + +(() => { + var numbers = [1, 2, 3]; + var add = function(a: number, b: number) { + return a + b + }; + R.reduce(add, 10, numbers); //=> 16; +})(); + +(() => { + var plus3 = R.add(3); +})(); + +(() => { + var pairs = [ ['a', 1], ['b', 2], ['c', 3] ]; + var flattenPairs = function(acc: [string, number], pair: [string, number]) { + return acc.concat(pair); + }; + R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] +})(); + +(() => { + var values = { x: 1, y: 2, z: 3 }; + var prependKeyAndDouble = function(num: number, key: string, obj: any) { + return key + (num * 2); + }; + R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' } +}); + +(() => { + const a: number[] = R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + const b: number[][] = R.of([1]); //=> [[1]] + const c: number[] = R.of(1); + +}); + +() => { + const a1 = R.empty([1,2,3,4,5]); //=> [] + const a2 = R.empty([1, 2, 3]); //=> [] + const a3 = R.empty('unicorns'); //=> '' + const a4 = R.empty({x: 1, y: 2}); //=> {} +} + +(() => { + R.length([1, 2, 3]); //=> 3 +}); + +(() => { + const isEven = function(n: number) { + return n % 2 === 0; + }; + const filterIndexed = R.addIndex(R.filter); + + R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + + var lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] + + var isOdd = function(n: number) { + return n % 2 === 1; + }; + R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] +}); +(() => { + var isNotFour = function(x: number) { + return !(x === 4); + }; + R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] + R.take(2, [1, 2, 3, 4]); //=> [1, 2] +}); +(() => { + var f = function(n: number) { return n > 50 ? false : [-n, n + 10] }; + let a = R.unfold(f, 10); //=> [-10, -20, -30, -40, -50] + let b = R.unfold(f); //=> [-10, -20, -30, -40, -50] + let c = b(10); +}); +/***************************************************************** + * Function category + */ + + + () => { + var mergeThree = function(a: number, b: number, c: number): number[] { + return ([]).concat(a, b, c); + }; + mergeThree(1, 2, 3); //=> [1, 2, 3] + var flipped = R.flip(mergeThree); + flipped(1, 2, 3); //=> [2, 1, 3] + } + +/********************* + * List category + ********************/ +() => { + var lessThan2 = R.flip(R.lt)(2); + var lessThan3 = R.flip(R.lt)(3); + R.all(lessThan2)([1, 2]); //=> false + R.all(lessThan3)([1, 2]); //=> true +} + +() => { + var lessThan0 = R.flip(R.lt)(0); + var lessThan2 = R.flip(R.lt)(2); + R.any(lessThan0)([1, 2]); //=> false + R.any(lessThan2)([1, 2]); //=> true +} + +() => { + R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]] + R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + R.aperture(7, [1, 2, 3, 4, 5]); //=> [] + R.aperture(7)([1, 2, 3, 4, 5]); //=> [] +} + +() => { + R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] + R.append('tests')(['write', 'more']); //=> ['write', 'more', 'tests'] + R.append('tests', []); //=> ['tests'] + R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'])(['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'])(['write', 'more']); //=> ['write', 'more', ['tests']] +} + +() => { + var duplicate = function(n: number) { + return [n, n]; + }; + R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] + R.chain(duplicate)([1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] +} + +() => { + R.clamp(1, 10, -1) // => 1 + R.clamp(1, 10)(11) // => 10 + R.clamp(1)(10, 4) // => 4 + R.clamp('a', 'd', 'e') // => 'd' +} + +() => { + R.concat([], []); //=> [] + R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + R.concat([4, 5, 6])([1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + R.concat('ABC')('DEF'); // 'ABCDEF' +} + +() => { + R.contains(3)([1, 2, 3]); //=> true + R.contains(3, [1, 2, 3]); //=> true + R.contains(4)([1, 2, 3]); //=> false + R.contains({})([{}, {}]); //=> false + var obj = {}; + R.contains(obj)([{}, obj, {}]); //=> true +} + +() => { + R.drop(3, [1,2,3,4,5,6,7]); //=> [4,5,6,7] + R.drop(3)([1,2,3,4,5,6,7]); //=> [4,5,6,7] + R.drop(3, 'ramda'); //=> 'ram' + R.drop(3)('ramda'); //=> 'ram' +} + +(() => { + R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] + R.dropLast(2)(['foo', 'bar', 'baz']); //=> ['foo'] + R.dropLast(3, 'ramda'); //=> 'ra' + R.dropLast(3)('ramda'); //=> 'ra' +}); + +(() => { + var lteThree = (x: number) => x <= 3; + R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4] +}); + +() => { + var lteTwo = function(x: number) { + return x <= 2; + }; + R.dropWhile(lteTwo, [1, 2, 3, 4]); //=> [3, 4] + R.dropWhile(lteTwo)([1, 2, 3, 4]); //=> [3, 4] +} + +() => { + var isEven = function(n: number) { + return n % 2 === 0; + }; + R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + var isEvenFn = R.filter(isEven); + isEvenFn([1, 2, 3, 4]); +} + +() => { + var lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + var filterIndexed = R.addIndex(R.filter); + + filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] + var lastTwoFn = filterIndexed(lastTwo); + lastTwoFn([8, 6, 7, 5, 3, 0, 9]); +} + +() => { + var xs = [{a: 1}, {a: 2}, {a: 3}]; + R.find(R.propEq('a', 2))(xs); //=> {a: 2} + R.find(R.propEq('a', 4))(xs); //=> undefined +} + +() => { + var xs = [{a: 1}, {a: 2}, {a: 3}]; + R.findIndex(R.propEq('a', 2))(xs); //=> 1 + R.findIndex(R.propEq('a', 4))(xs); //=> -1 + + R.findIndex((x: number) => x === 1, [1, 2, 3]); +} + +() => { + var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} + R.findLast(R.propEq('a', 4))(xs); //=> undefined +} + +() => { + var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 + R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 + R.findLastIndex((x: number) => x === 1, [1, 2, 3]); +} +() => { + var user1 = { address: { zipCode: 90210 } }; + var user2 = { address: { zipCode: 55555 } }; + var user3 = { name: 'Bob' }; + var users = [ user1, user2, user3 ]; + var isFamous = R.pathEq(['address', 'zipCode'], 90210); + R.filter(isFamous, users); //=> [ user1 ] +} +() => { + var xs: {[key:string]: string} = {a: '1', b: '0'}; + R.propEq('a', '1', xs);//=> true + R.propEq('a', '4', xs); //=> false +} +() => { + var xs: {[key:string]: number} = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} +() => { + var xs = {a: '1', b: '0'}; + R.propEq('a', '1', xs);//=> true + R.propEq('a', '4', xs); //=> false +} +() => { + var xs = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} + +interface Obj { a: number; b: number }; +() => { + var xs: Obj = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} + +() => { + R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); + //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] +} + +() => { + var printXPlusFive = function(x: number) { console.log(x + 5); }; + R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] + R.forEach(printXPlusFive)([1, 2, 3]); //=> [1, 2, 3] + //-> 6 + //-> 7 + //-> 8 +} + +() => { + var plusFive = function(num: number, idx: number, list: number[]) { list[idx] = num + 5 }; + R.addIndex(R.forEach)(plusFive)([1, 2, 3]); //=> [6, 7, 8] +} + +() => { + var byGrade = R.groupBy(function(student: {score: number; name: string}) { + var score = student.score; + return score < 65 ? 'F' : + score < 70 ? 'D' : + score < 80 ? 'C' : + score < 90 ? 'B' : 'A'; + }); + var students = [{name: 'Abby', score: 84}, + {name: 'Eddy', score: 58}, + {name: 'Jack', score: 69}]; + byGrade(students); +} + +() => { + R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + // [[0], [1, 1], [2, 3, 5, 8, 13, 21]] + + R.groupWith((a: number, b: number) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + // [[0], [1, 1], [2], [3, 5], [8], [13, 21]] + + const isVowel = (a: string) => R.contains(a, 'aeiou') ? a : ''; + R.groupWith(R.eqBy(isVowel), 'aestiou') + // ['ae', 'st', 'iou'] +} + +() => { + R.head(['fi', 'fo', 'fum']); //=> 'fi' + R.head([10, 'ten']); // => 10 + R.head(['10', 10]); // => '10' +} + +(() => { + let list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}]; + const a1 = R.indexBy(R.prop('id'), list); + const a2 = R.indexBy(R.prop('id'))(list); + const a3 = R.indexBy<{id:string}>(R.prop('id'))(list); +}); + +() => { + R.indexOf(3, [1,2,3,4]); //=> 2 + R.indexOf(10)([1,2,3,4]); //=> -1 +} + +() => { + R.init(['fi', 'fo', 'fum']); //=> ['fi', 'fo'] +} + +() => { + R.insert(2, 5, [1,2,3,4]); //=> [1,2,5,3,4] + R.insert(2)(5, [1,2,3,4]); //=> [1,2,5,3,4] + R.insert(2, 5)([1,2,3,4]); //=> [1,2,5,3,4] +} + +() => { + R.insertAll(2, [10,11,12], [1,2,3,4]); + R.insertAll(2)([10,11,12], [1,2,3,4]); + R.insertAll(2, [10,11,12])([1,2,3,4]); +} + +() => { + var numbers = [1, 2, 3, 4]; + var transducer = R.compose(R.map(R.add(1)), R.take(2)); + + R.into([], transducer, numbers); //=> [2, 3] + + var intoArray = R.into([]); + intoArray(transducer, numbers); //=> [2, 3] +} + +() => { + var spacer = R.join(' '); + spacer(['a', 2, 3.4]); //=> 'a 2 3.4' + R.join('|', [1, 2, 3]); //=> '1|2|3' +} + +() => { + R.last(['fi', 'fo', 'fum']); //=> 'fum' +} + +() => { + R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 + R.lastIndexOf(10, [1,2,3,4]); //=> -1 +} + +() => { + R.length([]); //=> 0 + R.length([1, 2, 3]); //=> 3 +} + +() => { + var headLens = R.lensIndex(0); + headLens([10, 20, 30, 40]); //=> 10 + headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40] + R.view(headLens, ['a', 'b', 'c']); //=> 'a' + R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] +} + +() => { + var double = function(x: number) { + return x * 2; + }; + R.map(double, [1, 2, 3]); //=> [2, 4, 6] + + // functor + const stringFunctor = { + map: (fn: (c: number) => number) => { + var chars = "Ifmmp!Xpsme".split(""); + return chars.map((char) => String.fromCharCode(fn(char.charCodeAt(0)))).join(""); + } + }; + R.map((x: number) => x-1, stringFunctor); // => "Hello World" +} + +() => { + var digits = ['1', '2', '3', '4']; + var append = function(a: string, b: string): [string, string]{ + return [a + b, a + b]; + } + R.mapAccum(append, '0', digits); //=> ['01234', ['01', '012', '0123', '01234']] + R.mapAccum(append)('0', digits); //=> ['01234', ['01', '012', '0123', '01234']] + R.mapAccum(append, '0')(digits); //=> ['01234', ['01', '012', '0123', '01234']] +} + +() => { + var digits = ['1', '2', '3', '4']; + var append = function(a: string, b: string): [string, string] { + return [a + b, a + b]; + } + + R.mapAccumRight(append, '0', digits); //=> ['04321', ['04321', '0432', '043', '04']] + R.mapAccumRight(append)('0', digits); //=> ['04321', ['04321', '0432', '043', '04']] + R.mapAccumRight(append, '0')(digits); //=> ['04321', ['04321', '0432', '043', '04']] +} + +() => { + var squareEnds = function(elt: number, idx: number, list: number[]) { + if (idx === 0 || idx === list.length - 1) { + return elt * elt; + } + return elt; + }; + R.addIndex(R.map)(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] + R.addIndex(R.map)(squareEnds)([8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] +} + +() => { + R.none(R.isNaN, [1, 2, 3]); //=> true + R.none(R.isNaN, [1, 2, 3, NaN]); //=> false + R.none(R.isNaN)([1, 2, 3, NaN]); //=> false +} + +() => { + var list = ['foo', 'bar', 'baz', 'quux']; + R.nth(1, list); //=> 'bar' + R.nth(-1, list); //=> 'quux' + R.nth(-99, list); //=> undefined + R.nth(-99)(list); //=> undefined +} + +() => { + R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']); + R.partition(R.contains('s'))(['sss', 'ttt', 'foo', 'bars']); + R.partition((x: number) => x > 2, [1, 2, 3, 4]); + R.partition((x: number) => x > 2)([1, 2, 3, 4]); +} + +() => { + const a = R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2] + const b = R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3] +} + +() => { + R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] + R.prepend('fee')(['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] +} + +() => { + R.range(1, 5); //=> [1, 2, 3, 4] + R.range(50)(53); //=> [50, 51, 52] +} + +() => { + var numbers = [1, 2, 3]; + var add = function(a: number, b: number) { + return a + b; + }; + R.reduce(add, 10, numbers); //=> 16 + R.reduce(add)(10, numbers); //=> 16 + R.reduce(add, 10)(numbers); //=> 16 +} + +interface Student { + name: string; + score: number; +} +() => { + const reduceToNamesBy = R.reduceBy((acc: string[], student: Student) => acc.concat(student.name), []); + const namesByGrade = reduceToNamesBy(function(student) { + let score = student.score; + return score < 65 ? 'F' : + score < 70 ? 'D' : + score < 80 ? 'C' : + score < 90 ? 'B' : 'A'; + }); + let students = [{name: 'Lucy', score: 92}, + {name: 'Drew', score: 85}, + {name: 'Bart', score: 62}]; + const names = namesByGrade(students); + // { + // 'A': ['Lucy'], + // 'B': ['Drew'] + // 'F': ['Bart'] + // } +} + +() => { + var reduceIndexed = R.addIndex(R.reduce); + var letters = ['a', 'b', 'c']; + var objectify = function(accObject: {[elem:string]: number}, elem: string, idx: number, list: string[]) { + accObject[elem] = idx; + return accObject; + }; + reduceIndexed(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } + reduceIndexed(objectify)({}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } + reduceIndexed(objectify, {})(letters); //=> { 'a': 0, 'b': 1, 'c': 2 } +} + +interface KeyValuePair extends Array { 0 : K; 1 : V; } +type Pair = KeyValuePair +() => { + var pairs: Pair[] = [ ['a', 1], ['b', 2], ['c', 3] ]; + var flattenPairs = function(acc: Pair[], pair: Pair): Pair[] { + return acc.concat(pair); + }; + R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + R.reduceRight(flattenPairs, [])(pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + R.reduceRight(flattenPairs)([], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] +} + +() => { + var isOdd = function(n: number) { + return n % 2 === 1; + }; + R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] + R.reject(isOdd)([1, 2, 3, 4]); //=> [2, 4] +} + +() => { + const lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + const rejectIndexed = R.addIndex(R.reject); + rejectIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] + rejectIndexed(lastTwo)([8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] +} + +() => { + R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + R.remove(2, 3)([1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + R.remove(2)(3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] +} + +() => { + R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] + var obj = {}; + var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}] + repeatedObjs[0] === repeatedObjs[1]; //=> true +} + +() => { + R.reverse([1, 2, 3]); //=> [3, 2, 1] + R.reverse([1, 2]); //=> [2, 1] + R.reverse([1]); //=> [1] + R.reverse([]); //=> [] +} + +() => { + var numbers = [1, 2, 3, 4]; + R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24] + R.scan(R.multiply, 1)(numbers); //=> [1, 1, 2, 6, 24] + R.scan(R.multiply)(1, numbers); //=> [1, 1, 2, 6, 24] +} + +() => { + var xs = R.range(0, 10); + R.slice(2, 5, xs); //=> [2, 3, 4] + R.slice(2, 5)(xs); //=> [2, 3, 4] + R.slice(2)(5, xs); //=> [2, 3, 4] + + var str = 'Hello World'; + R.slice(2, 5, str); //=> 'llo' + R.slice(2, 5)(str); //=> 'llo' + R.slice(2)(5, str); //=> 'llo' +} + +() => { + var diff = function(a: number, b: number) { return a - b; }; + R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] + R.sort(diff)([4,2,7,5]); //=> [2, 4, 5, 7] +} + +() => { + const fn = R.cond([ + [R.equals(0), R.always('water freezes at 0°C')], + [R.equals(100), R.always('water boils at 100°C')], + [R.T, (temp: number) => 'nothing special happens at ' + temp + '°C'] + ]); + const a: string = fn(0); //=> 'water freezes at 0°C' + const b: string = fn(50); //=> 'nothing special happens at 50°C' + const c: string = fn(100); //=> 'water boils at 100°C' +} + +() => { + R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum'] + R.tail([1, 2, 3]); //=> [2, 3] +} + +() => { + R.take(3,[1,2,3,4,5]); //=> [1,2,3] + + var members= [ "Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis","Joe Morello","Norman Bates", + "Eugene Wright","Gerry Mulligan","Jack Six","Alan Dawson","Darius Brubeck","Chris Brubeck", + "Dan Brubeck","Bobby Militello","Michael Moore","Randy Jones"]; + var takeFive = R.take(5); + takeFive(members); //=> ["Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis"] +} +() => { + R.take(3,"Example"); //=> "Exa" + + var takeThree = R.take(3); + takeThree("Example"); //=> "Exa" +} + + + +() => { + const a: string[] = R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz'] + const b: string[] = R.takeLast(2)(['foo', 'bar', 'baz']); //=> ['bar', 'baz'] + const c: string = R.takeLast(3, 'ramda'); //=> 'mda' + const d: string = R.takeLast(3)('ramda'); //=> 'mda' +} + +() => { + const isNotOne = (x: number) => x !== 1; + const a: number[] = R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4] + const b: number[] = R.takeLastWhile(isNotOne)([1, 2, 3, 4]); //=> [2, 3, 4] +} + +() => { + var isNotFour = function(x: number) { + return !(x === 4); + }; + + R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] + R.takeWhile(isNotFour)([1, 2, 3, 4]); //=> [1, 2, 3] +} + +() => { + const sayX = (x: number) => console.log('x is ' + x); + const a: number = R.tap(sayX, 100); //=> 100 +} + +() => { + const a: boolean = R.test(/^x/, 'xyz'); //=> true + const b: boolean = R.test(/^y/)('xyz'); //=> false +} + +() => { + const a1 = R.times(R.identity, 5); //=> [0, 1, 2, 3, 4] + const a2 = R.times(R.identity)(5); //=> [0, 1, 2, 3, 4] +} + +() => { + class Point { + constructor(public x: number, public y: number) { + this.x = x; + this.y = y; + } + toStringn() { + return 'new Point(' + this.x + ', ' + this.y + ')'; + } + }; + R.toString(new Point(1, 2)); //=> 'new Point(1, 2)' + + R.toString(42); //=> '42' + R.toString('abc'); //=> '"abc"' + R.toString([1, 2, 3]); //=> '[1, 2, 3]' + R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}' + R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")' +} + +() => { + var numbers = [1, 2, 3, 4]; + var transducer = R.compose(R.map(R.add(1)), R.take(2)); + var fn = R.flip(R.append); + R.transduce(transducer, fn, [], numbers); //=> [2, 3] + R.transduce(transducer, fn, [])(numbers); //=> [2, 3] + R.transduce(transducer, fn)([], numbers); //=> [2, 3] + R.transduce(transducer)(fn, [], numbers); //=> [2, 3] +} + +() => { + const a: any[][] = R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']] + const b: any[][] = R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']] + const c: any[][] = R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]] +} + +() => { + const x = R.prop('x'); + const a: boolean = R.tryCatch(R.prop('x'), R.F, {x: true}); //=> true + const b: boolean = R.tryCatch(R.prop('x'), R.F, null); //=> false +} + +() => { + R.uniq([1, 1, 2, 1]); //=> [1, 2] + R.uniq([{}, {}]); //=> [{}, {}] + R.uniq([1, '1']); //=> [1, '1'] +} + +() => { + var strEq = function(a: any, b: any) { return String(a) === String(b); }; + R.uniqWith(strEq, [1, '1', 2, 1]); //=> [1, 2] + R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2] + R.uniqWith(strEq)([{}, {}]); //=> [{}] + R.uniqWith(strEq)([1, '1', 1]); //=> [1] + R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] +} + +() => { + R.equals(R.unnest([1, [2], [[3]]]), [1,2,[3]]); //=> true + R.equals(R.unnest([[1, 2], [3, 4], [5, 6]]),[1,2,3,4,5,6]); //=> true +} + +() => { + R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] + R.xprod([1, 2])(['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] +} + +() => { + R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] + R.zip([1, 2, 3])(['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] +} + +() => { + R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} + R.zipObj(['a', 'b', 'c'])([1, 2, 3]); //=> {a: 1, b: 2, c: 3} +} + +() => { + var f = function(x:number, y:string) { + // ... + }; + R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + R.zipWith(f)([1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + R.zipWith(f, [1, 2, 3])(['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] +} + +/***************************************************************** + * Object category + */ +() => { + const a = R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + const b = R.assoc('c')(3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + const c = R.assoc('c', 3)({a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} +} + +() => { + const a1 = R.dissoc<{a:number, c:number}>('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + const a2 = R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + const a4 = R.dissoc('b')<{a:number, c:number}>({a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} +} + +() => { + const a = R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + const b = R.assocPath(['a', 'b', 'c'])(42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + const c = R.assocPath(['a', 'b', 'c'], 42)({a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} +} + +() => { + const a1 = R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + // optionally specify return type + const a2 = R.dissocPath<{a :{ b: number}}>(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + const a3 = R.dissocPath(['a', 'b', 'c'])({a: {b: {c: 42}}}); //=> {a: {b: {}}} +} + +() => { + var obj1 = [{}, {}, {}]; + var obj2 = [{a:1}, {a:2}, {a:3}]; + const a1: any[] = R.clone(obj1); + const a2: {a: number}[] = R.clone(obj2); + const a3: any = R.clone({}); + const a4: number = R.clone(10); + const a5: string = R.clone('foo'); + const a6: number = R.clone(Date.now()); +} + +() => { + var o1 = { a: 1, b: 2, c: 3, d: 4 }; + var o2 = { a: 10, b: 20, c: 3, d: 40 }; + const a1 = R.eqProps('a', o1, o2); //=> false + const a2 = R.eqProps('c', o1, o2); //=> true + const a3: {(obj1: T, obj2: U): boolean} = R.eqProps('c'); + const a4: {(obj2: U): boolean} = R.eqProps('c', o1); +} + +() => { + const a1 = R.evolve({ elapsed: R.add(1), remaining: R.add(-1) }, { name: 'Tomato', elapsed: 100, remaining: 1400 }); + const a2 = R.evolve({ elapsed: R.add(1), remaining: R.add(-1) })({ name: 'Tomato', elapsed: 100, remaining: 1400 }); +} + +() => { + // var tomato = {firstName: 'Tomato ', data: {elapsed: 100, remaining: 1400}, id:123}; + // var transformations = { + // firstName: R.trim, + // lastName: R.trim, // Will not get invoked. + // data: {elapsed: R.add(1), remaining: R.add(-1)} + // }; + // const a = R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} + // const b = R.evolve(transformations)(tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} +} + +() => { + const hasName = R.has('name'); + const a1: boolean = hasName({name: 'alice'}); //=> true + const a2: boolean = hasName({name: 'bob'}); //=> true + const a3: boolean = hasName({}); //=> false + + const point = {x: 0, y: 0}; + const pointHas = R.flip(R.has)(point); + const b1: boolean = pointHas('x'); //=> true + const b2: boolean = pointHas('y'); //=> true + const b3: boolean = pointHas('z'); //=> false +} + +class Rectangle { + constructor(public width: number, public height: number) { + this.width = width; + this.height = height; + } + area():number { + return this.width * this.height; + } +}; +() => { + + var square = new Rectangle(2, 2); + R.hasIn('width', square); //=> true + R.hasIn('area', square); //=> true + R.flip(R.hasIn)(square)('area'); //=> true +} + +() => { + var raceResultsByFirstName = { + first: 'alice', + second: 'jake', + third: 'alice', + }; + R.invert(raceResultsByFirstName); + //=> { 'alice': ['first', 'third'], 'jake':['second'] } +} + +() => { + let raceResults0 = { + first: 'alice', + second: 'jake' + }; + R.invertObj(raceResults0); + //=> { 'alice': 'first', 'jake':'second' } + + // Alternatively: + let raceResults1 = ['alice', 'jake']; + R.invertObj(raceResults1); + //=> { 'alice': '0', 'jake':'1' } +} + +() => { + R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] +} + +() => { + var f = new F(); + R.keysIn(f); //=> ['x', 'y'] +} + +() => { + var xLens = R.lens(R.prop('x'), R.assoc('x')); + R.view(xLens, {x: 1, y: 2}); //=> 1 + R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.set(xLens)(4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.set(xLens, 4)({x: 1, y: 2}); //=> {x: 4, y: 2} + R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} + R.over(xLens, R.negate)({x: 1, y: 2}); //=> {x: -1, y: 2} + R.over(xLens)(R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} +} +() => { + var headLens = R.lensIndex(0); + R.view(headLens, ['a', 'b', 'c']); //=> 'a' + R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] +} +() => { + var xLens = R.lensProp('x'); + R.view(xLens, {x: 1, y: 2}); //=> 1 + R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} +} + +() => { + const xyLens = R.lensPath(['x', 'y']); + + R.view(xyLens, {x: {y: 2, z: 3}}); //=> 2 + R.set(xyLens, 4, {x: {y: 2, z: 3}}); //=> {x: {y: 4, z: 3}} + R.over(xyLens, R.negate, {x: {y: 2, z: 3}}); //=> {x: {y: -2, z: 3}} +} + +() => { + R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] +} + +() => { + var f = new F(); + R.keysIn(f); //=> ['x', 'y'] +} + +() => { + var headLens = R.lens( + function get(arr: number[]) { return arr[0]; }, + function set(val: number, arr: number[]) { return [val].concat(arr.slice(1)); } + ); + headLens([10, 20, 30, 40]); //=> 10 + headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40] + + var phraseLens = R.lens( + function get(obj: any) { return obj.phrase; }, + function set(val: string, obj: any) { + var out = R.clone(obj); + out.phrase = val; + return out; + } + ); + var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'}; + var obj2 = { phrase: "What's all this, then?"}; + phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!' + phraseLens(obj2); // => "What's all this, then?" + phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'} +} + + +() => { + var phraseLens = R.lensProp('phrase'); + var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'}; + var obj2 = { phrase: "What's all this, then?"}; + phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!' + phraseLens(obj2); // => "What's all this, then?" + phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'} +} + +() => { + R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); + //=> { 'name': 'fred', 'age': 40 } + + var resetToDefault = R.flip(R.merge)({x: 0}); + resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2} +} + +() => { + const a = R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3} + const b = R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2} +} + +() => { + const a = R.mergeWith(R.concat, + { a: true, values: [10, 20] }, + { b: true, values: [15, 35] }); + //=> { a: true, b: true, values: [10, 20, 15, 35] } +} + +() => { + let concatValues = (k:string, l: string, r: string) => k == 'values' ? R.concat(l, r) : r; + R.mergeWithKey(concatValues, + { a: true, thing: 'foo', values: [10, 20] }, + { b: true, thing: 'bar', values: [15, 35] }); + const merge = R.mergeWithKey(concatValues); + merge({ a: true, thing: 'foo', values: [10, 20] }, { b: true, thing: 'bar', values: [15, 35] }); +} + +() => { + const a1 = R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2 + const a2 = R.pathOr('N/A', ['a', 'b'])({a: {b: 2}}); //=> 2 + const a3 = R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A" + const a4 = R.pathOr({c:2})(['a', 'b'], {c: {b: 2}}); //=> "N/A" +} + +() => { + var isPositive = function(n: number) { + return n > 0; + }; + const a1 = R.pickBy(isPositive, {a: 1, b: 2, c: -1, d: 0, e: 5}); //=> {a: 1, b: 2, e: 5} + var containsBackground = function(val: any) { + return val.bgcolor; + }; + var colors = {1: {color: 'read'}, 2: {color: 'black', bgcolor: 'yellow'}}; + R.pickBy(containsBackground, colors); //=> {2: {color: 'black', bgcolor: 'yellow'}} + + var isUpperCase = function(val: number, key: string) { return key.toUpperCase() === key; } + R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} +} + + +() => { + const a1 = R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + const a2 = R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + const a3 = R.pick(['a', 'e', 'f'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + const a4 = R.pick(['a', 'e', 'f'], [1, 2, 3, 4]); //=> {a: 1} +} + +() => { + var matchPhrases = R.compose( + R.objOf('must'), + R.map(R.objOf('match_phrase')) +) + +matchPhrases(['foo', 'bar', 'baz']); +} +() => { + R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} + R.omit(['a', 'd'])({a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} +} + + +() => { + R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} +} + +() => { + R.pair('foo', 'bar'); //=> ['foo', 'bar'] + let p = R.pair('foo', 1); //=> ['foo', 'bar'] + let x: string = p[0]; + let y: number = p[1]; +} + +() => { + var headLens = R.lensIndex(0); + R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz'] +} + +() => { + R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + R.pickAll(['a', 'd'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} + R.pickAll(['a', 'e', 'f'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} +} + +() => { + var isUpperCase = function(val: number, key: string) { return key.toUpperCase() === key; } + R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} +} + +() => { + var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; + var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; + var kids = [abby, fred]; + R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] +} + +() => { + var x: number = R.prop('x', {x: 100}); //=> 100 + const a = R.prop('x', {}); //=> undefined +} + +() => { + var alice = { + name: 'ALICE', + age: 101 + }; + var favorite = R.prop('favoriteLibrary'); + var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary'); + + const s1 = favorite(alice); //=> undefined + const s2 = favoriteWithDefault(alice); //=> 'Ramda' +} + +() => { + const a: boolean = R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true + const b: boolean = R.propSatisfies(x => x > 0, 'x')({x: 1, y: 2}); //=> true + const c: boolean = R.propSatisfies(x => x > 0)('x')({x: 1, y: 2}); //=> true +} + +() => { + R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2] + R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2] + + var fullName = R.compose(R.join(' '), R.props(['first', 'last'])); + fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth' +} + +() => { + const a = R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] +} + +() => { + var f = new F(); + const a1 = R.toPairsIn(f); //=> [['x','X'], ['y','Y']] + const a2 = R.toPairsIn(f); //=> [['x','X'], ['y','Y']] +} + +() => { + const a = R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] +} +() => { + var f = new F(); + const a = R.valuesIn(f); //=> ['X', 'Y'] +} + +() => { + var spec = {x: 2}; + var x1: boolean = R.where(spec, {w: 10, x: 2, y: 300}); //=> true + var x2: boolean = R.where(spec, {x: 1, y: 'moo', z: true}); //=> false + var x3: boolean = R.where(spec)({w: 10, x: 2, y: 300}); //=> true + var x4: boolean = R.where(spec)({x: 1, y: 'moo', z: true}); //=> false + + // There's no way to represent the below functionality in typescript + // per http://stackoverflow.com/a/29803848/632495 + // will need a work around. + + var spec2 = {x: function(val: number, obj: any) { return val + obj.y > 10; }}; + R.where(spec2, {x: 2, y: 7}); //=> false + R.where(spec2, {x: 3, y: 8}); //=> true + + var xs = [{x: 2, y: 1}, {x: 10, y: 2}, {x: 8, y: 3}, {x: 10, y: 4}]; + R.filter(R.where({x: 10}), xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] + R.filter(R.where({x: 10}))(xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] +} + +() => { + // pred :: Object -> Boolean + var pred = R.whereEq({a: 1, b: 2}); + pred({a: 1}); //=> false + pred({a: 1, b: 2}); //=> true + pred({a: 1, b: 2, c: 3}); //=> true + pred({a: 1, b: 1}); //=> false + R.whereEq({a: 'one'}, {a: 'one'}); // => true +} + +() => { + const a: number[] = R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4] +} + +() => { + var mapIndexed = R.addIndex(R.map); + mapIndexed(function(val: string, idx: number) {return idx + '-' + val;})(['f', 'o', 'o', 'b', 'a', 'r']); + //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r'] + mapIndexed((rectangle: Rectangle, idx: number):number => rectangle.area()*idx, [new Rectangle(1,2), new Rectangle(4,7)]); + //=> [2, 56] +} + +() => { + var reduceIndexed = R.addIndex(R.reduce); + reduceIndexed(function(acc: string, val: string, idx: number) { + return acc + ',' + idx + '-' + val; + } + ,'' + ,['f', 'o', 'o', 'b', 'a', 'r']); + //=> ['0-f,1-o,2-o,3-b,4-a,5-r'] +} + + + +() => { + var t = R.always('Tee'); + const x: string = t(); //=> 'Tee' +} + +() => { + const x: number[] = R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + const y: number[] = R.ap([R.multiply(2), R.add(3)])([1,2,3]); //=> [2, 4, 6, 4, 5, 6] +} + +() => { + var nums = [1, 2, 3, -99, 42, 6, 7]; + R.apply(Math.max, nums); //=> 42 + R.apply(Math.max)(nums); //=> 42 +} + +() => { + type T = {sum: number, nested: {mul: number}}; + const getMetrics = R.applySpec({ + sum: R.add, nested: { mul: R.multiply } + }); + const result = getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } } +} + +() => { + var takesThreeArgs = function(a: number, b: number, c: number) { + return [a, b, c]; + }; + takesThreeArgs.length; //=> 3 + takesThreeArgs(1, 2, 3); //=> [1, 2, 3] + + var takesTwoArgs = R.binary(takesThreeArgs); + takesTwoArgs.length; //=> 2 + // Only 2 arguments are passed to the wrapped function + takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] +} + +() => { + var indentN = R.pipe(R.times(R.always(' ')), + R.join(''), + R.replace(/^(?!$)/gm) + ); + + var format = R.converge( + R.call, [ + R.pipe(R.prop('indent'), indentN), + R.prop('value') + ] + ); + + format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n' +} + +() => { + type T = {age: number}; + var cmp = R.comparator(function(a: T, b: T) { + return a.age < b.age; + }); + var people = [ + {name: 'Agy', age:33}, {name: 'Bib', age: 15}, {name: 'Cari', age: 16} + ]; + R.sort(cmp, people); +} + +() => { + var add = function(a: number, b: number) { return a + b; }; + var multiply = function(a: number, b: number) { return a * b; }; + var subtract = function(a: number, b: number) { return a - b; }; + + //≅ multiply( add(1, 2), subtract(1, 2) ); + const x: number = R.converge(multiply, [ add, subtract ])(1, 2); //=> -3 + + var add3 = function(a: number, b: number, c: number) { return a + b + c; }; + const y: number = R.converge(add3, [ multiply, add, subtract ])(1, 2); //=> 4 +} + +() => { + const f0 = R.compose(Math.pow); + const f1 = R.compose(R.negate, Math.pow); + const f2 = R.compose(R.inc, R.negate, Math.pow); + const f3 = R.compose(R.inc, R.inc, R.negate, Math.pow); + const f4 = R.compose(R.inc, R.inc, R.inc, R.negate, Math.pow); + const f5 = R.compose(R.inc, R.inc, R.inc, R.inc, R.negate, Math.pow); + const x0: number = f0(3, 4); // -(3^4) + 1 + const x1: number = f1(3, 4); // -(3^4) + 1 + const x2: number = f2(3, 4); // -(3^4) + 1 + const x3: number = f3(3, 4); // -(3^4) + 1 + const x4: number = f4(3, 4); // -(3^4) + 1 + const x5: number = f5(3, 4); // -(3^4) + 1 +} + +() => { + const fn = function(a: string, b: number, c: string) { + return [a,b,c]; + } + const gn = R.compose(R.length, fn); + const x: number = gn('Hello', 4, "world"); +} + +(() => { + var Circle = function(r: number) { + this.r = r; + this.colors = Array.prototype.slice.call(arguments, 1); + }; + Circle.prototype.area = function() {return Math.PI * Math.pow(this.r, 2);}; + var circleN = R.constructN(2, Circle); + var c1 = circleN(1, 'red'); + var circle = R.construct(Circle); + var c1 = circle(1, 'red'); +})(); + +/***************************************************************** + * Relation category + */ + +() => { + var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2]; + var letters = R.split('', 'abcABCaaaBBc'); + R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1} + R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3} +} + +() => { + R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] + R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] +} + +() => { + function cmp(x: any, y: any) { return x.a === y.a; } + var l1 = [{a: 1}, {a: 2}, {a: 3}]; + var l2 = [{a: 3}, {a: 4}]; + R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] +} + +() => { + R.equals(1, 1); //=> true + R.equals('2', '1'); //=> false + R.equals([1, 2, 3], [1, 2, 3]); //=> true + + var a: any = {}; a.v = a; + var b: any = {}; b.v = b; + R.equals(a, b); //=> true +} + +() => { + const a1 = R.identity(1); //=> 1 + let obj = {}; + const a2 = R.identity([1,2,3]); + const a3 = R.identity(['a','b','c']); + const a4 = R.identity(obj) === obj; //=> true +} + +() => { + var o = {}; + R.identical(o, o); //=> true + R.identical(1, 1); //=> true + R.identical('2', '1'); //=> false + R.identical([], []); //=> false + R.identical(0, -0); //=> false + R.identical(NaN, NaN); //=> true +} + +() => { + R.path(['a', 'b'], {a: {b: 2}}); //=> 2 + R.path(['a', 'b'])({a: {b: 2}}); //=> 2 +} + +() => { + var sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name'))); + var alice = { + name: 'ALICE', + age: 101 + }; + var bob = { + name: 'Bob', + age: -10 + }; + var clara = { + name: 'clara', + age: 314.159 + }; + var people = [clara, bob, alice]; + sortByNameCaseInsensitive(people); //=> [alice, bob, clara] +} + +() => { + const a: number[][] = R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]] + const b: number[][] = R.splitAt(1)([1, 2, 3]); //=> [[1], [2, 3]] + const c: string[] = R.splitAt(5, 'hello world'); //=> ['hello', ' world'] + const d: string[] = R.splitAt(-1, 'foobar'); //=> ['fooba', 'r'] +} + +() => { + const a: number[][] = R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] + const b: number[][] = R.splitWhen(R.equals(2))([1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] +} + +() => { + R.add(2, 3); //=> 5 + R.add(7)(10); //=> 17 + R.add("Hello", " World"); //=> "Hello World" + R.add("Hello")(" World"); //=> "Hello World" +} + +() => { + R.dec(42); //=> 41 +} + +() => { + R.divide(71, 100); //=> 0.71 + + var half = R.flip(R.divide)(2); + half(42); //=> 21 + + var reciprocal = R.divide(1); + reciprocal(4); //=> 0.25 +} + +() => { + R.gt(2, 6); //=> false + R.gt(2, 0); //=> true + R.gt(2, 2); //=> false + R.flip(R.gt)(2)(10); //=> true + R.gt(2)(10); //=> false +} + +() => { + R.gte(2, 6); //=> false + R.gte(2, 0); //=> true + R.gte(2, 2); //=> false + R.flip(R.gte)(2)(10); //=> true + R.gte(2)(10); //=> false +} + +() => { + R.isNaN(NaN); //=> true + R.isNaN(undefined); //=> false + R.isNaN({}); //=> false +} + +() => { + R.lt(2, 6); //=> true + R.lt(2, 0); //=> false + R.lt(2, 2); //=> false + R.lt(5)(10); //=> true + R.flip(R.lt)(5)(10); //=> false // right-sectioned currying +} + +() => { + R.lte(2, 6); //=> true + R.lte(2, 0); //=> false + R.lte(2, 2); //=> true + R.flip(R.lte)(2)(1); //=> true + R.lte(2)(10); //=> true +} + +() => { + R.mathMod(-17, 5); //=> 3 + R.mathMod(17, 5); //=> 2 + R.mathMod(17, -5); //=> NaN + R.mathMod(17, 0); //=> NaN + R.mathMod(17.2, 5); //=> NaN + R.mathMod(17, 5.3); //=> NaN + + var clock = R.flip(R.mathMod)(12); + clock(15); //=> 3 + clock(24); //=> 0 + + var seventeenMod = R.mathMod(17); + seventeenMod(3); //=> 2 +} + +() => { + var hasName = R.has('name'); + hasName({name: 'alice'}); //=> true + hasName({name: 'bob'}); //=> true + hasName({}); //=> false + + var point = {x: 0, y: 0}; + var pointHas = R.flip(R.has)(point); + pointHas('x'); //=> true + pointHas('y'); //=> true + pointHas('z'); //=> false +} + +() => { + let x: R.Ord = R.max(7, 3); //=> 7 + let y: R.Ord = R.max('a', 'z'); //=> 'z' +} + +() => { + function cmp(obj: { x: R.Ord }) { return obj.x; } + var a = {x: 1}, b = {x: 2}, c = {x: 3}, d = {x: "a"}, e = {x:"z"}; + R.maxBy(cmp, a, c); //=> {x: 3} + R.maxBy(cmp)(a, c); //=> {x: 3} + R.maxBy(cmp)(a)(b); + R.maxBy(cmp)(d)(e); +} + +() => { + const a: number = R.mean([2, 7, 9]); //=> 6 + const b: number = R.mean([]); //=> NaN +} + +() => { + const a: number = R.median([7, 2, 10, 9]); //=> 8 + const b: number = R.median([]); //=> NaN +} + +() => { + let x: R.Ord = R.min(9, 3); //=> 3 + let y: R.Ord = R.min('a', 'z'); //=> 'a' +} + +() => { + function cmp(obj: {x: R.Ord}) { return obj.x; } + var a = {x: 1}, b = {x: 2}, c = {x: 3}, d = {x: "a"}, e = {x: "z"}; + R.minBy(cmp, a, b); //=> {x: 1} + R.minBy(cmp)(a, b); //=> {x: 1} + R.minBy(cmp)(a)(c); + R.minBy(cmp, d, e); +} + +() => { + R.modulo(17, 3); //=> 2 + // JS behavior: + R.modulo(-17, 3); //=> -2 + R.modulo(17, -3); //=> 2 + + var isOdd = R.flip(R.modulo)(2); + isOdd(42); //=> 0 + isOdd(21); //=> 1 +} + +() => { + var double = R.multiply(2); + var triple = R.multiply(3); + double(3); //=> 6 + triple(4); //=> 12 + R.multiply(2, 5); //=> 10 +} + +() => { + R.negate(42); //=> -42 +} + +() => { + R.product([2,4,6,8,100,1]); //=> 38400 +} + +() => { + R.subtract(10, 8); //=> 2 + + var minus5 = R.flip(R.subtract)(5); + minus5(17); //=> 12 + + var complementaryAngle = R.subtract(90); + complementaryAngle(30); //=> 60 + complementaryAngle(72); //=> 18 +} + +() => { + R.sum([2,4,6,8,100,1]); //=> 121 +} + +() => { + const a: number[] = R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5] + const b: number[] = R.symmetricDifference([7,6,5,4,3])([1,2,3,4]); //=> [7,6,5,1,2] +} + +() => { + const eqA = R.eqBy(R.prop('a')); + const l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}]; + const l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}]; + R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + R.symmetricDifferenceWith(eqA)(l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + const c: (a: any[]) => any[] = R.symmetricDifferenceWith(eqA)(l1); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] +} + +/***************************************************************** + * String category + */ + +() => { + R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo' + R.replace('foo', 'bar')('foo foo foo'); //=> 'bar foo foo' + R.replace('foo')('bar')('foo foo foo'); //=> 'bar foo foo' + R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo' + + // Use the "g" (global) flag to replace all occurrences: + R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar' + R.replace(/foo/g, 'bar')('foo foo foo'); //=> 'bar bar bar' + R.replace(/foo/g)('bar')('foo foo foo'); //=> 'bar bar bar' +} + +/***************************************************************** + * Is category + */ + +() => { + R.is(Object, {}); //=> true + R.is(Object)({}); //=> true + R.is(Number, 1); //=> true + R.is(Number)(1); //=> true + R.is(Object, 1); //=> false + R.is(Object)(1); //=> false + R.is(String, 's'); //=> true + R.is(String)('s'); //=> true + R.is(String, new String('')); //=> true + R.is(String)(new String('')); //=> true + R.is(Object, new String('')); //=> true + R.is(Object)(new String('')); //=> true + R.is(Object, 's'); //=> false + R.is(Object)('s'); //=> false + R.is(Number, {}); //=> false + R.is(Number)({}); //=> false +} + +/***************************************************************** + * Logic category + */ +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0}; + var f = R.allPass([gt10, even]); + f(11); //=> false + f(12); //=> true +} + +() => { + R.and(false, true); //=> false + R.and(0, []); //=> 0 + R.and(0)([]); //=> 0 + R.and(null, ''); //=> null + var Why: any = (function(val: boolean) { + var why: any; + why.val = val; + why.and = function(x: boolean) { + return this.val && x; + } + return Why; + })(true); + var why = new Why(true); + R.and(why, false); // false +} +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0}; + var f = R.anyPass([gt10, even]); + f(11); //=> true + f(8); //=> true + f(9); //=> false +} + +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0 }; + var f = R.both(gt10, even); + var g = R.both(gt10)(even); + f(100); //=> true + f(101); //=> false +} +() => { + var isEven = function(n: number) { return n % 2 === 0; }; + var isOdd = R.complement(isEven); + isOdd(21); //=> true + isOdd(42); //=> false +} + +(() => { + R.eqBy(Math.abs, 5, -5); //=> true +}); + +() => { + var defaultTo42 = R.defaultTo(42); + defaultTo42(null); //=> 42 + defaultTo42(undefined); //=> 42 + defaultTo42('Ramda'); //=> 'Ramda' +} +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0 }; + var f = R.either(gt10, even); + var g = R.either(gt10)(even); + f(101); //=> true + f(8); //=> true +} +() => { + // Flatten all arrays in the list but leave other values alone. + var flattenArrays = R.map(R.ifElse(Array.isArray, R.flatten, R.identity)); + + flattenArrays([[0], [[10], [8]], 1234, {}]); //=> [[0], [10, 8], 1234, {}] + flattenArrays([[[10], 123], [8, [10]], "hello"]); //=> [[10, 123], [8, 10], "hello"] +} +() => { + R.isEmpty([1, 2, 3]); //=> false + R.isEmpty([]); //=> true + R.isEmpty(''); //=> true + R.isEmpty(null); //=> false + R.isEmpty({}); //=>true + R.isEmpty({a:1}); //=> false +} + +() => { + R.not(true); //=> false + R.not(false); //=> true + R.not(0); // => true + R.not(1); // => false +} + +class Why { + val: boolean; + constructor(val: boolean) { + this.val = val; + } + or(x: boolean) { + return this.val && x; + } +} +() => { + const x0: boolean = R.or(false, true); //=> false + const x1: number|any[] = R.or(0, []); //=> [] + const x2: number|any[] = R.or(0)([]); //=> [] + const x3: string = R.or(null, ''); //=> '' + + var why = new Why(true); + why.or(true) + const x4: Why|boolean = R.or(why, false); // false +} + +() => { + R.intersperse(',', ['foo', 'bar']); //=> ['foo', ',', 'bar'] + R.intersperse(0, [1, 2]); //=> [1, 0, 2] + R.intersperse(0, [1]); //=> [1] +} diff --git a/ramda/ramda.d.ts b/ramda/ramda.d.ts new file mode 100644 index 0000000000..ffa11ca2cb --- /dev/null +++ b/ramda/ramda.d.ts @@ -0,0 +1,1807 @@ +// Type definitions for ramda (www.ramdajs.com) v0.21.0 +// Project: https://github.com/donnut/typescript-ramda +// Definitions by: Erwin Poeze +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var R: R.Static; + +declare namespace R { + type Ord = number | string | boolean; + + interface ListIterator { + (value: T, index: number, list: T[]): TResult; + } + + interface Functor { + map(a: any): T; + } + + interface ObjectIterator { + (element: T, key: string, obj: Dictionary): Dictionary; + } + + interface KeyValuePair extends Array { 0 : K; 1 : V; } + + interface ArrayLike { + nodeType: number; + } + + interface Arity0Fn { + (): any + } + + interface Arity1Fn { + (a: any): any + } + + interface Arity2Fn { + (a: any, b: any): any + } + + interface ObjFunc { + [index:string]: Function; + } + + interface ObjFunc2 { + [index:string]: (x: any, y: any) => boolean; + } + + interface Pred { + (...a: any[]): boolean; + } + + interface ObjPred { + (value: any, key: string): boolean; + } + + interface Dictionary { + [index: string]: T; + } + + interface CharList extends String { + push(x: string): void; + } + + interface Nested { + [index: string]: Nested|{(value: any): U}; + } + + interface Lens { + (obj: T): U; + set(str: string, obj: T): U; + } + + // @see https://gist.github.com/donnut/fd56232da58d25ceecf1, comment by @albrow + interface CurriedFunction2 { + (t1: T1): (t2: T2) => R; + (t1: T1, t2: T2): R; + } + + interface CurriedFunction3 { + (t1: T1): CurriedFunction2; + (t1: T1, t2: T2): (t3: T3) => R; + (t1: T1, t2: T2, t3: T3): R; + } + + interface CurriedFunction4 { + (t1: T1): CurriedFunction3; + (t1: T1, t2: T2): CurriedFunction2; + (t1: T1, t2: T2, t3: T3): (t4: T4) => R; + (t1: T1, t2: T2, t3: T3, t4: T4): R; + } + + interface CurriedFunction5 { + (t1: T1): CurriedFunction4; + (t1: T1, t2: T2): CurriedFunction3; + (t1: T1, t2: T2, t3: T3): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4): (t5: T5) => R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; + } + + interface CurriedFunction6 { + (t1: T1): CurriedFunction5; + (t1: T1, t2: T2): CurriedFunction4; + (t1: T1, t2: T2, t3: T3): CurriedFunction3; + (t1: T1, t2: T2, t3: T3, t4: T4): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): (t6: T6) => R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; + } + + interface Reduced {} + + interface Static { + + /** + * Adds two numbers (or strings). Equivalent to a + b but curried. + */ + add(a: number, b: number): number; + add(a: string, b: string): string; + add(a: number): (b: number) => number; + add(a: string): (b: string) => string; + + /** + * Creates a new list iteration function from an existing one by adding two new parameters to its callback + * function: the current index, and the entire list. + */ + addIndex(fn: (f: (item: T) => U, list: T[]) => U[] ) + : CurriedFunction2<(item: T, idx: number, list?: T[]) => U, T[], U[]>; + /* Special case for forEach */ + addIndex(fn: (f: (item: T) => void, list: T[]) => T[]) + : CurriedFunction2<(item: T, idx: number, list?: T[]) => void, T[], T[]>; + /* Special case for reduce */ + addIndex(fn: (f: (acc:U, item: T) => U, aci:U, list: T[]) => U) + : CurriedFunction3<(acc:U, item: T, idx: number, list?: T[]) => U, U, T[], U>; + + /** + * Applies a function to the value at the given index of an array, returning a new copy of the array with the + * element at the given index replaced with the result of the function application. + */ + adjust(fn: (a: T) => T, index: number, list: T[]): T[]; + adjust(fn: (a: T) => T, index: number): (list: T[]) => T[]; + + /** + * Returns true if all elements of the list match the predicate, false if there are any that don't. + */ + all(fn: (a: T) => boolean, list: T[]): boolean; + all(fn: (a: T) => boolean): (list: T[]) => boolean; + + /** + * Given a list of predicates, returns a new predicate that will be true exactly when all of them are. + */ + allPass(preds: Pred[]): Pred; + + /** + * Returns a function that always returns the given value. + */ + always(val: T): () => T; + + + /** + * A function that returns the first argument if it's falsy otherwise the second argument. Note that this is + * NOT short-circuited, meaning that if expressions are passed they are both evaluated. + */ + and(fn1: T, val2: boolean|any): boolean; + and(fn1: T): (val2: boolean|any) => boolean; + + /** + * Returns true if at least one of elements of the list match the predicate, false otherwise. + */ + any(fn: (a: T) => boolean, list: T[]): boolean; + any(fn: (a: T) => boolean): (list: T[]) => boolean; + + /** + * Given a list of predicates returns a new predicate that will be true exactly when any one of them is. + */ + anyPass(preds: Pred[]): Pred; + + /** + * ap applies a list of functions to a list of values. + */ + ap(fns: ((a: T) => U)[], vs: T[]): U[]; + ap(fns: ((a: T) => U)[]): (vs: T[]) => U[]; + + + /** + * Returns a new list, composed of n-tuples of consecutive elements If n is greater than the length of the list, + * an empty list is returned. + */ + aperture(n: number, list: T): T[][]; + aperture(n: number): (list: T) => T[][]; + + /** + * Returns a new list containing the contents of the given list, followed by the given element. + */ + append(el: U, list: T[]): (T & U)[]; + append(el: U): (list: T[]) => (T & U)[]; + append(el: U): (list: T[]) => (T & U)[]; + + /** + * Applies function fn to the argument list args. This is useful for creating a fixed-arity function from + * a variadic function. fn should be a bound function if context is significant. + */ + apply(fn: (arg0: T, ...args: T[]) => TResult, args: U[]): TResult; + apply(fn: (arg0: T, ...args: T[]) => TResult): (args: U[]) => TResult; + + /** + * Given a spec object recursively mapping properties to functions, creates a function producing an object + * of the same structure, by mapping each property to the result of calling its associated function with + * the supplied arguments. + */ + applySpec(obj: any): (...args: any[]) => T; + + /** + * Makes a shallow clone of an object, setting or overriding the specified property with the given value. + */ + assoc(prop: string, val: T, obj: U): {prop: T} & U; + assoc(prop: string): (val: T, obj: U) => {prop: T} & U; + assoc(prop: string, val: T): (obj: U) => {prop: T} & U; + + + /** + * Makes a shallow clone of an object, setting or overriding the nodes required to create the given path, and + * placing the specific value at the tail end of that path. + */ + assocPath(path: string[], val: T, obj: U): U; + assocPath(path: string[]): (val: T, obj: U) => U; + assocPath(path: string[], val: T): (obj: U) => U; + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly 2 + * parameters. Any extraneous parameters will not be passed to the supplied function. + */ + binary(fn: (...args: any[]) => any): Function; + + /** + * Creates a function that is bound to a context. Note: R.bind does not provide the additional argument-binding + * capabilities of Function.prototype.bind. + */ + bind(thisObj: T, fn: (...args: any[]) => any): (...args: any[]) => any; + + + /** + * A function wrapping calls to the two functions in an && operation, returning the result of the first function + * if it is false-y and the result of the second function otherwise. Note that this is short-circuited, meaning + * that the second function will not be invoked if the first returns a false-y value. + */ + both(pred1: Pred, pred2: Pred): Pred; + both(pred1: Pred): (pred2: Pred) => Pred; + + /** + * Returns the result of calling its first argument with the remaining arguments. This is occasionally useful + * as a converging function for R.converge: the left branch can produce a function while the right branch + * produces a value to be passed to that function as an argument. + */ + call(fn: (...args: any[])=> (...args: any[]) => any, ...args: any[]): any; + + /** + * `chain` maps a function over a list and concatenates the results. + * This implementation is compatible with the Fantasy-land Chain spec + */ + chain(fn: (n: T) => U[], list: T[]): U[]; + chain(fn: (n: T) => U[]): (list: T[]) => U[]; + + /** + * Restricts a number to be within a range. + * Also works for other ordered types such as Strings and Date + */ + clamp(min: T, max: T, value: T): T; + clamp(min: T, max: T): (value: T) => T; + clamp(min: T): (max: T, value: T) => T; + clamp(min: T): (max: T) => (value: T) => T; + + /** + * Creates a deep copy of the value which may contain (nested) Arrays and Objects, Numbers, Strings, Booleans and Dates. + */ + clone(value: T): T; + clone(value: T[]): T[]; + + /** + * Makes a comparator function out of a function that reports whether the first element is less than the second. + */ + // comparator(pred: (a: any, b: any) => boolean): (x: number, y: number) => number; + comparator(pred: (a: T, b: T) => boolean): (x: T, y: T) => number; + + /** + * Takes a function f and returns a function g such that: + * - applying g to zero or more arguments will give true if applying the same arguments to f gives + * a logical false value; and + * - applying g to zero or more arguments will give false if applying the same arguments to f gives + * a logical true value. + */ + complement(pred: (...args: any[]) => boolean): (...args: any[]) => boolean + + /** + * Performs right-to-left function composition. The rightmost function may have any arity; the remaining + * functions must be unary. + */ + compose(fn0: (x0: V0) => T1): (x0: V0) => T1; + compose(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; + compose(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; + + compose(fn1: (x: T1) => T2, fn0: (x0: V0) => T1): (x0: V0) => T2; + compose(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T2; + compose(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T2; + + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T3; + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T3; + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T3; + + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T4; + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T4; + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T4; + + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T5; + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T5; + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T5; + + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T6; + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T6; + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T6; + + /** + * TODO composeK + */ + + /** + * TODO composeP + */ + + + /** + * Returns a new list consisting of the elements of the first list followed by the elements + * of the second. + */ + concat(list1: T[], list2: T[]): T[]; + concat(list1: T[]): (list2: T[]) => T[]; + concat(list1: string, list2: string): string; + concat(list1: string): (list2: string) => string; + + /** + * Returns a function, fn, which encapsulates if/else-if/else logic. R.cond takes a list of [predicate, transform] pairs. + * All of the arguments to fn are applied to each of the predicates in turn until one returns a "truthy" value, at which + * point fn returns the result of applying its arguments to the corresponding transformer. If none of the predicates + * matches, fn returns undefined. + */ + cond(fns: [Pred, Function][]): Function; + + + /** + * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. + */ + construct(fn: Function): Function; + + + /** + * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. + * The arity of the function returned is specified to allow using variadic constructor functions. + */ + constructN(n: number, fn: Function): Function; + + + /** + * Returns `true` if the specified item is somewhere in the list, `false` otherwise. + * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. + */ + contains(a: string, list: string): boolean; + contains(a: T, list: T[]): boolean; + contains(a: string): (list: string) => boolean; + contains(a: T): (list: T[]) => boolean; + + /** + * Accepts a converging function and a list of branching functions and returns a new + * function. When invoked, this new function is applied to some arguments, each branching + * function is applied to those same arguments. The results of each branching function + * are passed as arguments to the converging function to produce the return value. + */ + converge(after: Function, fns: Function[]): Function; + + /** + * Counts the elements of a list according to how many match each value + * of a key generated by the supplied function. Returns an object + * mapping the keys produced by `fn` to the number of occurrences in + * the list. Note that all keys are coerced to strings because of how + * JavaScript objects work. + */ + countBy(fn: (a: any) => string|number, list: any[]): any; + countBy(fn: (a: any) => string|number): (list: any[]) => any; + + /** + * Returns a curried equivalent of the provided function. The curried function has two unusual capabilities. + * First, its arguments needn't be provided one at a time. + */ + curry(fn: (a: T1, b: T2) => TResult): CurriedFunction2 + curry(fn: (a: T1, b: T2, c: T3) => TResult): CurriedFunction3 + curry(fn: (a: T1, b: T2, c: T3, d: T4) => TResult): CurriedFunction4 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => TResult): CurriedFunction5 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5, f: T6) => TResult): CurriedFunction6 + curry(fn: Function): Function + + + /** + * Returns a curried equivalent of the provided function, with the specified arity. The curried function has + * two unusual capabilities. First, its arguments needn't be provided one at a time. + */ + curryN(length: number, fn: (...args: any[]) => any): Function; + + + /** + * Decrements its argument. + */ + dec(n: number): number; + + /** + * Returns the second argument if it is not null or undefined. If it is null or undefined, the + * first (default) argument is returned. + */ + defaultTo(a: T, b: U): T|U + defaultTo(a: T): (b: U) => T|U + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. + */ + difference(list1: T[], list2: T[]): T[]; + difference(list1: T[]): (list2: T[]) => T[]; + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. + * Duplication is determined according to the value returned by applying the supplied predicate to two list + * elements. + */ + differenceWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + + /* + * Returns a new object that does not contain a prop property. + */ + // It seems impossible to infer the return type, so this may to be specified explicitely + dissoc(prop: string, obj: any): T; + dissoc(prop: string): (obj: any) => U; + + /** + * Makes a shallow clone of an object, omitting the property at the given path. + */ + dissocPath(path: string[], obj: any): T; + dissocPath(path: string[]): (obj: any) => T; + + /** + * Divides two numbers. Equivalent to a / b. + */ + divide(a: number, b: number): number; + divide(a: number): (b: number) => number; + + /** + * Returns a new list containing all but the first n elements of the given list. + */ + drop(n: number, xs: T[]): T[]; + drop(n: number, xs: string): string; + drop(n: number): { + (xs: string): string; + (xs: T[]): T[]; + } + + /** + * Returns a list containing all but the last n elements of the given list. + */ + dropLast(n: number, xs: T[]): T[]; + dropLast(n: number, xs: string): string; + dropLast(n: number): { + (xs: T[]): T[]; + (xs: string): string; + } + + /** + * Returns a new list containing all but last then elements of a given list, passing each value from the + * right to the supplied predicate function, skipping elements while the predicate function returns true. + */ + dropLastWhile(fn: (a: T) => boolean, list: T[]): T[]; + dropLastWhile(fn: (a: T) => boolean): (list: T[]) => T[]; + + /** + * Returns a new list containing the last n elements of a given list, passing each value to the supplied + * predicate function, skipping elements while the predicate function returns true. + */ + dropWhile(fn: (a: T) => boolean, list: T[]): T[]; + dropWhile(fn: (a: T) => boolean): (list: T[]) => T[]; + + /** + * A function wrapping calls to the two functions in an || operation, returning the result of the first + * function if it is truth-y and the result of the second function otherwise. Note that this is + * short-circuited, meaning that the second function will not be invoked if the first returns a truth-y value. + */ + either(pred1: Pred, pred2: Pred): Pred; + either(pred1: Pred): (pred2: Pred) => Pred; + + /** + * Returns the empty value of its argument's type. Ramda defines the empty value of Array ([]), Object ({}), + * String (''), and Arguments. Other types are supported if they define .empty and/or .prototype.empty. + * Dispatches to the empty method of the first argument, if present. + */ + empty(x: T): T; + + /** + * Takes a function and two values in its domain and returns true if the values map to the same value in the + * codomain; false otherwise. + */ + eqBy(fn: (a: T) => T, a: T, b: T): boolean; + eqBy(fn: (a: T) => T, a: T): (b: T) => boolean; + eqBy(fn: (a: T) => T): (a: T, b: T) => boolean; + eqBy(fn: (a: T) => T): (a: T) => (b: T) => boolean; + + /** + * Reports whether two functions have the same value for the specified property. + */ + eqProps(prop: string, obj1: T, obj2: U): boolean; + eqProps(prop: string): (obj1: T, obj2: U) => boolean; + eqProps(prop: string, obj1: T): (obj2: U) => boolean; + + /** + * Returns true if its arguments are equivalent, false otherwise. Dispatches to an equals method if present. + * Handles cyclical data structures. + */ + equals(a: T, b: T): boolean; + equals(a: T): (b: T) => boolean; + + /** + * Creates a new object by evolving a shallow copy of object, according to the transformation functions. + */ + evolve(transformations: Nested, obj: V): Nested; + evolve(transformations: Nested): (obj: V) => Nested; + /* + * A function that always returns false. Any passed in parameters are ignored. + */ + F(): boolean; + + /** + * Returns a new list containing only those items that match a given predicate function. The predicate function is passed one argument: (value). + */ + filter(fn: (value: T) => boolean): (list: T[]) => T[]; + filter(fn: (value: T) => boolean, list: T[]): T[]; + + /** + * Returns the first element of the list which matches the predicate, or `undefined` if no + * element matches. + */ + find(fn: (a: T) => boolean, list: T[]): T; + find(fn: (a: T) => boolean): (list: T[]) => T; + + + /** + * Returns the index of the first element of the list which matches the predicate, or `-1` + * if no element matches. + */ + findIndex(fn: (a: T) => boolean, list: T[]): number; + findIndex(fn: (a: T) => boolean): (list: T[]) => number; + + /** + * Returns the last element of the list which matches the predicate, or `undefined` if no + * element matches. + */ + findLast(fn: (a: T) => boolean, list: T[]): T; + findLast(fn: (a: T) => boolean): (list: T[]) => T; + + /** + * Returns the index of the last element of the list which matches the predicate, or + * `-1` if no element matches. + */ + findLastIndex(fn: (a: T) => boolean, list: T[]): number; + findLastIndex(fn: (a: T) => boolean): (list: T[]) => number; + + /** + * Returns a new list by pulling every item out of it (and all its sub-arrays) and putting + * them in a new array, depth-first. + */ + flatten(x: T[][]): T[]; + flatten(x: T[]): T[]; + + /** + * Returns a new function much like the supplied one, except that the first two arguments' + * order is reversed. + */ + flip(fn: (arg0: T, arg1: U) => TResult): (arg1: U, arg0?: T) => TResult; + flip(fn: (arg0: T, arg1: U, ...args: any[]) => TResult): (arg1: U, arg0?: T, ...args: any[]) => TResult; + + + /** + * Iterate over an input list, calling a provided function fn for each element in the list. + */ + forEach(fn: (x: T) => void, list: T[]): T[]; + forEach(fn: (x: T) => void): (list: T[]) => T[]; + + /** + * Creates a new object out of a list key-value pairs. + */ + fromPairs(pairs: KeyValuePair[]): {[index: string]: V}; + fromPairs(pairs: KeyValuePair[]): {[index: number]: V}; + + /** + * Splits a list into sublists stored in an object, based on the result of + * calling a String-returning function + * on each element, and grouping the results according to values returned. + */ + groupBy(fn: (a: T) => string, list: T[]): {[index: string]: T[]} + groupBy(fn: (a: T) => string): (list: T[]) => {[index: string]: T[]} + + /** + * Takes a list and returns a list of lists where each sublist's elements are all "equal" according to the provided equality function + */ + groupWith(fn: (x: T, y: T) => boolean, list: T[]): T[][] + groupWith(fn: (x: T, y: T) => boolean, list: string): string[] + + /** + * Returns true if the first parameter is greater than the second. + */ + gt(a: number, b: number): boolean; + gt(a: number): (b: number) => boolean; + + /** + * Returns true if the first parameter is greater than or equal to the second. + */ + gte(a: number, b: number): boolean; + gte(a: number): (b: number) => boolean; + + /** + * Returns whether or not an object has an own property with the specified name. + */ + has(s: string, obj: T): boolean; + has(s: string): (obj: T) => boolean; + + /** + * Returns whether or not an object or its prototype chain has a property with the specified name + */ + hasIn(s: string, obj: T): boolean; + hasIn(s: string): (obj: T) => boolean; + + /** + * Returns the first element in a list. + * In some libraries this function is named `first`. + */ + head(list: T[]): T; + head(list: string): string; + + /** + * Returns true if its arguments are identical, false otherwise. Values are identical if they reference the + * same memory. NaN is identical to NaN; 0 and -0 are not identical. + */ + identical(a: T, b: T): boolean; + identical(a: T): (b: T) => boolean; + + + /** + * A function that does nothing but return the parameter supplied to it. Good as a default + * or placeholder function. + */ + identity(a: T): T; + + /** + * Creates a function that will process either the onTrue or the onFalse function depending upon the result + * of the condition predicate. + */ + ifElse(fn: Pred, onTrue: Arity1Fn, onFalse: Arity1Fn): Arity1Fn; + + + /** + * Increments its argument. + */ + inc(n: number): number; + + /** + * Given a function that generates a key, turns a list of objects into an object indexing the objects + * by the given key. + */ + indexBy(fn: (a: T) => string, list: T[]): U; + indexBy(fn: (a: T) => string): (list: T[]) => U; + + /** + * Returns the position of the first occurrence of an item in an array + * (by strict equality), + * or -1 if the item is not included in the array. + */ + indexOf(target: T, list: T[]): number; + indexOf(target: T): (list: T[]) => number; + + /** + * Returns all but the last element of a list. + */ + init(list: T[]): T[]; + + /** + * Inserts the supplied element into the list, at index index. Note that + * this is not destructive: it returns a copy of the list with the changes. + */ + insert(index: number, elt: T, list: T[]): T[]; + insert(index: number, elt: T): (list: T[]) => T[]; + insert(index: number): (elt: T, list: T[]) => T[]; + + /** + * Inserts the sub-list into the list, at index `index`. _Note that this + * is not destructive_: it returns a copy of the list with the changes. + */ + insertAll(index: number, elts: T[], list: T[]): T[]; + insertAll(index: number, elts: T[]): (list: T[]) => T[]; + insertAll(index: number): (elts: T[], list: T[]) => T[]; + + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists. + */ + intersection(list1: T[], list2: T[]): T[]; + + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those + * elements common to both lists. Duplication is determined according + * to the value returned by applying the supplied predicate to two list + * elements. + */ + intersectionWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + + /** + * Creates a new list with the separator interposed between elements. + */ + intersperse(separator: T, list: T[]): T[]; + intersperse(separator: T): (list: T[]) => T[]; + + /** + * Transforms the items of the list with the transducer and appends the transformed items to the accumulator + * using an appropriate iterator function based on the accumulator type. + */ + into(acc: any, xf: Function, list: T[]): T[]; + into(acc: any, xf: Function): (list: T[]) => T[]; + into(acc: any): (xf: Function, list: T[]) => T[]; + + /** + * Same as R.invertObj, however this accounts for objects with duplicate values by putting the values into an array. + */ + invert(obj: T): {[index:string]: string[]}; + + /** + * Returns a new object with the keys of the given object as values, and the values of the given object as keys. + */ + invertObj(obj: any): {[index:string]: string}; + invertObj(obj: {[index: number]: string}): {[index:string]: string}; + + + /** + * Turns a named method of an object (or object prototype) into a function that can be + * called directly. Passing the optional `len` parameter restricts the returned function to + * the initial `len` parameters of the method. + * + * The returned function is curried and accepts `len + 1` parameters (or `method.length + 1` + * when `len` is not specified), and the final parameter is the target object. + */ + invoker(name: string, obj: any, len?: number): Function; + invoker(name: string): (obj: any, len?: number) => Function; + + /** + * See if an object (`val`) is an instance of the supplied constructor. + * This function will check up the inheritance chain, if any. + */ + is(ctor: any, val: any): boolean; + is(ctor: any): (val: any) => boolean; + + /** + * Tests whether or not an object is similar to an array. + */ + isArrayLike(val: any): boolean; + + /** + * Reports whether the list has zero elements. + */ + isEmpty(value: any): boolean; + + + /** + * Returns true if the input value is NaN. + */ + isNaN(x: any): boolean; + + /** + * Checks if the input value is null or undefined. + */ + isNil(value: any): boolean; + + /** + * Returns a string made by inserting the `separator` between each + * element and concatenating all the elements into a single string. + */ + join(x: string, xs: any[]): string; + join(x: string): (xs: any[]) => string; + + /** + * Applies a list of functions to a list of values. + */ + juxt(fns: {(...args: T[]): U}[]): (...args: T[]) => U[]; + + + /** + * Returns a list containing the names of all the enumerable own + * properties of the supplied object. + */ + keys(x: T): string[]; + + /** + * Returns a list containing the names of all the + * properties of the supplied object, including prototype properties. + */ + keysIn(obj: T): string[]; + + /** + * Returns the last element from a list. + */ + last(list: T[]): T; + last(list: string): string; + + /** + * Returns the position of the last occurrence of an item (by strict equality) in + * an array, or -1 if the item is not included in the array. + */ + lastIndexOf(target: T, list: T[]): number; + + /** + * Returns the number of elements in the array by returning list.length. + */ + length(list: any[]): number; + + /** + * Returns a lens for the given getter and setter functions. The getter + * "gets" the value of the focus; the setter "sets" the value of the focus. + * The setter should not mutate the data structure. + */ + lens(getter: (s: T) => U, setter: (a: U, s: T) => V): Lens; + + /** + * Creates a lens that will focus on index n of the source array. + */ + lensIndex(n: number): Lens; + + /** + * Returns a lens whose focus is the specified path. + * See also view, set, over. + */ + lensPath(path: string[]): Lens; + + /** + * lensProp creates a lens that will focus on property k of the source object. + */ + lensProp(str: string): { + (obj: T): U; + set(val: T, obj: U): V; + /*map(fn: Function, obj: T): T*/ + } + + /** + * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other object that satisfies + * the FantasyLand Apply spec. + */ + lift(fn: Function, ...args: any[]): any; + + /** + * "lifts" a function to be the specified arity, so that it may "map over" that many lists, Functions or other + * objects that satisfy the FantasyLand Apply spec. + */ + liftN(n: number, fn: Function, ...args: any[]): any; + + + /** + * Returns true if the first parameter is less than the second. + */ + lt(a: number, b: number): boolean; + lt(a: number): (b: number) => boolean; + + /** + * Returns true if the first parameter is less than or equal to the second. + */ + lte(a: number, b: number): boolean; + lte(a: number): (b: number) => boolean; + + /** + * Returns a new list, constructed by applying the supplied function to every element of the supplied list. + */ + map(fn: (x: T) => U, list: T[]): U[]; + map(fn: (x: T) => U, obj: Functor): Functor; // used in functors + map(fn: (x: T) => U): (list: T[]) => U[]; + + /** + * The mapAccum function behaves like a combination of map and reduce. + */ + mapAccum(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; + mapAccum(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; + mapAccum(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; + + /** + * The mapAccumRight function behaves like a combination of map and reduce. + */ + mapAccumRight(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; + mapAccumRight(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; + mapAccumRight(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; + + + /** + * Like mapObj, but but passes additional arguments to the predicate function. + */ + mapObjIndexed(fn: (value: T, key: string, obj?: any) => TResult, obj: any): {[index:string]: TResult}; + mapObjIndexed(fn: (value: T, key: string, obj?: any) => TResult): (obj: any) => {[index:string]: TResult}; + + /** + * Tests a regular expression agains a String + */ + match(regexp: RegExp, str: string): any[]; + match(regexp: RegExp): (str: string) => any[]; + + + /** + * mathMod behaves like the modulo operator should mathematically, unlike the `%` + * operator (and by extension, R.modulo). So while "-17 % 5" is -2, + * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN + * when the modulus is zero or negative. + */ + mathMod(a: number, b: number): number; + mathMod(a: number): (b: number) => number; + + + /** + * Returns the larger of its two arguments. + */ + max(a: Ord, b: Ord): Ord; + max(a: Ord): (b: Ord) => Ord; + + /** + * Takes a function and two values, and returns whichever value produces + * the larger result when passed to the provided function. + */ + maxBy(keyFn: (a: T) => Ord, a: T, b: T): T; + maxBy(keyFn: (a: T) => Ord, a: T): (b: T) => T; + maxBy(keyFn: (a: T) => Ord): CurriedFunction2 + + /** + * Returns the mean of the given list of numbers. + */ + mean(list: number[]): number; + + /** + * Returns the median of the given list of numbers. + */ + median(list: number[]): number; + + /** + * Creates a new function that, when invoked, caches the result of calling fn for a given argument set and + * returns the result. Subsequent calls to the memoized fn with the same argument set will not result in an + * additional call to fn; instead, the cached result for that set of arguments will be returned. + */ + memoize(fn: Function): Function; + + /** + * Create a new object with the own properties of a + * merged with the own properties of object b. + * This function will *not* mutate passed-in objects. + */ + merge(a: T1, b: T2): T1 & T2; + merge(a: T1): (b: T2) => T1 & T2; + + + /** + * Merges a list of objects together into one object. + */ + mergeAll(list: any[]): T; + + /** + * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, + * the provided function is applied to the values associated with the key in each object, with the result being used as + * the value associated with the key in the returned object. The key will be excluded from the returned object if the + * resulting value is undefined. + */ + mergeWith(fn: (x: any, z: any) => any, a: U, b: V): U & V; + mergeWith(fn: (x: any, z: any) => any, a: U): (b: V) => U & V; + mergeWith(fn: (x: any, z: any) => any): (a: U, b: V) => U & V; + + /** + * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, + * the provided function is applied to the key and the values associated with the key in each object, with the + * result being used as the value associated with the key in the returned object. The key will be excluded from + * the returned object if the resulting value is undefined. + */ + mergeWithKey(fn: (str: string, x: any, z: any) => any, a: U, b: V): U & V; + mergeWithKey(fn: (str: string, x: any, z: any) => any, a: U): (b: V) => U & V; + mergeWithKey(fn: (str: string, x: any, z: any) => any): (a: U, b: V) => U & V; + + /** + * Returns the smaller of its two arguments. + */ + min(a: Ord, b: Ord): Ord; + min(a: Ord): (b: Ord) => Ord; + + /** + * Takes a function and two values, and returns whichever value produces + * the smaller result when passed to the provided function. + */ + minBy(keyFn: (a: T) => Ord, a: T, b: T): T; + minBy(keyFn: (a: T) => Ord, a: T): (b: T) => T; + minBy(keyFn: (a: T) => Ord): CurriedFunction2 + + /** + * Divides the second parameter by the first and returns the remainder. + * The flipped version (`moduloBy`) may be more useful curried. + * Note that this functions preserves the JavaScript-style behavior for + * modulo. For mathematical modulo see `mathMod` + */ + modulo(a: number, b: number): number; + modulo(a: number): (b: number) => number; + + /** + * Multiplies two numbers. Equivalent to a * b but curried. + */ + multiply(a: number, b: number): number; + multiply(a: number): (b: number) => number; + + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. + * Any extraneous parameters will not be passed to the supplied function. + */ + nAry(n: number, fn: (...arg: any[]) => any): Function; + + /** + * Negates its argument. + */ + negate(n: number): number; + + + /** + * Returns true if no elements of the list match the predicate, false otherwise. + */ + none(fn: (a: T) => boolean, list: T[]): boolean; + none(fn: (a: T) => boolean): (list: T[]) => boolean; + + + /** + * A function wrapping a call to the given function in a `!` operation. It will return `true` when the + * underlying function would return a false-y value, and `false` when it would return a truth-y one. + */ + not(value: any): boolean; + + /** + * Returns the nth element in a list. + */ + nth(n: number, list: T[]): T; + nth(n: number): (list: T[]) => T; + + /** + * Returns a function which returns its nth argument. + */ + nthArg(n: number): (...a: any[]) => any; + + /** + * Creates an object containing a single key:value pair. + */ + objOf(key: string, value: T): {string: T}; + objOf(key: string): (value: T) => {string: T}; + + /** + * Returns a singleton array containing the value provided. + */ + of(x: T): T[]; + //of(x: T[]): T[][]; unnecessary typing and introduced error in unless example + + /** + * Returns a partial copy of an object omitting the keys specified. + */ + omit(names: string[], obj: T): T; + omit(names: string[]): (obj: T) => T; + + /** + * Accepts a function fn and returns a function that guards invocation of fn such that fn can only ever be + * called once, no matter how many times the returned function is invoked. The first value calculated is + * returned in subsequent invocations. + */ + once(fn: Function): Function; + + /** + * A function that returns the first truthy of two arguments otherwise the last argument. Note that this is + * NOT short-circuited, meaning that if expressions are passed they are both evaluated. + * Dispatches to the or method of the first argument if applicable. + */ + or(a: T, b: U): T|U; + or(a: T): (b: U) => T|U; + or(fn1: T, val2: U): T|U; + or(fn1: T): (val2: U) => T|U; + + + /** + * Returns the result of "setting" the portion of the given data structure + * focused by the given lens to the given value. + */ + over(lens: Lens, fn: Arity1Fn, value: T): T; + over(lens: Lens, fn: Arity1Fn, value: T[]): T[]; + over(lens: Lens, fn: Arity1Fn): (value: T) => T; + over(lens: Lens, fn: Arity1Fn): (value: T[]) => T[]; + over(lens: Lens): (fn: Arity1Fn, value: T) => T; + over(lens: Lens): (fn: Arity1Fn, value: T[]) => T[]; + + + /** + * Takes two arguments, fst and snd, and returns [fst, snd]. + */ + pair(fst: F, snd: S): [F, S]; + + /** + * Accepts as its arguments a function and any number of values and returns a function that, + * when invoked, calls the original function with all of the values prepended to the + * original function's arguments list. In some libraries this function is named `applyLeft`. + */ + partial(fn: Function, ...args: any[]): Function; + + /** + * Accepts as its arguments a function and any number of values and returns a function that, + * when invoked, calls the original function with all of the values appended to the original + * function's arguments list. + */ + partialRight(fn: Function, ...args: any[]): Function; + + /** + * Takes a predicate and a list and returns the pair of lists of elements + * which do and do not satisfy the predicate, respectively. + */ + partition(fn: (a: string) => boolean, list: string[]): string[][]; + partition(fn: (a: T) => boolean, list: T[]): T[][]; + partition(fn: (a: T) => boolean): (list: T[]) => T[][]; + partition(fn: (a: string) => boolean): (list: string[]) => string[][]; + + /** + * Retrieve the value at a given path. + */ + path(path: string[], obj: any): T; + path(path: string[]): (obj: any) => T; + + /** + * Determines whether a nested path on an object has a specific value, + * in `R.equals` terms. Most likely used to filter a list. + */ + pathEq(path: string[], val: any, obj: any): boolean; + pathEq(path: string[], val: any): (obj: any) => boolean; + pathEq(path: string[]): (val: any, obj: any) => boolean; + pathEq(path: string[]): (val: any) => (obj: any) => boolean; + + /** + * If the given, non-null object has a value at the given path, returns the value at that path. + * Otherwise returns the provided default value. + */ + pathOr(d: T, p: string[], obj: any): T|any; + pathOr(d: T, p: string[]): (obj: any) => T|any; + pathOr(d: T): (p: string[], obj: any) => T|any; + + + /** + * Returns a partial copy of an object containing only the keys specified. If the key does not exist, the + * property is ignored. + */ + pick(names: string[], obj: T): U; + pick(names: string[]): (obj: T) => U; + + + /** + * Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist. + */ + pickAll(names: string[], obj: T): U; + pickAll(names: string[]): (obj: T) => U; + + + /** + * Returns a partial copy of an object containing only the keys that satisfy the supplied predicate. + */ + pickBy(pred: ObjPred, obj: T): U; + pickBy(pred: ObjPred): (obj: T) => U; + + + /** + * Creates a new function that runs each of the functions supplied as parameters in turn, + * passing the return value of each function invocation to the next function invocation, + * beginning with whatever arguments were passed to the initial invocation. + */ + pipe(fn0: (x0: V0) => T1): (x0: V0) => T1; + pipe(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; + + pipe(fn0: (x0: V0) => T1, fn1: (x: T1) => T2): (x0: V0) => T2; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1) => T2; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1, x2: V2) => T2; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x: V0) => T3; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1) => T3; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1, x2: V2) => T3; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x: V0) => T4; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1) => T4; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1, x2: V2) => T4; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x: V0) => T5; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1) => T5; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1, x2: V2) => T5; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x: V0) => T6; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1) => T6; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1, x2: V2) => T6; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn: (x: T6) => T7): (x: V0) => T7; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1) => T7; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1, x2: V2) => T7; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn: (x: T7) => T8): (x: V0) => T8; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T5) => T6, fn7: (x: T7) => T8): (x0: V0, x1: V1) => T8; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T5) => T6, fn7: (x: T7) => T8): (x0: V0, x1: V1, x2: V2) => T8; + + + /** + * Returns a new list by plucking the same named property off all objects in the list supplied. + */ + pluck(p: string|number, list: any[]): T[]; + pluck(p: string|number): (list: any[]) => T[]; + + /** + * Returns a new list with the given element at the front, followed by the contents of the + * list. + */ + prepend(el: T, list: T[]): T[]; + prepend(el: T): (list: T[]) => T[]; + + /** + * Multiplies together all the elements of a list. + */ + product(list: number[]): number; + + + /** + * Reasonable analog to SQL `select` statement. + */ + project(props: string[], objs: T[]): U[]; + + /** + * Returns a function that when supplied an object returns the indicated property of that object, if it exists. + * Note: TS1.9 # replace any by dictionary + */ + prop(p: string, obj: any): T; + prop(p: string): (obj: any) => T; + + /** + * Determines whether the given property of an object has a specific + * value according to strict equality (`===`). Most likely used to + * filter a list. + */ + // propEq(name: string, val: T, obj: {[index:string]: T}): boolean; + // propEq(name: string, val: T, obj: {[index:number]: T}): boolean; + propEq(name: string, val: T, obj: any): boolean; + // propEq(name: number, val: T, obj: any): boolean; + propEq(name: string, val: T): (obj: any) => boolean; + // propEq(name: number, val: T): (obj: any) => boolean; + propEq(name: string): (val: T, obj: any) => boolean; + // propEq(name: number): (val: T, obj: any) => boolean; + + /** + * Returns true if the specified object property is of the given type; false otherwise. + */ + propIs(type: any, name: string, obj: any): boolean; + propIs(type: any, name: string): (obj: any) => boolean; + propIs(type: any): { + (name: string, obj: any): boolean; + (name: string): (obj: any) => boolean; + } + + /** + * If the given, non-null object has an own property with the specified name, returns the value of that property. + * Otherwise returns the provided default value. + */ + propOr(val: T, p: string, obj: U): V; + propOr(val: T, p: string): (obj: U) => V; + propOr(val: T): (p: string, obj: U) => V; + + /** + * Returns the value at the specified property. + * The only difference from `prop` is the parameter order. + * Note: TS1.9 # replace any by dictionary + */ + props(ps: string[], obj: any): T[]; + props(ps: string[]): (obj: any) => T[]; + + /** + * Returns true if the specified object property satisfies the given predicate; false otherwise. + */ + propSatisfies(pred: (val: T) => boolean, name: string, obj: U): boolean; + propSatisfies(pred: (val: T) => boolean, name: string): (obj: U) => boolean; + propSatisfies(pred: (val: T) => boolean): CurriedFunction2; + + /** + * Returns a list of numbers from `from` (inclusive) to `to` + * (exclusive). In mathematical terms, `range(a, b)` is equivalent to + * the half-open interval `[a, b)`. + */ + range(from: number, to: number): number[]; + range(from: number): (to: number) => number[]; + + /** + * Returns a single item by iterating through the list, successively calling the iterator + * function and passing it an accumulator value and the current value from the array, and + * then passing the result to the next call. + */ + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult, list: T[]): TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced): (acc: TResult, list: T[]) => TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult): (list: T[]) => TResult; + + /** + * Groups the elements of the list according to the result of calling the String-returning function keyFn on each + * element and reduces the elements of each group to a single value via the reducer function valueFn. + */ + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string, list: T[]): {[index: string]: TResult}; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string): (list: T[]) => {[index: string]: TResult}; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult): CurriedFunction2<(elem: T) => string, T[], {[index: string]: TResult}>; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult): CurriedFunction3 string, T[], {[index: string]: TResult}>; + + /** + * Returns a value wrapped to indicate that it is the final value of the reduce and + * transduce functions. The returned value should be considered a black box: the internal + * structure is not guaranteed to be stable. + */ + reduced(elem: T): Reduced; + + /** + * Returns a single item by iterating through the list, successively calling the iterator + * function and passing it an accumulator value and the current value from the array, and + * then passing the result to the next call. + */ + reduceRight(fn: (acc: TResult, elem: T) => TResult, acc: TResult, list: T[]): TResult; + reduceRight(fn: (acc: TResult, elem: T) => TResult): (acc: TResult, list: T[]) => TResult; + reduceRight(fn: (acc: TResult, elem: T) => TResult, acc: TResult): (list: T[]) => TResult; + + /** + * Similar to `filter`, except that it keeps only values for which the given predicate + * function returns falsy. + */ + reject(fn: (value: T) => boolean, list: T[]): T[]; + reject(fn: (value: T) => boolean): (list: T[]) => T[]; + + /** + * Removes the sub-list of `list` starting at index `start` and containing `count` elements. + */ + remove(start: number, count: number, list: T[]): T[]; + remove(start: number): (count: number, list: T[]) => T[]; + remove(start: number, count: number): (list: T[]) => T[]; + + /** + * Returns a fixed list of size n containing a specified identical value. + */ + repeat(a: T, n: number): T[]; + repeat(a: T): (n: number) => T[]; + + + /** + * Replace a substring or regex match in a string with a replacement. + */ + replace(pattern: RegExp, replacement: string, str: string): string; + replace(pattern: RegExp, replacement: string): (str: string) => string; + replace(pattern: RegExp): (replacement: string) => (str: string) => string; + replace(pattern: String, replacement: string, str: string): string; + replace(pattern: String, replacement: string): (str: string) => string; + replace(pattern: String): (replacement: string) => (str: string) => string; + + + /** + * Returns a new list with the same elements as the original list, just in the reverse order. + */ + reverse(list: T[]): T[]; + + /** + * Scan is similar to reduce, but returns a list of successively reduced values from the left. + */ + scan(fn: (acc: TResult, elem: T) => any, acc: TResult, list: T[]): TResult[]; + scan(fn: (acc: TResult, elem: T) => any, acc: TResult): (list: T[]) => TResult[]; + scan(fn: (acc: TResult, elem: T) => any): (acc: TResult, list: T[]) => TResult[]; + + /** + * Returns the result of "setting" the portion of the given data structure focused by the given lens to the + * given value. + */ + set(lens: Lens, a: U, obj: T): T; + set(lens: Lens, a: U): (obj: T) => T; + set(lens: Lens): (a: U, obj: T) => T; + + /** + * Returns the elements from `xs` starting at `a` and ending at `b - 1`. + */ + slice(a: number, b: number, list: string): string; + slice(a: number, b: number, list: T[]): T[]; + slice(a: number, b: number): (list: string|T[]) => string|T[]; + slice(a: number): (b: number, list: string|T[]) => string|T[]; + + /** + * Returns a copy of the list, sorted according to the comparator function, which should accept two values at a + * time and return a negative number if the first value is smaller, a positive number if it's larger, and zero + * if they are equal. + */ + sort(fn: (a: T, b: T) => number, list: T[]): T[]; + sort(fn: (a: T, b: T) => number): (list: T[]) => T[]; + + + /** + * Sorts the list according to a key generated by the supplied function. + */ + sortBy(fn: (a: any) => string, list: T[]): T[]; + sortBy(fn: (a: any) => string): (list: T[]) => T[]; + + /** + * Splits a string into an array of strings based on the given + * separator. + */ + split(sep: string): (str: string) => string[]; + split(sep: RegExp): (str: string) => string[]; + split(sep: string, str: string): string[]; + split(sep: RegExp, str: string): string[]; + + /** + * Splits a given list or string at a given index. + */ + splitAt(index: number, list: T): T[]; + splitAt(index: number): (list: T) => T[]; + splitAt(index: number, list: T[]): T[][]; + splitAt(index: number): (list: T[]) => T[][]; + + /** + * Splits a collection into slices of the specified length. + */ + splitEvery(a: number, list: T[]): T[][]; + splitEvery(a: number): (list: T[]) => T[][]; + + + /** + * Takes a list and a predicate and returns a pair of lists with the following properties: + * - the result of concatenating the two output lists is equivalent to the input list; + * - none of the elements of the first output list satisfies the predicate; and + * - if the second output list is non-empty, its first element satisfies the predicate. + */ + splitWhen(pred: (val: T) => boolean, list: U[]): U[][]; + splitWhen(pred: (val: T) => boolean): (list: U[]) => U[][]; + + /** + * Subtracts two numbers. Equivalent to `a - b` but curried. + */ + subtract(a: number, b: number): number; + subtract(a: number): (b: number) => number; + + /** + * Adds together all the elements of a list. + */ + sum(list: number[]): number; + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. + */ + symmetricDifference(list1: T[], list2: T[]): T[]; + symmetricDifference(list: T[]): (list: T[]) => T[]; + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. + * Duplication is determined according to the value returned by applying the supplied predicate to two list elements. + */ + symmetricDifferenceWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + symmetricDifferenceWith(pred: (a: T, b: T) => boolean): CurriedFunction2; + + /** + * A function that always returns true. Any passed in parameters are ignored. + */ + T(): boolean; + + /** + * Returns all but the first element of a list. + */ + tail(list: T[]): T[]; + + /** + * Returns a new list containing the first `n` elements of the given list. If + * `n > * list.length`, returns a list of `list.length` elements. + */ + take(n: number, xs: T[]): T[]; + take(n: number, xs: string): string; + take(n: number): { + (xs: string): string; + (xs: T[]): T[]; + } + + + /** + * Returns a new list containing the last n elements of the given list. If n > list.length, + * returns a list of list.length elements. + */ + takeLast(n: number, xs: T[]): T[]; + takeLast(n: number, xs: string): string; + takeLast(n: number): { + (xs: T[]): T[]; + (xs: string): string; + } + + /** + * Returns a new list containing the last n elements of a given list, passing each value + * to the supplied predicate function, and terminating when the predicate function returns + * false. Excludes the element that caused the predicate function to fail. The predicate + * function is passed one argument: (value). + */ + takeLastWhile(pred: (a: T) => Boolean, list: T[]): T[]; + takeLastWhile(pred: (a: T) => Boolean): (list: T[]) => T[]; + + /** + * Returns a new list containing the first `n` elements of a given list, passing each value + * to the supplied predicate function, and terminating when the predicate function returns + * `false`. + */ + takeWhile(fn: (x: T) => boolean, list: T[]): T[]; + takeWhile(fn: (x: T) => boolean): (list: T[]) => T[]; + + /** + * The function to call with x. The return value of fn will be thrown away. + */ + tap(fn: (a: T) => any, value: T): T; + tap(fn: (a: T) => any): (value: T) => T; + + /** + * Determines whether a given string matches a given regular expression. + */ + test(regexp: RegExp, str: string): boolean; + test(regexp: RegExp): (str: string) => boolean; + + /** + * Calls an input function `n` times, returning an array containing the results of those + * function calls. + */ + times(fn: (i: number) => T, n: number): T[]; + times(fn: (i: number) => T): (n: number) => T[]; + + + /** + * The lower case version of a string. + */ + toLower(str: string): string; + + /** + * Converts an object into an array of key, value arrays. + * Only the object's own properties are used. + * Note that the order of the output array is not guaranteed to be + * consistent across different JS platforms. + */ + toPairs(obj: {[k: string]: S} | {[k: number]: S} | any): [F,S][]; + + /** + * Converts an object into an array of key, value arrays. + * The object's own properties and prototype properties are used. + * Note that the order of the output array is not guaranteed to be + * consistent across different JS platforms. + */ + toPairsIn(obj: {[k: string]: S} | {[k: number]: S} | any): [F,S][]; + + /** + * Returns the string representation of the given value. eval'ing the output should + * result in a value equivalent to the input value. Many of the built-in toString + * methods do not satisfy this requirement. + * + * If the given value is an [object Object] with a toString method other than + * Object.prototype.toString, this method is invoked with no arguments to produce the + * return value. This means user-defined constructor functions can provide a suitable + * toString method. + */ + toString(val: T): string; + + /** + * The upper case version of a string. + */ + toUpper(str: string): string; + + /** + * Initializes a transducer using supplied iterator function. Returns a single item by iterating through the + * list, successively calling the transformed iterator function and passing it an accumulator value and the + * current value from the array, and then passing the result to the next call. + */ + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[], list: T[]): U; + transduce(xf: (arg: T[]) => T[]): (fn: (acc: U[], val: U) => U[], acc: T[], list: T[]) => U; + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[]): (acc: T[], list: T[]) => U; + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[]): (list: T[]) => U; + + /** + * Transposes the rows and columns of a 2D list. When passed a list of n lists of length x, returns a list of x lists of length n. + */ + transpose(list: any[][]): any[][]; + + /** + * Removes (strips) whitespace from both ends of the string. + */ + trim(str: string): string; + + /** + * tryCatch takes two functions, a tryer and a catcher. The returned function evaluates the tryer; if it does + * not throw, it simply returns the result. If the tryer does throw, the returned function evaluates the catcher + * function and returns its result. Note that for effective composition with this function, both the tryer and + * catcher functions must return the same type of results. + */ + tryCatch(tryer: (...args: any[]) => T, catcher: (...args: any[]) => T, x: any): T; + + /** + * Gives a single-word string description of the (native) type of a value, returning such answers as 'Object', + * 'Number', 'Array', or 'Null'. Does not attempt to distinguish user Object types any further, reporting them + * all as 'Object'. + */ + type(val: any): string; + + /** + * Takes a function fn, which takes a single array argument, and returns a function which: + * - takes any number of positional arguments; + * - passes these arguments to fn as an array; and + * - returns the result. + * In other words, R.unapply derives a variadic function from a function which takes an array. + * R.unapply is the inverse of R.apply. + */ + unapply(fn: (args: any[]) => T): (...args: any[]) => T; + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly 1 parameter. + * Any extraneous parameters will not be passed to the supplied function. + */ + unary(fn: (a: T, ...args: any[]) => any): (a: T) => any + + /** + * Returns a function of arity n from a (manually) curried function. + */ + uncurryN(len: number, fn: (a: any) => any): (...a: any[]) => T; + + /** + * Builds a list from a seed value. Accepts an iterator function, which returns either false + * to stop iteration or an array of length 2 containing the value to add to the resulting + * list and the seed to be used in the next call to the iterator function. + */ + unfold(fn: (seed: T) => TResult[]|boolean, seed: T): TResult[]; + unfold(fn: (seed: T) => TResult[]|boolean): (seed: T) => TResult[]; + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the + * elements of each list. + */ + union(as: T[], bs: T[]): T[]; + union(as: T[]): (bs: T[]) => T[]; + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is + * determined according to the value returned by applying the supplied predicate to two list elements. + */ + unionWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + unionWith(pred: (a: T, b: T) => boolean): CurriedFunction2 + + /** + * Returns a new list containing only one copy of each element in the original list. + */ + uniq(list: T[]): T[]; + + /** + * Returns a new list containing only one copy of each element in the original list, based upon the value returned by applying the supplied function to each list element. Prefers the first item if the supplied function produces the same value on two items. R.equals is used for comparison. + */ + uniqBy(fn: (a: T) => U, list: T[]): T[]; + uniqBy(fn: (a: T) => U): (list: T[]) => T[]; + + /** + * Returns a new list containing only one copy of each element in the original list, based upon the value + * returned by applying the supplied predicate to two list elements. + */ + uniqWith(pred: (x: T, y: T) => boolean, list: T[]): T[]; + uniqWith(pred: (x: T, y: T) => boolean): (list: T[]) => T[]; + + /** + * Tests the final argument by passing it to the given predicate function. If the predicate is not satisfied, + * the function will return the result of calling the whenFalseFn function with the same argument. If the + * predicate is satisfied, the argument is returned as is. + */ + unless(pred: (a: T) => boolean, whenFalseFn: (a: T) => U, obj: T): U; + unless(pred: (a: T) => boolean, whenFalseFn: (a: T) => U): (obj: T) => U; + + /** + * Returns a new list by pulling every item at the first level of nesting out, and putting + * them in a new array. + */ + unnest(x: T[][]): T[]; + unnest(x: T[]): T[]; + + /** + * Takes a predicate, a transformation function, and an initial value, and returns a value of the same type as + * the initial value. It does so by applying the transformation until the predicate is satisfied, at which point + * it returns the satisfactory value. + */ + until(pred: (val: T) => boolean, fn: (val: T) => U, init: U): U; + until(pred: (val: T) => boolean, fn: (val: T) => U): (init: U) => U; + + /** + * Returns a new copy of the array with the element at the provided index replaced with the given value. + */ + update(index: number, value: T, list: T[]): T[]; + update(index: number, value: T): (list: T[]) => T[]; + + /** + * Accepts a function fn and a list of transformer functions and returns a new curried function. + * When the new function is invoked, it calls the function fn with parameters consisting of the + * result of calling each supplied handler on successive arguments to the new function. + * + * If more arguments are passed to the returned function than transformer functions, those arguments + * are passed directly to fn as additional parameters. If you expect additional arguments that don't + * need to be transformed, although you can ignore them, it's best to pass an identity function so + * that the new function reports the correct arity. + */ + useWith(fn: Function, transformers: Function[]): Function; + + /** + * Returns a list of all the enumerable own properties of the supplied object. + * Note that the order of the output array is not guaranteed across + * different JS platforms. + */ + values(obj: {[index: string]: T}): T[]; + values(obj: any): T[]; + + /** + * Returns a list of all the properties, including prototype properties, of the supplied + * object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. + */ + valuesIn(obj: any): T[]; + + /** + * Returns a "view" of the given data structure, determined by the given lens. The lens's focus determines which + * portion of the data structure is visible. + */ + view(lens: Lens, obj: T): U; + + /** + * Tests the final argument by passing it to the given predicate function. If the predicate is satisfied, the function + * will return the result of calling the whenTrueFn function with the same argument. If the predicate is not satisfied, + * the argument is returned as is. + */ + when(pred: (a: T) => boolean, whenTrueFn: (a: T) => U, obj: T): U; + when(pred: (a: T) => boolean, whenTrueFn: (a: T) => U): (obj: T) => U; + + /** + * Takes a spec object and a test object and returns true if the test satisfies the spec. + * Any property on the spec that is not a function is interpreted as an equality + * relation. + * + * If the spec has a property mapped to a function, then `where` evaluates the function, passing in + * the test object's value for the property in question, as well as the whole test object. + * + * `where` is well suited to declarativley expressing constraints for other functions, e.g., + * `filter`, `find`, `pickWith`, etc. + */ + where(spec: T, testObj: U): boolean; + where(spec: T): (testObj: U) => boolean; + where(spec: ObjFunc2, testObj: U): boolean; + where(spec: ObjFunc2): (testObj: U) => boolean; + + /** + * Takes a spec object and a test object; returns true if the test satisfies the spec, + * false otherwise. An object satisfies the spec if, for each of the spec's own properties, + * accessing that property of the object gives the same value (in R.eq terms) as accessing + * that property of the spec. + */ + whereEq(spec: T, obj: U): boolean; + whereEq(spec: T): (obj: U) => boolean; + + /** + * Returns a new list without values in the first argument. R.equals is used to determine equality. + * Acts as a transducer if a transformer is given in list position. + */ + without(list1: T[], list2: T[]): T[]; + without(list1: T[]): (list2: T[]) => T[]; + + /** + * Wrap a function inside another to allow you to make adjustments to the parameters, or do other processing + * either before the internal function is called or with its results. + */ + wrap(fn: Function, wrapper: Function): Function; + + /** + * Creates a new list out of the two supplied by creating each possible pair from the lists. + */ + xprod(as: K[], bs: V[]): KeyValuePair[]; + xprod(as: K[]): (bs: V[]) => KeyValuePair[]; + + /** + * Creates a new list out of the two supplied by pairing up equally-positioned items from + * both lists. Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. + */ + zip(list1: K[], list2: V[]): KeyValuePair[]; + zip(list1: K[]): (list2: V[]) => KeyValuePair[]; + + /** + * Creates a new object out of a list of keys and a list of values. + */ + // TODO: Dictionary as a return value is to specific, any seems to loose + zipObj(keys: string[], values: T[]): {[index:string]: T}; + zipObj(keys: string[]): (values: T[]) => {[index:string]: T}; + + + /** + * Creates a new list out of the two supplied by applying the function to each + * equally-positioned pair in the lists. + */ + zipWith(fn: (x: T, y: U) => TResult, list1: T[], list2: U[]): TResult[]; + zipWith(fn: (x: T, y: U) => TResult, list1: T[]): (list2: U[]) => TResult[]; + zipWith(fn: (x: T, y: U) => TResult): (list1: T[], list2: U[]) => TResult[]; + + } +} + +export = R; From 5433909c8b63d013257193c4dec60ac93ce05d77 Mon Sep 17 00:00:00 2001 From: Erwin Poeze Date: Tue, 16 Aug 2016 08:38:54 +0200 Subject: [PATCH 08/56] ramda typings --- ramda/ramda-tests.ts | 1952 ++++++++++++++++++++++++++++++++++++++++++ ramda/ramda.d.ts | 1807 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 3759 insertions(+) create mode 100644 ramda/ramda-tests.ts create mode 100644 ramda/ramda.d.ts diff --git a/ramda/ramda-tests.ts b/ramda/ramda-tests.ts new file mode 100644 index 0000000000..15ec5eb274 --- /dev/null +++ b/ramda/ramda-tests.ts @@ -0,0 +1,1952 @@ +import * as R from './ramda'; + +var double = function(x: number): number { + return x + x +}; + +var shout = function(x: number): string { + return x >= 10 + ? 'big' + : 'small' +}; + +class F { + x = 'X'; + y = 'Y'; +} +class F2 { + a = 100; + y = 1; + x(){}; + z() {}; +} + +(() => { + var x: boolean; + x = R.isArrayLike('a'); + x = R.isArrayLike([1,2,3]); + x = R.isArrayLike([]); +}); + +(() => { + R.propIs(Number, 'x', {x: 1, y: 2}); //=> true + R.propIs(Number, 'x')({x: 1, y: 2}); //=> true + R.propIs(Number)('x', {x: 1, y: 2}); //=> true + R.propIs(Number)('x')({x: 1, y: 2}); //=> true + R.propIs(Number, 'x', {x: 'foo'}); //=> false + R.propIs(Number, 'x', {}); //=> false +}); + +(() => { + R.type({}); //=> "Object" + R.type(1); //=> "Number" + R.type(false); //=> "Boolean" + R.type('s'); //=> "String" + R.type(null); //=> "Null" + R.type([]); //=> "Array" + R.type(/[A-z]/); //=> "RegExp" +}); + +() => { + var takesNoArg = function() { return true; }; + var takesOneArg = function(a: number) { return [a]; }; + var takesTwoArgs = function(a: number, b: number) { return [a, b]; }; + var takesThreeArgs = function(a: number, b: number, c: number) { return [a, b, c]; }; + + var addFourNumbers = function(a: number, b: number, c: number, d: number): number { + return a + b + c + d; + }; + + var x1: Function = R.curry(addFourNumbers) + // because of the current way of currying, the following call results in a type error + // var x2: Function = R.curry(addFourNumbers)(1,2,4) + var x3: Function = R.curry(addFourNumbers)(1)(2) + var x4: Function = R.curry(addFourNumbers)(1)(2)(3) + var y1: number = R.curry(addFourNumbers)(1)(2)(3)(4) + var y2: number = R.curry(addFourNumbers)(1,2)(3,4) + var y3: number = R.curry(addFourNumbers)(1,2,3)(4) + + R.nAry(0, takesNoArg); + R.nAry(0, takesOneArg); + R.nAry(1, takesTwoArgs); + R.nAry(1, takesThreeArgs); + + var u1: {(a: any): any} = R.unary(takesOneArg); + var u2: {(a: any): any} = R.unary(takesTwoArgs); + var u3: {(a: any): any} = R.unary(takesThreeArgs); + + R.binary(takesTwoArgs); + R.binary(takesThreeArgs); + + var addTwoNumbers = function(a:number, b:number) { return a + b; } + var addTwoNumbersCurried = R.curry(addTwoNumbers); + + var inc = addTwoNumbersCurried(1); + var z1:number = inc(2); + var z2:number = addTwoNumbersCurried(2,3); +} + +() => { + const addFour = (a:number) => (b:number) => (c:number) => (d:number) => a + b + c + d; + const uncurriedAddFour = R.uncurryN(4, addFour); + const res: number = uncurriedAddFour(1, 2, 3, 4); //=> 10 +} + +() => { + // coerceArray :: (a|[a]) -> [a] + const coerceArray = R.unless(R.isArrayLike, R.of); + const a: number[] = coerceArray([1, 2, 3]); //=> [1, 2, 3] + const b: number[] = coerceArray(1); //=> [1] +} + +(() => { + R.nthArg(1)('a', 'b', 'c'); //=> 'b' + R.nthArg(-1)('a', 'b', 'c'); //=> 'c' +}); + +() => { + const fn: (...args: string[])=>string = R.unapply(JSON.stringify); + const res: string = R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]' +} + +() => { + const a: number = R.until(R.flip(R.gt)(100), R.multiply(2))(1) // => 128 +} + +() => { + const truncate = R.when( + R.propSatisfies(R.flip(R.gt)(10), 'length'), + R.pipe(R.take(10), R.append('…'), R.join('')) + ); + const a: string = truncate('12345'); //=> '12345' + const b: string = truncate('0123456789ABC'); //=> '0123456789…' +} + +/* compose */ +() => { + var double = function(x: number): number { + return x + x + } + var limit10 = function(x: number): boolean { + return x >= 10 + } + var func: (x: number) => boolean = R.compose(limit10, double) + var res: boolean = R.compose(limit10, double)(10) + + const f0 = (s: string) => +s; // string -> number + const f1 = (n: number) => n === 1; // number -> boolean + const f2 = R.compose(f1, f0); // string -> boolean + + // akward example that bounces types between number and string + const g0 = (list: number[]) => R.map(R.inc, list); + const g1 = R.dropWhile(R.gt(10)); + const g2 = R.map((i: number) => i > 5 ? 'bigger' : 'smaller'); + const g3 = R.all((i: string) => i === 'smaller'); + const g = R.compose(g3, g2, g1, g0); + const g_res: boolean = g([1, 2, 10, 13]); +} + +/* pipe */ +() => { + var func: (x: number) => string = R.pipe(double, double, shout) + var res: string = R.pipe(double, double, shout)(10); + + const capitalize = (str: string) => R.pipe( + R.split(''), + R.adjust(R.toUpper, 0), + R.join('') + )(str); + + var f = R.pipe(Math.pow, R.negate, R.inc); + var fr: number = f(3, 4); // -(3^4) + 1 +} + +() => { + R.invoker('charAt', String.prototype); + R.invoker('charAt', String.prototype, 1); +} + +(() => { + const range = R.juxt([Math.min, Math.max]); + range(3, 4, 9, -3); //=> [-3, 9] + + const chopped = R.juxt([R.head, R.last]); + chopped('longstring'); // => ["l", "g"] +}); + +var square = function(x: number) { return x * x; }; +var add = function(a: number, b: number) { return a + b; }; +// Adds any number of arguments together +var addAll = function() { + return 0; +}; + +// Basic example +R.useWith(addAll, [ double, square ]); + +(() => { + var printXPlusFive = function(x: number) { console.log(x + 5); }; + R.forEach(printXPlusFive, [1, 2, 3]); + R.clone([{},{},{}]) + R.clone([1,2,3]); +})(); + +// (() => { +// var printXPlusFive = function(x, i) { console.log(i + 5); }; +// R.forEach.idx(printXPlusFive, [{name: 1}, {name: 2}, {name: 3}]); +// })(); + +var i = function(x: number) {return x;}; +R.times(i, 5); + +(() => { + var triple = function(x: number): number { return x * 3; }; + var square = function(x: number): number { return x * x; }; + var squareThenDoubleThenTriple = R.pipe(square, double, triple); + squareThenDoubleThenTriple(5); //=> 150 + + +})(); + +(() => { + var multiply = function(a: number, b: number) { return a * b; }; + var double = R.partial(multiply, 2); + double(2); //=> 4 + + var greet = function(salutation: string, title: string, firstName: string, lastName: string) { + return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; + }; + var sayHello = R.partial(greet, 'Hello'); + var sayHelloToMs = R.partial(sayHello, 'Ms.'); + sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' + + var greetMsJaneJones = R.partialRight(greet, 'Ms.', 'Jane', 'Jones'); + greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' +})(); + +(() => { + var numberOfCalls = 0; + var trackedAdd = function(a: number, b: number) { + numberOfCalls += 1; + return a + b; + }; + var memoTrackedAdd = R.memoize(trackedAdd); + + memoTrackedAdd(1, 2); //=> 3 + numberOfCalls; //=> 1 + memoTrackedAdd(1, 2); //=> 3 + numberOfCalls; //=> 1 + memoTrackedAdd(2, 3); //=> 5 + numberOfCalls; //=> 2 + + // Note that argument order matters + memoTrackedAdd(2, 1); //=> 3 + numberOfCalls; //=> 3 +})(); + +(() => { + var addOneOnce = R.once(function(x: number){ return x + 1; }); + addOneOnce(10); //=> 11 + addOneOnce(addOneOnce(50)); //=> 11 +})(); + +(() => { + var slashify = R.wrap(R.flip(R.add)('/'), function(f: Function, x: string) { + return R.match(/\/$/, x) ? x : f(x); + }); + + slashify('a'); //=> 'a/' + slashify('a/'); //=> 'a/' +})(); + + + +(() => { + var numbers = [1, 2, 3]; + var add = function(a: number, b: number) { + return a + b + }; + R.reduce(add, 10, numbers); //=> 16; +})(); + +(() => { + var plus3 = R.add(3); +})(); + +(() => { + var pairs = [ ['a', 1], ['b', 2], ['c', 3] ]; + var flattenPairs = function(acc: [string, number], pair: [string, number]) { + return acc.concat(pair); + }; + R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] +})(); + +(() => { + var values = { x: 1, y: 2, z: 3 }; + var prependKeyAndDouble = function(num: number, key: string, obj: any) { + return key + (num * 2); + }; + R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' } +}); + +(() => { + const a: number[] = R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + const b: number[][] = R.of([1]); //=> [[1]] + const c: number[] = R.of(1); + +}); + +() => { + const a1 = R.empty([1,2,3,4,5]); //=> [] + const a2 = R.empty([1, 2, 3]); //=> [] + const a3 = R.empty('unicorns'); //=> '' + const a4 = R.empty({x: 1, y: 2}); //=> {} +} + +(() => { + R.length([1, 2, 3]); //=> 3 +}); + +(() => { + const isEven = function(n: number) { + return n % 2 === 0; + }; + const filterIndexed = R.addIndex(R.filter); + + R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + + var lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] + + var isOdd = function(n: number) { + return n % 2 === 1; + }; + R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] +}); +(() => { + var isNotFour = function(x: number) { + return !(x === 4); + }; + R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] + R.take(2, [1, 2, 3, 4]); //=> [1, 2] +}); +(() => { + var f = function(n: number) { return n > 50 ? false : [-n, n + 10] }; + let a = R.unfold(f, 10); //=> [-10, -20, -30, -40, -50] + let b = R.unfold(f); //=> [-10, -20, -30, -40, -50] + let c = b(10); +}); +/***************************************************************** + * Function category + */ + + + () => { + var mergeThree = function(a: number, b: number, c: number): number[] { + return ([]).concat(a, b, c); + }; + mergeThree(1, 2, 3); //=> [1, 2, 3] + var flipped = R.flip(mergeThree); + flipped(1, 2, 3); //=> [2, 1, 3] + } + +/********************* + * List category + ********************/ +() => { + var lessThan2 = R.flip(R.lt)(2); + var lessThan3 = R.flip(R.lt)(3); + R.all(lessThan2)([1, 2]); //=> false + R.all(lessThan3)([1, 2]); //=> true +} + +() => { + var lessThan0 = R.flip(R.lt)(0); + var lessThan2 = R.flip(R.lt)(2); + R.any(lessThan0)([1, 2]); //=> false + R.any(lessThan2)([1, 2]); //=> true +} + +() => { + R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]] + R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + R.aperture(7, [1, 2, 3, 4, 5]); //=> [] + R.aperture(7)([1, 2, 3, 4, 5]); //=> [] +} + +() => { + R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] + R.append('tests')(['write', 'more']); //=> ['write', 'more', 'tests'] + R.append('tests', []); //=> ['tests'] + R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'])(['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'])(['write', 'more']); //=> ['write', 'more', ['tests']] +} + +() => { + var duplicate = function(n: number) { + return [n, n]; + }; + R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] + R.chain(duplicate)([1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] +} + +() => { + R.clamp(1, 10, -1) // => 1 + R.clamp(1, 10)(11) // => 10 + R.clamp(1)(10, 4) // => 4 + R.clamp('a', 'd', 'e') // => 'd' +} + +() => { + R.concat([], []); //=> [] + R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + R.concat([4, 5, 6])([1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + R.concat('ABC')('DEF'); // 'ABCDEF' +} + +() => { + R.contains(3)([1, 2, 3]); //=> true + R.contains(3, [1, 2, 3]); //=> true + R.contains(4)([1, 2, 3]); //=> false + R.contains({})([{}, {}]); //=> false + var obj = {}; + R.contains(obj)([{}, obj, {}]); //=> true +} + +() => { + R.drop(3, [1,2,3,4,5,6,7]); //=> [4,5,6,7] + R.drop(3)([1,2,3,4,5,6,7]); //=> [4,5,6,7] + R.drop(3, 'ramda'); //=> 'ram' + R.drop(3)('ramda'); //=> 'ram' +} + +(() => { + R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] + R.dropLast(2)(['foo', 'bar', 'baz']); //=> ['foo'] + R.dropLast(3, 'ramda'); //=> 'ra' + R.dropLast(3)('ramda'); //=> 'ra' +}); + +(() => { + var lteThree = (x: number) => x <= 3; + R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4] +}); + +() => { + var lteTwo = function(x: number) { + return x <= 2; + }; + R.dropWhile(lteTwo, [1, 2, 3, 4]); //=> [3, 4] + R.dropWhile(lteTwo)([1, 2, 3, 4]); //=> [3, 4] +} + +() => { + var isEven = function(n: number) { + return n % 2 === 0; + }; + R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + var isEvenFn = R.filter(isEven); + isEvenFn([1, 2, 3, 4]); +} + +() => { + var lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + var filterIndexed = R.addIndex(R.filter); + + filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] + var lastTwoFn = filterIndexed(lastTwo); + lastTwoFn([8, 6, 7, 5, 3, 0, 9]); +} + +() => { + var xs = [{a: 1}, {a: 2}, {a: 3}]; + R.find(R.propEq('a', 2))(xs); //=> {a: 2} + R.find(R.propEq('a', 4))(xs); //=> undefined +} + +() => { + var xs = [{a: 1}, {a: 2}, {a: 3}]; + R.findIndex(R.propEq('a', 2))(xs); //=> 1 + R.findIndex(R.propEq('a', 4))(xs); //=> -1 + + R.findIndex((x: number) => x === 1, [1, 2, 3]); +} + +() => { + var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} + R.findLast(R.propEq('a', 4))(xs); //=> undefined +} + +() => { + var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 + R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 + R.findLastIndex((x: number) => x === 1, [1, 2, 3]); +} +() => { + var user1 = { address: { zipCode: 90210 } }; + var user2 = { address: { zipCode: 55555 } }; + var user3 = { name: 'Bob' }; + var users = [ user1, user2, user3 ]; + var isFamous = R.pathEq(['address', 'zipCode'], 90210); + R.filter(isFamous, users); //=> [ user1 ] +} +() => { + var xs: {[key:string]: string} = {a: '1', b: '0'}; + R.propEq('a', '1', xs);//=> true + R.propEq('a', '4', xs); //=> false +} +() => { + var xs: {[key:string]: number} = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} +() => { + var xs = {a: '1', b: '0'}; + R.propEq('a', '1', xs);//=> true + R.propEq('a', '4', xs); //=> false +} +() => { + var xs = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} + +interface Obj { a: number; b: number }; +() => { + var xs: Obj = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} + +() => { + R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); + //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] +} + +() => { + var printXPlusFive = function(x: number) { console.log(x + 5); }; + R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] + R.forEach(printXPlusFive)([1, 2, 3]); //=> [1, 2, 3] + //-> 6 + //-> 7 + //-> 8 +} + +() => { + var plusFive = function(num: number, idx: number, list: number[]) { list[idx] = num + 5 }; + R.addIndex(R.forEach)(plusFive)([1, 2, 3]); //=> [6, 7, 8] +} + +() => { + var byGrade = R.groupBy(function(student: {score: number; name: string}) { + var score = student.score; + return score < 65 ? 'F' : + score < 70 ? 'D' : + score < 80 ? 'C' : + score < 90 ? 'B' : 'A'; + }); + var students = [{name: 'Abby', score: 84}, + {name: 'Eddy', score: 58}, + {name: 'Jack', score: 69}]; + byGrade(students); +} + +() => { + R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + // [[0], [1, 1], [2, 3, 5, 8, 13, 21]] + + R.groupWith((a: number, b: number) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + // [[0], [1, 1], [2], [3, 5], [8], [13, 21]] + + const isVowel = (a: string) => R.contains(a, 'aeiou') ? a : ''; + R.groupWith(R.eqBy(isVowel), 'aestiou') + // ['ae', 'st', 'iou'] +} + +() => { + R.head(['fi', 'fo', 'fum']); //=> 'fi' + R.head([10, 'ten']); // => 10 + R.head(['10', 10]); // => '10' +} + +(() => { + let list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}]; + const a1 = R.indexBy(R.prop('id'), list); + const a2 = R.indexBy(R.prop('id'))(list); + const a3 = R.indexBy<{id:string}>(R.prop('id'))(list); +}); + +() => { + R.indexOf(3, [1,2,3,4]); //=> 2 + R.indexOf(10)([1,2,3,4]); //=> -1 +} + +() => { + R.init(['fi', 'fo', 'fum']); //=> ['fi', 'fo'] +} + +() => { + R.insert(2, 5, [1,2,3,4]); //=> [1,2,5,3,4] + R.insert(2)(5, [1,2,3,4]); //=> [1,2,5,3,4] + R.insert(2, 5)([1,2,3,4]); //=> [1,2,5,3,4] +} + +() => { + R.insertAll(2, [10,11,12], [1,2,3,4]); + R.insertAll(2)([10,11,12], [1,2,3,4]); + R.insertAll(2, [10,11,12])([1,2,3,4]); +} + +() => { + var numbers = [1, 2, 3, 4]; + var transducer = R.compose(R.map(R.add(1)), R.take(2)); + + R.into([], transducer, numbers); //=> [2, 3] + + var intoArray = R.into([]); + intoArray(transducer, numbers); //=> [2, 3] +} + +() => { + var spacer = R.join(' '); + spacer(['a', 2, 3.4]); //=> 'a 2 3.4' + R.join('|', [1, 2, 3]); //=> '1|2|3' +} + +() => { + R.last(['fi', 'fo', 'fum']); //=> 'fum' +} + +() => { + R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 + R.lastIndexOf(10, [1,2,3,4]); //=> -1 +} + +() => { + R.length([]); //=> 0 + R.length([1, 2, 3]); //=> 3 +} + +() => { + var headLens = R.lensIndex(0); + headLens([10, 20, 30, 40]); //=> 10 + headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40] + R.view(headLens, ['a', 'b', 'c']); //=> 'a' + R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] +} + +() => { + var double = function(x: number) { + return x * 2; + }; + R.map(double, [1, 2, 3]); //=> [2, 4, 6] + + // functor + const stringFunctor = { + map: (fn: (c: number) => number) => { + var chars = "Ifmmp!Xpsme".split(""); + return chars.map((char) => String.fromCharCode(fn(char.charCodeAt(0)))).join(""); + } + }; + R.map((x: number) => x-1, stringFunctor); // => "Hello World" +} + +() => { + var digits = ['1', '2', '3', '4']; + var append = function(a: string, b: string): [string, string]{ + return [a + b, a + b]; + } + R.mapAccum(append, '0', digits); //=> ['01234', ['01', '012', '0123', '01234']] + R.mapAccum(append)('0', digits); //=> ['01234', ['01', '012', '0123', '01234']] + R.mapAccum(append, '0')(digits); //=> ['01234', ['01', '012', '0123', '01234']] +} + +() => { + var digits = ['1', '2', '3', '4']; + var append = function(a: string, b: string): [string, string] { + return [a + b, a + b]; + } + + R.mapAccumRight(append, '0', digits); //=> ['04321', ['04321', '0432', '043', '04']] + R.mapAccumRight(append)('0', digits); //=> ['04321', ['04321', '0432', '043', '04']] + R.mapAccumRight(append, '0')(digits); //=> ['04321', ['04321', '0432', '043', '04']] +} + +() => { + var squareEnds = function(elt: number, idx: number, list: number[]) { + if (idx === 0 || idx === list.length - 1) { + return elt * elt; + } + return elt; + }; + R.addIndex(R.map)(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] + R.addIndex(R.map)(squareEnds)([8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] +} + +() => { + R.none(R.isNaN, [1, 2, 3]); //=> true + R.none(R.isNaN, [1, 2, 3, NaN]); //=> false + R.none(R.isNaN)([1, 2, 3, NaN]); //=> false +} + +() => { + var list = ['foo', 'bar', 'baz', 'quux']; + R.nth(1, list); //=> 'bar' + R.nth(-1, list); //=> 'quux' + R.nth(-99, list); //=> undefined + R.nth(-99)(list); //=> undefined +} + +() => { + R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']); + R.partition(R.contains('s'))(['sss', 'ttt', 'foo', 'bars']); + R.partition((x: number) => x > 2, [1, 2, 3, 4]); + R.partition((x: number) => x > 2)([1, 2, 3, 4]); +} + +() => { + const a = R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2] + const b = R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3] +} + +() => { + R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] + R.prepend('fee')(['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] +} + +() => { + R.range(1, 5); //=> [1, 2, 3, 4] + R.range(50)(53); //=> [50, 51, 52] +} + +() => { + var numbers = [1, 2, 3]; + var add = function(a: number, b: number) { + return a + b; + }; + R.reduce(add, 10, numbers); //=> 16 + R.reduce(add)(10, numbers); //=> 16 + R.reduce(add, 10)(numbers); //=> 16 +} + +interface Student { + name: string; + score: number; +} +() => { + const reduceToNamesBy = R.reduceBy((acc: string[], student: Student) => acc.concat(student.name), []); + const namesByGrade = reduceToNamesBy(function(student) { + let score = student.score; + return score < 65 ? 'F' : + score < 70 ? 'D' : + score < 80 ? 'C' : + score < 90 ? 'B' : 'A'; + }); + let students = [{name: 'Lucy', score: 92}, + {name: 'Drew', score: 85}, + {name: 'Bart', score: 62}]; + const names = namesByGrade(students); + // { + // 'A': ['Lucy'], + // 'B': ['Drew'] + // 'F': ['Bart'] + // } +} + +() => { + var reduceIndexed = R.addIndex(R.reduce); + var letters = ['a', 'b', 'c']; + var objectify = function(accObject: {[elem:string]: number}, elem: string, idx: number, list: string[]) { + accObject[elem] = idx; + return accObject; + }; + reduceIndexed(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } + reduceIndexed(objectify)({}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } + reduceIndexed(objectify, {})(letters); //=> { 'a': 0, 'b': 1, 'c': 2 } +} + +interface KeyValuePair extends Array { 0 : K; 1 : V; } +type Pair = KeyValuePair +() => { + var pairs: Pair[] = [ ['a', 1], ['b', 2], ['c', 3] ]; + var flattenPairs = function(acc: Pair[], pair: Pair): Pair[] { + return acc.concat(pair); + }; + R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + R.reduceRight(flattenPairs, [])(pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + R.reduceRight(flattenPairs)([], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] +} + +() => { + var isOdd = function(n: number) { + return n % 2 === 1; + }; + R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] + R.reject(isOdd)([1, 2, 3, 4]); //=> [2, 4] +} + +() => { + const lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + const rejectIndexed = R.addIndex(R.reject); + rejectIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] + rejectIndexed(lastTwo)([8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] +} + +() => { + R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + R.remove(2, 3)([1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + R.remove(2)(3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] +} + +() => { + R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] + var obj = {}; + var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}] + repeatedObjs[0] === repeatedObjs[1]; //=> true +} + +() => { + R.reverse([1, 2, 3]); //=> [3, 2, 1] + R.reverse([1, 2]); //=> [2, 1] + R.reverse([1]); //=> [1] + R.reverse([]); //=> [] +} + +() => { + var numbers = [1, 2, 3, 4]; + R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24] + R.scan(R.multiply, 1)(numbers); //=> [1, 1, 2, 6, 24] + R.scan(R.multiply)(1, numbers); //=> [1, 1, 2, 6, 24] +} + +() => { + var xs = R.range(0, 10); + R.slice(2, 5, xs); //=> [2, 3, 4] + R.slice(2, 5)(xs); //=> [2, 3, 4] + R.slice(2)(5, xs); //=> [2, 3, 4] + + var str = 'Hello World'; + R.slice(2, 5, str); //=> 'llo' + R.slice(2, 5)(str); //=> 'llo' + R.slice(2)(5, str); //=> 'llo' +} + +() => { + var diff = function(a: number, b: number) { return a - b; }; + R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] + R.sort(diff)([4,2,7,5]); //=> [2, 4, 5, 7] +} + +() => { + const fn = R.cond([ + [R.equals(0), R.always('water freezes at 0°C')], + [R.equals(100), R.always('water boils at 100°C')], + [R.T, (temp: number) => 'nothing special happens at ' + temp + '°C'] + ]); + const a: string = fn(0); //=> 'water freezes at 0°C' + const b: string = fn(50); //=> 'nothing special happens at 50°C' + const c: string = fn(100); //=> 'water boils at 100°C' +} + +() => { + R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum'] + R.tail([1, 2, 3]); //=> [2, 3] +} + +() => { + R.take(3,[1,2,3,4,5]); //=> [1,2,3] + + var members= [ "Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis","Joe Morello","Norman Bates", + "Eugene Wright","Gerry Mulligan","Jack Six","Alan Dawson","Darius Brubeck","Chris Brubeck", + "Dan Brubeck","Bobby Militello","Michael Moore","Randy Jones"]; + var takeFive = R.take(5); + takeFive(members); //=> ["Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis"] +} +() => { + R.take(3,"Example"); //=> "Exa" + + var takeThree = R.take(3); + takeThree("Example"); //=> "Exa" +} + + + +() => { + const a: string[] = R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz'] + const b: string[] = R.takeLast(2)(['foo', 'bar', 'baz']); //=> ['bar', 'baz'] + const c: string = R.takeLast(3, 'ramda'); //=> 'mda' + const d: string = R.takeLast(3)('ramda'); //=> 'mda' +} + +() => { + const isNotOne = (x: number) => x !== 1; + const a: number[] = R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4] + const b: number[] = R.takeLastWhile(isNotOne)([1, 2, 3, 4]); //=> [2, 3, 4] +} + +() => { + var isNotFour = function(x: number) { + return !(x === 4); + }; + + R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] + R.takeWhile(isNotFour)([1, 2, 3, 4]); //=> [1, 2, 3] +} + +() => { + const sayX = (x: number) => console.log('x is ' + x); + const a: number = R.tap(sayX, 100); //=> 100 +} + +() => { + const a: boolean = R.test(/^x/, 'xyz'); //=> true + const b: boolean = R.test(/^y/)('xyz'); //=> false +} + +() => { + const a1 = R.times(R.identity, 5); //=> [0, 1, 2, 3, 4] + const a2 = R.times(R.identity)(5); //=> [0, 1, 2, 3, 4] +} + +() => { + class Point { + constructor(public x: number, public y: number) { + this.x = x; + this.y = y; + } + toStringn() { + return 'new Point(' + this.x + ', ' + this.y + ')'; + } + }; + R.toString(new Point(1, 2)); //=> 'new Point(1, 2)' + + R.toString(42); //=> '42' + R.toString('abc'); //=> '"abc"' + R.toString([1, 2, 3]); //=> '[1, 2, 3]' + R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}' + R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")' +} + +() => { + var numbers = [1, 2, 3, 4]; + var transducer = R.compose(R.map(R.add(1)), R.take(2)); + var fn = R.flip(R.append); + R.transduce(transducer, fn, [], numbers); //=> [2, 3] + R.transduce(transducer, fn, [])(numbers); //=> [2, 3] + R.transduce(transducer, fn)([], numbers); //=> [2, 3] + R.transduce(transducer)(fn, [], numbers); //=> [2, 3] +} + +() => { + const a: any[][] = R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']] + const b: any[][] = R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']] + const c: any[][] = R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]] +} + +() => { + const x = R.prop('x'); + const a: boolean = R.tryCatch(R.prop('x'), R.F, {x: true}); //=> true + const b: boolean = R.tryCatch(R.prop('x'), R.F, null); //=> false +} + +() => { + R.uniq([1, 1, 2, 1]); //=> [1, 2] + R.uniq([{}, {}]); //=> [{}, {}] + R.uniq([1, '1']); //=> [1, '1'] +} + +() => { + var strEq = function(a: any, b: any) { return String(a) === String(b); }; + R.uniqWith(strEq, [1, '1', 2, 1]); //=> [1, 2] + R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2] + R.uniqWith(strEq)([{}, {}]); //=> [{}] + R.uniqWith(strEq)([1, '1', 1]); //=> [1] + R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] +} + +() => { + R.equals(R.unnest([1, [2], [[3]]]), [1,2,[3]]); //=> true + R.equals(R.unnest([[1, 2], [3, 4], [5, 6]]),[1,2,3,4,5,6]); //=> true +} + +() => { + R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] + R.xprod([1, 2])(['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] +} + +() => { + R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] + R.zip([1, 2, 3])(['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] +} + +() => { + R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} + R.zipObj(['a', 'b', 'c'])([1, 2, 3]); //=> {a: 1, b: 2, c: 3} +} + +() => { + var f = function(x:number, y:string) { + // ... + }; + R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + R.zipWith(f)([1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + R.zipWith(f, [1, 2, 3])(['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] +} + +/***************************************************************** + * Object category + */ +() => { + const a = R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + const b = R.assoc('c')(3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + const c = R.assoc('c', 3)({a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} +} + +() => { + const a1 = R.dissoc<{a:number, c:number}>('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + const a2 = R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + const a4 = R.dissoc('b')<{a:number, c:number}>({a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} +} + +() => { + const a = R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + const b = R.assocPath(['a', 'b', 'c'])(42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + const c = R.assocPath(['a', 'b', 'c'], 42)({a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} +} + +() => { + const a1 = R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + // optionally specify return type + const a2 = R.dissocPath<{a :{ b: number}}>(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + const a3 = R.dissocPath(['a', 'b', 'c'])({a: {b: {c: 42}}}); //=> {a: {b: {}}} +} + +() => { + var obj1 = [{}, {}, {}]; + var obj2 = [{a:1}, {a:2}, {a:3}]; + const a1: any[] = R.clone(obj1); + const a2: {a: number}[] = R.clone(obj2); + const a3: any = R.clone({}); + const a4: number = R.clone(10); + const a5: string = R.clone('foo'); + const a6: number = R.clone(Date.now()); +} + +() => { + var o1 = { a: 1, b: 2, c: 3, d: 4 }; + var o2 = { a: 10, b: 20, c: 3, d: 40 }; + const a1 = R.eqProps('a', o1, o2); //=> false + const a2 = R.eqProps('c', o1, o2); //=> true + const a3: {(obj1: T, obj2: U): boolean} = R.eqProps('c'); + const a4: {(obj2: U): boolean} = R.eqProps('c', o1); +} + +() => { + const a1 = R.evolve({ elapsed: R.add(1), remaining: R.add(-1) }, { name: 'Tomato', elapsed: 100, remaining: 1400 }); + const a2 = R.evolve({ elapsed: R.add(1), remaining: R.add(-1) })({ name: 'Tomato', elapsed: 100, remaining: 1400 }); +} + +() => { + // var tomato = {firstName: 'Tomato ', data: {elapsed: 100, remaining: 1400}, id:123}; + // var transformations = { + // firstName: R.trim, + // lastName: R.trim, // Will not get invoked. + // data: {elapsed: R.add(1), remaining: R.add(-1)} + // }; + // const a = R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} + // const b = R.evolve(transformations)(tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} +} + +() => { + const hasName = R.has('name'); + const a1: boolean = hasName({name: 'alice'}); //=> true + const a2: boolean = hasName({name: 'bob'}); //=> true + const a3: boolean = hasName({}); //=> false + + const point = {x: 0, y: 0}; + const pointHas = R.flip(R.has)(point); + const b1: boolean = pointHas('x'); //=> true + const b2: boolean = pointHas('y'); //=> true + const b3: boolean = pointHas('z'); //=> false +} + +class Rectangle { + constructor(public width: number, public height: number) { + this.width = width; + this.height = height; + } + area():number { + return this.width * this.height; + } +}; +() => { + + var square = new Rectangle(2, 2); + R.hasIn('width', square); //=> true + R.hasIn('area', square); //=> true + R.flip(R.hasIn)(square)('area'); //=> true +} + +() => { + var raceResultsByFirstName = { + first: 'alice', + second: 'jake', + third: 'alice', + }; + R.invert(raceResultsByFirstName); + //=> { 'alice': ['first', 'third'], 'jake':['second'] } +} + +() => { + let raceResults0 = { + first: 'alice', + second: 'jake' + }; + R.invertObj(raceResults0); + //=> { 'alice': 'first', 'jake':'second' } + + // Alternatively: + let raceResults1 = ['alice', 'jake']; + R.invertObj(raceResults1); + //=> { 'alice': '0', 'jake':'1' } +} + +() => { + R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] +} + +() => { + var f = new F(); + R.keysIn(f); //=> ['x', 'y'] +} + +() => { + var xLens = R.lens(R.prop('x'), R.assoc('x')); + R.view(xLens, {x: 1, y: 2}); //=> 1 + R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.set(xLens)(4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.set(xLens, 4)({x: 1, y: 2}); //=> {x: 4, y: 2} + R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} + R.over(xLens, R.negate)({x: 1, y: 2}); //=> {x: -1, y: 2} + R.over(xLens)(R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} +} +() => { + var headLens = R.lensIndex(0); + R.view(headLens, ['a', 'b', 'c']); //=> 'a' + R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] +} +() => { + var xLens = R.lensProp('x'); + R.view(xLens, {x: 1, y: 2}); //=> 1 + R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} +} + +() => { + const xyLens = R.lensPath(['x', 'y']); + + R.view(xyLens, {x: {y: 2, z: 3}}); //=> 2 + R.set(xyLens, 4, {x: {y: 2, z: 3}}); //=> {x: {y: 4, z: 3}} + R.over(xyLens, R.negate, {x: {y: 2, z: 3}}); //=> {x: {y: -2, z: 3}} +} + +() => { + R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] +} + +() => { + var f = new F(); + R.keysIn(f); //=> ['x', 'y'] +} + +() => { + var headLens = R.lens( + function get(arr: number[]) { return arr[0]; }, + function set(val: number, arr: number[]) { return [val].concat(arr.slice(1)); } + ); + headLens([10, 20, 30, 40]); //=> 10 + headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40] + + var phraseLens = R.lens( + function get(obj: any) { return obj.phrase; }, + function set(val: string, obj: any) { + var out = R.clone(obj); + out.phrase = val; + return out; + } + ); + var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'}; + var obj2 = { phrase: "What's all this, then?"}; + phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!' + phraseLens(obj2); // => "What's all this, then?" + phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'} +} + + +() => { + var phraseLens = R.lensProp('phrase'); + var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'}; + var obj2 = { phrase: "What's all this, then?"}; + phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!' + phraseLens(obj2); // => "What's all this, then?" + phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'} +} + +() => { + R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); + //=> { 'name': 'fred', 'age': 40 } + + var resetToDefault = R.flip(R.merge)({x: 0}); + resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2} +} + +() => { + const a = R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3} + const b = R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2} +} + +() => { + const a = R.mergeWith(R.concat, + { a: true, values: [10, 20] }, + { b: true, values: [15, 35] }); + //=> { a: true, b: true, values: [10, 20, 15, 35] } +} + +() => { + let concatValues = (k:string, l: string, r: string) => k == 'values' ? R.concat(l, r) : r; + R.mergeWithKey(concatValues, + { a: true, thing: 'foo', values: [10, 20] }, + { b: true, thing: 'bar', values: [15, 35] }); + const merge = R.mergeWithKey(concatValues); + merge({ a: true, thing: 'foo', values: [10, 20] }, { b: true, thing: 'bar', values: [15, 35] }); +} + +() => { + const a1 = R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2 + const a2 = R.pathOr('N/A', ['a', 'b'])({a: {b: 2}}); //=> 2 + const a3 = R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A" + const a4 = R.pathOr({c:2})(['a', 'b'], {c: {b: 2}}); //=> "N/A" +} + +() => { + var isPositive = function(n: number) { + return n > 0; + }; + const a1 = R.pickBy(isPositive, {a: 1, b: 2, c: -1, d: 0, e: 5}); //=> {a: 1, b: 2, e: 5} + var containsBackground = function(val: any) { + return val.bgcolor; + }; + var colors = {1: {color: 'read'}, 2: {color: 'black', bgcolor: 'yellow'}}; + R.pickBy(containsBackground, colors); //=> {2: {color: 'black', bgcolor: 'yellow'}} + + var isUpperCase = function(val: number, key: string) { return key.toUpperCase() === key; } + R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} +} + + +() => { + const a1 = R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + const a2 = R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + const a3 = R.pick(['a', 'e', 'f'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + const a4 = R.pick(['a', 'e', 'f'], [1, 2, 3, 4]); //=> {a: 1} +} + +() => { + var matchPhrases = R.compose( + R.objOf('must'), + R.map(R.objOf('match_phrase')) +) + +matchPhrases(['foo', 'bar', 'baz']); +} +() => { + R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} + R.omit(['a', 'd'])({a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} +} + + +() => { + R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} +} + +() => { + R.pair('foo', 'bar'); //=> ['foo', 'bar'] + let p = R.pair('foo', 1); //=> ['foo', 'bar'] + let x: string = p[0]; + let y: number = p[1]; +} + +() => { + var headLens = R.lensIndex(0); + R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz'] +} + +() => { + R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + R.pickAll(['a', 'd'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} + R.pickAll(['a', 'e', 'f'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} +} + +() => { + var isUpperCase = function(val: number, key: string) { return key.toUpperCase() === key; } + R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} +} + +() => { + var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; + var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; + var kids = [abby, fred]; + R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] +} + +() => { + var x: number = R.prop('x', {x: 100}); //=> 100 + const a = R.prop('x', {}); //=> undefined +} + +() => { + var alice = { + name: 'ALICE', + age: 101 + }; + var favorite = R.prop('favoriteLibrary'); + var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary'); + + const s1 = favorite(alice); //=> undefined + const s2 = favoriteWithDefault(alice); //=> 'Ramda' +} + +() => { + const a: boolean = R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true + const b: boolean = R.propSatisfies(x => x > 0, 'x')({x: 1, y: 2}); //=> true + const c: boolean = R.propSatisfies(x => x > 0)('x')({x: 1, y: 2}); //=> true +} + +() => { + R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2] + R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2] + + var fullName = R.compose(R.join(' '), R.props(['first', 'last'])); + fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth' +} + +() => { + const a = R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] +} + +() => { + var f = new F(); + const a1 = R.toPairsIn(f); //=> [['x','X'], ['y','Y']] + const a2 = R.toPairsIn(f); //=> [['x','X'], ['y','Y']] +} + +() => { + const a = R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] +} +() => { + var f = new F(); + const a = R.valuesIn(f); //=> ['X', 'Y'] +} + +() => { + var spec = {x: 2}; + var x1: boolean = R.where(spec, {w: 10, x: 2, y: 300}); //=> true + var x2: boolean = R.where(spec, {x: 1, y: 'moo', z: true}); //=> false + var x3: boolean = R.where(spec)({w: 10, x: 2, y: 300}); //=> true + var x4: boolean = R.where(spec)({x: 1, y: 'moo', z: true}); //=> false + + // There's no way to represent the below functionality in typescript + // per http://stackoverflow.com/a/29803848/632495 + // will need a work around. + + var spec2 = {x: function(val: number, obj: any) { return val + obj.y > 10; }}; + R.where(spec2, {x: 2, y: 7}); //=> false + R.where(spec2, {x: 3, y: 8}); //=> true + + var xs = [{x: 2, y: 1}, {x: 10, y: 2}, {x: 8, y: 3}, {x: 10, y: 4}]; + R.filter(R.where({x: 10}), xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] + R.filter(R.where({x: 10}))(xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] +} + +() => { + // pred :: Object -> Boolean + var pred = R.whereEq({a: 1, b: 2}); + pred({a: 1}); //=> false + pred({a: 1, b: 2}); //=> true + pred({a: 1, b: 2, c: 3}); //=> true + pred({a: 1, b: 1}); //=> false + R.whereEq({a: 'one'}, {a: 'one'}); // => true +} + +() => { + const a: number[] = R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4] +} + +() => { + var mapIndexed = R.addIndex(R.map); + mapIndexed(function(val: string, idx: number) {return idx + '-' + val;})(['f', 'o', 'o', 'b', 'a', 'r']); + //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r'] + mapIndexed((rectangle: Rectangle, idx: number):number => rectangle.area()*idx, [new Rectangle(1,2), new Rectangle(4,7)]); + //=> [2, 56] +} + +() => { + var reduceIndexed = R.addIndex(R.reduce); + reduceIndexed(function(acc: string, val: string, idx: number) { + return acc + ',' + idx + '-' + val; + } + ,'' + ,['f', 'o', 'o', 'b', 'a', 'r']); + //=> ['0-f,1-o,2-o,3-b,4-a,5-r'] +} + + + +() => { + var t = R.always('Tee'); + const x: string = t(); //=> 'Tee' +} + +() => { + const x: number[] = R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + const y: number[] = R.ap([R.multiply(2), R.add(3)])([1,2,3]); //=> [2, 4, 6, 4, 5, 6] +} + +() => { + var nums = [1, 2, 3, -99, 42, 6, 7]; + R.apply(Math.max, nums); //=> 42 + R.apply(Math.max)(nums); //=> 42 +} + +() => { + type T = {sum: number, nested: {mul: number}}; + const getMetrics = R.applySpec({ + sum: R.add, nested: { mul: R.multiply } + }); + const result = getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } } +} + +() => { + var takesThreeArgs = function(a: number, b: number, c: number) { + return [a, b, c]; + }; + takesThreeArgs.length; //=> 3 + takesThreeArgs(1, 2, 3); //=> [1, 2, 3] + + var takesTwoArgs = R.binary(takesThreeArgs); + takesTwoArgs.length; //=> 2 + // Only 2 arguments are passed to the wrapped function + takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] +} + +() => { + var indentN = R.pipe(R.times(R.always(' ')), + R.join(''), + R.replace(/^(?!$)/gm) + ); + + var format = R.converge( + R.call, [ + R.pipe(R.prop('indent'), indentN), + R.prop('value') + ] + ); + + format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n' +} + +() => { + type T = {age: number}; + var cmp = R.comparator(function(a: T, b: T) { + return a.age < b.age; + }); + var people = [ + {name: 'Agy', age:33}, {name: 'Bib', age: 15}, {name: 'Cari', age: 16} + ]; + R.sort(cmp, people); +} + +() => { + var add = function(a: number, b: number) { return a + b; }; + var multiply = function(a: number, b: number) { return a * b; }; + var subtract = function(a: number, b: number) { return a - b; }; + + //≅ multiply( add(1, 2), subtract(1, 2) ); + const x: number = R.converge(multiply, [ add, subtract ])(1, 2); //=> -3 + + var add3 = function(a: number, b: number, c: number) { return a + b + c; }; + const y: number = R.converge(add3, [ multiply, add, subtract ])(1, 2); //=> 4 +} + +() => { + const f0 = R.compose(Math.pow); + const f1 = R.compose(R.negate, Math.pow); + const f2 = R.compose(R.inc, R.negate, Math.pow); + const f3 = R.compose(R.inc, R.inc, R.negate, Math.pow); + const f4 = R.compose(R.inc, R.inc, R.inc, R.negate, Math.pow); + const f5 = R.compose(R.inc, R.inc, R.inc, R.inc, R.negate, Math.pow); + const x0: number = f0(3, 4); // -(3^4) + 1 + const x1: number = f1(3, 4); // -(3^4) + 1 + const x2: number = f2(3, 4); // -(3^4) + 1 + const x3: number = f3(3, 4); // -(3^4) + 1 + const x4: number = f4(3, 4); // -(3^4) + 1 + const x5: number = f5(3, 4); // -(3^4) + 1 +} + +() => { + const fn = function(a: string, b: number, c: string) { + return [a,b,c]; + } + const gn = R.compose(R.length, fn); + const x: number = gn('Hello', 4, "world"); +} + +(() => { + var Circle = function(r: number) { + this.r = r; + this.colors = Array.prototype.slice.call(arguments, 1); + }; + Circle.prototype.area = function() {return Math.PI * Math.pow(this.r, 2);}; + var circleN = R.constructN(2, Circle); + var c1 = circleN(1, 'red'); + var circle = R.construct(Circle); + var c1 = circle(1, 'red'); +})(); + +/***************************************************************** + * Relation category + */ + +() => { + var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2]; + var letters = R.split('', 'abcABCaaaBBc'); + R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1} + R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3} +} + +() => { + R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] + R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] +} + +() => { + function cmp(x: any, y: any) { return x.a === y.a; } + var l1 = [{a: 1}, {a: 2}, {a: 3}]; + var l2 = [{a: 3}, {a: 4}]; + R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] +} + +() => { + R.equals(1, 1); //=> true + R.equals('2', '1'); //=> false + R.equals([1, 2, 3], [1, 2, 3]); //=> true + + var a: any = {}; a.v = a; + var b: any = {}; b.v = b; + R.equals(a, b); //=> true +} + +() => { + const a1 = R.identity(1); //=> 1 + let obj = {}; + const a2 = R.identity([1,2,3]); + const a3 = R.identity(['a','b','c']); + const a4 = R.identity(obj) === obj; //=> true +} + +() => { + var o = {}; + R.identical(o, o); //=> true + R.identical(1, 1); //=> true + R.identical('2', '1'); //=> false + R.identical([], []); //=> false + R.identical(0, -0); //=> false + R.identical(NaN, NaN); //=> true +} + +() => { + R.path(['a', 'b'], {a: {b: 2}}); //=> 2 + R.path(['a', 'b'])({a: {b: 2}}); //=> 2 +} + +() => { + var sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name'))); + var alice = { + name: 'ALICE', + age: 101 + }; + var bob = { + name: 'Bob', + age: -10 + }; + var clara = { + name: 'clara', + age: 314.159 + }; + var people = [clara, bob, alice]; + sortByNameCaseInsensitive(people); //=> [alice, bob, clara] +} + +() => { + const a: number[][] = R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]] + const b: number[][] = R.splitAt(1)([1, 2, 3]); //=> [[1], [2, 3]] + const c: string[] = R.splitAt(5, 'hello world'); //=> ['hello', ' world'] + const d: string[] = R.splitAt(-1, 'foobar'); //=> ['fooba', 'r'] +} + +() => { + const a: number[][] = R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] + const b: number[][] = R.splitWhen(R.equals(2))([1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] +} + +() => { + R.add(2, 3); //=> 5 + R.add(7)(10); //=> 17 + R.add("Hello", " World"); //=> "Hello World" + R.add("Hello")(" World"); //=> "Hello World" +} + +() => { + R.dec(42); //=> 41 +} + +() => { + R.divide(71, 100); //=> 0.71 + + var half = R.flip(R.divide)(2); + half(42); //=> 21 + + var reciprocal = R.divide(1); + reciprocal(4); //=> 0.25 +} + +() => { + R.gt(2, 6); //=> false + R.gt(2, 0); //=> true + R.gt(2, 2); //=> false + R.flip(R.gt)(2)(10); //=> true + R.gt(2)(10); //=> false +} + +() => { + R.gte(2, 6); //=> false + R.gte(2, 0); //=> true + R.gte(2, 2); //=> false + R.flip(R.gte)(2)(10); //=> true + R.gte(2)(10); //=> false +} + +() => { + R.isNaN(NaN); //=> true + R.isNaN(undefined); //=> false + R.isNaN({}); //=> false +} + +() => { + R.lt(2, 6); //=> true + R.lt(2, 0); //=> false + R.lt(2, 2); //=> false + R.lt(5)(10); //=> true + R.flip(R.lt)(5)(10); //=> false // right-sectioned currying +} + +() => { + R.lte(2, 6); //=> true + R.lte(2, 0); //=> false + R.lte(2, 2); //=> true + R.flip(R.lte)(2)(1); //=> true + R.lte(2)(10); //=> true +} + +() => { + R.mathMod(-17, 5); //=> 3 + R.mathMod(17, 5); //=> 2 + R.mathMod(17, -5); //=> NaN + R.mathMod(17, 0); //=> NaN + R.mathMod(17.2, 5); //=> NaN + R.mathMod(17, 5.3); //=> NaN + + var clock = R.flip(R.mathMod)(12); + clock(15); //=> 3 + clock(24); //=> 0 + + var seventeenMod = R.mathMod(17); + seventeenMod(3); //=> 2 +} + +() => { + var hasName = R.has('name'); + hasName({name: 'alice'}); //=> true + hasName({name: 'bob'}); //=> true + hasName({}); //=> false + + var point = {x: 0, y: 0}; + var pointHas = R.flip(R.has)(point); + pointHas('x'); //=> true + pointHas('y'); //=> true + pointHas('z'); //=> false +} + +() => { + let x: R.Ord = R.max(7, 3); //=> 7 + let y: R.Ord = R.max('a', 'z'); //=> 'z' +} + +() => { + function cmp(obj: { x: R.Ord }) { return obj.x; } + var a = {x: 1}, b = {x: 2}, c = {x: 3}, d = {x: "a"}, e = {x:"z"}; + R.maxBy(cmp, a, c); //=> {x: 3} + R.maxBy(cmp)(a, c); //=> {x: 3} + R.maxBy(cmp)(a)(b); + R.maxBy(cmp)(d)(e); +} + +() => { + const a: number = R.mean([2, 7, 9]); //=> 6 + const b: number = R.mean([]); //=> NaN +} + +() => { + const a: number = R.median([7, 2, 10, 9]); //=> 8 + const b: number = R.median([]); //=> NaN +} + +() => { + let x: R.Ord = R.min(9, 3); //=> 3 + let y: R.Ord = R.min('a', 'z'); //=> 'a' +} + +() => { + function cmp(obj: {x: R.Ord}) { return obj.x; } + var a = {x: 1}, b = {x: 2}, c = {x: 3}, d = {x: "a"}, e = {x: "z"}; + R.minBy(cmp, a, b); //=> {x: 1} + R.minBy(cmp)(a, b); //=> {x: 1} + R.minBy(cmp)(a)(c); + R.minBy(cmp, d, e); +} + +() => { + R.modulo(17, 3); //=> 2 + // JS behavior: + R.modulo(-17, 3); //=> -2 + R.modulo(17, -3); //=> 2 + + var isOdd = R.flip(R.modulo)(2); + isOdd(42); //=> 0 + isOdd(21); //=> 1 +} + +() => { + var double = R.multiply(2); + var triple = R.multiply(3); + double(3); //=> 6 + triple(4); //=> 12 + R.multiply(2, 5); //=> 10 +} + +() => { + R.negate(42); //=> -42 +} + +() => { + R.product([2,4,6,8,100,1]); //=> 38400 +} + +() => { + R.subtract(10, 8); //=> 2 + + var minus5 = R.flip(R.subtract)(5); + minus5(17); //=> 12 + + var complementaryAngle = R.subtract(90); + complementaryAngle(30); //=> 60 + complementaryAngle(72); //=> 18 +} + +() => { + R.sum([2,4,6,8,100,1]); //=> 121 +} + +() => { + const a: number[] = R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5] + const b: number[] = R.symmetricDifference([7,6,5,4,3])([1,2,3,4]); //=> [7,6,5,1,2] +} + +() => { + const eqA = R.eqBy(R.prop('a')); + const l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}]; + const l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}]; + R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + R.symmetricDifferenceWith(eqA)(l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + const c: (a: any[]) => any[] = R.symmetricDifferenceWith(eqA)(l1); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] +} + +/***************************************************************** + * String category + */ + +() => { + R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo' + R.replace('foo', 'bar')('foo foo foo'); //=> 'bar foo foo' + R.replace('foo')('bar')('foo foo foo'); //=> 'bar foo foo' + R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo' + + // Use the "g" (global) flag to replace all occurrences: + R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar' + R.replace(/foo/g, 'bar')('foo foo foo'); //=> 'bar bar bar' + R.replace(/foo/g)('bar')('foo foo foo'); //=> 'bar bar bar' +} + +/***************************************************************** + * Is category + */ + +() => { + R.is(Object, {}); //=> true + R.is(Object)({}); //=> true + R.is(Number, 1); //=> true + R.is(Number)(1); //=> true + R.is(Object, 1); //=> false + R.is(Object)(1); //=> false + R.is(String, 's'); //=> true + R.is(String)('s'); //=> true + R.is(String, new String('')); //=> true + R.is(String)(new String('')); //=> true + R.is(Object, new String('')); //=> true + R.is(Object)(new String('')); //=> true + R.is(Object, 's'); //=> false + R.is(Object)('s'); //=> false + R.is(Number, {}); //=> false + R.is(Number)({}); //=> false +} + +/***************************************************************** + * Logic category + */ +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0}; + var f = R.allPass([gt10, even]); + f(11); //=> false + f(12); //=> true +} + +() => { + R.and(false, true); //=> false + R.and(0, []); //=> 0 + R.and(0)([]); //=> 0 + R.and(null, ''); //=> null + var Why: any = (function(val: boolean) { + var why: any; + why.val = val; + why.and = function(x: boolean) { + return this.val && x; + } + return Why; + })(true); + var why = new Why(true); + R.and(why, false); // false +} +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0}; + var f = R.anyPass([gt10, even]); + f(11); //=> true + f(8); //=> true + f(9); //=> false +} + +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0 }; + var f = R.both(gt10, even); + var g = R.both(gt10)(even); + f(100); //=> true + f(101); //=> false +} +() => { + var isEven = function(n: number) { return n % 2 === 0; }; + var isOdd = R.complement(isEven); + isOdd(21); //=> true + isOdd(42); //=> false +} + +(() => { + R.eqBy(Math.abs, 5, -5); //=> true +}); + +() => { + var defaultTo42 = R.defaultTo(42); + defaultTo42(null); //=> 42 + defaultTo42(undefined); //=> 42 + defaultTo42('Ramda'); //=> 'Ramda' +} +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0 }; + var f = R.either(gt10, even); + var g = R.either(gt10)(even); + f(101); //=> true + f(8); //=> true +} +() => { + // Flatten all arrays in the list but leave other values alone. + var flattenArrays = R.map(R.ifElse(Array.isArray, R.flatten, R.identity)); + + flattenArrays([[0], [[10], [8]], 1234, {}]); //=> [[0], [10, 8], 1234, {}] + flattenArrays([[[10], 123], [8, [10]], "hello"]); //=> [[10, 123], [8, 10], "hello"] +} +() => { + R.isEmpty([1, 2, 3]); //=> false + R.isEmpty([]); //=> true + R.isEmpty(''); //=> true + R.isEmpty(null); //=> false + R.isEmpty({}); //=>true + R.isEmpty({a:1}); //=> false +} + +() => { + R.not(true); //=> false + R.not(false); //=> true + R.not(0); // => true + R.not(1); // => false +} + +class Why { + val: boolean; + constructor(val: boolean) { + this.val = val; + } + or(x: boolean) { + return this.val && x; + } +} +() => { + const x0: boolean = R.or(false, true); //=> false + const x1: number|any[] = R.or(0, []); //=> [] + const x2: number|any[] = R.or(0)([]); //=> [] + const x3: string = R.or(null, ''); //=> '' + + var why = new Why(true); + why.or(true) + const x4: Why|boolean = R.or(why, false); // false +} + +() => { + R.intersperse(',', ['foo', 'bar']); //=> ['foo', ',', 'bar'] + R.intersperse(0, [1, 2]); //=> [1, 0, 2] + R.intersperse(0, [1]); //=> [1] +} diff --git a/ramda/ramda.d.ts b/ramda/ramda.d.ts new file mode 100644 index 0000000000..7ed44bf148 --- /dev/null +++ b/ramda/ramda.d.ts @@ -0,0 +1,1807 @@ +// Type definitions for ramda (www.ramdajs.com) 0.21.0 +// Project: https://github.com/donnut/typescript-ramda +// Definitions by: Erwin Poeze +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var R: R.Static; + +declare namespace R { + type Ord = number | string | boolean; + + interface ListIterator { + (value: T, index: number, list: T[]): TResult; + } + + interface Functor { + map(a: any): T; + } + + interface ObjectIterator { + (element: T, key: string, obj: Dictionary): Dictionary; + } + + interface KeyValuePair extends Array { 0 : K; 1 : V; } + + interface ArrayLike { + nodeType: number; + } + + interface Arity0Fn { + (): any + } + + interface Arity1Fn { + (a: any): any + } + + interface Arity2Fn { + (a: any, b: any): any + } + + interface ObjFunc { + [index:string]: Function; + } + + interface ObjFunc2 { + [index:string]: (x: any, y: any) => boolean; + } + + interface Pred { + (...a: any[]): boolean; + } + + interface ObjPred { + (value: any, key: string): boolean; + } + + interface Dictionary { + [index: string]: T; + } + + interface CharList extends String { + push(x: string): void; + } + + interface Nested { + [index: string]: Nested|{(value: any): U}; + } + + interface Lens { + (obj: T): U; + set(str: string, obj: T): U; + } + + // @see https://gist.github.com/donnut/fd56232da58d25ceecf1, comment by @albrow + interface CurriedFunction2 { + (t1: T1): (t2: T2) => R; + (t1: T1, t2: T2): R; + } + + interface CurriedFunction3 { + (t1: T1): CurriedFunction2; + (t1: T1, t2: T2): (t3: T3) => R; + (t1: T1, t2: T2, t3: T3): R; + } + + interface CurriedFunction4 { + (t1: T1): CurriedFunction3; + (t1: T1, t2: T2): CurriedFunction2; + (t1: T1, t2: T2, t3: T3): (t4: T4) => R; + (t1: T1, t2: T2, t3: T3, t4: T4): R; + } + + interface CurriedFunction5 { + (t1: T1): CurriedFunction4; + (t1: T1, t2: T2): CurriedFunction3; + (t1: T1, t2: T2, t3: T3): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4): (t5: T5) => R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; + } + + interface CurriedFunction6 { + (t1: T1): CurriedFunction5; + (t1: T1, t2: T2): CurriedFunction4; + (t1: T1, t2: T2, t3: T3): CurriedFunction3; + (t1: T1, t2: T2, t3: T3, t4: T4): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): (t6: T6) => R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; + } + + interface Reduced {} + + interface Static { + + /** + * Adds two numbers (or strings). Equivalent to a + b but curried. + */ + add(a: number, b: number): number; + add(a: string, b: string): string; + add(a: number): (b: number) => number; + add(a: string): (b: string) => string; + + /** + * Creates a new list iteration function from an existing one by adding two new parameters to its callback + * function: the current index, and the entire list. + */ + addIndex(fn: (f: (item: T) => U, list: T[]) => U[] ) + : CurriedFunction2<(item: T, idx: number, list?: T[]) => U, T[], U[]>; + /* Special case for forEach */ + addIndex(fn: (f: (item: T) => void, list: T[]) => T[]) + : CurriedFunction2<(item: T, idx: number, list?: T[]) => void, T[], T[]>; + /* Special case for reduce */ + addIndex(fn: (f: (acc:U, item: T) => U, aci:U, list: T[]) => U) + : CurriedFunction3<(acc:U, item: T, idx: number, list?: T[]) => U, U, T[], U>; + + /** + * Applies a function to the value at the given index of an array, returning a new copy of the array with the + * element at the given index replaced with the result of the function application. + */ + adjust(fn: (a: T) => T, index: number, list: T[]): T[]; + adjust(fn: (a: T) => T, index: number): (list: T[]) => T[]; + + /** + * Returns true if all elements of the list match the predicate, false if there are any that don't. + */ + all(fn: (a: T) => boolean, list: T[]): boolean; + all(fn: (a: T) => boolean): (list: T[]) => boolean; + + /** + * Given a list of predicates, returns a new predicate that will be true exactly when all of them are. + */ + allPass(preds: Pred[]): Pred; + + /** + * Returns a function that always returns the given value. + */ + always(val: T): () => T; + + + /** + * A function that returns the first argument if it's falsy otherwise the second argument. Note that this is + * NOT short-circuited, meaning that if expressions are passed they are both evaluated. + */ + and(fn1: T, val2: boolean|any): boolean; + and(fn1: T): (val2: boolean|any) => boolean; + + /** + * Returns true if at least one of elements of the list match the predicate, false otherwise. + */ + any(fn: (a: T) => boolean, list: T[]): boolean; + any(fn: (a: T) => boolean): (list: T[]) => boolean; + + /** + * Given a list of predicates returns a new predicate that will be true exactly when any one of them is. + */ + anyPass(preds: Pred[]): Pred; + + /** + * ap applies a list of functions to a list of values. + */ + ap(fns: ((a: T) => U)[], vs: T[]): U[]; + ap(fns: ((a: T) => U)[]): (vs: T[]) => U[]; + + + /** + * Returns a new list, composed of n-tuples of consecutive elements If n is greater than the length of the list, + * an empty list is returned. + */ + aperture(n: number, list: T): T[][]; + aperture(n: number): (list: T) => T[][]; + + /** + * Returns a new list containing the contents of the given list, followed by the given element. + */ + append(el: U, list: T[]): (T & U)[]; + append(el: U): (list: T[]) => (T & U)[]; + append(el: U): (list: T[]) => (T & U)[]; + + /** + * Applies function fn to the argument list args. This is useful for creating a fixed-arity function from + * a variadic function. fn should be a bound function if context is significant. + */ + apply(fn: (arg0: T, ...args: T[]) => TResult, args: U[]): TResult; + apply(fn: (arg0: T, ...args: T[]) => TResult): (args: U[]) => TResult; + + /** + * Given a spec object recursively mapping properties to functions, creates a function producing an object + * of the same structure, by mapping each property to the result of calling its associated function with + * the supplied arguments. + */ + applySpec(obj: any): (...args: any[]) => T; + + /** + * Makes a shallow clone of an object, setting or overriding the specified property with the given value. + */ + assoc(prop: string, val: T, obj: U): {prop: T} & U; + assoc(prop: string): (val: T, obj: U) => {prop: T} & U; + assoc(prop: string, val: T): (obj: U) => {prop: T} & U; + + + /** + * Makes a shallow clone of an object, setting or overriding the nodes required to create the given path, and + * placing the specific value at the tail end of that path. + */ + assocPath(path: string[], val: T, obj: U): U; + assocPath(path: string[]): (val: T, obj: U) => U; + assocPath(path: string[], val: T): (obj: U) => U; + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly 2 + * parameters. Any extraneous parameters will not be passed to the supplied function. + */ + binary(fn: (...args: any[]) => any): Function; + + /** + * Creates a function that is bound to a context. Note: R.bind does not provide the additional argument-binding + * capabilities of Function.prototype.bind. + */ + bind(thisObj: T, fn: (...args: any[]) => any): (...args: any[]) => any; + + + /** + * A function wrapping calls to the two functions in an && operation, returning the result of the first function + * if it is false-y and the result of the second function otherwise. Note that this is short-circuited, meaning + * that the second function will not be invoked if the first returns a false-y value. + */ + both(pred1: Pred, pred2: Pred): Pred; + both(pred1: Pred): (pred2: Pred) => Pred; + + /** + * Returns the result of calling its first argument with the remaining arguments. This is occasionally useful + * as a converging function for R.converge: the left branch can produce a function while the right branch + * produces a value to be passed to that function as an argument. + */ + call(fn: (...args: any[])=> (...args: any[]) => any, ...args: any[]): any; + + /** + * `chain` maps a function over a list and concatenates the results. + * This implementation is compatible with the Fantasy-land Chain spec + */ + chain(fn: (n: T) => U[], list: T[]): U[]; + chain(fn: (n: T) => U[]): (list: T[]) => U[]; + + /** + * Restricts a number to be within a range. + * Also works for other ordered types such as Strings and Date + */ + clamp(min: T, max: T, value: T): T; + clamp(min: T, max: T): (value: T) => T; + clamp(min: T): (max: T, value: T) => T; + clamp(min: T): (max: T) => (value: T) => T; + + /** + * Creates a deep copy of the value which may contain (nested) Arrays and Objects, Numbers, Strings, Booleans and Dates. + */ + clone(value: T): T; + clone(value: T[]): T[]; + + /** + * Makes a comparator function out of a function that reports whether the first element is less than the second. + */ + // comparator(pred: (a: any, b: any) => boolean): (x: number, y: number) => number; + comparator(pred: (a: T, b: T) => boolean): (x: T, y: T) => number; + + /** + * Takes a function f and returns a function g such that: + * - applying g to zero or more arguments will give true if applying the same arguments to f gives + * a logical false value; and + * - applying g to zero or more arguments will give false if applying the same arguments to f gives + * a logical true value. + */ + complement(pred: (...args: any[]) => boolean): (...args: any[]) => boolean + + /** + * Performs right-to-left function composition. The rightmost function may have any arity; the remaining + * functions must be unary. + */ + compose(fn0: (x0: V0) => T1): (x0: V0) => T1; + compose(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; + compose(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; + + compose(fn1: (x: T1) => T2, fn0: (x0: V0) => T1): (x0: V0) => T2; + compose(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T2; + compose(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T2; + + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T3; + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T3; + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T3; + + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T4; + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T4; + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T4; + + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T5; + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T5; + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T5; + + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T6; + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T6; + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T6; + + /** + * TODO composeK + */ + + /** + * TODO composeP + */ + + + /** + * Returns a new list consisting of the elements of the first list followed by the elements + * of the second. + */ + concat(list1: T[], list2: T[]): T[]; + concat(list1: T[]): (list2: T[]) => T[]; + concat(list1: string, list2: string): string; + concat(list1: string): (list2: string) => string; + + /** + * Returns a function, fn, which encapsulates if/else-if/else logic. R.cond takes a list of [predicate, transform] pairs. + * All of the arguments to fn are applied to each of the predicates in turn until one returns a "truthy" value, at which + * point fn returns the result of applying its arguments to the corresponding transformer. If none of the predicates + * matches, fn returns undefined. + */ + cond(fns: [Pred, Function][]): Function; + + + /** + * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. + */ + construct(fn: Function): Function; + + + /** + * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. + * The arity of the function returned is specified to allow using variadic constructor functions. + */ + constructN(n: number, fn: Function): Function; + + + /** + * Returns `true` if the specified item is somewhere in the list, `false` otherwise. + * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. + */ + contains(a: string, list: string): boolean; + contains(a: T, list: T[]): boolean; + contains(a: string): (list: string) => boolean; + contains(a: T): (list: T[]) => boolean; + + /** + * Accepts a converging function and a list of branching functions and returns a new + * function. When invoked, this new function is applied to some arguments, each branching + * function is applied to those same arguments. The results of each branching function + * are passed as arguments to the converging function to produce the return value. + */ + converge(after: Function, fns: Function[]): Function; + + /** + * Counts the elements of a list according to how many match each value + * of a key generated by the supplied function. Returns an object + * mapping the keys produced by `fn` to the number of occurrences in + * the list. Note that all keys are coerced to strings because of how + * JavaScript objects work. + */ + countBy(fn: (a: any) => string|number, list: any[]): any; + countBy(fn: (a: any) => string|number): (list: any[]) => any; + + /** + * Returns a curried equivalent of the provided function. The curried function has two unusual capabilities. + * First, its arguments needn't be provided one at a time. + */ + curry(fn: (a: T1, b: T2) => TResult): CurriedFunction2 + curry(fn: (a: T1, b: T2, c: T3) => TResult): CurriedFunction3 + curry(fn: (a: T1, b: T2, c: T3, d: T4) => TResult): CurriedFunction4 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => TResult): CurriedFunction5 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5, f: T6) => TResult): CurriedFunction6 + curry(fn: Function): Function + + + /** + * Returns a curried equivalent of the provided function, with the specified arity. The curried function has + * two unusual capabilities. First, its arguments needn't be provided one at a time. + */ + curryN(length: number, fn: (...args: any[]) => any): Function; + + + /** + * Decrements its argument. + */ + dec(n: number): number; + + /** + * Returns the second argument if it is not null or undefined. If it is null or undefined, the + * first (default) argument is returned. + */ + defaultTo(a: T, b: U): T|U + defaultTo(a: T): (b: U) => T|U + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. + */ + difference(list1: T[], list2: T[]): T[]; + difference(list1: T[]): (list2: T[]) => T[]; + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. + * Duplication is determined according to the value returned by applying the supplied predicate to two list + * elements. + */ + differenceWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + + /* + * Returns a new object that does not contain a prop property. + */ + // It seems impossible to infer the return type, so this may to be specified explicitely + dissoc(prop: string, obj: any): T; + dissoc(prop: string): (obj: any) => U; + + /** + * Makes a shallow clone of an object, omitting the property at the given path. + */ + dissocPath(path: string[], obj: any): T; + dissocPath(path: string[]): (obj: any) => T; + + /** + * Divides two numbers. Equivalent to a / b. + */ + divide(a: number, b: number): number; + divide(a: number): (b: number) => number; + + /** + * Returns a new list containing all but the first n elements of the given list. + */ + drop(n: number, xs: T[]): T[]; + drop(n: number, xs: string): string; + drop(n: number): { + (xs: string): string; + (xs: T[]): T[]; + } + + /** + * Returns a list containing all but the last n elements of the given list. + */ + dropLast(n: number, xs: T[]): T[]; + dropLast(n: number, xs: string): string; + dropLast(n: number): { + (xs: T[]): T[]; + (xs: string): string; + } + + /** + * Returns a new list containing all but last then elements of a given list, passing each value from the + * right to the supplied predicate function, skipping elements while the predicate function returns true. + */ + dropLastWhile(fn: (a: T) => boolean, list: T[]): T[]; + dropLastWhile(fn: (a: T) => boolean): (list: T[]) => T[]; + + /** + * Returns a new list containing the last n elements of a given list, passing each value to the supplied + * predicate function, skipping elements while the predicate function returns true. + */ + dropWhile(fn: (a: T) => boolean, list: T[]): T[]; + dropWhile(fn: (a: T) => boolean): (list: T[]) => T[]; + + /** + * A function wrapping calls to the two functions in an || operation, returning the result of the first + * function if it is truth-y and the result of the second function otherwise. Note that this is + * short-circuited, meaning that the second function will not be invoked if the first returns a truth-y value. + */ + either(pred1: Pred, pred2: Pred): Pred; + either(pred1: Pred): (pred2: Pred) => Pred; + + /** + * Returns the empty value of its argument's type. Ramda defines the empty value of Array ([]), Object ({}), + * String (''), and Arguments. Other types are supported if they define .empty and/or .prototype.empty. + * Dispatches to the empty method of the first argument, if present. + */ + empty(x: T): T; + + /** + * Takes a function and two values in its domain and returns true if the values map to the same value in the + * codomain; false otherwise. + */ + eqBy(fn: (a: T) => T, a: T, b: T): boolean; + eqBy(fn: (a: T) => T, a: T): (b: T) => boolean; + eqBy(fn: (a: T) => T): (a: T, b: T) => boolean; + eqBy(fn: (a: T) => T): (a: T) => (b: T) => boolean; + + /** + * Reports whether two functions have the same value for the specified property. + */ + eqProps(prop: string, obj1: T, obj2: U): boolean; + eqProps(prop: string): (obj1: T, obj2: U) => boolean; + eqProps(prop: string, obj1: T): (obj2: U) => boolean; + + /** + * Returns true if its arguments are equivalent, false otherwise. Dispatches to an equals method if present. + * Handles cyclical data structures. + */ + equals(a: T, b: T): boolean; + equals(a: T): (b: T) => boolean; + + /** + * Creates a new object by evolving a shallow copy of object, according to the transformation functions. + */ + evolve(transformations: Nested, obj: V): Nested; + evolve(transformations: Nested): (obj: V) => Nested; + /* + * A function that always returns false. Any passed in parameters are ignored. + */ + F(): boolean; + + /** + * Returns a new list containing only those items that match a given predicate function. The predicate function is passed one argument: (value). + */ + filter(fn: (value: T) => boolean): (list: T[]) => T[]; + filter(fn: (value: T) => boolean, list: T[]): T[]; + + /** + * Returns the first element of the list which matches the predicate, or `undefined` if no + * element matches. + */ + find(fn: (a: T) => boolean, list: T[]): T; + find(fn: (a: T) => boolean): (list: T[]) => T; + + + /** + * Returns the index of the first element of the list which matches the predicate, or `-1` + * if no element matches. + */ + findIndex(fn: (a: T) => boolean, list: T[]): number; + findIndex(fn: (a: T) => boolean): (list: T[]) => number; + + /** + * Returns the last element of the list which matches the predicate, or `undefined` if no + * element matches. + */ + findLast(fn: (a: T) => boolean, list: T[]): T; + findLast(fn: (a: T) => boolean): (list: T[]) => T; + + /** + * Returns the index of the last element of the list which matches the predicate, or + * `-1` if no element matches. + */ + findLastIndex(fn: (a: T) => boolean, list: T[]): number; + findLastIndex(fn: (a: T) => boolean): (list: T[]) => number; + + /** + * Returns a new list by pulling every item out of it (and all its sub-arrays) and putting + * them in a new array, depth-first. + */ + flatten(x: T[][]): T[]; + flatten(x: T[]): T[]; + + /** + * Returns a new function much like the supplied one, except that the first two arguments' + * order is reversed. + */ + flip(fn: (arg0: T, arg1: U) => TResult): (arg1: U, arg0?: T) => TResult; + flip(fn: (arg0: T, arg1: U, ...args: any[]) => TResult): (arg1: U, arg0?: T, ...args: any[]) => TResult; + + + /** + * Iterate over an input list, calling a provided function fn for each element in the list. + */ + forEach(fn: (x: T) => void, list: T[]): T[]; + forEach(fn: (x: T) => void): (list: T[]) => T[]; + + /** + * Creates a new object out of a list key-value pairs. + */ + fromPairs(pairs: KeyValuePair[]): {[index: string]: V}; + fromPairs(pairs: KeyValuePair[]): {[index: number]: V}; + + /** + * Splits a list into sublists stored in an object, based on the result of + * calling a String-returning function + * on each element, and grouping the results according to values returned. + */ + groupBy(fn: (a: T) => string, list: T[]): {[index: string]: T[]} + groupBy(fn: (a: T) => string): (list: T[]) => {[index: string]: T[]} + + /** + * Takes a list and returns a list of lists where each sublist's elements are all "equal" according to the provided equality function + */ + groupWith(fn: (x: T, y: T) => boolean, list: T[]): T[][] + groupWith(fn: (x: T, y: T) => boolean, list: string): string[] + + /** + * Returns true if the first parameter is greater than the second. + */ + gt(a: number, b: number): boolean; + gt(a: number): (b: number) => boolean; + + /** + * Returns true if the first parameter is greater than or equal to the second. + */ + gte(a: number, b: number): boolean; + gte(a: number): (b: number) => boolean; + + /** + * Returns whether or not an object has an own property with the specified name. + */ + has(s: string, obj: T): boolean; + has(s: string): (obj: T) => boolean; + + /** + * Returns whether or not an object or its prototype chain has a property with the specified name + */ + hasIn(s: string, obj: T): boolean; + hasIn(s: string): (obj: T) => boolean; + + /** + * Returns the first element in a list. + * In some libraries this function is named `first`. + */ + head(list: T[]): T; + head(list: string): string; + + /** + * Returns true if its arguments are identical, false otherwise. Values are identical if they reference the + * same memory. NaN is identical to NaN; 0 and -0 are not identical. + */ + identical(a: T, b: T): boolean; + identical(a: T): (b: T) => boolean; + + + /** + * A function that does nothing but return the parameter supplied to it. Good as a default + * or placeholder function. + */ + identity(a: T): T; + + /** + * Creates a function that will process either the onTrue or the onFalse function depending upon the result + * of the condition predicate. + */ + ifElse(fn: Pred, onTrue: Arity1Fn, onFalse: Arity1Fn): Arity1Fn; + + + /** + * Increments its argument. + */ + inc(n: number): number; + + /** + * Given a function that generates a key, turns a list of objects into an object indexing the objects + * by the given key. + */ + indexBy(fn: (a: T) => string, list: T[]): U; + indexBy(fn: (a: T) => string): (list: T[]) => U; + + /** + * Returns the position of the first occurrence of an item in an array + * (by strict equality), + * or -1 if the item is not included in the array. + */ + indexOf(target: T, list: T[]): number; + indexOf(target: T): (list: T[]) => number; + + /** + * Returns all but the last element of a list. + */ + init(list: T[]): T[]; + + /** + * Inserts the supplied element into the list, at index index. Note that + * this is not destructive: it returns a copy of the list with the changes. + */ + insert(index: number, elt: T, list: T[]): T[]; + insert(index: number, elt: T): (list: T[]) => T[]; + insert(index: number): (elt: T, list: T[]) => T[]; + + /** + * Inserts the sub-list into the list, at index `index`. _Note that this + * is not destructive_: it returns a copy of the list with the changes. + */ + insertAll(index: number, elts: T[], list: T[]): T[]; + insertAll(index: number, elts: T[]): (list: T[]) => T[]; + insertAll(index: number): (elts: T[], list: T[]) => T[]; + + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists. + */ + intersection(list1: T[], list2: T[]): T[]; + + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those + * elements common to both lists. Duplication is determined according + * to the value returned by applying the supplied predicate to two list + * elements. + */ + intersectionWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + + /** + * Creates a new list with the separator interposed between elements. + */ + intersperse(separator: T, list: T[]): T[]; + intersperse(separator: T): (list: T[]) => T[]; + + /** + * Transforms the items of the list with the transducer and appends the transformed items to the accumulator + * using an appropriate iterator function based on the accumulator type. + */ + into(acc: any, xf: Function, list: T[]): T[]; + into(acc: any, xf: Function): (list: T[]) => T[]; + into(acc: any): (xf: Function, list: T[]) => T[]; + + /** + * Same as R.invertObj, however this accounts for objects with duplicate values by putting the values into an array. + */ + invert(obj: T): {[index:string]: string[]}; + + /** + * Returns a new object with the keys of the given object as values, and the values of the given object as keys. + */ + invertObj(obj: any): {[index:string]: string}; + invertObj(obj: {[index: number]: string}): {[index:string]: string}; + + + /** + * Turns a named method of an object (or object prototype) into a function that can be + * called directly. Passing the optional `len` parameter restricts the returned function to + * the initial `len` parameters of the method. + * + * The returned function is curried and accepts `len + 1` parameters (or `method.length + 1` + * when `len` is not specified), and the final parameter is the target object. + */ + invoker(name: string, obj: any, len?: number): Function; + invoker(name: string): (obj: any, len?: number) => Function; + + /** + * See if an object (`val`) is an instance of the supplied constructor. + * This function will check up the inheritance chain, if any. + */ + is(ctor: any, val: any): boolean; + is(ctor: any): (val: any) => boolean; + + /** + * Tests whether or not an object is similar to an array. + */ + isArrayLike(val: any): boolean; + + /** + * Reports whether the list has zero elements. + */ + isEmpty(value: any): boolean; + + + /** + * Returns true if the input value is NaN. + */ + isNaN(x: any): boolean; + + /** + * Checks if the input value is null or undefined. + */ + isNil(value: any): boolean; + + /** + * Returns a string made by inserting the `separator` between each + * element and concatenating all the elements into a single string. + */ + join(x: string, xs: any[]): string; + join(x: string): (xs: any[]) => string; + + /** + * Applies a list of functions to a list of values. + */ + juxt(fns: {(...args: T[]): U}[]): (...args: T[]) => U[]; + + + /** + * Returns a list containing the names of all the enumerable own + * properties of the supplied object. + */ + keys(x: T): string[]; + + /** + * Returns a list containing the names of all the + * properties of the supplied object, including prototype properties. + */ + keysIn(obj: T): string[]; + + /** + * Returns the last element from a list. + */ + last(list: T[]): T; + last(list: string): string; + + /** + * Returns the position of the last occurrence of an item (by strict equality) in + * an array, or -1 if the item is not included in the array. + */ + lastIndexOf(target: T, list: T[]): number; + + /** + * Returns the number of elements in the array by returning list.length. + */ + length(list: any[]): number; + + /** + * Returns a lens for the given getter and setter functions. The getter + * "gets" the value of the focus; the setter "sets" the value of the focus. + * The setter should not mutate the data structure. + */ + lens(getter: (s: T) => U, setter: (a: U, s: T) => V): Lens; + + /** + * Creates a lens that will focus on index n of the source array. + */ + lensIndex(n: number): Lens; + + /** + * Returns a lens whose focus is the specified path. + * See also view, set, over. + */ + lensPath(path: string[]): Lens; + + /** + * lensProp creates a lens that will focus on property k of the source object. + */ + lensProp(str: string): { + (obj: T): U; + set(val: T, obj: U): V; + /*map(fn: Function, obj: T): T*/ + } + + /** + * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other object that satisfies + * the FantasyLand Apply spec. + */ + lift(fn: Function, ...args: any[]): any; + + /** + * "lifts" a function to be the specified arity, so that it may "map over" that many lists, Functions or other + * objects that satisfy the FantasyLand Apply spec. + */ + liftN(n: number, fn: Function, ...args: any[]): any; + + + /** + * Returns true if the first parameter is less than the second. + */ + lt(a: number, b: number): boolean; + lt(a: number): (b: number) => boolean; + + /** + * Returns true if the first parameter is less than or equal to the second. + */ + lte(a: number, b: number): boolean; + lte(a: number): (b: number) => boolean; + + /** + * Returns a new list, constructed by applying the supplied function to every element of the supplied list. + */ + map(fn: (x: T) => U, list: T[]): U[]; + map(fn: (x: T) => U, obj: Functor): Functor; // used in functors + map(fn: (x: T) => U): (list: T[]) => U[]; + + /** + * The mapAccum function behaves like a combination of map and reduce. + */ + mapAccum(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; + mapAccum(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; + mapAccum(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; + + /** + * The mapAccumRight function behaves like a combination of map and reduce. + */ + mapAccumRight(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; + mapAccumRight(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; + mapAccumRight(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; + + + /** + * Like mapObj, but but passes additional arguments to the predicate function. + */ + mapObjIndexed(fn: (value: T, key: string, obj?: any) => TResult, obj: any): {[index:string]: TResult}; + mapObjIndexed(fn: (value: T, key: string, obj?: any) => TResult): (obj: any) => {[index:string]: TResult}; + + /** + * Tests a regular expression agains a String + */ + match(regexp: RegExp, str: string): any[]; + match(regexp: RegExp): (str: string) => any[]; + + + /** + * mathMod behaves like the modulo operator should mathematically, unlike the `%` + * operator (and by extension, R.modulo). So while "-17 % 5" is -2, + * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN + * when the modulus is zero or negative. + */ + mathMod(a: number, b: number): number; + mathMod(a: number): (b: number) => number; + + + /** + * Returns the larger of its two arguments. + */ + max(a: Ord, b: Ord): Ord; + max(a: Ord): (b: Ord) => Ord; + + /** + * Takes a function and two values, and returns whichever value produces + * the larger result when passed to the provided function. + */ + maxBy(keyFn: (a: T) => Ord, a: T, b: T): T; + maxBy(keyFn: (a: T) => Ord, a: T): (b: T) => T; + maxBy(keyFn: (a: T) => Ord): CurriedFunction2 + + /** + * Returns the mean of the given list of numbers. + */ + mean(list: number[]): number; + + /** + * Returns the median of the given list of numbers. + */ + median(list: number[]): number; + + /** + * Creates a new function that, when invoked, caches the result of calling fn for a given argument set and + * returns the result. Subsequent calls to the memoized fn with the same argument set will not result in an + * additional call to fn; instead, the cached result for that set of arguments will be returned. + */ + memoize(fn: Function): Function; + + /** + * Create a new object with the own properties of a + * merged with the own properties of object b. + * This function will *not* mutate passed-in objects. + */ + merge(a: T1, b: T2): T1 & T2; + merge(a: T1): (b: T2) => T1 & T2; + + + /** + * Merges a list of objects together into one object. + */ + mergeAll(list: any[]): T; + + /** + * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, + * the provided function is applied to the values associated with the key in each object, with the result being used as + * the value associated with the key in the returned object. The key will be excluded from the returned object if the + * resulting value is undefined. + */ + mergeWith(fn: (x: any, z: any) => any, a: U, b: V): U & V; + mergeWith(fn: (x: any, z: any) => any, a: U): (b: V) => U & V; + mergeWith(fn: (x: any, z: any) => any): (a: U, b: V) => U & V; + + /** + * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, + * the provided function is applied to the key and the values associated with the key in each object, with the + * result being used as the value associated with the key in the returned object. The key will be excluded from + * the returned object if the resulting value is undefined. + */ + mergeWithKey(fn: (str: string, x: any, z: any) => any, a: U, b: V): U & V; + mergeWithKey(fn: (str: string, x: any, z: any) => any, a: U): (b: V) => U & V; + mergeWithKey(fn: (str: string, x: any, z: any) => any): (a: U, b: V) => U & V; + + /** + * Returns the smaller of its two arguments. + */ + min(a: Ord, b: Ord): Ord; + min(a: Ord): (b: Ord) => Ord; + + /** + * Takes a function and two values, and returns whichever value produces + * the smaller result when passed to the provided function. + */ + minBy(keyFn: (a: T) => Ord, a: T, b: T): T; + minBy(keyFn: (a: T) => Ord, a: T): (b: T) => T; + minBy(keyFn: (a: T) => Ord): CurriedFunction2 + + /** + * Divides the second parameter by the first and returns the remainder. + * The flipped version (`moduloBy`) may be more useful curried. + * Note that this functions preserves the JavaScript-style behavior for + * modulo. For mathematical modulo see `mathMod` + */ + modulo(a: number, b: number): number; + modulo(a: number): (b: number) => number; + + /** + * Multiplies two numbers. Equivalent to a * b but curried. + */ + multiply(a: number, b: number): number; + multiply(a: number): (b: number) => number; + + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. + * Any extraneous parameters will not be passed to the supplied function. + */ + nAry(n: number, fn: (...arg: any[]) => any): Function; + + /** + * Negates its argument. + */ + negate(n: number): number; + + + /** + * Returns true if no elements of the list match the predicate, false otherwise. + */ + none(fn: (a: T) => boolean, list: T[]): boolean; + none(fn: (a: T) => boolean): (list: T[]) => boolean; + + + /** + * A function wrapping a call to the given function in a `!` operation. It will return `true` when the + * underlying function would return a false-y value, and `false` when it would return a truth-y one. + */ + not(value: any): boolean; + + /** + * Returns the nth element in a list. + */ + nth(n: number, list: T[]): T; + nth(n: number): (list: T[]) => T; + + /** + * Returns a function which returns its nth argument. + */ + nthArg(n: number): (...a: any[]) => any; + + /** + * Creates an object containing a single key:value pair. + */ + objOf(key: string, value: T): {string: T}; + objOf(key: string): (value: T) => {string: T}; + + /** + * Returns a singleton array containing the value provided. + */ + of(x: T): T[]; + //of(x: T[]): T[][]; unnecessary typing and introduced error in unless example + + /** + * Returns a partial copy of an object omitting the keys specified. + */ + omit(names: string[], obj: T): T; + omit(names: string[]): (obj: T) => T; + + /** + * Accepts a function fn and returns a function that guards invocation of fn such that fn can only ever be + * called once, no matter how many times the returned function is invoked. The first value calculated is + * returned in subsequent invocations. + */ + once(fn: Function): Function; + + /** + * A function that returns the first truthy of two arguments otherwise the last argument. Note that this is + * NOT short-circuited, meaning that if expressions are passed they are both evaluated. + * Dispatches to the or method of the first argument if applicable. + */ + or(a: T, b: U): T|U; + or(a: T): (b: U) => T|U; + or(fn1: T, val2: U): T|U; + or(fn1: T): (val2: U) => T|U; + + + /** + * Returns the result of "setting" the portion of the given data structure + * focused by the given lens to the given value. + */ + over(lens: Lens, fn: Arity1Fn, value: T): T; + over(lens: Lens, fn: Arity1Fn, value: T[]): T[]; + over(lens: Lens, fn: Arity1Fn): (value: T) => T; + over(lens: Lens, fn: Arity1Fn): (value: T[]) => T[]; + over(lens: Lens): (fn: Arity1Fn, value: T) => T; + over(lens: Lens): (fn: Arity1Fn, value: T[]) => T[]; + + + /** + * Takes two arguments, fst and snd, and returns [fst, snd]. + */ + pair(fst: F, snd: S): [F, S]; + + /** + * Accepts as its arguments a function and any number of values and returns a function that, + * when invoked, calls the original function with all of the values prepended to the + * original function's arguments list. In some libraries this function is named `applyLeft`. + */ + partial(fn: Function, ...args: any[]): Function; + + /** + * Accepts as its arguments a function and any number of values and returns a function that, + * when invoked, calls the original function with all of the values appended to the original + * function's arguments list. + */ + partialRight(fn: Function, ...args: any[]): Function; + + /** + * Takes a predicate and a list and returns the pair of lists of elements + * which do and do not satisfy the predicate, respectively. + */ + partition(fn: (a: string) => boolean, list: string[]): string[][]; + partition(fn: (a: T) => boolean, list: T[]): T[][]; + partition(fn: (a: T) => boolean): (list: T[]) => T[][]; + partition(fn: (a: string) => boolean): (list: string[]) => string[][]; + + /** + * Retrieve the value at a given path. + */ + path(path: string[], obj: any): T; + path(path: string[]): (obj: any) => T; + + /** + * Determines whether a nested path on an object has a specific value, + * in `R.equals` terms. Most likely used to filter a list. + */ + pathEq(path: string[], val: any, obj: any): boolean; + pathEq(path: string[], val: any): (obj: any) => boolean; + pathEq(path: string[]): (val: any, obj: any) => boolean; + pathEq(path: string[]): (val: any) => (obj: any) => boolean; + + /** + * If the given, non-null object has a value at the given path, returns the value at that path. + * Otherwise returns the provided default value. + */ + pathOr(d: T, p: string[], obj: any): T|any; + pathOr(d: T, p: string[]): (obj: any) => T|any; + pathOr(d: T): (p: string[], obj: any) => T|any; + + + /** + * Returns a partial copy of an object containing only the keys specified. If the key does not exist, the + * property is ignored. + */ + pick(names: string[], obj: T): U; + pick(names: string[]): (obj: T) => U; + + + /** + * Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist. + */ + pickAll(names: string[], obj: T): U; + pickAll(names: string[]): (obj: T) => U; + + + /** + * Returns a partial copy of an object containing only the keys that satisfy the supplied predicate. + */ + pickBy(pred: ObjPred, obj: T): U; + pickBy(pred: ObjPred): (obj: T) => U; + + + /** + * Creates a new function that runs each of the functions supplied as parameters in turn, + * passing the return value of each function invocation to the next function invocation, + * beginning with whatever arguments were passed to the initial invocation. + */ + pipe(fn0: (x0: V0) => T1): (x0: V0) => T1; + pipe(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; + + pipe(fn0: (x0: V0) => T1, fn1: (x: T1) => T2): (x0: V0) => T2; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1) => T2; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1, x2: V2) => T2; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x: V0) => T3; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1) => T3; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1, x2: V2) => T3; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x: V0) => T4; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1) => T4; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1, x2: V2) => T4; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x: V0) => T5; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1) => T5; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1, x2: V2) => T5; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x: V0) => T6; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1) => T6; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1, x2: V2) => T6; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn: (x: T6) => T7): (x: V0) => T7; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1) => T7; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1, x2: V2) => T7; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn: (x: T7) => T8): (x: V0) => T8; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T5) => T6, fn7: (x: T7) => T8): (x0: V0, x1: V1) => T8; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T5) => T6, fn7: (x: T7) => T8): (x0: V0, x1: V1, x2: V2) => T8; + + + /** + * Returns a new list by plucking the same named property off all objects in the list supplied. + */ + pluck(p: string|number, list: any[]): T[]; + pluck(p: string|number): (list: any[]) => T[]; + + /** + * Returns a new list with the given element at the front, followed by the contents of the + * list. + */ + prepend(el: T, list: T[]): T[]; + prepend(el: T): (list: T[]) => T[]; + + /** + * Multiplies together all the elements of a list. + */ + product(list: number[]): number; + + + /** + * Reasonable analog to SQL `select` statement. + */ + project(props: string[], objs: T[]): U[]; + + /** + * Returns a function that when supplied an object returns the indicated property of that object, if it exists. + * Note: TS1.9 # replace any by dictionary + */ + prop(p: string, obj: any): T; + prop(p: string): (obj: any) => T; + + /** + * Determines whether the given property of an object has a specific + * value according to strict equality (`===`). Most likely used to + * filter a list. + */ + // propEq(name: string, val: T, obj: {[index:string]: T}): boolean; + // propEq(name: string, val: T, obj: {[index:number]: T}): boolean; + propEq(name: string, val: T, obj: any): boolean; + // propEq(name: number, val: T, obj: any): boolean; + propEq(name: string, val: T): (obj: any) => boolean; + // propEq(name: number, val: T): (obj: any) => boolean; + propEq(name: string): (val: T, obj: any) => boolean; + // propEq(name: number): (val: T, obj: any) => boolean; + + /** + * Returns true if the specified object property is of the given type; false otherwise. + */ + propIs(type: any, name: string, obj: any): boolean; + propIs(type: any, name: string): (obj: any) => boolean; + propIs(type: any): { + (name: string, obj: any): boolean; + (name: string): (obj: any) => boolean; + } + + /** + * If the given, non-null object has an own property with the specified name, returns the value of that property. + * Otherwise returns the provided default value. + */ + propOr(val: T, p: string, obj: U): V; + propOr(val: T, p: string): (obj: U) => V; + propOr(val: T): (p: string, obj: U) => V; + + /** + * Returns the value at the specified property. + * The only difference from `prop` is the parameter order. + * Note: TS1.9 # replace any by dictionary + */ + props(ps: string[], obj: any): T[]; + props(ps: string[]): (obj: any) => T[]; + + /** + * Returns true if the specified object property satisfies the given predicate; false otherwise. + */ + propSatisfies(pred: (val: T) => boolean, name: string, obj: U): boolean; + propSatisfies(pred: (val: T) => boolean, name: string): (obj: U) => boolean; + propSatisfies(pred: (val: T) => boolean): CurriedFunction2; + + /** + * Returns a list of numbers from `from` (inclusive) to `to` + * (exclusive). In mathematical terms, `range(a, b)` is equivalent to + * the half-open interval `[a, b)`. + */ + range(from: number, to: number): number[]; + range(from: number): (to: number) => number[]; + + /** + * Returns a single item by iterating through the list, successively calling the iterator + * function and passing it an accumulator value and the current value from the array, and + * then passing the result to the next call. + */ + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult, list: T[]): TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced): (acc: TResult, list: T[]) => TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult): (list: T[]) => TResult; + + /** + * Groups the elements of the list according to the result of calling the String-returning function keyFn on each + * element and reduces the elements of each group to a single value via the reducer function valueFn. + */ + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string, list: T[]): {[index: string]: TResult}; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string): (list: T[]) => {[index: string]: TResult}; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult): CurriedFunction2<(elem: T) => string, T[], {[index: string]: TResult}>; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult): CurriedFunction3 string, T[], {[index: string]: TResult}>; + + /** + * Returns a value wrapped to indicate that it is the final value of the reduce and + * transduce functions. The returned value should be considered a black box: the internal + * structure is not guaranteed to be stable. + */ + reduced(elem: T): Reduced; + + /** + * Returns a single item by iterating through the list, successively calling the iterator + * function and passing it an accumulator value and the current value from the array, and + * then passing the result to the next call. + */ + reduceRight(fn: (acc: TResult, elem: T) => TResult, acc: TResult, list: T[]): TResult; + reduceRight(fn: (acc: TResult, elem: T) => TResult): (acc: TResult, list: T[]) => TResult; + reduceRight(fn: (acc: TResult, elem: T) => TResult, acc: TResult): (list: T[]) => TResult; + + /** + * Similar to `filter`, except that it keeps only values for which the given predicate + * function returns falsy. + */ + reject(fn: (value: T) => boolean, list: T[]): T[]; + reject(fn: (value: T) => boolean): (list: T[]) => T[]; + + /** + * Removes the sub-list of `list` starting at index `start` and containing `count` elements. + */ + remove(start: number, count: number, list: T[]): T[]; + remove(start: number): (count: number, list: T[]) => T[]; + remove(start: number, count: number): (list: T[]) => T[]; + + /** + * Returns a fixed list of size n containing a specified identical value. + */ + repeat(a: T, n: number): T[]; + repeat(a: T): (n: number) => T[]; + + + /** + * Replace a substring or regex match in a string with a replacement. + */ + replace(pattern: RegExp, replacement: string, str: string): string; + replace(pattern: RegExp, replacement: string): (str: string) => string; + replace(pattern: RegExp): (replacement: string) => (str: string) => string; + replace(pattern: String, replacement: string, str: string): string; + replace(pattern: String, replacement: string): (str: string) => string; + replace(pattern: String): (replacement: string) => (str: string) => string; + + + /** + * Returns a new list with the same elements as the original list, just in the reverse order. + */ + reverse(list: T[]): T[]; + + /** + * Scan is similar to reduce, but returns a list of successively reduced values from the left. + */ + scan(fn: (acc: TResult, elem: T) => any, acc: TResult, list: T[]): TResult[]; + scan(fn: (acc: TResult, elem: T) => any, acc: TResult): (list: T[]) => TResult[]; + scan(fn: (acc: TResult, elem: T) => any): (acc: TResult, list: T[]) => TResult[]; + + /** + * Returns the result of "setting" the portion of the given data structure focused by the given lens to the + * given value. + */ + set(lens: Lens, a: U, obj: T): T; + set(lens: Lens, a: U): (obj: T) => T; + set(lens: Lens): (a: U, obj: T) => T; + + /** + * Returns the elements from `xs` starting at `a` and ending at `b - 1`. + */ + slice(a: number, b: number, list: string): string; + slice(a: number, b: number, list: T[]): T[]; + slice(a: number, b: number): (list: string|T[]) => string|T[]; + slice(a: number): (b: number, list: string|T[]) => string|T[]; + + /** + * Returns a copy of the list, sorted according to the comparator function, which should accept two values at a + * time and return a negative number if the first value is smaller, a positive number if it's larger, and zero + * if they are equal. + */ + sort(fn: (a: T, b: T) => number, list: T[]): T[]; + sort(fn: (a: T, b: T) => number): (list: T[]) => T[]; + + + /** + * Sorts the list according to a key generated by the supplied function. + */ + sortBy(fn: (a: any) => string, list: T[]): T[]; + sortBy(fn: (a: any) => string): (list: T[]) => T[]; + + /** + * Splits a string into an array of strings based on the given + * separator. + */ + split(sep: string): (str: string) => string[]; + split(sep: RegExp): (str: string) => string[]; + split(sep: string, str: string): string[]; + split(sep: RegExp, str: string): string[]; + + /** + * Splits a given list or string at a given index. + */ + splitAt(index: number, list: T): T[]; + splitAt(index: number): (list: T) => T[]; + splitAt(index: number, list: T[]): T[][]; + splitAt(index: number): (list: T[]) => T[][]; + + /** + * Splits a collection into slices of the specified length. + */ + splitEvery(a: number, list: T[]): T[][]; + splitEvery(a: number): (list: T[]) => T[][]; + + + /** + * Takes a list and a predicate and returns a pair of lists with the following properties: + * - the result of concatenating the two output lists is equivalent to the input list; + * - none of the elements of the first output list satisfies the predicate; and + * - if the second output list is non-empty, its first element satisfies the predicate. + */ + splitWhen(pred: (val: T) => boolean, list: U[]): U[][]; + splitWhen(pred: (val: T) => boolean): (list: U[]) => U[][]; + + /** + * Subtracts two numbers. Equivalent to `a - b` but curried. + */ + subtract(a: number, b: number): number; + subtract(a: number): (b: number) => number; + + /** + * Adds together all the elements of a list. + */ + sum(list: number[]): number; + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. + */ + symmetricDifference(list1: T[], list2: T[]): T[]; + symmetricDifference(list: T[]): (list: T[]) => T[]; + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. + * Duplication is determined according to the value returned by applying the supplied predicate to two list elements. + */ + symmetricDifferenceWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + symmetricDifferenceWith(pred: (a: T, b: T) => boolean): CurriedFunction2; + + /** + * A function that always returns true. Any passed in parameters are ignored. + */ + T(): boolean; + + /** + * Returns all but the first element of a list. + */ + tail(list: T[]): T[]; + + /** + * Returns a new list containing the first `n` elements of the given list. If + * `n > * list.length`, returns a list of `list.length` elements. + */ + take(n: number, xs: T[]): T[]; + take(n: number, xs: string): string; + take(n: number): { + (xs: string): string; + (xs: T[]): T[]; + } + + + /** + * Returns a new list containing the last n elements of the given list. If n > list.length, + * returns a list of list.length elements. + */ + takeLast(n: number, xs: T[]): T[]; + takeLast(n: number, xs: string): string; + takeLast(n: number): { + (xs: T[]): T[]; + (xs: string): string; + } + + /** + * Returns a new list containing the last n elements of a given list, passing each value + * to the supplied predicate function, and terminating when the predicate function returns + * false. Excludes the element that caused the predicate function to fail. The predicate + * function is passed one argument: (value). + */ + takeLastWhile(pred: (a: T) => Boolean, list: T[]): T[]; + takeLastWhile(pred: (a: T) => Boolean): (list: T[]) => T[]; + + /** + * Returns a new list containing the first `n` elements of a given list, passing each value + * to the supplied predicate function, and terminating when the predicate function returns + * `false`. + */ + takeWhile(fn: (x: T) => boolean, list: T[]): T[]; + takeWhile(fn: (x: T) => boolean): (list: T[]) => T[]; + + /** + * The function to call with x. The return value of fn will be thrown away. + */ + tap(fn: (a: T) => any, value: T): T; + tap(fn: (a: T) => any): (value: T) => T; + + /** + * Determines whether a given string matches a given regular expression. + */ + test(regexp: RegExp, str: string): boolean; + test(regexp: RegExp): (str: string) => boolean; + + /** + * Calls an input function `n` times, returning an array containing the results of those + * function calls. + */ + times(fn: (i: number) => T, n: number): T[]; + times(fn: (i: number) => T): (n: number) => T[]; + + + /** + * The lower case version of a string. + */ + toLower(str: string): string; + + /** + * Converts an object into an array of key, value arrays. + * Only the object's own properties are used. + * Note that the order of the output array is not guaranteed to be + * consistent across different JS platforms. + */ + toPairs(obj: {[k: string]: S} | {[k: number]: S} | any): [F,S][]; + + /** + * Converts an object into an array of key, value arrays. + * The object's own properties and prototype properties are used. + * Note that the order of the output array is not guaranteed to be + * consistent across different JS platforms. + */ + toPairsIn(obj: {[k: string]: S} | {[k: number]: S} | any): [F,S][]; + + /** + * Returns the string representation of the given value. eval'ing the output should + * result in a value equivalent to the input value. Many of the built-in toString + * methods do not satisfy this requirement. + * + * If the given value is an [object Object] with a toString method other than + * Object.prototype.toString, this method is invoked with no arguments to produce the + * return value. This means user-defined constructor functions can provide a suitable + * toString method. + */ + toString(val: T): string; + + /** + * The upper case version of a string. + */ + toUpper(str: string): string; + + /** + * Initializes a transducer using supplied iterator function. Returns a single item by iterating through the + * list, successively calling the transformed iterator function and passing it an accumulator value and the + * current value from the array, and then passing the result to the next call. + */ + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[], list: T[]): U; + transduce(xf: (arg: T[]) => T[]): (fn: (acc: U[], val: U) => U[], acc: T[], list: T[]) => U; + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[]): (acc: T[], list: T[]) => U; + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[]): (list: T[]) => U; + + /** + * Transposes the rows and columns of a 2D list. When passed a list of n lists of length x, returns a list of x lists of length n. + */ + transpose(list: any[][]): any[][]; + + /** + * Removes (strips) whitespace from both ends of the string. + */ + trim(str: string): string; + + /** + * tryCatch takes two functions, a tryer and a catcher. The returned function evaluates the tryer; if it does + * not throw, it simply returns the result. If the tryer does throw, the returned function evaluates the catcher + * function and returns its result. Note that for effective composition with this function, both the tryer and + * catcher functions must return the same type of results. + */ + tryCatch(tryer: (...args: any[]) => T, catcher: (...args: any[]) => T, x: any): T; + + /** + * Gives a single-word string description of the (native) type of a value, returning such answers as 'Object', + * 'Number', 'Array', or 'Null'. Does not attempt to distinguish user Object types any further, reporting them + * all as 'Object'. + */ + type(val: any): string; + + /** + * Takes a function fn, which takes a single array argument, and returns a function which: + * - takes any number of positional arguments; + * - passes these arguments to fn as an array; and + * - returns the result. + * In other words, R.unapply derives a variadic function from a function which takes an array. + * R.unapply is the inverse of R.apply. + */ + unapply(fn: (args: any[]) => T): (...args: any[]) => T; + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly 1 parameter. + * Any extraneous parameters will not be passed to the supplied function. + */ + unary(fn: (a: T, ...args: any[]) => any): (a: T) => any + + /** + * Returns a function of arity n from a (manually) curried function. + */ + uncurryN(len: number, fn: (a: any) => any): (...a: any[]) => T; + + /** + * Builds a list from a seed value. Accepts an iterator function, which returns either false + * to stop iteration or an array of length 2 containing the value to add to the resulting + * list and the seed to be used in the next call to the iterator function. + */ + unfold(fn: (seed: T) => TResult[]|boolean, seed: T): TResult[]; + unfold(fn: (seed: T) => TResult[]|boolean): (seed: T) => TResult[]; + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the + * elements of each list. + */ + union(as: T[], bs: T[]): T[]; + union(as: T[]): (bs: T[]) => T[]; + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is + * determined according to the value returned by applying the supplied predicate to two list elements. + */ + unionWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + unionWith(pred: (a: T, b: T) => boolean): CurriedFunction2 + + /** + * Returns a new list containing only one copy of each element in the original list. + */ + uniq(list: T[]): T[]; + + /** + * Returns a new list containing only one copy of each element in the original list, based upon the value returned by applying the supplied function to each list element. Prefers the first item if the supplied function produces the same value on two items. R.equals is used for comparison. + */ + uniqBy(fn: (a: T) => U, list: T[]): T[]; + uniqBy(fn: (a: T) => U): (list: T[]) => T[]; + + /** + * Returns a new list containing only one copy of each element in the original list, based upon the value + * returned by applying the supplied predicate to two list elements. + */ + uniqWith(pred: (x: T, y: T) => boolean, list: T[]): T[]; + uniqWith(pred: (x: T, y: T) => boolean): (list: T[]) => T[]; + + /** + * Tests the final argument by passing it to the given predicate function. If the predicate is not satisfied, + * the function will return the result of calling the whenFalseFn function with the same argument. If the + * predicate is satisfied, the argument is returned as is. + */ + unless(pred: (a: T) => boolean, whenFalseFn: (a: T) => U, obj: T): U; + unless(pred: (a: T) => boolean, whenFalseFn: (a: T) => U): (obj: T) => U; + + /** + * Returns a new list by pulling every item at the first level of nesting out, and putting + * them in a new array. + */ + unnest(x: T[][]): T[]; + unnest(x: T[]): T[]; + + /** + * Takes a predicate, a transformation function, and an initial value, and returns a value of the same type as + * the initial value. It does so by applying the transformation until the predicate is satisfied, at which point + * it returns the satisfactory value. + */ + until(pred: (val: T) => boolean, fn: (val: T) => U, init: U): U; + until(pred: (val: T) => boolean, fn: (val: T) => U): (init: U) => U; + + /** + * Returns a new copy of the array with the element at the provided index replaced with the given value. + */ + update(index: number, value: T, list: T[]): T[]; + update(index: number, value: T): (list: T[]) => T[]; + + /** + * Accepts a function fn and a list of transformer functions and returns a new curried function. + * When the new function is invoked, it calls the function fn with parameters consisting of the + * result of calling each supplied handler on successive arguments to the new function. + * + * If more arguments are passed to the returned function than transformer functions, those arguments + * are passed directly to fn as additional parameters. If you expect additional arguments that don't + * need to be transformed, although you can ignore them, it's best to pass an identity function so + * that the new function reports the correct arity. + */ + useWith(fn: Function, transformers: Function[]): Function; + + /** + * Returns a list of all the enumerable own properties of the supplied object. + * Note that the order of the output array is not guaranteed across + * different JS platforms. + */ + values(obj: {[index: string]: T}): T[]; + values(obj: any): T[]; + + /** + * Returns a list of all the properties, including prototype properties, of the supplied + * object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. + */ + valuesIn(obj: any): T[]; + + /** + * Returns a "view" of the given data structure, determined by the given lens. The lens's focus determines which + * portion of the data structure is visible. + */ + view(lens: Lens, obj: T): U; + + /** + * Tests the final argument by passing it to the given predicate function. If the predicate is satisfied, the function + * will return the result of calling the whenTrueFn function with the same argument. If the predicate is not satisfied, + * the argument is returned as is. + */ + when(pred: (a: T) => boolean, whenTrueFn: (a: T) => U, obj: T): U; + when(pred: (a: T) => boolean, whenTrueFn: (a: T) => U): (obj: T) => U; + + /** + * Takes a spec object and a test object and returns true if the test satisfies the spec. + * Any property on the spec that is not a function is interpreted as an equality + * relation. + * + * If the spec has a property mapped to a function, then `where` evaluates the function, passing in + * the test object's value for the property in question, as well as the whole test object. + * + * `where` is well suited to declarativley expressing constraints for other functions, e.g., + * `filter`, `find`, `pickWith`, etc. + */ + where(spec: T, testObj: U): boolean; + where(spec: T): (testObj: U) => boolean; + where(spec: ObjFunc2, testObj: U): boolean; + where(spec: ObjFunc2): (testObj: U) => boolean; + + /** + * Takes a spec object and a test object; returns true if the test satisfies the spec, + * false otherwise. An object satisfies the spec if, for each of the spec's own properties, + * accessing that property of the object gives the same value (in R.eq terms) as accessing + * that property of the spec. + */ + whereEq(spec: T, obj: U): boolean; + whereEq(spec: T): (obj: U) => boolean; + + /** + * Returns a new list without values in the first argument. R.equals is used to determine equality. + * Acts as a transducer if a transformer is given in list position. + */ + without(list1: T[], list2: T[]): T[]; + without(list1: T[]): (list2: T[]) => T[]; + + /** + * Wrap a function inside another to allow you to make adjustments to the parameters, or do other processing + * either before the internal function is called or with its results. + */ + wrap(fn: Function, wrapper: Function): Function; + + /** + * Creates a new list out of the two supplied by creating each possible pair from the lists. + */ + xprod(as: K[], bs: V[]): KeyValuePair[]; + xprod(as: K[]): (bs: V[]) => KeyValuePair[]; + + /** + * Creates a new list out of the two supplied by pairing up equally-positioned items from + * both lists. Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. + */ + zip(list1: K[], list2: V[]): KeyValuePair[]; + zip(list1: K[]): (list2: V[]) => KeyValuePair[]; + + /** + * Creates a new object out of a list of keys and a list of values. + */ + // TODO: Dictionary as a return value is to specific, any seems to loose + zipObj(keys: string[], values: T[]): {[index:string]: T}; + zipObj(keys: string[]): (values: T[]) => {[index:string]: T}; + + + /** + * Creates a new list out of the two supplied by applying the function to each + * equally-positioned pair in the lists. + */ + zipWith(fn: (x: T, y: U) => TResult, list1: T[], list2: U[]): TResult[]; + zipWith(fn: (x: T, y: U) => TResult, list1: T[]): (list2: U[]) => TResult[]; + zipWith(fn: (x: T, y: U) => TResult): (list1: T[], list2: U[]) => TResult[]; + + } +} + +export = R; From 27cbba9005c03368e5d53f11465e96c560f6cdc9 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 21:52:38 +0300 Subject: [PATCH 09/56] Templating type definition --- object-assign/object-assign.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/object-assign/object-assign.d.ts b/object-assign/object-assign.d.ts index 52ef486c72..ad797b25ef 100644 --- a/object-assign/object-assign.d.ts +++ b/object-assign/object-assign.d.ts @@ -4,6 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "object-assign" { + function objectAssign(target: T, source: U): T & U; + function objectAssign(target: T, source1: U, source2: V): T & U & V; + function objectAssign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q): T & U & V & W & Q; + function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: T): T & U & V & W & Q & R; function objectAssign(target: any, ...sources: any[]): any; export = objectAssign; } From d3d99d650b27beaf7f8c436f3e49f96977a5aec9 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 22:35:52 +0300 Subject: [PATCH 10/56] Update react-redux-tests.tsx --- react-redux/react-redux-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index 7dba7f2fa2..3ebf6ae539 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -268,8 +268,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { - return objectAssign({}, ownProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { + return objectAssign({}, ownProps, dispatchProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From a0e4d1fc3740d86e28e8856e981f95fffd5d813d Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 22:41:01 +0300 Subject: [PATCH 11/56] Update react-redux-2.1.2-tests.tsx --- react-redux/react-redux-2.1.2-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-2.1.2-tests.tsx b/react-redux/react-redux-2.1.2-tests.tsx index 7ead497767..a2aade3ff4 100644 --- a/react-redux/react-redux-2.1.2-tests.tsx +++ b/react-redux/react-redux-2.1.2-tests.tsx @@ -233,8 +233,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { - return objectAssign({}, ownProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { + return objectAssign({}, ownProps, dispatchProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From 2f07f4c429ca54253faa4b2ee072645299b63e48 Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Fri, 19 Aug 2016 12:27:12 -0500 Subject: [PATCH 12/56] Fix module name. --- auth0-js/auth0-js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth0-js/auth0-js.d.ts b/auth0-js/auth0-js.d.ts index 1ee4ab9d7c..515d52af7e 100644 --- a/auth0-js/auth0-js.d.ts +++ b/auth0-js/auth0-js.d.ts @@ -127,6 +127,6 @@ interface Auth0DelegationToken { declare var Auth0: Auth0Static; -declare module "auth0" { +declare module "auth0-js" { export = Auth0 } From 6e9b95facc04e268b48be30c605653055c6be046 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 22:37:37 +0300 Subject: [PATCH 13/56] Update object-assign.d.ts --- object-assign/object-assign.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/object-assign/object-assign.d.ts b/object-assign/object-assign.d.ts index ad797b25ef..c3f92b7592 100644 --- a/object-assign/object-assign.d.ts +++ b/object-assign/object-assign.d.ts @@ -8,7 +8,7 @@ declare module "object-assign" { function objectAssign(target: T, source1: U, source2: V): T & U & V; function objectAssign(target: T, source1: U, source2: V, source3: W): T & U & V & W; function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q): T & U & V & W & Q; - function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: T): T & U & V & W & Q & R; + function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: R): T & U & V & W & Q & R; function objectAssign(target: any, ...sources: any[]): any; export = objectAssign; } From 912e35ffabf81a20987c185b90eeee616ac6ec1d Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:00:49 +0300 Subject: [PATCH 14/56] Update object-assign-tests.ts --- object-assign/object-assign-tests.ts | 80 ++++++++++++++++++++++++---- 1 file changed, 71 insertions(+), 9 deletions(-) diff --git a/object-assign/object-assign-tests.ts b/object-assign/object-assign-tests.ts index 53dfd5e707..d1304422d3 100644 --- a/object-assign/object-assign-tests.ts +++ b/object-assign/object-assign-tests.ts @@ -1,17 +1,79 @@ /// import objectAssign = require("object-assign"); -function assign1() { - var result = objectAssign({hello: "world"}); - return result; +interface Target { + hellow: string; } -function assign2() { - var result = objectAssign({hello: "world"}, {hello: "worlds", second: "extra"}); - return result; +interface Source1 { + source1: string; } -function assign3() { - var result = objectAssign({hello: "world"}, {hello: "worlds", second: "extra"}, {hello: "stop", the: "spinning"}); - return result; +interface Result extends Target, Source1 { + } + +interface Source2 { + source2: string; +} + +interface Result2 extends Result, Source2 { + +} + +interface Source3 { + source3: string; +} + +interface Result3 extends Result2, Source3 { + +} + +interface Source4 { + source4: string; +} + +interface Result4 extends Result4, Source3 { + +} + +interface Source5 { + source2: string; +} + +interface Result5 extends Result4, Source5 { + +} + +function assign1(): Result { + return objectAssign({hellow: "world"}, {source1: "U"}); +} + +function assign2(): Result2 { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}); +} + +function assign3(): Result3 { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}); +} + +function assign4(): Result4 { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}); +} + +function assign5(): Result5 { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}); +} + +function assign() { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}, { + hellow: "hellow", + source1: "source1", + source2: "source2", + source3: "source3", + source4: "source4", + source5: "source5", + generic: "any" + }); +} + From 3af3e291f296fb37426660fdd042e4a4d00a4b75 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:01:15 +0300 Subject: [PATCH 15/56] Update object-assign-tests.ts --- object-assign/object-assign-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/object-assign/object-assign-tests.ts b/object-assign/object-assign-tests.ts index d1304422d3..d285219b24 100644 --- a/object-assign/object-assign-tests.ts +++ b/object-assign/object-assign-tests.ts @@ -38,7 +38,7 @@ interface Result4 extends Result4, Source3 { } interface Source5 { - source2: string; + source5: string; } interface Result5 extends Result4, Source5 { From 3e194fcd32705d0934ed4a545bb2bb96754b48d9 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:03:34 +0300 Subject: [PATCH 16/56] Update object-assign-tests.ts --- object-assign/object-assign-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/object-assign/object-assign-tests.ts b/object-assign/object-assign-tests.ts index d285219b24..6b9a898ed4 100644 --- a/object-assign/object-assign-tests.ts +++ b/object-assign/object-assign-tests.ts @@ -33,7 +33,7 @@ interface Source4 { source4: string; } -interface Result4 extends Result4, Source3 { +interface Result4 extends Result3, Source4 { } From f1760b924d1f7b13f6f9c936811fd1a0ac5bb6c7 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:06:33 +0300 Subject: [PATCH 17/56] Update react-redux-tests.tsx --- react-redux/react-redux-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index 3ebf6ae539..7dba7f2fa2 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -268,8 +268,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { - return objectAssign({}, ownProps, dispatchProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { + return objectAssign({}, ownProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From 5bd8afe661c476ffbb32a195d7dc2422babd6b2b Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:07:41 +0300 Subject: [PATCH 18/56] Update react-redux-2.1.2-tests.tsx --- react-redux/react-redux-2.1.2-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-2.1.2-tests.tsx b/react-redux/react-redux-2.1.2-tests.tsx index a2aade3ff4..7ead497767 100644 --- a/react-redux/react-redux-2.1.2-tests.tsx +++ b/react-redux/react-redux-2.1.2-tests.tsx @@ -233,8 +233,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { - return objectAssign({}, ownProps, dispatchProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { + return objectAssign({}, ownProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From f340b21d40bf4f2f2f93421953b2ca35c187e33b Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:19:38 +0300 Subject: [PATCH 19/56] Fixing broken test due to object-assign type definition change Not familiar with redux but merging and `dispatchProps` in `mergeProps` seems valid since `action` is required property of `DispatchProps` and should come from somewhere. --- react-redux/react-redux-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index 7dba7f2fa2..3ebf6ae539 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -268,8 +268,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { - return objectAssign({}, ownProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { + return objectAssign({}, ownProps, dispatchProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From 52a9758e65b175c1b7f3affd360735714d89ed36 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:23:31 +0300 Subject: [PATCH 20/56] Mirroring test fixes from react-redux-tests.tsx --- react-redux/react-redux-2.1.2-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-2.1.2-tests.tsx b/react-redux/react-redux-2.1.2-tests.tsx index 7ead497767..a2aade3ff4 100644 --- a/react-redux/react-redux-2.1.2-tests.tsx +++ b/react-redux/react-redux-2.1.2-tests.tsx @@ -233,8 +233,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { - return objectAssign({}, ownProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { + return objectAssign({}, ownProps, dispatchProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From 1005f869a53b929a767a873bfe6c7201f32d1ef0 Mon Sep 17 00:00:00 2001 From: Paul Oppenheim Date: Fri, 19 Aug 2016 14:29:55 -0700 Subject: [PATCH 21/56] knex allows usage of Buffer types for values --- knex/knex.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 23dc58af82..ec6403ed2c 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -12,7 +12,7 @@ declare module "knex" { type Callback = Function; type Client = Function; - type Value = string|number|boolean|Date|Array|Array|Array|Array; + type Value = string|number|boolean|Date|Array|Array|Array|Array|Buffer; type ColumnName = string|Knex.Raw|Knex.QueryBuilder; type TableName = string|Knex.Raw|Knex.QueryBuilder; From 88c5e9aca6c4a8c065cca68204ba36b8c2ffdb73 Mon Sep 17 00:00:00 2001 From: Maciej Suchecki Date: Sat, 20 Aug 2016 11:54:27 +0200 Subject: [PATCH 22/56] Modified color properties to accept gradients in whole Highcharts lib (#10700) Updated setExtremes method to accept 'eventArguments' parameter Updated 'crosshair' field to accept boolean value in HighchartsAxisOptions --- highcharts/highcharts.d.ts | 76 +++++++++++++++++++------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index de1e5343ca..bfe5a70235 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -240,7 +240,7 @@ interface HighchartsPlotBands { * Border color for the plot band. Also requires borderWidth to be set. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * Border width for the plot band. Also requires borderColor to be set. * @default 0 @@ -471,7 +471,7 @@ interface HighchartsAxisOptions { /** * Configure a crosshair that follows either the mouse pointer or the hovered point. */ - crosshair?: HighchartsCrosshairObject; + crosshair?: HighchartsCrosshairObject | boolean; /** * For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default * string representations used for each unit. For an overview of the replacement codes, see dateFormat. @@ -556,7 +556,7 @@ interface HighchartsAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0'. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 1 @@ -820,7 +820,7 @@ interface HighchartsAxisOptions { interface HighchartsColorAxisDataClass { from?: number; to?: number; - color?: string; + color?: string | HighchartsGradient; name?: string; } @@ -906,7 +906,7 @@ interface HighchartsColorAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0' */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 0 @@ -926,7 +926,7 @@ interface HighchartsColorAxisOptions { * The color of the marker. * @default 'gray' */ - color?: string; + color?: string | HighchartsGradient; }; /** * The maximum value of the axis in terms of map point values. If null, the max value is automatically calculated. @@ -1382,7 +1382,7 @@ interface HighchartsShadow { /** * @default 'black' */ - color?: string; + color?: string | HighchartsGradient; /** * @default 1 */ @@ -1491,7 +1491,7 @@ interface HighchartsChartOptions { * The color of the outer chart border. * @default '#4572A7' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the outer chart border. * @default 0 @@ -1721,7 +1721,7 @@ interface HighchartsChartOptions { interface HighchartsCSSObject { background?: string; border?: string; - color?: string; + color?: string | HighchartsGradient; cursor?: string; font?: string; fontFamily?: string; @@ -2429,7 +2429,7 @@ interface HighchartsLegendOptions { * The color of the drawn border around the legend. * @default '#909090' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border corner radius of the legend. * @default 0 @@ -2724,7 +2724,7 @@ interface HighchartsPaneBackground { /** * @default 'silver' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * @default 1 */ @@ -2803,7 +2803,7 @@ interface HighchartsDataLabels { * The border color for the data label. * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -2820,7 +2820,7 @@ interface HighchartsDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3066,7 +3066,7 @@ interface HighchartsMarkerState { * The color of the point marker's outline. When null, the series' or point's color is used. * @default '#FFFFFF', '#000000' for select state */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the point marker's outline. * @default 0 @@ -3276,7 +3276,7 @@ interface HighchartsAreaZone { * Defines the color of the series. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * A name for the dash style to use for the graph. * @since 4.1.0 @@ -3321,7 +3321,7 @@ interface HighchartsRangeDataLabels { * @default undefined * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -3338,7 +3338,7 @@ interface HighchartsRangeDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3471,7 +3471,7 @@ interface HighchartsDial { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The length of the dial's base part, relative to the total radius or length of the dial. * @default '70%'. @@ -3490,7 +3490,7 @@ interface HighchartsDial { * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the gauge dial border in pixels. * @default 0 @@ -3524,14 +3524,14 @@ interface HighchartsPivot { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The border or stroke color of the pivot. In able to change this, the borderWidth must also be set to something * other than the default 0. * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border or stroke width of the pivot. * @default 0 @@ -3554,7 +3554,7 @@ interface HighchartsTreeMapLevel { * Can set borderColor on all points which lies on the same level. * @since 4.1.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * et the dash style of the border of all the point which lies on the level. * @since 4.1.0 @@ -3569,7 +3569,7 @@ interface HighchartsTreeMapLevel { * Can set a color on all points which lies on the same level. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * Can set the options of dataLabels on each point which lies on the level. * @default undefined @@ -3594,7 +3594,7 @@ interface HighchartsTreeMapLevel { } /** - * General options for all series types + * General options for all series types. */ interface HighchartsSeriesChart { /** @@ -3615,7 +3615,7 @@ interface HighchartsSeriesChart { * specified. In bar type series it applies to the bars unless a color is specified per point. The default value is * pulled from the options.colors array. */ - color?: string; + color?: string | HighchartsGradient; /** * Polar charts only. Whether to connect the ends of a line series plot across the extremes. * @default true @@ -3860,7 +3860,7 @@ interface HighchartsAreaChart extends HighchartsSeriesChart { * A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting * allows setting a separate color for the line without altering the fillColor. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * A separate color for the negative part of the area. * @since 3.0 @@ -3902,7 +3902,7 @@ interface HighchartsBarChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4263,7 +4263,7 @@ interface HighchartsFunnelChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4385,7 +4385,7 @@ interface HighchartsHeatMapChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4468,7 +4468,7 @@ interface HighchartsPieChart extends HighchartsSeriesChart { * borderless pies. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4573,7 +4573,7 @@ interface HighchartsPyramidChart extends HighchartsSeriesChart { * The color of the border surrounding each slice * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each slice * @default 1 @@ -4688,7 +4688,7 @@ interface HighchartsTreeMapChart extends HighchartsSeriesChart { * The color of the border surrounding each tree map item. * @default '#E0E0E0' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4783,7 +4783,7 @@ interface HighchartsWaterFallChart extends HighchartsBarChart { * @default '#333333' * @since 3.0 */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The color used specifically for positive point columns. When not specified, the general series color is used. */ @@ -4834,7 +4834,7 @@ interface HighchartsIndividualSeriesOptions { * specified. In bar type series it applies to the bars unless a color is specified per point. The default * value is pulled from the options.colors array. */ - color?: string; + color?: string | HighchartsGradient; /** * You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user * that the points and lines can be clicked. @@ -4949,7 +4949,7 @@ interface HighchartsDataPoint { * Individual color for the point. By default the color is pulled from the global colors array. * @default undefined */ - color?: string; + color?: string | HighchartsGradient; /** * Serves a purpose only if a colorAxis object is defined in the chart options. This value will decide which color * the point gets from the scale of the colorAxis. @@ -5173,7 +5173,7 @@ interface HighchartsTitleOptions { } interface HighchartsCrosshairObject { - color?: string; + color?: string | HighchartsGradient; width?: number; dashStyle?: string; //Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot zIndex?: number; @@ -5200,7 +5200,7 @@ interface HighchartsTooltipOptions extends HighchartsSeriesTooltipOptions { * The color of the tooltip border. When null, the border takes the color of the corresponding series or point. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The radius of the rounded border corners. * @default 3 @@ -5602,7 +5602,7 @@ interface HighchartsAxisObject { * @param {boolean | HighchartsAnimation} animation When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation): void; + setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation, eventArguments?: any): void; /** * Update the title of the axis after render time. * @param {HighchartsAxisTitle} title The new title options on the same format as given in xAxis.title. From 502f0dfb79a3f1587a4b49b0c756bdcd12dbd1b1 Mon Sep 17 00:00:00 2001 From: Ezekiel Victor Date: Sat, 20 Aug 2016 02:55:51 -0700 Subject: [PATCH 23/56] definitions for karma-fixture (#10724) * definitions for karma-fixture * return type here can be any object with any keys (arbitrary JSON) * Update karma-fixture.d.ts --- karma-fixture/karma-fixture-tests.ts | 10 ++++++++++ karma-fixture/karma-fixture.d.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 karma-fixture/karma-fixture-tests.ts create mode 100644 karma-fixture/karma-fixture.d.ts diff --git a/karma-fixture/karma-fixture-tests.ts b/karma-fixture/karma-fixture-tests.ts new file mode 100644 index 0000000000..b3a1d8e51c --- /dev/null +++ b/karma-fixture/karma-fixture-tests.ts @@ -0,0 +1,10 @@ +/// + +fixture.setBase('fixtures/base/path'); +fixture.load('test1.html', 'test1.json', false); +fixture.load('test1.html', 'test2.html', 'test1.json'); +fixture.set('', true); +fixture.set('', ''); +fixture.cleanup(); +fixture.el.firstChild; +JSON.stringify(fixture.json[0]); diff --git a/karma-fixture/karma-fixture.d.ts b/karma-fixture/karma-fixture.d.ts new file mode 100644 index 0000000000..8e4d18fd47 --- /dev/null +++ b/karma-fixture/karma-fixture.d.ts @@ -0,0 +1,27 @@ +// Type definitions for karma-fixture 0.2.6 +// Project: https://github.com/billtrik/karma-fixture +// Definitions by: Ezekiel Victor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module fixture { + var el: HTMLElement; + var json: any[]; + + function load(...files: string[]): any; + function load(file1: string, append?: boolean): any; + function load(file1: string, file2: string, append?: boolean): any; + function load(file1: string, file2: string, file3: string, append?: boolean): any; + function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any; + function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any; + + function set(...htmlStrs: string[]): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[]; + + function cleanup(): void; + + function setBase(fixtureBasePath: string): void; +} From cf44ce85f33d43a9e1717efbf47ea6a11560b302 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Sat, 20 Aug 2016 12:56:15 +0300 Subject: [PATCH 24/56] source5 type should be generic R (#10726) * source5 should be of generic type R * Update simple-assign-tests.ts --- simple-assign/simple-assign-tests.ts | 79 +++++++++++++++++++++++++--- simple-assign/simple-assign.d.ts | 2 +- 2 files changed, 72 insertions(+), 9 deletions(-) diff --git a/simple-assign/simple-assign-tests.ts b/simple-assign/simple-assign-tests.ts index 3970356f5b..d39583bc8c 100644 --- a/simple-assign/simple-assign-tests.ts +++ b/simple-assign/simple-assign-tests.ts @@ -1,15 +1,78 @@ - /// -import assign = require("simple-assign"); +import simpleAssign = require("simple-assign"); -function assign1() { - return assign({hello: "world"}); +interface Target { + hellow: string; } -function assign2() { - return assign({hello: "world"}, {hello: "worlds", second: "extra"}); +interface Source1 { + source1: string; } -function assign3() { - return assign({hello: "world"}, {hello: "worlds", second: "extra"}, {hello: "stop", the: "spinning"}); +interface Result extends Target, Source1 { + +} + +interface Source2 { + source2: string; +} + +interface Result2 extends Result, Source2 { + +} + +interface Source3 { + source3: string; +} + +interface Result3 extends Result2, Source3 { + +} + +interface Source4 { + source4: string; +} + +interface Result4 extends Result3, Source4 { + +} + +interface Source5 { + source5: string; +} + +interface Result5 extends Result4, Source5 { + +} + +function assign1(): Result { + return simpleAssign({hellow: "world"}, {source1: "U"}); +} + +function assign2(): Result2 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}); +} + +function assign3(): Result3 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}); +} + +function assign4(): Result4 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}); +} + +function assign5(): Result5 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}); +} + +function assign() { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}, { + hellow: "hellow", + source1: "source1", + source2: "source2", + source3: "source3", + source4: "source4", + source5: "source5", + generic: "any" + }); } diff --git a/simple-assign/simple-assign.d.ts b/simple-assign/simple-assign.d.ts index 3b9229bd65..7c44236f4c 100644 --- a/simple-assign/simple-assign.d.ts +++ b/simple-assign/simple-assign.d.ts @@ -8,7 +8,7 @@ declare module "simple-assign" { function simpleAssign(target: T, source1: U, source2: V): T & U & V; function simpleAssign(target: T, source1: U, source2: V, source3: W): T & U & V & W; function simpleAssign(target: T, source1: U, source2: V, source3: W, source4: Q): T & U & V & W & Q; - function simpleAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: T): T & U & V & W & Q & R; + function simpleAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: R): T & U & V & W & Q & R; function simpleAssign(target: any, ...sources: any[]): any; export = simpleAssign; } From 8ff9b5f4ad74ecdecbf3aa6acf1dcc0efc43b70f Mon Sep 17 00:00:00 2001 From: Gary Blackwood Date: Sat, 20 Aug 2016 10:59:25 +0100 Subject: [PATCH 25/56] Update ravenjs configuration options. (#10732) The configuration options available to the ravenjs client have changed since the initial creation of the type definitions. See: https://docs.sentry.io/hosted/clients/javascript/config/ --- ravenjs/ravenjs.d.ts | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/ravenjs/ravenjs.d.ts b/ravenjs/ravenjs.d.ts index 53cf4ad9cb..ae891a7cda 100644 --- a/ravenjs/ravenjs.d.ts +++ b/ravenjs/ravenjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js -// Definitions by: Santi Albo , Benjamin Pannell +// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var Raven: RavenStatic; @@ -10,15 +10,15 @@ declare module 'raven-js' { } interface RavenOptions { - /** The log level associated with this event. Default: error */ - level?: string; - /** The name of the logger used by Sentry. Default: javascript */ logger?: string; /** The release version of the application you are monitoring with Sentry */ release?: string; + /** The environment in which the application is running. */ + environment?: string; + /** The name of the server or device that the client is running on */ serverName?: string; @@ -39,11 +39,6 @@ interface RavenOptions { [id: string]: string; }; - extra?: any; - - /** In some cases you may see issues where Sentry groups multiple events together when they should be separate entities. In other cases, Sentry simply doesn’t group events together because they’re so sporadic that they never look the same. */ - fingerprint?: string[]; - /** A function which allows mutation of the data payload right before being sent to Sentry */ dataCallback?: (data: any) => any; @@ -53,8 +48,17 @@ interface RavenOptions { /** By default, Raven does not truncate messages. If you need to truncate characters for whatever reason, you may set this to limit the length. */ maxMessageLength?: number; + /** Enables/disables automatic collection of breadcrumbs. Default: true. */ + autoBreadcrumbs?: any; + + /** The max number of breadcrumb captures. Default: 100. */ + maxBreadcrumbs?: number; + /** Override the default HTTP data transport handler. */ transport?: (options: RavenTransportOptions) => void; + + /** Allow the use of a Sentry DSN with a private key. Default: false. */ + allowSecretKey?: boolean; } interface RavenStatic { From 55c3e254e151847b8d37ca09b1a566ad4a48a66a Mon Sep 17 00:00:00 2001 From: York Yao Date: Sat, 20 Aug 2016 18:00:18 +0800 Subject: [PATCH 26/56] fix type of iconlib (#10716) * fix type of iconlib * better type of icon lib and theme --- json-editor/json-editor.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/json-editor/json-editor.d.ts b/json-editor/json-editor.d.ts index cbb0c9c29c..280c17e70f 100644 --- a/json-editor/json-editor.d.ts +++ b/json-editor/json-editor.d.ts @@ -39,7 +39,7 @@ type JSONEditorOptions = { /** * The icon library to use for the editor. */ - iconlib?: boolean; + iconlib?: "bootstrap2" | "bootstrap3" | "foundation2" | "foundation3" | "jqueryui" | "fontawesome3" | "fontawesome4"; /** * If true, objects can only contain properties defined with the properties keyword. */ @@ -75,7 +75,7 @@ type JSONEditorOptions = { /** * The CSS theme to use. */ - theme?: string; + theme?: "barebones" | "html" | "bootstrap2" | "bootstrap3" | "foundation3" | "foundation4" | "foundation5" | "foundation6" | "jqueryui"; /** * If true, only required properties will be included by default. */ From 198bb0ca9a8cbe7060bb5c75f883bbdc0c35d014 Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Mon, 22 Aug 2016 22:58:55 +0200 Subject: [PATCH 27/56] Add missing method --- github-electron/github-electron.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 7b246966ab..f2fe5c3ba4 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -4766,6 +4766,10 @@ declare namespace Electron { * @returns Whether the web page is destroyed. */ isDestroyed(): boolean; + /** + * @returns Whether the web page is focused. + */ + isFocused(): boolean; /** * @returns Whether guest page is still loading resources. */ From 3636b4436eb3f76101c1991ed1a83d855aeca0ec Mon Sep 17 00:00:00 2001 From: hanjung Date: Mon, 22 Aug 2016 20:53:57 -0700 Subject: [PATCH 28/56] Adding OneNoteApi 1.1 --- office-js/office-js.d.ts | 2173 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 2173 insertions(+) diff --git a/office-js/office-js.d.ts b/office-js/office-js.d.ts index f2bebfe3da..f69f4a531f 100644 --- a/office-js/office-js.d.ts +++ b/office-js/office-js.d.ts @@ -13086,3 +13086,2176 @@ declare namespace Office { } } +declare namespace OneNote { + /** + * + * Represents the top-level object that contains all globally addressable OneNote objects such as notebooks, the active notebook, and the active section. + * + * [Api set: OneNoteApi 1.1] + */ + class Application extends OfficeExtension.ClientObject { + private m_notebooks; + /** + * + * Gets the collection of notebooks that are open in the OneNote application instance. In OneNote Online, only one notebook at a time is open in the application instance. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + notebooks: OneNote.NotebookCollection; + /** + * + * Gets the active notebook if one exists. If no notebook is active, throws ItemNotFound. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveNotebook(): OneNote.Notebook; + /** + * + * Gets the active notebook if one exists. If no notebook is active, returns null. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveNotebookOrNull(): OneNote.Notebook; + /** + * + * Gets the active outline if one exists, If no outline is active, throws ItemNotFound. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveOutline(): OneNote.Outline; + /** + * + * Gets the active outline if one exists, otherwise returns null. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveOutlineOrNull(): OneNote.Outline; + /** + * + * Gets the active page if one exists. If no page is active, throws ItemNotFound. + * + * [Api set: OneNoteApi 1.1] + */ + getActivePage(): OneNote.Page; + /** + * + * Gets the active page if one exists. If no page is active, returns null. + * + * [Api set: OneNoteApi 1.1] + */ + getActivePageOrNull(): OneNote.Page; + /** + * + * Gets the active section if one exists. If no section is active, throws ItemNotFound. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveSection(): OneNote.Section; + /** + * + * Gets the active section if one exists. If no section is active, returns null. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveSectionOrNull(): OneNote.Section; + /** + * + * Opens the specified page in the application instance. + * + * @param page The page to open. + * + * [Api set: OneNoteApi 1.1] + */ + navigateToPage(page: OneNote.Page): void; + /** + * + * Gets the specified page, and opens it in the application instance. + * + * @param url The client url of the page to open. + * + * [Api set: OneNoteApi 1.1] + */ + navigateToPageWithClientUrl(url: string): OneNote.Page; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Application; + } + /** + * + * Represents ink analysis data for a given set of ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysis extends OfficeExtension.ClientObject { + private m_id; + private m_page; + private m_paragraphs; + private m__ReferenceId; + /** + * + * Gets the parent page object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + page: OneNote.Page; + /** + * + * Gets the ink analysis paragraphs in this page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraphs: OneNote.InkAnalysisParagraphCollection; + /** + * + * Gets the ID of the InkAnalysis object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysis; + } + /** + * + * Represents ink analysis data for an identified paragraph formed by ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisParagraph extends OfficeExtension.ClientObject { + private m_id; + private m_inkAnalysis; + private m_lines; + private m__ReferenceId; + /** + * + * Reference to the parent InkAnalysisPage. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + inkAnalysis: OneNote.InkAnalysis; + /** + * + * Gets the ink analysis lines in this ink analysis paragraph. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + lines: OneNote.InkAnalysisLineCollection; + /** + * + * Gets the ID of the InkAnalysisParagraph object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisParagraph; + } + /** + * + * Represents a collection of InkAnalysisParagraph objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisParagraphCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkAnalysisParagraphs in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkAnalysisParagraph object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkAnalysisParagraph object, or the index location of the InkAnalysisParagraph object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkAnalysisParagraph; + /** + * + * Gets a InkAnalysisParagraph on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkAnalysisParagraph; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisParagraphCollection; + } + /** + * + * Represents ink analysis data for an identified text line formed by ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisLine extends OfficeExtension.ClientObject { + private m_id; + private m_paragraph; + private m_words; + private m__ReferenceId; + /** + * + * Reference to the parent InkAnalysisParagraph. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.InkAnalysisParagraph; + /** + * + * Gets the ink analysis words in this ink analysis line. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + words: OneNote.InkAnalysisWordCollection; + /** + * + * Gets the ID of the InkAnalysisLine object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisLine; + } + /** + * + * Represents a collection of InkAnalysisLine objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisLineCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkAnalysisLines in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkAnalysisLine object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkAnalysisLine object, or the index location of the InkAnalysisLine object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkAnalysisLine; + /** + * + * Gets a InkAnalysisLine on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkAnalysisLine; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisLineCollection; + } + /** + * + * Represents ink analysis data for an identified word formed by ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisWord extends OfficeExtension.ClientObject { + private m_id; + private m_languageId; + private m_line; + private m_strokePointers; + private m_wordAlternates; + private m__ReferenceId; + /** + * + * Reference to the parent InkAnalysisLine. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + line: OneNote.InkAnalysisLine; + /** + * + * Gets the ID of the InkAnalysisWord object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * The id of the recognized language in this inkAnalysisWord. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + languageId: string; + /** + * + * Weak references to the ink strokes that were recognized as part of this ink analysis word. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + strokePointers: Array; + /** + * + * The words that were recognized in this ink word, in order of likelihood. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + wordAlternates: Array; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisWord; + } + /** + * + * Represents a collection of InkAnalysisWord objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisWordCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkAnalysisWords in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkAnalysisWord object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkAnalysisWord object, or the index location of the InkAnalysisWord object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkAnalysisWord; + /** + * + * Gets a InkAnalysisWord on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkAnalysisWord; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisWordCollection; + } + /** + * + * Represents a group of ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class FloatingInk extends OfficeExtension.ClientObject { + private m_id; + private m_inkStrokes; + private m_pageContent; + private m__ReferenceId; + /** + * + * Gets the strokes of the FloatingInk object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + inkStrokes: OneNote.InkStrokeCollection; + /** + * + * Gets the PageContent parent of the FloatingInk object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + pageContent: OneNote.PageContent; + /** + * + * Gets the ID of the FloatingInk object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.FloatingInk; + } + /** + * + * Represents a single stroke of ink. + * + * [Api set: OneNoteApi 1.1] + */ + class InkStroke extends OfficeExtension.ClientObject { + private m_floatingInk; + private m_id; + private m__ReferenceId; + /** + * + * Gets the ID of the InkStroke object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + floatingInk: OneNote.FloatingInk; + /** + * + * Gets the ID of the InkStroke object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkStroke; + } + /** + * + * Represents a collection of InkStroke objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkStrokeCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkStrokes in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkStroke object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkStroke object, or the index location of the InkStroke object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkStroke; + /** + * + * Gets a InkStroke on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkStroke; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkStrokeCollection; + } + /** + * + * A container for the ink in a word in a paragraph. + * + * [Api set: OneNoteApi 1.1] + */ + class InkWord extends OfficeExtension.ClientObject { + private m_id; + private m_languageId; + private m_paragraph; + private m_wordAlternates; + private m__ReferenceId; + /** + * + * The parent paragraph containing the ink word. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.Paragraph; + /** + * + * Gets the ID of the InkWord object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * The id of the recognized language in this ink word. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + languageId: string; + /** + * + * The words that were recognized in this ink word, in order of likelihood. Read-only. + * + * [Api set: OneNoteApi] + */ + wordAlternates: Array; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkWord; + } + /** + * + * Represents a collection of InkWord objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkWordCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkWords in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkWord object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkWord object, or the index location of the InkWord object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkWord; + /** + * + * Gets a InkWord on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkWord; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkWordCollection; + } + /** + * + * Represents a OneNote notebook. Notebooks contain section groups and sections. + * + * [Api set: OneNoteApi 1.1] + */ + class Notebook extends OfficeExtension.ClientObject { + private m_clientUrl; + private m_id; + private m_name; + private m_sectionGroups; + private m_sections; + private m__ReferenceId; + /** + * + * The section groups in the notebook. Read only + * + * [Api set: OneNoteApi 1.1] + */ + sectionGroups: OneNote.SectionGroupCollection; + /** + * + * The the sections of the notebook. Read only + * + * [Api set: OneNoteApi 1.1] + */ + sections: OneNote.SectionCollection; + /** + * + * The client url of the notebook. Read only + * + * [Api set: OneNoteApi 1.1] + */ + clientUrl: string; + /** + * + * Gets the ID of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the name of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + name: string; + /** + * + * Adds a new section to the end of the notebook. + * + * @param name The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + addSection(name: string): OneNote.Section; + /** + * + * Adds a new section group to the end of the notebook. + * + * @param name The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + addSectionGroup(name: string): OneNote.SectionGroup; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Notebook; + } + /** + * + * Represents a collection of notebooks. + * + * [Api set: OneNoteApi 1.1] + */ + class NotebookCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of notebooks in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets the collection of notebooks with the specified name that are open in the application instance. + * + * @param name The name of the notebook. + * + * [Api set: OneNoteApi 1.1] + */ + getByName(name: string): OneNote.NotebookCollection; + /** + * + * Gets a notebook by ID or by its index in the collection. Read-only. + * + * @param index The ID of the notebook, or the index location of the notebook in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.Notebook; + /** + * + * Gets a notebook on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.Notebook; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.NotebookCollection; + } + /** + * + * Represents a OneNote section group. Section groups can contain sections and other section groups. + * + * [Api set: OneNoteApi 1.1] + */ + class SectionGroup extends OfficeExtension.ClientObject { + private m_clientUrl; + private m_id; + private m_name; + private m_notebook; + private m_parentSectionGroup; + private m_parentSectionGroupOrNull; + private m_sectionGroups; + private m_sections; + private m__ReferenceId; + /** + * + * Gets the notebook that contains the section group. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + notebook: OneNote.Notebook; + /** + * + * Gets the section group that contains the section group. Throws ItemNotFound if the section group is a direct child of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSectionGroup: OneNote.SectionGroup; + /** + * + * Gets the section group that contains the section group. Returns null if the section group is a direct child of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSectionGroupOrNull: OneNote.SectionGroup; + /** + * + * The collection of section groups in the section group. Read only + * + * [Api set: OneNoteApi 1.1] + */ + sectionGroups: OneNote.SectionGroupCollection; + /** + * + * The collection of sections in the section group. Read only + * + * [Api set: OneNoteApi 1.1] + */ + sections: OneNote.SectionCollection; + /** + * + * The client url of the section group. Read only + * + * [Api set: OneNoteApi 1.1] + */ + clientUrl: string; + /** + * + * Gets the ID of the section group. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the name of the section group. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + name: string; + /** + * + * Adds a new section to the end of the section group. + * + * @param title The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + addSection(title: string): OneNote.Section; + /** + * + * Adds a new section group to the end of this sectionGroup. + * + * @param name The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + addSectionGroup(name: string): OneNote.SectionGroup; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.SectionGroup; + } + /** + * + * Represents a collection of section groups. + * + * [Api set: OneNoteApi 1.1] + */ + class SectionGroupCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of section groups in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets the collection of section groups with the specified name. + * + * @param name The name of the section group. + * + * [Api set: OneNoteApi 1.1] + */ + getByName(name: string): OneNote.SectionGroupCollection; + /** + * + * Gets a section group by ID or by its index in the collection. Read-only. + * + * @param index The ID of the section group, or the index location of the section group in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.SectionGroup; + /** + * + * Gets a section group on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.SectionGroup; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.SectionGroupCollection; + } + /** + * + * Represents a OneNote section. Sections can contain pages. + * + * [Api set: OneNoteApi 1.1] + */ + class Section extends OfficeExtension.ClientObject { + private m_clientUrl; + private m_id; + private m_name; + private m_notebook; + private m_pages; + private m_parentSectionGroup; + private m_parentSectionGroupOrNull; + private m__ReferenceId; + /** + * + * Gets the notebook that contains the section. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + notebook: OneNote.Notebook; + /** + * + * The collection of pages in the section. Read only + * + * [Api set: OneNoteApi 1.1] + */ + pages: OneNote.PageCollection; + /** + * + * Gets the section group that contains the section. Throws ItemNotFound if the section is a direct child of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSectionGroup: OneNote.SectionGroup; + /** + * + * Gets the section group that contains the section. Returns null if the section is a direct child of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSectionGroupOrNull: OneNote.SectionGroup; + /** + * + * The client url of the section. Read only + * + * [Api set: OneNoteApi 1.1] + */ + clientUrl: string; + /** + * + * Gets the ID of the section. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the name of the section. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + name: string; + /** + * + * Adds a new page to the end of the section. + * + * @param title The title of the new page. + * + * [Api set: OneNoteApi 1.1] + */ + addPage(title: string): OneNote.Page; + /** + * + * Copies this section to specified notebook. + * + * @param destinationNotebook The notebook to copy this section to. + * + * [Api set: OneNoteApi 1.1] + */ + copyToNotebook(destinationNotebook: OneNote.Notebook): OneNote.Section; + /** + * + * Copies this section to specified section group. + * + * @param destinationSectionGroup The section group to copy this section to. + * + * [Api set: OneNoteApi 1.1] + */ + copyToSectionGroup(destinationSectionGroup: OneNote.SectionGroup): OneNote.Section; + /** + * + * Inserts a new section before or after the current section. + * + * @param location The location of the new section relative to the current section. + * @param title The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + insertSectionAsSibling(location: string, title: string): OneNote.Section; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Section; + } + /** + * + * Represents a collection of sections. + * + * [Api set: OneNoteApi 1.1] + */ + class SectionCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of sections in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets the collection of sections with the specified name. + * + * @param name The name of the section. + * + * [Api set: OneNoteApi 1.1] + */ + getByName(name: string): OneNote.SectionCollection; + /** + * + * Gets a section by ID or by its index in the collection. Read-only. + * + * @param index The ID of the section, or the index location of the section in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.Section; + /** + * + * Gets a section on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.Section; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.SectionCollection; + } + /** + * + * Represents a OneNote page. + * + * [Api set: OneNoteApi 1.1] + */ + class Page extends OfficeExtension.ClientObject { + private m_clientUrl; + private m_contents; + private m_id; + private m_inkAnalysisOrNull; + private m_pageLevel; + private m_parentSection; + private m_title; + private m_webUrl; + private m__ReferenceId; + /** + * + * The collection of PageContent objects on the page. Read only + * + * [Api set: OneNoteApi 1.1] + */ + contents: OneNote.PageContentCollection; + /** + * + * Text interpretation for the ink on the page. Returns null if there is no ink analysis information. Read only. + * + * [Api set: OneNoteApi 1.1] + */ + inkAnalysisOrNull: OneNote.InkAnalysis; + /** + * + * Gets the section that contains the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSection: OneNote.Section; + /** + * + * The client url of the page. Read only + * + * [Api set: OneNoteApi 1.1] + */ + clientUrl: string; + /** + * + * Gets the ID of the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets or sets the indentation level of the page. + * + * [Api set: OneNoteApi 1.1] + */ + pageLevel: number; + /** + * + * Gets or sets the title of the page. + * + * [Api set: OneNoteApi 1.1] + */ + title: string; + /** + * + * The web url of the page. Read only + * + * [Api set: OneNoteApi 1.1] + */ + webUrl: string; + /** + * + * Adds an Outline to the page at the specified position. + * + * @param left The left position of the top, left corner of the Outline. + * @param top The top position of the top, left corner of the Outline. + * @param html An HTML string that describes the visual presentation of the Outline. See [supported HTML](../../docs/onenote/onenote-add-ins-page-content.md#supported-html) for the OneNote add-ins JavaScript API. + * + * [Api set: OneNoteApi 1.1] + */ + addOutline(left: number, top: number, html: string): OneNote.Outline; + /** + * + * Copies this page to specified section. + * + * @param destinationSection The section to copy this page to. + * + * [Api set: OneNoteApi 1.1] + */ + copyToSection(destinationSection: OneNote.Section): OneNote.Page; + /** + * + * Inserts a new page before or after the current page. + * + * @param location The location of the new page relative to the current page. + * @param title The title of the new page. + * + * [Api set: OneNoteApi 1.1] + */ + insertPageAsSibling(location: string, title: string): OneNote.Page; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Page; + } + /** + * + * Represents a collection of pages. + * + * [Api set: OneNoteApi 1.1] + */ + class PageCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of pages in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets the collection of pages with the specified title. + * + * @param title The title of the page. + * + * [Api set: OneNoteApi 1.1] + */ + getByTitle(title: string): OneNote.PageCollection; + /** + * + * Gets a page by ID or by its index in the collection. Read-only. + * + * @param index The ID of the page, or the index location of the page in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.Page; + /** + * + * Gets a page on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.Page; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.PageCollection; + } + /** + * + * Represents a region on a page that contains top-level content types such as Outline or Image. A PageContent object can be assigned an XY position. + * + * [Api set: OneNoteApi 1.1] + */ + class PageContent extends OfficeExtension.ClientObject { + private m_id; + private m_image; + private m_ink; + private m_left; + private m_outline; + private m_parentPage; + private m_top; + private m_type; + private m__ReferenceId; + /** + * + * Gets the Image in the PageContent object. Throws an exception if PageContentType is not Image. + * + * [Api set: OneNoteApi 1.1] + */ + image: OneNote.Image; + /** + * + * Gets the ink in the PageContent object. Throws an exception if PageContentType is not Ink. + * + * [Api set: OneNoteApi 1.1] + */ + ink: OneNote.FloatingInk; + /** + * + * Gets the Outline in the PageContent object. Throws an exception if PageContentType is not Outline. + * + * [Api set: OneNoteApi 1.1] + */ + outline: OneNote.Outline; + /** + * + * Gets the page that contains the PageContent object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentPage: OneNote.Page; + /** + * + * Gets the ID of the PageContent object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets or sets the left (X-axis) position of the PageContent object. + * + * [Api set: OneNoteApi 1.1] + */ + left: number; + /** + * + * Gets or sets the top (Y-axis) position of the PageContent object. + * + * [Api set: OneNoteApi 1.1] + */ + top: number; + /** + * + * Gets the type of the PageContent object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + type: string; + /** + * + * Deletes the PageContent object. + * + * [Api set: OneNoteApi 1.1] + */ + delete(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.PageContent; + } + /** + * + * Represents the contents of a page, as a collection of PageContent objects. + * + * [Api set: OneNoteApi 1.1] + */ + class PageContentCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of page contents in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a PageContent object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the PageContent object, or the index location of the PageContent object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.PageContent; + /** + * + * Gets a page content on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.PageContent; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.PageContentCollection; + } + /** + * + * Represents a container for Paragraph objects. + * + * [Api set: OneNoteApi 1.1] + */ + class Outline extends OfficeExtension.ClientObject { + private m_id; + private m_pageContent; + private m_paragraphs; + private m__ReferenceId; + /** + * + * Gets the PageContent object that contains the Outline. This object defines the position of the Outline on the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + pageContent: OneNote.PageContent; + /** + * + * Gets the collection of Paragraph objects in the Outline. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraphs: OneNote.ParagraphCollection; + /** + * + * Gets the ID of the Outline object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Adds the specified HTML to the bottom of the Outline. + * + * @param html The HTML string to append. See [supported HTML](../../docs/onenote/onenote-add-ins-page-content.md#supported-html) for the OneNote add-ins JavaScript API. + * + * [Api set: OneNoteApi 1.1] + */ + appendHtml(html: string): void; + /** + * + * Adds the specified image to the bottom of the Outline. + * + * @param base64EncodedImage HTML string to append. + * @param width Optional. Width in the unit of Points. The default value is null and image width will be respected. + * @param height Optional. Height in the unit of Points. The default value is null and image height will be respected. + * + * [Api set: OneNoteApi 1.1] + */ + appendImage(base64EncodedImage: string, width: number, height: number): OneNote.Image; + /** + * + * Adds the specified text to the bottom of the Outline. + * + * @param paragraphText HTML string to append. + * + * [Api set: OneNoteApi 1.1] + */ + appendRichText(paragraphText: string): OneNote.RichText; + /** + * + * Adds a table with the specified number of rows and columns to the bottom of the outline. + * + * @param rowCount Required. The number of rows in the table. + * @param columnCount Required. The number of columns in the table. + * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. + * + * [Api set: OneNoteApi 1.1] + */ + appendTable(rowCount: number, columnCount: number, values?: Array>): OneNote.Table; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Outline; + } + /** + * + * A container for the visible content on a page. A Paragraph can contain any one ParagraphType type of content. + * + * [Api set: OneNoteApi 1.1] + */ + class Paragraph extends OfficeExtension.ClientObject { + private m_id; + private m_image; + private m_inkWords; + private m_outline; + private m_paragraphs; + private m_parentParagraph; + private m_parentParagraphOrNull; + private m_parentTableCell; + private m_parentTableCellOrNull; + private m_richText; + private m_table; + private m_type; + private m__ReferenceId; + /** + * + * Gets the Image object in the Paragraph. Throws an exception if ParagraphType is not Image. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + image: OneNote.Image; + /** + * + * Gets the Ink collection in the Paragraph. Throws an exception if ParagraphType is not Ink. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + inkWords: OneNote.InkWordCollection; + /** + * + * Gets the Outline object that contains the Paragraph. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + outline: OneNote.Outline; + /** + * + * The collection of paragraphs under this paragraph. Read only + * + * [Api set: OneNoteApi 1.1] + */ + paragraphs: OneNote.ParagraphCollection; + /** + * + * Gets the parent paragraph object. Throws if a parent paragraph does not exist. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentParagraph: OneNote.Paragraph; + /** + * + * Gets the parent paragraph object. Returns null if a parent paragraph does not exist. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentParagraphOrNull: OneNote.Paragraph; + /** + * + * Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, throws ItemNotFound. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentTableCell: OneNote.TableCell; + /** + * + * Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, returns null. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentTableCellOrNull: OneNote.TableCell; + /** + * + * Gets the RichText object in the Paragraph. Throws an exception if ParagraphType is not RichText. Read-only + * + * [Api set: OneNoteApi 1.1] + */ + richText: OneNote.RichText; + /** + * + * Gets the Table object in the Paragraph. Throws an exception if ParagraphType is not Table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + table: OneNote.Table; + /** + * + * Gets the ID of the Paragraph object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the type of the Paragraph object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + type: string; + /** + * + * Deletes the paragraph + * + * [Api set: OneNoteApi 1.1] + */ + delete(): void; + /** + * + * Inserts the specified HTML content + * + * @param insertLocation The location of new contents relative to the current Paragraph. + * @param html An HTML string that describes the visual presentation of the content. See [supported HTML](../../docs/onenote/onenote-add-ins-page-content.md#supported-html) for the OneNote add-ins JavaScript API. + * + * [Api set: OneNoteApi 1.1] + */ + insertHtmlAsSibling(insertLocation: string, html: string): void; + /** + * + * Inserts the image at the specified insert location.. + * + * @param insertLocation The location of the table relative to the current Paragraph. + * @param base64EncodedImage HTML string to append. + * @param width Optional. Width in the unit of Points. The default value is null and image width will be respected. + * @param height Optional. Height in the unit of Points. The default value is null and image height will be respected. + * + * [Api set: OneNoteApi 1.1] + */ + insertImageAsSibling(insertLocation: string, base64EncodedImage: string, width: number, height: number): OneNote.Image; + /** + * + * Inserts the paragraph text at the specifiec insert location. + * + * @param insertLocation The location of the table relative to the current Paragraph. + * @param paragraphText HTML string to append. + * + * [Api set: OneNoteApi 1.1] + */ + insertRichTextAsSibling(insertLocation: string, paragraphText: string): OneNote.RichText; + /** + * + * Adds a table with the specified number of rows and columns before or after the current paragraph. + * + * @param insertLocation The location of the table relative to the current Paragraph. + * @param rowCount The number of rows in the table. + * @param columnCount The number of columns in the table. + * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. + * + * [Api set: OneNoteApi 1.1] + */ + insertTableAsSibling(insertLocation: string, rowCount: number, columnCount: number, values?: Array>): OneNote.Table; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Paragraph; + } + /** + * + * Represents a collection of Paragraph objects. + * + * [Api set: OneNoteApi 1.1] + */ + class ParagraphCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of paragraphs in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a Paragraph object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the Paragraph object, or the index location of the Paragraph object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.Paragraph; + /** + * + * Gets a paragraph on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.Paragraph; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.ParagraphCollection; + } + /** + * + * Represents a RichText object in a Paragraph. + * + * [Api set: OneNoteApi 1.1] + */ + class RichText extends OfficeExtension.ClientObject { + private m_id; + private m_paragraph; + private m_text; + private m__ReferenceId; + /** + * + * Gets the Paragraph object that contains the RichText object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.Paragraph; + /** + * + * Gets the ID of the RichText object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the text content of the RichText object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + text: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.RichText; + } + /** + * + * Represents an Image. An Image can be a direct child of a PageContent object or a Paragraph object. + * + * [Api set: OneNoteApi 1.1] + */ + class Image extends OfficeExtension.ClientObject { + private m_description; + private m_height; + private m_hyperlink; + private m_id; + private m_ocrData; + private m_pageContent; + private m_paragraph; + private m_width; + private m__ReferenceId; + /** + * + * Gets the PageContent object that contains the Image. Throws if the Image is not a direct child of a PageContent. This object defines the position of the Image on the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + pageContent: OneNote.PageContent; + /** + * + * Gets the Paragraph object that contains the Image. Throws if the Image is not a direct child of a Paragraph. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.Paragraph; + /** + * + * Gets or sets the description of the Image. + * + * [Api set: OneNoteApi 1.1] + */ + description: string; + /** + * + * Gets or sets the height of the Image layout. + * + * [Api set: OneNoteApi 1.1] + */ + height: number; + /** + * + * Gets or sets the hyperlink of the Image. + * + * [Api set: OneNoteApi 1.1] + */ + hyperlink: string; + /** + * + * Gets the ID of the Image object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the data obtained by OCR (Optical Character Recognition) of this Image, such as OCR text and language. + * + * [Api set: OneNoteApi 1.1] + */ + ocrData: OneNote.ImageOcrData; + /** + * + * Gets or sets the width of the Image layout. + * + * [Api set: OneNoteApi 1.1] + */ + width: number; + /** + * + * Gets the base64-encoded binary representation of the Image. + Example: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA... + * + * [Api set: OneNoteApi 1.1] + */ + getBase64Image(): OfficeExtension.ClientResult; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Image; + } + /** + * + * Represents a table in a OneNote page. + * + * [Api set: OneNoteApi 1.1] + */ + class Table extends OfficeExtension.ClientObject { + private m_borderVisible; + private m_columnCount; + private m_id; + private m_paragraph; + private m_rowCount; + private m_rows; + private m__ReferenceId; + /** + * + * Gets the Paragraph object that contains the Table object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.Paragraph; + /** + * + * Gets all of the table rows. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + rows: OneNote.TableRowCollection; + /** + * + * Gets or sets whether the borders are visible or not. True if they are visible, false if they are hidden. + * + * [Api set: OneNoteApi 1.1] + */ + borderVisible: boolean; + /** + * + * Gets the number of columns in the table. + * + * [Api set: OneNoteApi 1.1] + */ + columnCount: number; + /** + * + * Gets the ID of the table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the number of rows in the table. + * + * [Api set: OneNoteApi 1.1] + */ + rowCount: number; + /** + * + * Adds a column to the end of the table. Values, if specified, are set in the new column. Otherwise the column is empty. + * + * @param values Optional. Strings to insert in the new column, specified as an array. Must not have more values than rows in the table. + * + * [Api set: OneNoteApi 1.1] + */ + appendColumn(values?: Array): void; + /** + * + * Adds a row to the end of the table. Values, if specified, are set in the new row. Otherwise the row is empty. + * + * @param values Optional. Strings to insert in the new row, specified as an array. Must not have more values than columns in the table. + * + * [Api set: OneNoteApi 1.1] + */ + appendRow(values?: Array): OneNote.TableRow; + /** + * + * Clears the contents of the table. + * + * [Api set: OneNoteApi 1.1] + */ + clear(): void; + /** + * + * Gets the table cell at a specified row and column. + * + * @param rowIndex The index of the row. + * @param cellIndex The index of the cell in the row. + * + * [Api set: OneNoteApi 1.1] + */ + getCell(rowIndex: number, cellIndex: number): OneNote.TableCell; + /** + * + * Inserts a column at the given index in the table. Values, if specified, are set in the new column. Otherwise the column is empty. + * + * @param index Index where the column will be inserted in the table. + * @param values Optional. Strings to insert in the new column, specified as an array. Must not have more values than rows in the table. + * + * [Api set: OneNoteApi 1.1] + */ + insertColumn(index: number, values?: Array): void; + /** + * + * Inserts a row at the given index in the table. Values, if specified, are set in the new row. Otherwise the row is empty. + * + * @param index Index where the row will be inserted in the table. + * @param values Optional. Strings to insert in the new row, specified as an array. Must not have more values than columns in the table. + * + * [Api set: OneNoteApi 1.1] + */ + insertRow(index: number, values?: Array): OneNote.TableRow; + setShadingColor(colorCode: string): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Table; + } + /** + * + * Represents a row in a table. + * + * [Api set: OneNoteApi 1.1] + */ + class TableRow extends OfficeExtension.ClientObject { + private m_cellCount; + private m_cells; + private m_id; + private m_parentTable; + private m_rowIndex; + private m__ReferenceId; + /** + * + * Gets the cells in the row. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + cells: OneNote.TableCellCollection; + /** + * + * Gets the parent table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentTable: OneNote.Table; + /** + * + * Gets the number of cells in the row. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + cellCount: number; + /** + * + * Gets the ID of the row. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the index of the row in its parent table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + rowIndex: number; + /** + * + * Clears the contents of the row. + * + * [Api set: OneNoteApi 1.1] + */ + clear(): void; + /** + * + * Inserts a row before or after the current row. + * + * @param insertLocation Where the new rows should be inserted relative to the current row. + * @param values Strings to insert in the new row, specified as an array. Must not have more cells than in the current row. Optional. + * + * [Api set: OneNoteApi 1.1] + */ + insertRowAsSibling(insertLocation: string, values?: Array): OneNote.TableRow; + setShadingColor(colorCode: string): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.TableRow; + } + /** + * + * Contains a collection of TableRow objects. + * + * [Api set: OneNoteApi 1.1] + */ + class TableRowCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of table rows in this collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a table row object by ID or by its index in the collection. Read-only. + * + * @param index A number that identifies the index location of a table row object. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.TableRow; + /** + * + * Gets a table row at its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.TableRow; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.TableRowCollection; + } + /** + * + * Represents a cell in a OneNote table. + * + * [Api set: OneNoteApi 1.1] + */ + class TableCell extends OfficeExtension.ClientObject { + private m_cellIndex; + private m_id; + private m_paragraphs; + private m_parentRow; + private m_rowIndex; + private m_shadingColor; + private m__ReferenceId; + /** + * + * Gets the collection of Paragraph objects in the TableCell. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraphs: OneNote.ParagraphCollection; + /** + * + * Gets the parent row of the cell. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentRow: OneNote.TableRow; + /** + * + * Gets the index of the cell in its row. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + cellIndex: number; + /** + * + * Gets the ID of the cell. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the index of the cell's row in the table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + rowIndex: number; + /** + * + * Gets and sets the shading color of the cell + * + * [Api set: OneNoteApi 1.1] + */ + shadingColor: string; + /** + * + * Adds the specified HTML to the bottom of the TableCell. + * + * @param html The HTML string to append. See [supported HTML](../../docs/onenote/onenote-add-ins-page-content.md#supported-html) for the OneNote add-ins JavaScript API. + * + * [Api set: OneNoteApi 1.1] + */ + appendHtml(html: string): void; + /** + * + * Adds the specified image to table cell. + * + * @param base64EncodedImage HTML string to append. + * @param width Optional. Width in the unit of Points. The default value is null and image width will be respected. + * @param height Optional. Height in the unit of Points. The default value is null and image height will be respected. + * + * [Api set: OneNoteApi 1.1] + */ + appendImage(base64EncodedImage: string, width: number, height: number): OneNote.Image; + /** + * + * Adds the specified text to table cell. + * + * @param paragraphText HTML string to append. + * + * [Api set: OneNoteApi 1.1] + */ + appendRichText(paragraphText: string): OneNote.RichText; + /** + * + * Adds a table with the specified number of rows and columns to table cell. + * + * @param rowCount Required. The number of rows in the table. + * @param columnCount Required. The number of columns in the table. + * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. + * + * [Api set: OneNoteApi 1.1] + */ + appendTable(rowCount: number, columnCount: number, values?: Array>): OneNote.Table; + /** + * + * Clears the contents of the cell. + * + * [Api set: OneNoteApi 1.1] + */ + clear(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.TableCell; + } + /** + * + * Contains a collection of TableCell objects. + * + * [Api set: OneNoteApi 1.1] + */ + class TableCellCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of tablecells in this collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a table cell object by ID or by its index in the collection. Read-only. + * + * @param index A number that identifies the index location of a table cell object. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.TableCell; + /** + * + * Gets a tablecell at its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.TableCell; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.TableCellCollection; + } + /** + * + * Represents data obtained by OCR (optical character recognition) of an image + * + * [Api set: OneNoteApi 1.1] + */ + interface ImageOcrData { + /** + * + * Represents the OCR language, with values such as EN-US + * + * [Api set: OneNoteApi 1.1] + */ + ocrLanguageId: string; + /** + * + * Represents the text obtained by OCR of the image + * + * [Api set: OneNoteApi 1.1] + */ + ocrText: string; + } + /** + * + * Weak reference to an ink stroke object and its content parent + * + * [Api set: OneNoteApi 1.1] + */ + interface InkStrokePointer { + /** + * + * Represents the id of the page content object corresponding to this stroke + * + * [Api set: OneNoteApi 1.1] + */ + contentId: string; + /** + * + * Represents the id of the ink stroke + * + * [Api set: OneNoteApi 1.1] + */ + inkStrokeId: string; + } + /** + * [Api set: OneNoteApi] + */ + module InsertLocation { + var before: string; + var after: string; + } + /** + * [Api set: OneNoteApi] + */ + module Alignment { + var left: string; + var centered: string; + var right: string; + var justified: string; + } + /** + * [Api set: OneNoteApi] + */ + module Selected { + var notSelected: string; + var partialSelected: string; + var selected: string; + } + /** + * [Api set: OneNoteApi] + */ + module PageContentType { + var outline: string; + var image: string; + var ink: string; + var other: string; + } + /** + * [Api set: OneNoteApi] + */ + module ParagraphType { + var richText: string; + var image: string; + var table: string; + var ink: string; + var other: string; + } + module ErrorCodes { + var generalException: string; + } +} +declare namespace OneNote { + class RequestContext extends OfficeExtension.ClientRequestContext { + private m_onenote; + constructor(url?: string); + application: Application; + } + /** + * Executes a batch script that performs actions on the OneNote object model. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the OneNote application. Since the Office add-in and the WoOneNote application run in two different processes, the request context is required to get access to the OneNote object model from the add-in. + */ + function run(batch: (context: OneNote.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; +} From 69ecb66f736eb83b490c916f6be8ac65a5cf6163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Mon, 22 Aug 2016 10:07:25 -0600 Subject: [PATCH 29/56] Made node Buffer's lastIndexOf and indexOf conformant to node API --- node/node-tests.ts | 11 +++++++++++ node/node.d.ts | 4 ++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index fd79f28f9d..bd19697f31 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -244,10 +244,21 @@ function bufferTests() { let index: number; index = buffer.indexOf("23"); index = buffer.indexOf("23", 1); + index = buffer.indexOf("23", 1, "utf8"); index = buffer.indexOf(23); index = buffer.indexOf(buffer); } + { + let buffer = new Buffer('123'); + let index: number; + index = buffer.lastIndexOf("23"); + index = buffer.lastIndexOf("23", 1); + index = buffer.lastIndexOf("23", 1, "utf8"); + index = buffer.lastIndexOf(23); + index = buffer.lastIndexOf(buffer); + } + // Imported Buffer from buffer module works properly { let b = new ImportedBuffer('123'); diff --git a/node/node.d.ts b/node/node.d.ts index 750d273988..d86dac906c 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -503,8 +503,8 @@ interface NodeBuffer extends Uint8Array { writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; fill(value: any, offset?: number, end?: number): this; - // TODO: encoding param - indexOf(value: string | number | Buffer, byteOffset?: number): number; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; // TODO: entries // TODO: includes // TODO: keys From c532a2d96c13392d92f70b8961dfa8cca159248d Mon Sep 17 00:00:00 2001 From: Zlatkovsky Date: Tue, 23 Aug 2016 12:13:16 -0700 Subject: [PATCH 30/56] Fixed "no implicit any" issue with previous commit. --- office-js/office-js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/office-js/office-js.d.ts b/office-js/office-js.d.ts index 4f21022fe5..55b20f93cf 100644 --- a/office-js/office-js.d.ts +++ b/office-js/office-js.d.ts @@ -258,7 +258,7 @@ declare module OfficeExtension { /** * Creates a new promise based on a function that accepts resolve and reject handlers. */ - constructor(func: (resolve, reject) => void); + constructor(func: (resolve : (value?: R | IPromise) => void, reject: (error?: any) => void) => void); /** * Creates a promise that resolves when all of the child promises resolve. From 76fc7cd3089c09deefe1a3e43b937cfd8b969d1b Mon Sep 17 00:00:00 2001 From: Michael Durling Date: Tue, 23 Aug 2016 16:08:06 -0400 Subject: [PATCH 31/56] Add allowHTML NotificationSystem property --- react-notification-system/react-notification-system.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/react-notification-system/react-notification-system.d.ts b/react-notification-system/react-notification-system.d.ts index 4f51314680..31b151662a 100644 --- a/react-notification-system/react-notification-system.d.ts +++ b/react-notification-system/react-notification-system.d.ts @@ -74,6 +74,7 @@ declare namespace NotificationSystem { noAnimation?: boolean; ref?: string; style?: Style | boolean; + allowHTML?: boolean; } } From aefccb9b431554179eaddf90281ac0b73a701a33 Mon Sep 17 00:00:00 2001 From: Michael Durling Date: Tue, 23 Aug 2016 16:23:34 -0400 Subject: [PATCH 32/56] Fix name of Pusher interface property - sessionId is incorrect, should be sessionID --- pusher-js/pusher-js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pusher-js/pusher-js.d.ts b/pusher-js/pusher-js.d.ts index 0a6dc18d24..76bdb83c0e 100644 --- a/pusher-js/pusher-js.d.ts +++ b/pusher-js/pusher-js.d.ts @@ -23,7 +23,7 @@ declare module "pusher-js" { config: Config; //TODO: add GlobalConfig typings channels: any; //TODO: Type this global_emitter: EventsDispatcher; - sessionId: number; + sessionID: number; timeline: any; //TODO: Type this connection: ConnectionManager; } From 9c5f574dd8d8b2a385cdff6e260123ec8e78ad40 Mon Sep 17 00:00:00 2001 From: Erwin Poeze Date: Wed, 24 Aug 2016 16:26:52 +0200 Subject: [PATCH 33/56] Removed generic type from Reduced --- ramda/ramda.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ramda/ramda.d.ts b/ramda/ramda.d.ts index a6fa682a3a..04623bdada 100644 --- a/ramda/ramda.d.ts +++ b/ramda/ramda.d.ts @@ -107,7 +107,7 @@ declare namespace R { (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; } - interface Reduced {} + interface Reduced {} interface Static { @@ -1300,9 +1300,9 @@ declare namespace R { * function and passing it an accumulator value and the current value from the array, and * then passing the result to the next call. */ - reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult, list: T[]): TResult; - reduce(fn: (acc: TResult, elem: T) => TResult|Reduced): (acc: TResult, list: T[]) => TResult; - reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult): (list: T[]) => TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult, list: T[]): TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced): (acc: TResult, list: T[]) => TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult): (list: T[]) => TResult; /** * Groups the elements of the list according to the result of calling the String-returning function keyFn on each @@ -1318,7 +1318,7 @@ declare namespace R { * transduce functions. The returned value should be considered a black box: the internal * structure is not guaranteed to be stable. */ - reduced(elem: T): Reduced; + reduced(elem: T): Reduced; /** * Returns a single item by iterating through the list, successively calling the iterator From 2ebcbf744729d1e4b305454cfdfbe3abdafb066a Mon Sep 17 00:00:00 2001 From: Hristian Hristov Date: Wed, 24 Aug 2016 16:13:49 +0100 Subject: [PATCH 34/56] Add module 'process' --- node/node.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index d86dac906c..280f17e045 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2625,3 +2625,8 @@ declare module "constants" { export var X_OK: number; export var UV_UDP_REUSEADDR: number; } + +declare module "process" { + var p: NodeJS.Process; + export default p; +} \ No newline at end of file From a94bce4fff73a65b3a4471b6ce91780cc09ece5c Mon Sep 17 00:00:00 2001 From: ltrain777 Date: Wed, 24 Aug 2016 09:05:30 -0700 Subject: [PATCH 35/56] Fix json method signatures to match restler apis to pass json data. (#10736) --- restler/restler-tests.ts | 18 ++++++++++++++++-- restler/restler.d.ts | 12 ++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/restler/restler-tests.ts b/restler/restler-tests.ts index a709fc3375..8c53455d08 100644 --- a/restler/restler-tests.ts +++ b/restler/restler-tests.ts @@ -33,14 +33,28 @@ rest.post("http://user:pass@service.com/action", { } }); -// post JSON +// post JSON with no options var jsonData = { id: 334 }; rest.postJson("http://example.com/action", jsonData).on("complete", function(data, response) { // handle response }); -// put JSON +// put JSON with no options var jsonData = { id: 334 }; rest.putJson("http://example.com/action", jsonData).on("complete", function(data, response) { // handle response }); + +// post JSON with options +var jsonData = { id: 334 }; +var options = { query: {"api-version": "1.0"}}; +rest.postJson("http://example.com/action", jsonData, options).on("complete", function(data, response) { + // handle response +}); + +// put JSON with options +var jsonData = { id: 334 }; +var options = { query: {"api-version": "1.0"}}; +rest.putJson("http://example.com/action", jsonData, options).on("complete", function(data, response) { + // handle response +}); diff --git a/restler/restler.d.ts b/restler/restler.d.ts index b504a4e75d..389203066d 100644 --- a/restler/restler.d.ts +++ b/restler/restler.d.ts @@ -40,10 +40,11 @@ declare module "restler" { /** * Send json data via GET method. * @param {string} url A url address. + * @param {any} data JSON body * @param {RestlerOptions} options Options. * @return {RestlerResult} Result. */ - json(url: string, options?: RestlerOptions): RestlerResult; + json(url: string, data?: any, options?: RestlerOptions, method?: string): RestlerResult; /** * Create a PATCH request. @@ -56,10 +57,11 @@ declare module "restler" { /** * Send json data via PATCH method. * @param {string} url A url address. + * @param {any} data JSON body * @param {RestlerOptions} options Options. * @return {RestlerResult} Result. */ - patchJson(url: string, options?: RestlerOptions): RestlerResult; + patchJson(url: string, data?: any, options?: RestlerOptions): RestlerResult; /** * Create a POST request. @@ -72,10 +74,11 @@ declare module "restler" { /** * Send json data via POST method. * @param {string} url A url address. + * @param {any} data JSON body * @param {RestlerOptions} options Options. * @return {RestlerResult} Result. */ - postJson(url: string, options?: RestlerOptions): RestlerResult; + postJson(url: string, data?: any, options?: RestlerOptions): RestlerResult; /** * Create a PUT request. @@ -88,10 +91,11 @@ declare module "restler" { /** * Send json data via PUT method. * @param {string} url A url address. + * @param {any} data JSON body * @param {RestlerOptions} options Options. * @return {RestlerResult} Result. */ - putJson(url: string, options?: RestlerOptions): RestlerResult; + putJson(url: string, data?: any, options?: RestlerOptions): RestlerResult; /** * Create a PUT request. From aba1694d0c591ff49e81115a46e2479d89a9ea84 Mon Sep 17 00:00:00 2001 From: Jack Moore Date: Wed, 24 Aug 2016 11:06:06 -0500 Subject: [PATCH 36/56] New definition for universal-router (#10744) * New definition for universal-router * Changed undefined return type to void --- universal-router/universal-router-tests.ts | 99 ++++++++++++++++++++++ universal-router/universal-router.d.ts | 70 +++++++++++++++ 2 files changed, 169 insertions(+) create mode 100644 universal-router/universal-router-tests.ts create mode 100644 universal-router/universal-router.d.ts diff --git a/universal-router/universal-router-tests.ts b/universal-router/universal-router-tests.ts new file mode 100644 index 0000000000..922ca137ad --- /dev/null +++ b/universal-router/universal-router-tests.ts @@ -0,0 +1,99 @@ +/// + +import {ActionContext, Params, resolve } from "universal-router"; + +// Test 1 +const routes1 = [ + { + path: "/one", + action: () => "Page One" + }, + { + path: "/two", + action: () => "Page Two" + } +]; + +resolve(routes1, { path: "/one" }) + .then(result => console.log(result)); + +// Test 2 +const routes2 = [ + { + path: "/hello/:username", + action: (context: ActionContext) => `Welcome, ${context.params["username"]}!` + } +]; + +resolve(routes2, { path: "/hello/john" }) + .then(result => console.log(result)); + + +// Test 3 +const routes3 = [ + { + path: "/hello/:username", + action: (ctx: ActionContext, { username }: Params) => `Welcome, ${username}!` + } +]; + +resolve(routes3, { path: "/hello/john" }) + .then(result => console.log(result)); + + +// Test 4 +const routes4 = [ + { + path: "/hello", + action: () => new Promise(resolve => { + setTimeout(() => resolve("Welcome!"), 1000); + }) + } +]; + +resolve(routes4, { path: "/hello" }) + .then(result => console.log(result)); + +// Test 5 +const routes5 = [ + { + path: "/hello/:username", + async action(ctx: ActionContext, { username }: Params) { + const waitable = async (name: string) => { + console.log(`Welcome ${name}`); + } + await waitable(username); + } + } +]; + +resolve(routes5, { path: "/hello/john" }) + .then(result => console.log(result)); + +// Test 6 +const routes6 = [ + { path: "/one", action: () => "

    Page One

    " }, + { path: "/two", action: () => "

    Page Two

    " } +]; + +resolve(routes6, { path: "/one" }).then(result => { + document.body.innerHTML = result || "

    Not Found

    "; +}); + +// Test 7 +interface Render { + render: typeof render; +} + +const routes7 = [ + { path: "/one", action: ({ render: func }: ActionContext & Render) => func("

    Page One

    ") }, + { path: "/two", action: ({ render: func }: ActionContext & Render) => func("

    Page Two

    ") } +]; + +function render(component: string) { + return new Promise(resolve => { + console.log(`Rendering... ${component}`); + }); +} + +resolve>(routes7, { path: "/one", render }); diff --git a/universal-router/universal-router.d.ts b/universal-router/universal-router.d.ts new file mode 100644 index 0000000000..6acba5c179 --- /dev/null +++ b/universal-router/universal-router.d.ts @@ -0,0 +1,70 @@ +// Type definitions for universal-router +// Project: https://github.com/kriasoft/universal-router +// Definitions by: Jack Moore +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "universal-router" { + /** + * Params is a key/value object that represents extracted URL paramters. Each + * URL parameter resolves to a string. + */ + export interface Params { + [key: string]: string; + } + + /** + * Context represents the context that is passed as the second argument + * passed to resolve. By default, it only is require to contain a path, but + * can be extended by the way of generics. + */ + export interface Context { + path: string; + } + + /** + * ActionContext is similar to Context, with the exception of an added params + * object. ActionContext is passed as the first argument to the action + * function. + */ + export interface ActionContext extends Context { + params: Params; + } + + /** + * A Route is a singular route in your application. It contains a path, an + * action function, and optional children which are an array of Route. + * + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ + export interface Route { + path: string; + action: (ctx: ActionContext & C, params: Params) => R | Promise | void; + children?: Routes; + } + + /** + * Routes in an array of type Route. + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ + export type Routes = Route[]; + + /** + * Resolve function that is given routes and a path or context object. + * Returns a Promise that resolves to result of the action function of the + * matched route. + * + * @template C User context that is made union with Context. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + * + * @param {Routes | Route} routes - Single route or array of routes. + * @param {string | String | Context & C} pathOrContext - path to resolve or + * context object that contains the path along with other data. + * @return {Promise} - Result of matched action function wrapped in a Promsie. + */ + export function resolve(routes: Routes | Route, pathOrContext: string | String | Context & C): Promise +} \ No newline at end of file From 1fa21ec5019826429cf99b8b87175f9ec59407e0 Mon Sep 17 00:00:00 2001 From: "Keith D. Moore" Date: Wed, 24 Aug 2016 11:07:10 -0500 Subject: [PATCH 37/56] add typings for pouchdb-upsert. resolves #10596 (#10752) --- pouchdb-upsert/pouchdb-upsert-tests.ts | 49 +++++++++++++++++++ pouchdb-upsert/pouchdb-upsert.d.ts | 66 ++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 pouchdb-upsert/pouchdb-upsert-tests.ts create mode 100644 pouchdb-upsert/pouchdb-upsert.d.ts diff --git a/pouchdb-upsert/pouchdb-upsert-tests.ts b/pouchdb-upsert/pouchdb-upsert-tests.ts new file mode 100644 index 0000000000..fa4eb83af3 --- /dev/null +++ b/pouchdb-upsert/pouchdb-upsert-tests.ts @@ -0,0 +1,49 @@ +/// + +import * as pouchdbUpsert from 'pouchdb-upsert'; +PouchDB.plugin(pouchdbUpsert); + +namespace PouchDBUpsertTests { + type UpsertDocModel = { _id: 'test-doc1', name: 'test' }; + let docToUpsert: PouchDB.Core.Document; + const db = new PouchDB(); + + function testUpsert_WithPromise_AndReturnDoc() { + db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + // Make some updates.... + return doc; + }).then((res: PouchDB.Core.Response) => { + }); + } + + function testUpsert_WithPromise_AndReturnBoolean() { + db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + // Make some updates.... + return false; + }).then((res: PouchDB.Core.Response) => { + }); + } + + function testUpsert_WithCallback_AndReturnDoc() { + db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + // Make some updates.... + return doc; + }, (res: PouchDB.Core.Response) => {}); + } + + function testUpsert_WithCallback_AndReturnBoolean() { + // callback return boolean + db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + // Make some updates.... + return false; + }, (res: PouchDB.Core.Response) => {}); + } + + function testPutIfNotExists_WithPromise() { + db.putIfNotExists(docToUpsert).then( (res: PouchDB.Core.Response) => {}); + } + + function testPutIfNotExists_WithCallback() { + db.putIfNotExists(docToUpsert, (res: PouchDB.Core.Response) => {}); + } +} diff --git a/pouchdb-upsert/pouchdb-upsert.d.ts b/pouchdb-upsert/pouchdb-upsert.d.ts new file mode 100644 index 0000000000..b0a4e760a3 --- /dev/null +++ b/pouchdb-upsert/pouchdb-upsert.d.ts @@ -0,0 +1,66 @@ +// Type definitions for pouchdb-upsert v2.0.1 +// Project: https://github.com/pouchdb/upsert +// Definitions by: Keith D. Moore , Andrew Mitchell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + + interface Database { + /** + * Perform an upsert (update or insert) operation. Returns a Promise. + * + * @param docId - the _id of the document. + * @param diffFun - function that takes the existing doc as input and returns an updated doc. + * If this diffFunc returns falsey, then the update won't be performed (as an optimization). + * If the document does not already exist, then {} will be the input to diffFunc. + * + */ + upsert(docId: Core.DocumentId, diffFun: UpsertDiffCallback): Promise; + + /** + * Perform an upsert (update or insert) operation. If a callback is not provided, the Promise based version + * of this function will be called. + * + * @param docId - the _id of the document. + * @param diffFun - function that takes the existing doc as input and returns an updated doc. + * If this diffFunc returns falsey, then the update won't be performed (as an optimization). + * If the document does not already exist, then {} will be the input to diffFunc. + * @param callback - called with the results after operation is completed. + */ + upsert(docId: Core.DocumentId, diffFun: UpsertDiffCallback, + callback: Core.Callback): void; + + /** + * Put a new document with the given docId, if it doesn't already exist. Returns a Promise. + * + * @param doc - the document to insert. Should contain an _id if docId is not specified + * If the document already exists, then the Promise will just resolve immediately. + */ + putIfNotExists(doc: Core.Document): Promise; + + // + /** + * Put a new document with the given docId, if it doesn't already exist. If a callback is not provided, + * the Promise based version of this function will be called. + * + * @param doc - the document to insert. Should contain an _id if docId is not specified + * If the document already exists, then the Promise will just resolve immediately. + * @param callback - called with the results after operation is completed. + * If you don't specify a callback, then the Promise version of this function will be invoked and it + * will return a Promise. + */ + putIfNotExists(doc: Core.Document, + callback: Core.Callback): void; + } + + interface UpsertDiffCallback { + (doc: Core.Document): Core.Document|boolean; + } +} + +declare module 'pouchdb-upsert' { + const plugin: PouchDB.Plugin; + export = plugin; +} From 77bc119042bdf92f5740d912a3a3bb336437ac08 Mon Sep 17 00:00:00 2001 From: Steven Date: Wed, 24 Aug 2016 09:11:07 -0700 Subject: [PATCH 38/56] Add extra static members to the Node v4 Error class (#10747) Defines `stackTraceLimit` and `captureStackTrace` as static members for the Error class in Node v4 so their usage can be recognized. --- node/node-4-tests.ts | 14 ++++++++++++++ node/node-4.d.ts | 4 ++++ 2 files changed, 18 insertions(+) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 8cddf66987..9db708b910 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -826,3 +826,17 @@ namespace vm_tests { Debug.scripts().forEach(function(script: any) { console.log(script.name); }); } } + +/////////////////////////////////////////////////////////////////////////////// +/// Errors Tests : https://nodejs.org/dist/latest-v4.x/docs/api/errors.html /// +/////////////////////////////////////////////////////////////////////////////// + +namespace errors_tests { + { + Error.stackTraceLimit = Infinity; + } + { + const myObject = {}; + Error.captureStackTrace(myObject); + } +} \ No newline at end of file diff --git a/node/node-4.d.ts b/node/node-4.d.ts index e60da8e309..848b0536d0 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -13,6 +13,10 @@ interface Error { stack?: string; } +interface ErrorConstructor { + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + stackTraceLimit: number; +} // compat for TypeScript 1.8 // if you use with --target es3 or --target es5 and use below definitions, From d7c91b7a92d4e42ca50d375454b869e06bb80bb3 Mon Sep 17 00:00:00 2001 From: "Keith D. Moore" Date: Wed, 24 Aug 2016 11:28:27 -0500 Subject: [PATCH 39/56] add remove function typings to pouchdb-core (#10754) --- pouchdb-core/pouchdb-core-tests.ts | 27 +++++++++++++++++++++++++++ pouchdb-core/pouchdb-core.d.ts | 14 ++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/pouchdb-core/pouchdb-core-tests.ts b/pouchdb-core/pouchdb-core-tests.ts index ac7a6c3e69..71f5db7d63 100644 --- a/pouchdb-core/pouchdb-core-tests.ts +++ b/pouchdb-core/pouchdb-core-tests.ts @@ -75,4 +75,31 @@ namespace PouchDBCoreTests { db.info({ ajax: { cache: true }}, (error, result) => { }); } + + function testRemove() { + type MyModel = { rev: 'rev', property: 'someProperty '}; + let model: PouchDB.Core.Document; + const id = 'model'; + const rev = 'rev'; + + const db = new PouchDB(); + + // Promise version with doc + db.remove(model).then( (res: PouchDB.Core.Response) => {}); + + // Promise version with doc and options + db.remove(model, {}).then( (res: PouchDB.Core.Response) => {}); + + // Promise version with docId and rev + db.remove(id, rev).then( (res: PouchDB.Core.Response) => {}); + + // Promise version with docId and rev and options + db.remove(id, rev, {}).then( (res: PouchDB.Core.Response) => {}); + + // Callback version with doc + db.remove(model, {}, (res: PouchDB.Core.Response) => {}); + + // Callback version with docId and rev + db.remove(id, rev, {}, (res: PouchDB.Core.Response) => {}); + } } diff --git a/pouchdb-core/pouchdb-core.d.ts b/pouchdb-core/pouchdb-core.d.ts index a8b6418510..1a56e51785 100644 --- a/pouchdb-core/pouchdb-core.d.ts +++ b/pouchdb-core/pouchdb-core.d.ts @@ -319,6 +319,20 @@ declare namespace PouchDB { revision?: Core.RevisionId, options?: Core.PutOptions): Promise; + /** Remove a doc from the database */ + remove(doc: Core.Document, + options: Core.Options, + callback: Core.Callback): void; + remove(docId: Core.DocumentId, + revision: Core.RevisionId, + options: Core.Options, + callback: Core.Callback): void; + remove(doc: Core.Document, + options?: Core.Options): Promise; + remove(docId: Core.DocumentId, + revision: Core.RevisionId, + options?: Core.Options): Promise; + /** Get database information */ info(options: Core.InfoOptions | void, callback: Core.Callback): void; From 3f9b9ed351d9fc5c64576de74527ba923f5d6ed0 Mon Sep 17 00:00:00 2001 From: "Keith D. Moore" Date: Wed, 24 Aug 2016 11:28:54 -0500 Subject: [PATCH 40/56] add compact function typings to pouchdb-core (#10753) --- pouchdb-core/pouchdb-core-tests.ts | 10 ++++++++++ pouchdb-core/pouchdb-core.d.ts | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/pouchdb-core/pouchdb-core-tests.ts b/pouchdb-core/pouchdb-core-tests.ts index 71f5db7d63..b46bce834d 100644 --- a/pouchdb-core/pouchdb-core-tests.ts +++ b/pouchdb-core/pouchdb-core-tests.ts @@ -38,6 +38,16 @@ namespace PouchDBCoreTests { }); } + function testCompact() { + const db = new PouchDB<{}>(); + // Promise version + db.compact().then( (res: PouchDB.Core.Response) => {}); + // Promise version with optional options + db.compact({interval: 300}).then( (res: PouchDB.Core.Response) => {}); + // Options with a callback + db.compact({interval: 300}, (res: PouchDB.Core.Response) => {}); + } + function testDestroy() { const db = new PouchDB<{}>(); diff --git a/pouchdb-core/pouchdb-core.d.ts b/pouchdb-core/pouchdb-core.d.ts index 1a56e51785..b0498e76af 100644 --- a/pouchdb-core/pouchdb-core.d.ts +++ b/pouchdb-core/pouchdb-core.d.ts @@ -164,6 +164,10 @@ declare namespace PouchDB { interface PostOptions extends PutOptions { } + interface CompactOptions extends Core.Options { + interval?: number; + } + interface InfoOptions extends Options { } } @@ -264,6 +268,11 @@ declare namespace PouchDB { allDocs(options?: Core.AllDocsOptions): Promise>; + /** Compact the database */ + compact(options?: Core.CompactOptions): Promise; + compact(options: Core.CompactOptions, + callback: Core.Callback): void; + /** Destroy the database */ destroy(options: Core.DestroyOptions | void, callback: Core.AnyCallback): void; From ccf79bc4f71390d180da5ef4499f61fed1f69077 Mon Sep 17 00:00:00 2001 From: nickp10 Date: Wed, 24 Aug 2016 10:31:03 -0600 Subject: [PATCH 41/56] Adding definitions for the set-cookie-parser library (#10756) * Adding definitions for the set-cookie-parser library * Adding newline to end of file --- set-cookie-parser/set-cookie-parser-tests.ts | 45 ++++++++++++++++++++ set-cookie-parser/set-cookie-parser.d.ts | 27 ++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 set-cookie-parser/set-cookie-parser-tests.ts create mode 100644 set-cookie-parser/set-cookie-parser.d.ts diff --git a/set-cookie-parser/set-cookie-parser-tests.ts b/set-cookie-parser/set-cookie-parser-tests.ts new file mode 100644 index 0000000000..731d38efaa --- /dev/null +++ b/set-cookie-parser/set-cookie-parser-tests.ts @@ -0,0 +1,45 @@ +/// +/// + +import assert = require("assert"); +import http = require("http"); +import setCookie = require("set-cookie-parser"); + +// Required properties only test +var requiredOnly = "foo=bar;"; +var cookies = setCookie(requiredOnly); +assert.equal(cookies.length, 1); +assert.equal(cookies[0].name, "foo"); +assert.equal(cookies[0].value, "bar"); + +// Optional properties included test +var optionalIncluded = "foo=bar; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 2025 10:01:11 GMT; HttpOnly; Secure"; +cookies = setCookie(optionalIncluded); +assert.equal(cookies.length, 1); +assert.equal(cookies[0].name, "foo"); +assert.equal(cookies[0].value, "bar"); +assert.equal(cookies[0].domain, ".example.com"); +assert.equal(cookies[0].path, "/"); +assert.deepEqual(cookies[0].expires, new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)')); +assert.equal(cookies[0].maxAge, 1000); +assert.equal(cookies[0].httpOnly, true); +assert.equal(cookies[0].secure, true); + +// Array of strings test +var arrayOfCookies = ["bam=baz", "foo=bar"]; +cookies = setCookie(arrayOfCookies); +assert.equal(cookies.length, 2); +assert.equal(cookies[0].name, "bam"); +assert.equal(cookies[0].value, "baz"); +assert.equal(cookies[1].name, "foo"); +assert.equal(cookies[1].value, "bar"); + +// HTTP response message test +var message = {}; +message.headers = { "set-cookie": ["bam=baz", "foo=bar"] }; +cookies = setCookie(message); +assert.equal(cookies.length, 2); +assert.equal(cookies[0].name, "bam"); +assert.equal(cookies[0].value, "baz"); +assert.equal(cookies[1].name, "foo"); +assert.equal(cookies[1].value, "bar"); diff --git a/set-cookie-parser/set-cookie-parser.d.ts b/set-cookie-parser/set-cookie-parser.d.ts new file mode 100644 index 0000000000..91ca3ef2c1 --- /dev/null +++ b/set-cookie-parser/set-cookie-parser.d.ts @@ -0,0 +1,27 @@ +// Type definitions for set-cookie-parser +// Project: https://github.com/nfriedly/set-cookie-parser +// Definitions by: Nick Paddock +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "set-cookie-parser" { + import http = require("http"); + + function SetCookieParser(input: string | string[] | http.IncomingMessage): SetCookieParser.Cookie[]; + + namespace SetCookieParser { + interface Cookie { + name: string; + value: string; + path?: string; + expires?: Date; + maxAge?: number; + domain?: string; + secure?: boolean; + httpOnly?: boolean; + } + } + + export = SetCookieParser; +} From f0fede9ce3fb165fe254c367e44a2370fa033735 Mon Sep 17 00:00:00 2001 From: Giacomo Rebonato Date: Wed, 24 Aug 2016 17:33:31 +0100 Subject: [PATCH 42/56] added minSize and maxSide to React-Dropzone (#10755) * added minSize and maxSide * added comment to properties and fixed test --- react-dropzone/react-dropzone-tests.tsx | 2 ++ react-dropzone/react-dropzone.d.ts | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/react-dropzone/react-dropzone-tests.tsx b/react-dropzone/react-dropzone-tests.tsx index 6216b5f20e..ca3d462596 100644 --- a/react-dropzone/react-dropzone-tests.tsx +++ b/react-dropzone/react-dropzone-tests.tsx @@ -19,6 +19,8 @@ class Test extends React.Component { style={{ borderStyle: "dashed" }} activeStyle={{ borderStyle: "dotted" }} className="regular" + minSize={2000} + maxSize={Infinity} activeClassName="active" rejectClassName="reject" disableClick={true} diff --git a/react-dropzone/react-dropzone.d.ts b/react-dropzone/react-dropzone.d.ts index a8198524de..792fd436ba 100644 --- a/react-dropzone/react-dropzone.d.ts +++ b/react-dropzone/react-dropzone.d.ts @@ -22,6 +22,14 @@ declare namespace ReactDropzone { * Clicking the brings up the browser file picker. To disable, set to true. */ disableClick?: boolean; + /** + * Min file size accepted + */ + minSize?: number; + /** + * Max file size accepted + */ + maxSize?: number; /** * To accept only a single file, set this to false. */ From 882c5665a1031acb2a791af1928b3b26a129e094 Mon Sep 17 00:00:00 2001 From: York Yao Date: Thu, 25 Aug 2016 00:38:18 +0800 Subject: [PATCH 43/56] add type of socket.io-parser (#10761) * add type of socket.io-parser * fix CI --- socket.io-parser/socket.io-parser-tests.ts | 41 ++++++++++++++++++++++ socket.io-parser/socket.io-parser.d.ts | 39 ++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 socket.io-parser/socket.io-parser-tests.ts create mode 100644 socket.io-parser/socket.io-parser.d.ts diff --git a/socket.io-parser/socket.io-parser-tests.ts b/socket.io-parser/socket.io-parser-tests.ts new file mode 100644 index 0000000000..917f72500f --- /dev/null +++ b/socket.io-parser/socket.io-parser-tests.ts @@ -0,0 +1,41 @@ +/// +/// + +import * as parser from 'socket.io-parser'; +var encoder = new parser.Encoder(); +var packet = { + type: parser.EVENT, + data: 'test-packet', + id: 13 +}; +encoder.encode(packet, function (encodedPackets) { + var decoder = new parser.Decoder(); + decoder.on('decoded', function (decodedPacket) { + decodedPacket.type == parser.EVENT + decodedPacket.data == 'test-packet' + decodedPacket.id == 13 + }); + + for (var i = 0; i < encodedPackets.length; i++) { + decoder.add(encodedPackets[i]); + } +}); + +var packet2 = { + type: parser.BINARY_EVENT, + data: { i: new Buffer(1234), j: new Blob([new ArrayBuffer(2)]) }, + id: 15 +}; +encoder.encode(packet2, function (encodedPackets) { + var decoder = new parser.Decoder(); + decoder.on('decoded', function (decodedPacket) { + decodedPacket.type == parser.BINARY_EVENT + Buffer.isBuffer(decodedPacket.data.i) == true + Buffer.isBuffer(decodedPacket.data.j) == true + decodedPacket.id == 15 + }); + + for (var i = 0; i < encodedPackets.length; i++) { + decoder.add(encodedPackets[i]); + } +}); diff --git a/socket.io-parser/socket.io-parser.d.ts b/socket.io-parser/socket.io-parser.d.ts new file mode 100644 index 0000000000..0c4903fda4 --- /dev/null +++ b/socket.io-parser/socket.io-parser.d.ts @@ -0,0 +1,39 @@ +// Type definitions for json-editor +// Project: https://github.com/socketio/socket.io-parser +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "socket.io-parser" { + namespace Parser { + type Packet = { + type: number, + data: any, + id: number + } + type EncodedPacket = string | Buffer | ArrayBuffer | Blob; + + var types: string[]; + + var CONNECT: number; + var DISCONNECT: number; + var EVENT: number; + var ACK: number; + var ERROR: number; + var BINARY_EVENT: number; + var BINARY_ACK: number; + + class Encoder { + encode(packet: Packet, callback: (encodedPackets: EncodedPacket[]) => void): void; + } + + class Decoder { + on(event: string, callback: (decodedPacket: Packet) => void): void; + add(encodedPacket: EncodedPacket): void; + destroy(): void; + } + } + + export = Parser; +} From 23c9f2230960c4a9b83e4297471d082a27d02b74 Mon Sep 17 00:00:00 2001 From: David Herges Date: Wed, 24 Aug 2016 18:38:38 +0200 Subject: [PATCH 44/56] Adding type definitions for 'halfred' (#10764) --- halfred/halfred-tests.ts | 13 +++ halfred/halfred.d.ts | 247 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 260 insertions(+) create mode 100644 halfred/halfred-tests.ts create mode 100644 halfred/halfred.d.ts diff --git a/halfred/halfred-tests.ts b/halfred/halfred-tests.ts new file mode 100644 index 0000000000..3aecf39962 --- /dev/null +++ b/halfred/halfred-tests.ts @@ -0,0 +1,13 @@ +/// + +// run test with: $ tsc --noImplicitAny --target es6 --module commonjs halfred-tests.ts +import { parse } from 'halfred'; // require('halfred'); +let resource = parse({foo: "bar", "_links": { "self": { href: "fooo" }}}); +console.log(resource); + +let allLinks = resource.allLinks(); +for (let key in allLinks) { + let link = allLinks[key]; + + console.log(link[0].href); +} diff --git a/halfred/halfred.d.ts b/halfred/halfred.d.ts new file mode 100644 index 0000000000..9c1d571a9d --- /dev/null +++ b/halfred/halfred.d.ts @@ -0,0 +1,247 @@ +// Type definitions for Halfred v1.0.0 +// Project: https://github.com/basti1302/halfred +// Definitions by: David Herges +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "halfred" { + + /** + * halfred.parse(object) returns a Resource object. + * + * @see https://github.com/basti1302/halfred#usage + */ + export function parse(object: any): Resource; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function enableValidation(flag: boolean): void; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function disableValidation(): void; + + /** @see https://github.com/basti1302/halfred#resource-api */ + export interface Resource { + + /** + * Returns an object which has an array for each link that was present in the source object. + * See below why each link is represented as an array. + */ + allLinkArrays(): LinkCollection; + + /** Alias for allLinkArrays() */ + allLinks(): LinkCollection; + + /** + * Returns the array of links for the given key, or null if there are no links for this key. + */ + linkArray(key: string): Link[]; + + /** + * Returns the first element of the array of links for the given key or null if there are no + * links for this key. + */ + link(key: string): Link; + + /** + * Returns an object which has an array for each embedded resource that was present in the + * source object. + * See below why each embedded resource is represented as an array. Each element of any of + * this arrays is in turn a Resource object. + */ + allEmbeddedResourceArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedResources(): ResourceCollection; + + /** + * Returns the array of embedded resources for the given key, or null if there are no embedded + * resources for this key. Each element of this arrays is in turn a Resource object. + */ + embeddedResourceArray(key: string): Resource[]; + + /** Alias for embeddedResourceArray() */ + embeddedArray(key: string): Resource[]; + + /** + * Returns the first element of the array of embedded resources for the given key or null if + * there are no embedded resources for this key. The returend object is a Resource object. + */ + embeddedResource(key: string): Resource; + + /** Alias for embeddedResource(key) */ + embedded(key: string): Resource; + + /** + * Returns the unmodified, original object that was parsed to this resource. This is rather + * uninteresting for the source object you give to the parse method (because you probably + * still have a reference to the source object) but it is a convenient way to get the part of + * the source object that corresponds to an embedded resource. + */ + original(): any; + + /** + * Returns true if the resource has any CURIEs (Compact URIs). + * + * @see http://www.w3.org/TR/2010/NOTE-curie-20101216/ + */ + hasCuries(): boolean; + + /** + * Returns the array of CURIEs. Each object in the array is a link object, which means it + * can be templated etc. See below for the link object API. + */ + curieArray(): Link[]; + + /** + * Returns the curie with the given name, if any. The returned object is a link object, which + * means it can be templated etc. See below for link object API. + */ + curie(name: string): Link; + + /** + * Returns the compact URI for the given full URL, if any + */ + reverseResolveCurie(fullUrl: string): string; + + /** + * Returns all validation issues. Validation issues are only gathered if validation has been + * turned on by calling ``halfred.enableValidation()`` before calling ``halfred.parse``. + */ + validationIssues(): any; + + /** + * Alias for validationIssues() + */ + validation(): any; + + /* + XX ... think we should NOT try to represent these things in TypeScript. + + In addition to the methods mentioned here, resource has all properties of the source object. + This is also true for embedded Resource objects. The non-HAL properties (that is, any + property except _links and _embedded) are copied over to the Resource object. This is always + a shallow copy, so modifying the a non-HAL property in the Resource object might also alter + the source object and vice versa. + + The Resource object also has the properties _links and _embedded but they might differ from + the _links/_embedded properties in the source object (Halfred applies some normalization to + them). These are not intended to be accessed by clients directly, instead, use the provided + methods to work with links and embedded resources. + */ + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface ResourceCollection { + [key: string]: Resource[]; + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface LinkCollection { + [rel: string]: Link[] + } + + /** + * A Link Object represents a hyperlink from the containing resource to a URI. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5 + */ + interface Link { + + /** + * The "href" property is REQUIRED. + * + * Its value is either a URI [RFC3986] or a URI Template [RFC6570]. + * + * If the value is a URI Template then the Link Object SHOULD have a + * "templated" attribute whose value is true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.1 + */ + href: string; + + /** + * The "templated" property is OPTIONAL. + * + * Its value is boolean and SHOULD be true when the Link Object's "href" + * property is a URI Template. + * + * Its value SHOULD be considered false if it is undefined or any other + * value than true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.2 + */ + templated?: boolean; + + /** + * The "type" property is OPTIONAL. + * + * Its value is a string used as a hint to indicate the media type + * expected when dereferencing the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.3 + */ + type?: string; + + /** + * The "deprecation" property is OPTIONAL. + * + * Its presence indicates that the link is to be deprecated (i.e. + * removed) at a future date. Its value is a URL that SHOULD provide + * further information about the deprecation. + * + * A client SHOULD provide some notification (for example, by logging a + * warning message) whenever it traverses over a link that has this + * property. The notification SHOULD include the deprecation property's + * value so that a client manitainer can easily find information about + * the deprecation. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.4 + */ + deprecation?: string; + + /** + * The "name" property is OPTIONAL. + * + * Its value MAY be used as a secondary key for selecting Link Objects + * which share the same relation type. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.5 + */ + name?: string; + + /** + * The "profile" property is OPTIONAL. + * + * Its value is a string which is a URI that hints about the profile (as + * defined by [I-D.wilde-profile-link]) of the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.6 + */ + profile?: string; + + /** + * The "title" property is OPTIONAL. + * + * Its value is a string and is intended for labelling the link with a + * human-readable identifier (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.7 + */ + title?: string; + + /** + * The "hreflang" property is OPTIONAL. + * + * Its value is a string and is intended for indicating the language of + * the target resource (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.8 + */ + hreflang?: string; + + } + +} From 2d3fcf5b626d5c0b89d1b93b5f2dd802f2036f44 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 25 Aug 2016 22:49:18 +0900 Subject: [PATCH 45/56] TypeScript-STL v1.0.1 List.sort() and its related methods are changed --- typescript-stl/typescript-stl.d.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index 5a83a405cd..96d22ceb8f 100644 --- a/typescript-stl/typescript-stl.d.ts +++ b/typescript-stl/typescript-stl.d.ts @@ -1,4 +1,4 @@ -// Type definitions for TypeScript-STL v1.0.0 +// Type definitions for TypeScript-STL v1.0.1 // Project: https://github.com/samchon/typescript-stl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7097,6 +7097,14 @@ declare namespace std { * shall be a function pointer or a function object. */ sort(compare: (left: T, right: T) => boolean): void; + /** + * @hidden + */ + private qsort(first, last, compare); + /** + * @hidden + */ + private partition(first, last, compare); /** * @inheritdoc */ @@ -9217,7 +9225,7 @@ declare namespace std { */ erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; /** - * @hiddde + * @hidden */ protected erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; /** From 992f7671e4154d5699eb050b638b28753584f993 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Thu, 25 Aug 2016 09:25:02 -0600 Subject: [PATCH 46/56] Fix #10725 - Use global / external-agnostic library pattern --- daterangepicker/daterangepicker.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts index f3534a197e..a86614cfe8 100644 --- a/daterangepicker/daterangepicker.d.ts +++ b/daterangepicker/daterangepicker.d.ts @@ -11,7 +11,7 @@ interface JQuery { daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; } -declare module daterangepicker { +declare namespace daterangepicker { interface DatepickerEventObject extends JQueryEventObject { date: Date; @@ -164,3 +164,7 @@ declare module daterangepicker { monthNames?: string[]; } } + +declare module "daterangepicker" { + export = daterangepicker; +} From 937516aae1def4a191497fde8af0d585007d1b41 Mon Sep 17 00:00:00 2001 From: nickp10 <=> Date: Thu, 25 Aug 2016 10:29:29 -0600 Subject: [PATCH 47/56] Add parse function definition to set-cookie-parse --- set-cookie-parser/set-cookie-parser-tests.ts | 33 +++++++++++++++++--- set-cookie-parser/set-cookie-parser.d.ts | 32 ++++++++++--------- 2 files changed, 46 insertions(+), 19 deletions(-) diff --git a/set-cookie-parser/set-cookie-parser-tests.ts b/set-cookie-parser/set-cookie-parser-tests.ts index 731d38efaa..8734fdfcdb 100644 --- a/set-cookie-parser/set-cookie-parser-tests.ts +++ b/set-cookie-parser/set-cookie-parser-tests.ts @@ -1,13 +1,20 @@ /// /// -import assert = require("assert"); -import http = require("http"); -import setCookie = require("set-cookie-parser"); +import * as assert from "assert"; +import * as http from "http"; +import * as setCookie from "set-cookie-parser"; + +// Call parse function on imported object +var input = "foo=bar;"; +var cookies = setCookie.parse(input); +assert.equal(cookies.length, 1); +assert.equal(cookies[0].name, "foo"); +assert.equal(cookies[0].value, "bar"); // Required properties only test var requiredOnly = "foo=bar;"; -var cookies = setCookie(requiredOnly); +cookies = setCookie(requiredOnly); assert.equal(cookies.length, 1); assert.equal(cookies[0].name, "foo"); assert.equal(cookies[0].value, "bar"); @@ -43,3 +50,21 @@ assert.equal(cookies[0].name, "bam"); assert.equal(cookies[0].value, "baz"); assert.equal(cookies[1].name, "foo"); assert.equal(cookies[1].value, "bar"); + +// Create new cookie with only required properties +var requiredOnlyCookie: setCookie.Cookie = { + name: "Foo", + value: "Bar" +} + +// Create new cookie with all properties included optional ones +var optionalIncludedCookie: setCookie.Cookie = { + name: "Bam", + value: "Baz", + domain: ".example.com", + path: "/", + expires: new Date("Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)"), + maxAge: 1000, + httpOnly: true, + secure: true +}; diff --git a/set-cookie-parser/set-cookie-parser.d.ts b/set-cookie-parser/set-cookie-parser.d.ts index 91ca3ef2c1..3cacde6043 100644 --- a/set-cookie-parser/set-cookie-parser.d.ts +++ b/set-cookie-parser/set-cookie-parser.d.ts @@ -6,22 +6,24 @@ /// declare module "set-cookie-parser" { - import http = require("http"); + import http = require("http"); - function SetCookieParser(input: string | string[] | http.IncomingMessage): SetCookieParser.Cookie[]; + function SetCookieParser(input: string | string[] | http.IncomingMessage): SetCookieParser.Cookie[]; - namespace SetCookieParser { - interface Cookie { - name: string; - value: string; - path?: string; - expires?: Date; - maxAge?: number; - domain?: string; - secure?: boolean; - httpOnly?: boolean; - } - } + namespace SetCookieParser { + function parse(input: string | string[] | http.IncomingMessage): Cookie[]; - export = SetCookieParser; + interface Cookie { + name: string; + value: string; + path?: string; + expires?: Date; + maxAge?: number; + domain?: string; + secure?: boolean; + httpOnly?: boolean; + } + } + + export = SetCookieParser; } From c610ec79c45eee462d0c1e22be9ee77cff51e3c1 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 02:11:15 +0900 Subject: [PATCH 48/56] Reflect the latest Fetch API spec --- whatwg-fetch/whatwg-fetch.d.ts | 191 +++++++++++++++++---------------- 1 file changed, 99 insertions(+), 92 deletions(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index 5a428fb47b..03e5c7473e 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -1,98 +1,105 @@ -// Type definitions for fetch API +// Type definitions for Fetch API // Project: https://github.com/github/fetch -// Definitions by: Ryan Graham +// Definitions by: Ryan Graham , Kagami Sascha Rosylight // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class Request extends Body { - constructor(input: string|Request, init?:RequestInit); - method: string; - url: string; - headers: Headers; - context: RequestContext; - referrer: string; - mode: RequestMode; - redirect: RequestRedirect; - credentials: RequestCredentials; - cache: RequestCache; -} - -interface RequestInit { - method?: string; - headers?: HeaderInit|{ [index: string]: string }; - body?: BodyInit; - mode?: RequestMode; - redirect?: RequestRedirect; - credentials?: RequestCredentials; - cache?: RequestCache; -} - -type RequestContext = - "audio" | "beacon" | "cspreport" | "download" | "embed" | - "eventsource" | "favicon" | "fetch" | "font" | "form" | "frame" | - "hyperlink" | "iframe" | "image" | "imageset" | "import" | - "internal" | "location" | "manifest" | "object" | "ping" | "plugin" | - "prefetch" | "script" | "serviceworker" | "sharedworker" | - "subresource" | "style" | "track" | "video" | "worker" | - "xmlhttprequest" | "xslt"; -type RequestMode = "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestCache = - "default" | "no-store" | "reload" | "no-cache" | - "force-cache" | "only-if-cached"; - -declare interface HeadersMap { - [index: string]: string; -} - -declare class Headers { - constructor(headers?:Headers|HeadersMap) - append(name: string, value: string): void; - delete(name: string):void; - get(name: string): string; - getAll(name: string): Array; - has(name: string): boolean; - set(name: string, value: string): void; - forEach(callback: (value: string, name: string) => void): void; -} - -declare class Body { - bodyUsed: boolean; - arrayBuffer(): Promise; - blob(): Promise; - formData(): Promise; - json(): Promise; - json(): Promise; - text(): Promise; -} - -declare class Response extends Body { - constructor(body?: BodyInit, init?: ResponseInit); - static error(): Response; - static redirect(url: string, status: number): Response; - type: ResponseType; - url: string; - status: number; - ok: boolean; - statusText: string; - headers: Headers; - clone(): Response; -} - -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; - -interface ResponseInit { - status: number; - statusText?: string; - headers?: HeaderInit; -} - -declare type HeaderInit = Headers|Array; -declare type BodyInit = ArrayBuffer|ArrayBufferView|Blob|FormData|string; -declare type RequestInfo = Request|string; - interface Window { - fetch(url: string|Request, init?: RequestInit): Promise; + fetch(url: RequestInfo, init?: RequestInit): Promise; +} +declare var fetch: typeof window.fetch; + +declare type HeadersInit = Headers | string[][] | { [key: string]: string }; +declare class Headers { + constructor(init?: HeadersInit); + + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + + // WebIDL pair iterator: iterable + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, index: number, headers: Headers) => void, thisArg?: any): void; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; } -declare var fetch: typeof window.fetch; +declare type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData /* | URLSearchParams */ | string; +interface Body { + bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +declare type RequestInfo = Request | string; +interface Request extends Body { + method: string; + url: string; + headers: Headers; + + type: "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; + destination: "" | "document" | "embed" | "font" | "image" | "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "worker" | "xslt"; + referrer: string; + referrerPolicy: ReferrerPolicy; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + redirect: RequestRedirect; + integrity: string; + + clone(): Request; +} +interface RequestInit { + method?: string; + headers?: HeadersInit; + body?: BodyInit; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + mode?: RequestMode; + credentials?: RequestCredentials; + cache?: RequestCache; + redirect?: RequestRedirect; + integrity?: string; + window?: any; +} +interface RequestConstructor { + new (input: RequestInfo, init?: RequestInit): Request; +} +declare var Request: RequestConstructor; + +type RequestMode = "same-origin" | "no-cors" | "cors"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestRedirect = "follow" | "error" | "manual"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "unsafe-url"; + +interface Response extends Body { + type: "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; + url: string; + redirected: boolean; + status: number; + ok: boolean; + statusText: string; + headers: Headers; + body: any /*ReadableStream | null*/; + trailer: Promise; + + clone(): Response; +} +interface ResponseInit { + status?: number; + statusText?: number; + headers?: HeadersInit; +} +interface ResponseConstructor { + new (body?: BodyInit, init?: ResponseInit): Response; + + error(): Response; + redirect(url: string, status?: number): Response; +} +declare var Response: ResponseConstructor; From 4d273e48487d1154719e7ec0da4902d3564cd74c Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 02:29:25 +0900 Subject: [PATCH 49/56] Add missing enum items --- whatwg-fetch/whatwg-fetch.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index 03e5c7473e..d9aeca1fe3 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -72,11 +72,11 @@ interface RequestConstructor { } declare var Request: RequestConstructor; -type RequestMode = "same-origin" | "no-cors" | "cors"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached"; type RequestRedirect = "follow" | "error" | "manual"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "unsafe-url"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url"; interface Response extends Body { type: "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; From 46a63785b7cf89900d1cdd2ad2b507d69c314c70 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 02:35:59 +0900 Subject: [PATCH 50/56] Remove null union as TS stable does not support it --- whatwg-fetch/whatwg-fetch.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index d9aeca1fe3..a5fe21dc09 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -14,7 +14,7 @@ declare class Headers { append(name: string, value: string): void; delete(name: string): void; - get(name: string): string | null; + get(name: string): string; // | null; (TS 2.0 strict null check) has(name: string): boolean; set(name: string, value: string): void; From ad7532875359ba339ac65d0a62c4ad312487e4f7 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 02:38:42 +0900 Subject: [PATCH 51/56] statusText fix --- whatwg-fetch/whatwg-fetch.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index a5fe21dc09..d6cfd2638a 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -93,7 +93,7 @@ interface Response extends Body { } interface ResponseInit { status?: number; - statusText?: number; + statusText?: string; headers?: HeadersInit; } interface ResponseConstructor { From 2d310f938eb552eadca2b14a1299c73172bb1924 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 03:02:42 +0900 Subject: [PATCH 52/56] HeadersMap was essentially a DOMStringMap ... and TS 2.0 even will not require the type --- whatwg-fetch/whatwg-fetch-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/whatwg-fetch/whatwg-fetch-tests.ts b/whatwg-fetch/whatwg-fetch-tests.ts index 090e114b5d..3f23abe914 100644 --- a/whatwg-fetch/whatwg-fetch-tests.ts +++ b/whatwg-fetch/whatwg-fetch-tests.ts @@ -7,7 +7,7 @@ function test_HeadersCopiedFromHeaders() { } function test_HeadersCopiedFromHash() { - var source:HeadersMap = { + var source: DOMStringMap = { 'Content-Type': 'application/json' }; return new Headers(source); From cc19e43b3d7eb0f5b598fd3ec17cc0edf1e6cf22 Mon Sep 17 00:00:00 2001 From: Sebastian Rogers Date: Thu, 25 Aug 2016 16:55:59 -0500 Subject: [PATCH 53/56] Added "identifier" property to PIXI.interaction.InteractionData. --- pixi.js/pixi.js.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/pixi.js/pixi.js.d.ts b/pixi.js/pixi.js.d.ts index dfccd33431..d8e6bf86d7 100644 --- a/pixi.js/pixi.js.d.ts +++ b/pixi.js/pixi.js.d.ts @@ -1456,6 +1456,7 @@ declare namespace PIXI { global: Point; target: DisplayObject; originalEvent: Event; + identifier: number; getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; From 8191eb49a6223d6cb5f9e5a38625983a62a01f4a Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 10:16:51 +0900 Subject: [PATCH 54/56] type aliases --- whatwg-fetch/whatwg-fetch.d.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index d6cfd2638a..21baca126f 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -42,8 +42,8 @@ interface Request extends Body { url: string; headers: Headers; - type: "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; - destination: "" | "document" | "embed" | "font" | "image" | "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "worker" | "xslt"; + type: RequestType + destination: RequestDestination; referrer: string; referrerPolicy: ReferrerPolicy; mode: RequestMode; @@ -72,6 +72,8 @@ interface RequestConstructor { } declare var Request: RequestConstructor; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type RequestDestination = "" | "document" | "embed" | "font" | "image" | "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "worker" | "xslt"; type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; type RequestCredentials = "omit" | "same-origin" | "include"; type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached"; @@ -79,7 +81,7 @@ type RequestRedirect = "follow" | "error" | "manual"; type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url"; interface Response extends Body { - type: "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; + type: ResponseType; url: string; redirected: boolean; status: number; @@ -103,3 +105,5 @@ interface ResponseConstructor { redirect(url: string, status?: number): Response; } declare var Response: ResponseConstructor; + +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; From 026d5663468d0e7f7337f3164fa92a8ff118f27d Mon Sep 17 00:00:00 2001 From: Hristian Hristov Date: Fri, 26 Aug 2016 13:04:25 +0100 Subject: [PATCH 55/56] Node.d.ts: Change definition for module process to be consistent with other declarations --- node/node.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 280f17e045..731b136585 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2627,6 +2627,5 @@ declare module "constants" { } declare module "process" { - var p: NodeJS.Process; - export default p; + export = process; } \ No newline at end of file From c3d42974315ac7f01a56ce10b57e7b71affbe8e9 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Sat, 27 Aug 2016 00:43:42 +0800 Subject: [PATCH 56/56] Add module "process" for Node v4 --- node/node-4.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/node/node-4.d.ts b/node/node-4.d.ts index 848b0536d0..d6fb33f750 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -2402,3 +2402,7 @@ declare module "constants" { export var X_OK: number; export var UV_UDP_REUSEADDR: number; } + +declare module "process" { + export = process; +}