From 58eb6d15541d562abb9af2773c1b50fec73ad27e Mon Sep 17 00:00:00 2001 From: James Baxley Date: Sat, 13 Aug 2016 19:05:46 -0400 Subject: [PATCH] Add immutable support (#137) * ensure it works with redux-loop * support immutable store * bump changelog --- Changelog.md | 4 + global.d.ts | 5 + package.json | 5 +- src/ApolloProvider.tsx | 4 + src/graphql.tsx | 12 +- test/react-web/client/libraries/redux.tsx | 431 ++- typings.json | 4 +- typings/index.d.ts | 2 + typings/modules/immutable/index.d.ts | 2533 ++++++++++++++++++ typings/modules/immutable/typings.json | 12 + typings/modules/redux-immutable/index.d.ts | 75 + typings/modules/redux-immutable/typings.json | 21 + 12 files changed, 2977 insertions(+), 131 deletions(-) create mode 100644 typings/modules/immutable/index.d.ts create mode 100644 typings/modules/immutable/typings.json create mode 100644 typings/modules/redux-immutable/index.d.ts create mode 100644 typings/modules/redux-immutable/typings.json diff --git a/Changelog.md b/Changelog.md index 2a5b29862b..04c03a7690 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,6 +2,10 @@ Expect active development and potentially significant breaking changes in the `0.x` track. We'll try to be diligent about releasing a `1.0` version in a timely fashion (ideally within 1 or 2 months), so that we can take advantage of SemVer to signify breaking changes from that point on. +### v4.0.3 + +- Feature: Support a different store in the tree that is immutable (support immutable redux) [#137](https://github.com/apollostack/react-apollo/pull/137) + ### v4.0.2 - Bug: Fixed refetch methods when no result is returned diff --git a/global.d.ts b/global.d.ts index 73a0a651b5..7cd4d5ebd2 100644 --- a/global.d.ts +++ b/global.d.ts @@ -28,3 +28,8 @@ declare module 'lodash.flatten' { import main = require('lodash'); export = main.flatten; } + +declare module 'redux-loop' { + function combineReducers(reducers: any, state?: any, get?: any, set?: any): any; + function install(): any; +} diff --git a/package.json b/package.json index 9563a4b722..275f8c1bfe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-apollo", - "version": "0.4.2", + "version": "0.4.3", "description": "React data container for Apollo Client", "main": "index.js", "scripts": { @@ -64,6 +64,7 @@ "graphql": "^0.5.0", "graphql-tag": "^0.1.7", "gzip-size": "^3.0.0", + "immutable": "^3.8.1", "isomorphic-fetch": "^2.2.1", "istanbul": "^0.4.2", "jest": "^14.1.0", @@ -82,6 +83,8 @@ "react-test-renderer": "^15.3.0", "redux": "^3.5.2", "redux-form": "^5.3.2", + "redux-immutable": "^3.0.7", + "redux-loop": "^2.2.2", "remap-istanbul": "^0.5.1", "source-map-support": "^0.4.0", "swapi-graphql": "0.0.4", diff --git a/src/ApolloProvider.tsx b/src/ApolloProvider.tsx index 6deabc0323..dd71b9d83e 100644 --- a/src/ApolloProvider.tsx +++ b/src/ApolloProvider.tsx @@ -16,6 +16,7 @@ import invariant = require('invariant'); export declare interface ProviderProps { store?: Store; + immutable?: boolean; client: ApolloClient; } @@ -27,6 +28,7 @@ export default class ApolloProvider extends Component { getState: PropTypes.func.isRequired, }), client: PropTypes.object.isRequired, + immutable: PropTypes.bool, children: PropTypes.element.isRequired, }; @@ -51,6 +53,8 @@ export default class ApolloProvider extends Component { if (props.store) { this.store = props.store; + // support an immutable store alongside apollo store + if (props.immutable) props.client.initStore(); return; } diff --git a/src/graphql.tsx b/src/graphql.tsx index c9546a6dae..64b28a2194 100644 --- a/src/graphql.tsx +++ b/src/graphql.tsx @@ -15,10 +15,6 @@ import assign = require('object-assign'); import hoistNonReactStatics = require('hoist-non-react-statics'); -import { - Store, -} from 'redux'; - import ApolloClient, { readQueryFromStore, } from 'apollo-client'; @@ -48,6 +44,10 @@ import { Subscription, } from 'apollo-client/util/Observable'; +import { + ApolloStore, +} from 'apollo-client/store'; + import { // GraphQLResult, Document, @@ -229,7 +229,7 @@ export default function graphql( public hasMounted: boolean; // data storage - private store: Store; + private store: ApolloStore; private client: ApolloClient; // apollo client private data: any = {}; // apollo data private type: DocumentType; @@ -251,8 +251,8 @@ export default function graphql( constructor(props, context) { super(props, context); this.version = version; - this.store = props.store || context.store; this.client = props.client || context.client; + this.store = this.client.store; invariant(!!this.client, `Could not find "client" in either the context or ` + diff --git a/test/react-web/client/libraries/redux.tsx b/test/react-web/client/libraries/redux.tsx index d37703005d..034769472f 100644 --- a/test/react-web/client/libraries/redux.tsx +++ b/test/react-web/client/libraries/redux.tsx @@ -5,6 +5,9 @@ import { mount } from 'enzyme'; import { createStore, combineReducers, applyMiddleware } from 'redux'; import { connect } from 'react-redux'; import { reducer as formReducer, reduxForm } from 'redux-form'; +import { combineReducers as loopCombine, install } from 'redux-loop'; +import { Map } from 'immutable'; +import { combineReducers as combineImmutable } from 'redux-immutable'; // import assign = require('object-assign'); import gql from 'graphql-tag'; @@ -22,7 +25,7 @@ import { import mockNetworkInterface from '../../../mocks/mockNetworkInterface'; -import graphql from '../../../../src/graphql'; +import { ApolloProvider, graphql } from '../../../../src'; describe('redux integration', () => { @@ -86,143 +89,325 @@ describe('redux integration', () => { }); - it('works with redux form to drive queries', (done) => { - const query = gql`query people($name: String) { allPeople(name: $name) { people { name } } }`; - const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } }; - const variables = { name: 'Luke' }; + describe('redux-form', () => { + it('works with redux form to drive queries', (done) => { + const query = gql`query people($name: String) { allPeople(name: $name) { people { name } } }`; + const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } }; + const variables = { name: 'Luke' }; + + const networkInterface = mockNetworkInterface( + { request: { query, variables }, result: { data } } + ); + + const client = new ApolloClient({ networkInterface }); + let wrapper; + + // Typscript workaround + const apolloReducer = client.reducer() as () => any; + + const store = createStore( + combineReducers({ + apollo: apolloReducer, + form: formReducer, + }), + applyMiddleware(client.middleware()) + ); + + @reduxForm({ + form: 'contact', + fields: ['firstName'], + }) + @graphql(query, { + options: ({ fields }) => ({ + variables: { name: fields.firstName.value }, + skip: !fields.firstName.value, + }), + }) + class Container extends React.Component { + componentWillReceiveProps(nextProps) { + const { value } = nextProps.fields.firstName; + if (!value) return; + + expect(value).to.equal(variables.name); + if (nextProps.data.loading) return; - const networkInterface = mockNetworkInterface( - { request: { query, variables }, result: { data } } - ); + expect(nextProps.data.loading).to.be.false; + expect(nextProps.data.allPeople).to.deep.equal(data.allPeople); + done(); + } - const client = new ApolloClient({ networkInterface }); - let wrapper; + render() { + const { fields: { firstName }, handleSubmit } = this.props; + return ( +
+
+ + +
+ +
+ ); + } + }; + + wrapper = mount( + + + + ) as any; + + setTimeout(() => { + wrapper.find('input').simulate('change', { + target: { value: variables.name }, + }); + }, 100); + + }); + + it('works with redux form to be prefilled by queries', (done) => { + const query = gql`query people($name: String) { allPeople(name: $name) { people { name } } }`; + const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } }; + const variables = { name: 'Luke' }; + + const networkInterface = mockNetworkInterface( + { request: { query, variables }, result: { data } } + ); + + const client = new ApolloClient({ networkInterface }); + let wrapper; + + // Typscript workaround + const apolloReducer = client.reducer() as () => any; + + const store = createStore( + combineReducers({ + apollo: apolloReducer, + form: formReducer, + }), + applyMiddleware(client.middleware()) + ); + + @graphql(query, { options: () => ({ variables }) }) + @reduxForm({ + form: 'contact', + fields: ['firstName'], + }, (state, ownProps) => ({ + initialValues: { + firstName: ownProps.data.loading ? '' : ownProps.data.allPeople.people[0].name, + }, + })) + class Container extends React.Component { + componentWillReceiveProps(nextProps) { + const { value, initialValue } = nextProps.fields.firstName; + if (!value) return; + + expect(initialValue).to.equal(data.allPeople.people[0].name); + expect(value).to.equal(data.allPeople.people[0].name); - // Typscript workaround - const apolloReducer = client.reducer() as () => any; + done(); + } - const store = createStore( - combineReducers({ - apollo: apolloReducer, - form: formReducer, - }), - applyMiddleware(client.middleware()) - ); + render() { + const { fields: { firstName }, handleSubmit } = this.props; + return ( +
+
+ + +
+ +
+ ); + } + }; - @reduxForm({ - form: 'contact', - fields: ['firstName'], - }) - @graphql(query, { - options: ({ fields }) => ({ - variables: { name: fields.firstName.value }, - skip: !fields.firstName.value, - }), - }) - class Container extends React.Component { - componentWillReceiveProps(nextProps) { - const { value } = nextProps.fields.firstName; - if (!value) return; + mount( + + + + ) as any; - expect(value).to.equal(variables.name); - if (nextProps.data.loading) return; + }); + }); - expect(nextProps.data.loading).to.be.false; - expect(nextProps.data.allPeople).to.deep.equal(data.allPeople); - done(); + describe('redux-loop', () => { + it('works with redux-loop with shared store', (done) => { + const query = gql`query people($first: Int) { allPeople(first: $first) { people { name } } }`; + const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } }; + const variables = { first: 1 }; + + const data2 = { allPeople: { people: [ { name: 'Leia Skywalker' } ] } }; + const variables2 = { first: 2 }; + + const networkInterface = mockNetworkInterface( + { request: { query, variables }, result: { data } }, + { request: { query, variables: variables2 }, result: { data: data2 } } + ); + + const client = new ApolloClient({ networkInterface }); + let wrapper; + + function counter(state = 1, action) { + switch (action.type) { + case 'INCREMENT': + return state + 1; + default: + return state; + } } - render() { - const { fields: { firstName }, handleSubmit } = this.props; - return ( -
-
- - -
- -
- ); + // Typscript workaround + const apolloReducer = client.reducer() as () => any; + + const store = createStore( + loopCombine({ + counter, + apollo: apolloReducer, + }), + applyMiddleware(client.middleware()), + install() + ); + + @connect((state) => ({ first: state.counter })) + @graphql(query) + class Container extends React.Component { + componentWillReceiveProps(nextProps) { + if (nextProps.first === 1) this.props.dispatch({ type: 'INCREMENT' }); + if (nextProps.first === 2) { + if (nextProps.data.loading) return; + expect(nextProps.data.allPeople).to.deep.equal(data2.allPeople); + done(); + } + } + render() { + return null; + } + }; + + wrapper = mount( + + + + ) as any; + }); + + it('works with redux-loop and an immutable store', (done) => { + const query = gql`query people($first: Int) { allPeople(first: $first) { people { name } } }`; + const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } }; + const variables = { first: 1 }; + + const data2 = { allPeople: { people: [ { name: 'Leia Skywalker' } ] } }; + const variables2 = { first: 2 }; + + const networkInterface = mockNetworkInterface( + { request: { query, variables }, result: { data } }, + { request: { query, variables: variables2 }, result: { data: data2 } } + ); + + const client = new ApolloClient({ networkInterface }); + let wrapper; + + function counter(state = 1, action) { + switch (action.type) { + case 'INCREMENT': + return state + 1; + default: + return state; + } } - }; - - wrapper = mount( - - - - ) as any; - - setTimeout(() => { - wrapper.find('input').simulate('change', { - target: { value: variables.name }, - }); - }, 100); + // initial state, accessor and mutator for supporting root-level + // immutable data with redux-loop reducer combinator + const immutableStateContainer = Map(); + const getImmutable = (child, key) => child ? child.get(key) : void 0; + const setImmutable = (child, key, value) => child.set(key, value); + + const store = createStore( + loopCombine({ + counter, + }, immutableStateContainer as any, getImmutable, setImmutable), + install() + ); + + @connect((state) => ({ first: state.get('counter') })) + @graphql(query) + class Container extends React.Component { + componentWillReceiveProps(nextProps) { + if (nextProps.first === 1) this.props.dispatch({ type: 'INCREMENT' }); + if (nextProps.first === 2) { + if (nextProps.data.loading) return; + expect(nextProps.data.allPeople).to.deep.equal(data2.allPeople); + done(); + } + } + render() { + return null; + } + }; + + wrapper = mount( + + + + ) as any; + }); }); - it('works with redux form to be prefilled by queries', (done) => { - const query = gql`query people($name: String) { allPeople(name: $name) { people { name } } }`; - const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } }; - const variables = { name: 'Luke' }; - - const networkInterface = mockNetworkInterface( - { request: { query, variables }, result: { data } } - ); - - const client = new ApolloClient({ networkInterface }); - let wrapper; - - // Typscript workaround - const apolloReducer = client.reducer() as () => any; - - const store = createStore( - combineReducers({ - apollo: apolloReducer, - form: formReducer, - }), - applyMiddleware(client.middleware()) - ); - - @graphql(query, { options: () => ({ variables }) }) - @reduxForm({ - form: 'contact', - fields: ['firstName'], - }, (state, ownProps) => ({ - initialValues: { - firstName: ownProps.data.loading ? '' : ownProps.data.allPeople.people[0].name, - }, - })) - class Container extends React.Component { - componentWillReceiveProps(nextProps) { - const { value, initialValue } = nextProps.fields.firstName; - if (!value) return; - - expect(initialValue).to.equal(data.allPeople.people[0].name); - expect(value).to.equal(data.allPeople.people[0].name); - - done(); + describe('immutable store', () => { + it('works an immutable store', (done) => { + const query = gql`query people($first: Int) { allPeople(first: $first) { people { name } } }`; + const data = { allPeople: { people: [ { name: 'Luke Skywalker' } ] } }; + const variables = { first: 1 }; + + const data2 = { allPeople: { people: [ { name: 'Leia Skywalker' } ] } }; + const variables2 = { first: 2 }; + + const networkInterface = mockNetworkInterface( + { request: { query, variables }, result: { data } }, + { request: { query, variables: variables2 }, result: { data: data2 } } + ); + + const client = new ApolloClient({ networkInterface }); + let wrapper; + + function counter(state = 1, action) { + switch (action.type) { + case 'INCREMENT': + return state + 1; + default: + return state; + } } - render() { - const { fields: { firstName }, handleSubmit } = this.props; - return ( -
-
- - -
- -
- ); - } - }; - - mount( - - - - ) as any; - + // initial state, accessor and mutator for supporting root-level + // immutable data with redux-loop reducer combinator + const initialState = Map(); + + const store = createStore(combineImmutable({ counter }), initialState); + + @connect((state) => ({ first: state.get('counter') })) + @graphql(query) + class Container extends React.Component { + componentWillReceiveProps(nextProps) { + if (nextProps.first === 1) this.props.dispatch({ type: 'INCREMENT' }); + if (nextProps.first === 2) { + if (nextProps.data.loading) return; + expect(nextProps.data.allPeople).to.deep.equal(data2.allPeople); + done(); + } + } + render() { + return null; + } + }; + + wrapper = mount( + + + + ) as any; + }); }); + }); diff --git a/typings.json b/typings.json index ab20a1bf5c..ff996fb2fe 100644 --- a/typings.json +++ b/typings.json @@ -17,10 +17,12 @@ }, "dependencies": { "apollo-client": "file:node_modules/apollo-client/index.d.ts", + "immutable": "registry:npm/immutable#3.7.6+20160411060006", "invariant": "registry:npm/invariant#2.0.0+20160211003958", "lodash": "registry:npm/lodash#4.0.0+20160412191219", "object-assign": "registry:npm/object-assign#4.0.1+20160301180549", "react-redux": "registry:npm/react-redux#4.4.0+20160614222153", - "redux-form": "registry:npm/redux-form#4.0.3+20160310030142" + "redux-form": "registry:npm/redux-form#4.0.3+20160310030142", + "redux-immutable": "registry:npm/redux-immutable#3.0.6+20160310030142" } } diff --git a/typings/index.d.ts b/typings/index.d.ts index 0905591f01..80f56e600e 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -10,9 +10,11 @@ /// /// /// +/// /// /// /// /// /// +/// /// diff --git a/typings/modules/immutable/index.d.ts b/typings/modules/immutable/index.d.ts new file mode 100644 index 0000000000..cdfb4240c1 --- /dev/null +++ b/typings/modules/immutable/index.d.ts @@ -0,0 +1,2533 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/alitaheri/immutable-unambient/3e5ef14e1677e2db90770b8263be889b71c4d444/immutable.d.ts +declare module 'immutable' { +/** + * Copyright (c) 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +/** + * Immutable data encourages pure functions (data-in, data-out) and lends itself + * to much simpler application development and enabling techniques from + * functional programming such as lazy evaluation. + * + * While designed to bring these powerful functional concepts to JavaScript, it + * presents an Object-Oriented API familiar to Javascript engineers and closely + * mirroring that of Array, Map, and Set. It is easy and efficient to convert to + * and from plain Javascript types. + + * Note: all examples are presented in [ES6][]. To run in all browsers, they + * need to be translated to ES3. For example: + * + * // ES6 + * foo.map(x => x * x); + * // ES3 + * foo.map(function (x) { return x * x; }); + * + * [ES6]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla + */ + +module Immutable { + + /** + * Deeply converts plain JS objects and arrays to Immutable Maps and Lists. + * + * If a `reviver` is optionally provided, it will be called with every + * collection as a Seq (beginning with the most nested collections + * and proceeding to the top-level collection itself), along with the key + * refering to each collection and the parent JS object provided as `this`. + * For the top level, object, the key will be `""`. This `reviver` is expected + * to return a new Immutable Iterable, allowing for custom conversions from + * deep JS objects. + * + * This example converts JSON to List and OrderedMap: + * + * Immutable.fromJS({a: {b: [10, 20, 30]}, c: 40}, function (key, value) { + * var isIndexed = Immutable.Iterable.isIndexed(value); + * return isIndexed ? value.toList() : value.toOrderedMap(); + * }); + * + * // true, "b", {b: [10, 20, 30]} + * // false, "a", {a: {b: [10, 20, 30]}, c: 40} + * // false, "", {"": {a: {b: [10, 20, 30]}, c: 40}} + * + * If `reviver` is not provided, the default behavior will convert Arrays into + * Lists and Objects into Maps. + * + * `reviver` acts similarly to the [same parameter in `JSON.parse`][1]. + * + * `Immutable.fromJS` is conservative in it's conversion. It will only convert + * arrays which pass `Array.isArray` to Lists, and only raw objects (no custom + * prototype) to Map. + * + * Keep in mind, when using JS objects to construct Immutable Maps, that + * JavaScript Object properties are always strings, even if written in a + * quote-less shorthand, while Immutable Maps accept keys of any type. + * + * ```js + * var obj = { 1: "one" }; + * Object.keys(obj); // [ "1" ] + * obj["1"]; // "one" + * obj[1]; // "one" + * + * var map = Map(obj); + * map.get("1"); // "one" + * map.get(1); // undefined + * ``` + * + * Property access for JavaScript Objects first converts the key to a string, + * but since Immutable Map keys can be of any type the argument to `get()` is + * not altered. + * + * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter + * "Using the reviver parameter" + */ + export function fromJS( + json: any, + reviver?: (k: any, v: Iterable) => any + ): any; + + + /** + * Value equality check with semantics similar to `Object.is`, but treats + * Immutable `Iterable`s as values, equal if the second `Iterable` includes + * equivalent values. + * + * It's used throughout Immutable when checking for equality, including `Map` + * key equality and `Set` membership. + * + * var map1 = Immutable.Map({a:1, b:1, c:1}); + * var map2 = Immutable.Map({a:1, b:1, c:1}); + * assert(map1 !== map2); + * assert(Object.is(map1, map2) === false); + * assert(Immutable.is(map1, map2) === true); + * + * Note: Unlike `Object.is`, `Immutable.is` assumes `0` and `-0` are the same + * value, matching the behavior of ES6 Map key equality. + */ + export function is(first: any, second: any): boolean; + + + /** + * Lists are ordered indexed dense collections, much like a JavaScript + * Array. + * + * Lists are immutable and fully persistent with O(log32 N) gets and sets, + * and O(1) push and pop. + * + * Lists implement Deque, with efficient addition and removal from both the + * end (`push`, `pop`) and beginning (`unshift`, `shift`). + * + * Unlike a JavaScript Array, there is no distinction between an + * "unset" index and an index set to `undefined`. `List#forEach` visits all + * indices from 0 to size, regardless of if they were explicitly defined. + */ + export module List { + + /** + * True if the provided value is a List + */ + function isList(maybeList: any): boolean; + + /** + * Creates a new List containing `values`. + */ + function of(...values: T[]): List; + } + + /** + * Create a new immutable List containing the values of the provided + * iterable-like. + */ + export function List(): List; + export function List(iter: Iterable.Indexed): List; + export function List(iter: Iterable.Set): List; + export function List(iter: Iterable.Keyed): List; + export function List(array: Array): List; + export function List(iterator: Iterator): List; + export function List(iterable: /*Iterable*/Object): List; + + + export interface List extends Collection.Indexed { + + // Persistent changes + + /** + * Returns a new List which includes `value` at `index`. If `index` already + * exists in this List, it will be replaced. + * + * `index` may be a negative number, which indexes back from the end of the + * List. `v.set(-1, "value")` sets the last item in the List. + * + * If `index` larger than `size`, the returned List's `size` will be large + * enough to include the `index`. + */ + set(index: number, value: T): List; + + /** + * Returns a new List which excludes this `index` and with a size 1 less + * than this List. Values at indices above `index` are shifted down by 1 to + * fill the position. + * + * This is synonymous with `list.splice(index, 1)`. + * + * `index` may be a negative number, which indexes back from the end of the + * List. `v.delete(-1)` deletes the last item in the List. + * + * Note: `delete` cannot be safely used in IE8 + * @alias remove + */ + delete(index: number): List; + remove(index: number): List; + + /** + * Returns a new List with `value` at `index` with a size 1 more than this + * List. Values at indices above `index` are shifted over by 1. + * + * This is synonymous with `list.splice(index, 0, value) + */ + insert(index: number, value: T): List; + + /** + * Returns a new List with 0 size and no values. + */ + clear(): List; + + /** + * Returns a new List with the provided `values` appended, starting at this + * List's `size`. + */ + push(...values: T[]): List; + + /** + * Returns a new List with a size ones less than this List, excluding + * the last index in this List. + * + * Note: this differs from `Array#pop` because it returns a new + * List rather than the removed value. Use `last()` to get the last value + * in this List. + */ + pop(): List; + + /** + * Returns a new List with the provided `values` prepended, shifting other + * values ahead to higher indices. + */ + unshift(...values: T[]): List; + + /** + * Returns a new List with a size ones less than this List, excluding + * the first index in this List, shifting all other values to a lower index. + * + * Note: this differs from `Array#shift` because it returns a new + * List rather than the removed value. Use `first()` to get the first + * value in this List. + */ + shift(): List; + + /** + * Returns a new List with an updated value at `index` with the return + * value of calling `updater` with the existing value, or `notSetValue` if + * `index` was not set. If called with a single argument, `updater` is + * called with the List itself. + * + * `index` may be a negative number, which indexes back from the end of the + * List. `v.update(-1)` updates the last item in the List. + * + * @see `Map#update` + */ + update(updater: (value: List) => List): List; + update(index: number, updater: (value: T) => T): List; + update(index: number, notSetValue: T, updater: (value: T) => T): List; + + /** + * @see `Map#merge` + */ + merge(...iterables: Iterable.Indexed[]): List; + merge(...iterables: Array[]): List; + + /** + * @see `Map#mergeWith` + */ + mergeWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Iterable.Indexed[] + ): List; + mergeWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Array[] + ): List; + + /** + * @see `Map#mergeDeep` + */ + mergeDeep(...iterables: Iterable.Indexed[]): List; + mergeDeep(...iterables: Array[]): List; + + /** + * @see `Map#mergeDeepWith` + */ + mergeDeepWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Iterable.Indexed[] + ): List; + mergeDeepWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Array[] + ): List; + + /** + * Returns a new List with size `size`. If `size` is less than this + * List's size, the new List will exclude values at the higher indices. + * If `size` is greater than this List's size, the new List will have + * undefined values for the newly available indices. + * + * When building a new List and the final size is known up front, `setSize` + * used in conjunction with `withMutations` may result in the more + * performant construction. + */ + setSize(size: number): List; + + + // Deep persistent changes + + /** + * Returns a new List having set `value` at this `keyPath`. If any keys in + * `keyPath` do not exist, a new immutable Map will be created at that key. + * + * Index numbers are used as keys to determine the path to follow in + * the List. + */ + setIn(keyPath: Array, value: any): List; + setIn(keyPath: Iterable, value: any): List; + + /** + * Returns a new List having removed the value at this `keyPath`. If any + * keys in `keyPath` do not exist, no change will occur. + * + * @alias removeIn + */ + deleteIn(keyPath: Array): List; + deleteIn(keyPath: Iterable): List; + removeIn(keyPath: Array): List; + removeIn(keyPath: Iterable): List; + + /** + * @see `Map#updateIn` + */ + updateIn( + keyPath: Array, + updater: (value: any) => any + ): List; + updateIn( + keyPath: Array, + notSetValue: any, + updater: (value: any) => any + ): List; + updateIn( + keyPath: Iterable, + updater: (value: any) => any + ): List; + updateIn( + keyPath: Iterable, + notSetValue: any, + updater: (value: any) => any + ): List; + + /** + * @see `Map#mergeIn` + */ + mergeIn( + keyPath: Iterable, + ...iterables: Iterable.Indexed[] + ): List; + mergeIn( + keyPath: Array, + ...iterables: Iterable.Indexed[] + ): List; + mergeIn( + keyPath: Array, + ...iterables: Array[] + ): List; + + /** + * @see `Map#mergeDeepIn` + */ + mergeDeepIn( + keyPath: Iterable, + ...iterables: Iterable.Indexed[] + ): List; + mergeDeepIn( + keyPath: Array, + ...iterables: Iterable.Indexed[] + ): List; + mergeDeepIn( + keyPath: Array, + ...iterables: Array[] + ): List; + + + // Transient changes + + /** + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set`, `push`, `pop`, `shift`, `unshift` and + * `merge` may be used mutatively. + * + * @see `Map#withMutations` + */ + withMutations(mutator: (mutable: List) => any): List; + + /** + * @see `Map#asMutable` + */ + asMutable(): List; + + /** + * @see `Map#asImmutable` + */ + asImmutable(): List; + } + + + /** + * Immutable Map is an unordered Iterable.Keyed of (key, value) pairs with + * `O(log32 N)` gets and `O(log32 N)` persistent sets. + * + * Iteration order of a Map is undefined, however is stable. Multiple + * iterations of the same Map will iterate in the same order. + * + * Map's keys can be of any type, and use `Immutable.is` to determine key + * equality. This allows the use of any value (including NaN) as a key. + * + * Because `Immutable.is` returns equality based on value semantics, and + * Immutable collections are treated as values, any Immutable collection may + * be used as a key. + * + * Map().set(List.of(1), 'listofone').get(List.of(1)); + * // 'listofone' + * + * Any JavaScript object may be used as a key, however strict identity is used + * to evaluate key equality. Two similar looking objects will represent two + * different keys. + * + * Implemented by a hash-array mapped trie. + */ + export module Map { + + /** + * True if the provided value is a Map + */ + function isMap(maybeMap: any): boolean; + } + + /** + * Creates a new Immutable Map. + * + * Created with the same key value pairs as the provided Iterable.Keyed or + * JavaScript Object or expects an Iterable of [K, V] tuple entries. + * + * var newMap = Map({key: "value"}); + * var newMap = Map([["key", "value"]]); + * + * Keep in mind, when using JS objects to construct Immutable Maps, that + * JavaScript Object properties are always strings, even if written in a + * quote-less shorthand, while Immutable Maps accept keys of any type. + * + * ```js + * var obj = { 1: "one" }; + * Object.keys(obj); // [ "1" ] + * obj["1"]; // "one" + * obj[1]; // "one" + * + * var map = Map(obj); + * map.get("1"); // "one" + * map.get(1); // undefined + * ``` + * + * Property access for JavaScript Objects first converts the key to a string, + * but since Immutable Map keys can be of any type the argument to `get()` is + * not altered. + */ + export function Map(): Map; + export function Map(iter: Iterable.Keyed): Map; + export function Map(iter: Iterable>): Map; + export function Map(array: Array>): Map; + export function Map(obj: {[key: string]: V}): Map; + export function Map(iterator: Iterator>): Map; + export function Map(iterable: /*Iterable<[K,V]>*/Object): Map; + + export interface Map extends Collection.Keyed { + + // Persistent changes + + /** + * Returns a new Map also containing the new key, value pair. If an equivalent + * key already exists in this Map, it will be replaced. + */ + set(key: K, value: V): Map; + + /** + * Returns a new Map which excludes this `key`. + * + * Note: `delete` cannot be safely used in IE8, but is provided to mirror + * the ES6 collection API. + * @alias remove + */ + delete(key: K): Map; + remove(key: K): Map; + + /** + * Returns a new Map containing no keys or values. + */ + clear(): Map; + + /** + * Returns a new Map having updated the value at this `key` with the return + * value of calling `updater` with the existing value, or `notSetValue` if + * the key was not set. If called with only a single argument, `updater` is + * called with the Map itself. + * + * Equivalent to: `map.set(key, updater(map.get(key, notSetValue)))`. + */ + update(updater: (value: Map) => Map): Map; + update(key: K, updater: (value: V) => V): Map; + update(key: K, notSetValue: V, updater: (value: V) => V): Map; + + /** + * Returns a new Map resulting from merging the provided Iterables + * (or JS objects) into this Map. In other words, this takes each entry of + * each iterable and sets it on this Map. + * + * If any of the values provided to `merge` are not Iterable (would return + * false for `Immutable.Iterable.isIterable`) then they are deeply converted + * via `Immutable.fromJS` before being merged. However, if the value is an + * Iterable but includes non-iterable JS objects or arrays, those nested + * values will be preserved. + * + * var x = Immutable.Map({a: 10, b: 20, c: 30}); + * var y = Immutable.Map({b: 40, a: 50, d: 60}); + * x.merge(y) // { a: 50, b: 40, c: 30, d: 60 } + * y.merge(x) // { b: 20, a: 10, d: 60, c: 30 } + * + */ + merge(...iterables: Iterable[]): Map; + merge(...iterables: {[key: string]: V}[]): Map; + + /** + * Like `merge()`, `mergeWith()` returns a new Map resulting from merging + * the provided Iterables (or JS objects) into this Map, but uses the + * `merger` function for dealing with conflicts. + * + * var x = Immutable.Map({a: 10, b: 20, c: 30}); + * var y = Immutable.Map({b: 40, a: 50, d: 60}); + * x.mergeWith((prev, next) => prev / next, y) // { a: 0.2, b: 0.5, c: 30, d: 60 } + * y.mergeWith((prev, next) => prev / next, x) // { b: 2, a: 5, d: 60, c: 30 } + * + */ + mergeWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: Iterable[] + ): Map; + mergeWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: {[key: string]: V}[] + ): Map; + + /** + * Like `merge()`, but when two Iterables conflict, it merges them as well, + * recursing deeply through the nested data. + * + * var x = Immutable.fromJS({a: { x: 10, y: 10 }, b: { x: 20, y: 50 } }); + * var y = Immutable.fromJS({a: { x: 2 }, b: { y: 5 }, c: { z: 3 } }); + * x.mergeDeep(y) // {a: { x: 2, y: 10 }, b: { x: 20, y: 5 }, c: { z: 3 } } + * + */ + mergeDeep(...iterables: Iterable[]): Map; + mergeDeep(...iterables: {[key: string]: V}[]): Map; + + /** + * Like `mergeDeep()`, but when two non-Iterables conflict, it uses the + * `merger` function to determine the resulting value. + * + * var x = Immutable.fromJS({a: { x: 10, y: 10 }, b: { x: 20, y: 50 } }); + * var y = Immutable.fromJS({a: { x: 2 }, b: { y: 5 }, c: { z: 3 } }); + * x.mergeDeepWith((prev, next) => prev / next, y) + * // {a: { x: 5, y: 10 }, b: { x: 20, y: 10 }, c: { z: 3 } } + * + */ + mergeDeepWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: Iterable[] + ): Map; + mergeDeepWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: {[key: string]: V}[] + ): Map; + + + // Deep persistent changes + + /** + * Returns a new Map having set `value` at this `keyPath`. If any keys in + * `keyPath` do not exist, a new immutable Map will be created at that key. + */ + setIn(keyPath: Array, value: any): Map; + setIn(KeyPath: Iterable, value: any): Map; + + /** + * Returns a new Map having removed the value at this `keyPath`. If any keys + * in `keyPath` do not exist, no change will occur. + * + * @alias removeIn + */ + deleteIn(keyPath: Array): Map; + deleteIn(keyPath: Iterable): Map; + removeIn(keyPath: Array): Map; + removeIn(keyPath: Iterable): Map; + + /** + * Returns a new Map having applied the `updater` to the entry found at the + * keyPath. + * + * If any keys in `keyPath` do not exist, new Immutable `Map`s will + * be created at those keys. If the `keyPath` does not already contain a + * value, the `updater` function will be called with `notSetValue`, if + * provided, otherwise `undefined`. + * + * var data = Immutable.fromJS({ a: { b: { c: 10 } } }); + * data = data.updateIn(['a', 'b', 'c'], val => val * 2); + * // { a: { b: { c: 20 } } } + * + * If the `updater` function returns the same value it was called with, then + * no change will occur. This is still true if `notSetValue` is provided. + * + * var data1 = Immutable.fromJS({ a: { b: { c: 10 } } }); + * data2 = data1.updateIn(['x', 'y', 'z'], 100, val => val); + * assert(data2 === data1); + * + */ + updateIn( + keyPath: Array, + updater: (value: any) => any + ): Map; + updateIn( + keyPath: Array, + notSetValue: any, + updater: (value: any) => any + ): Map; + updateIn( + keyPath: Iterable, + updater: (value: any) => any + ): Map; + updateIn( + keyPath: Iterable, + notSetValue: any, + updater: (value: any) => any + ): Map; + + /** + * A combination of `updateIn` and `merge`, returning a new Map, but + * performing the merge at a point arrived at by following the keyPath. + * In other words, these two lines are equivalent: + * + * x.updateIn(['a', 'b', 'c'], abc => abc.merge(y)); + * x.mergeIn(['a', 'b', 'c'], y); + * + */ + mergeIn( + keyPath: Iterable, + ...iterables: Iterable[] + ): Map; + mergeIn( + keyPath: Array, + ...iterables: Iterable[] + ): Map; + mergeIn( + keyPath: Array, + ...iterables: {[key: string]: V}[] + ): Map; + + /** + * A combination of `updateIn` and `mergeDeep`, returning a new Map, but + * performing the deep merge at a point arrived at by following the keyPath. + * In other words, these two lines are equivalent: + * + * x.updateIn(['a', 'b', 'c'], abc => abc.mergeDeep(y)); + * x.mergeDeepIn(['a', 'b', 'c'], y); + * + */ + mergeDeepIn( + keyPath: Iterable, + ...iterables: Iterable[] + ): Map; + mergeDeepIn( + keyPath: Array, + ...iterables: Iterable[] + ): Map; + mergeDeepIn( + keyPath: Array, + ...iterables: {[key: string]: V}[] + ): Map; + + + // Transient changes + + /** + * Every time you call one of the above functions, a new immutable Map is + * created. If a pure function calls a number of these to produce a final + * return value, then a penalty on performance and memory has been paid by + * creating all of the intermediate immutable Maps. + * + * If you need to apply a series of mutations to produce a new immutable + * Map, `withMutations()` creates a temporary mutable copy of the Map which + * can apply mutations in a highly performant manner. In fact, this is + * exactly how complex mutations like `merge` are done. + * + * As an example, this results in the creation of 2, not 4, new Maps: + * + * var map1 = Immutable.Map(); + * var map2 = map1.withMutations(map => { + * map.set('a', 1).set('b', 2).set('c', 3); + * }); + * assert(map1.size === 0); + * assert(map2.size === 3); + * + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set` and `merge` may be used mutatively. + * + */ + withMutations(mutator: (mutable: Map) => any): Map; + + /** + * Another way to avoid creation of intermediate Immutable maps is to create + * a mutable copy of this collection. Mutable copies *always* return `this`, + * and thus shouldn't be used for equality. Your function should never return + * a mutable copy of a collection, only use it internally to create a new + * collection. If possible, use `withMutations` as it provides an easier to + * use API. + * + * Note: if the collection is already mutable, `asMutable` returns itself. + * + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set` and `merge` may be used mutatively. + */ + asMutable(): Map; + + /** + * The yin to `asMutable`'s yang. Because it applies to mutable collections, + * this operation is *mutable* and returns itself. Once performed, the mutable + * copy has become immutable and can be safely returned from a function. + */ + asImmutable(): Map; + } + + + /** + * A type of Map that has the additional guarantee that the iteration order of + * entries will be the order in which they were set(). + * + * The iteration behavior of OrderedMap is the same as native ES6 Map and + * JavaScript Object. + * + * Note that `OrderedMap` are more expensive than non-ordered `Map` and may + * consume more memory. `OrderedMap#set` is amortized O(log32 N), but not + * stable. + */ + + export module OrderedMap { + + /** + * True if the provided value is an OrderedMap. + */ + function isOrderedMap(maybeOrderedMap: any): boolean; + } + + /** + * Creates a new Immutable OrderedMap. + * + * Created with the same key value pairs as the provided Iterable.Keyed or + * JavaScript Object or expects an Iterable of [K, V] tuple entries. + * + * The iteration order of key-value pairs provided to this constructor will + * be preserved in the OrderedMap. + * + * var newOrderedMap = OrderedMap({key: "value"}); + * var newOrderedMap = OrderedMap([["key", "value"]]); + * + */ + export function OrderedMap(): OrderedMap; + export function OrderedMap(iter: Iterable.Keyed): OrderedMap; + export function OrderedMap(iter: Iterable>): OrderedMap; + export function OrderedMap(array: Array>): OrderedMap; + export function OrderedMap(obj: {[key: string]: V}): OrderedMap; + export function OrderedMap(iterator: Iterator>): OrderedMap; + export function OrderedMap(iterable: /*Iterable<[K,V]>*/Object): OrderedMap; + + export interface OrderedMap extends Map {} + + + /** + * A Collection of unique values with `O(log32 N)` adds and has. + * + * When iterating a Set, the entries will be (value, value) pairs. Iteration + * order of a Set is undefined, however is stable. Multiple iterations of the + * same Set will iterate in the same order. + * + * Set values, like Map keys, may be of any type. Equality is determined using + * `Immutable.is`, enabling Sets to uniquely include other Immutable + * collections, custom value types, and NaN. + */ + export module Set { + + /** + * True if the provided value is a Set + */ + function isSet(maybeSet: any): boolean; + + /** + * Creates a new Set containing `values`. + */ + function of(...values: T[]): Set; + + /** + * `Set.fromKeys()` creates a new immutable Set containing the keys from + * this Iterable or JavaScript Object. + */ + function fromKeys(iter: Iterable): Set; + function fromKeys(obj: {[key: string]: any}): Set; + } + + /** + * Create a new immutable Set containing the values of the provided + * iterable-like. + */ + export function Set(): Set; + export function Set(iter: Iterable.Set): Set; + export function Set(iter: Iterable.Indexed): Set; + export function Set(iter: Iterable.Keyed): Set; + export function Set(array: Array): Set; + export function Set(iterator: Iterator): Set; + export function Set(iterable: /*Iterable*/Object): Set; + + export interface Set extends Collection.Set { + + // Persistent changes + + /** + * Returns a new Set which also includes this value. + */ + add(value: T): Set; + + /** + * Returns a new Set which excludes this value. + * + * Note: `delete` cannot be safely used in IE8 + * @alias remove + */ + delete(value: T): Set; + remove(value: T): Set; + + /** + * Returns a new Set containing no values. + */ + clear(): Set; + + /** + * Returns a Set including any value from `iterables` that does not already + * exist in this Set. + * @alias merge + */ + union(...iterables: Iterable[]): Set; + union(...iterables: Array[]): Set; + merge(...iterables: Iterable[]): Set; + merge(...iterables: Array[]): Set; + + + /** + * Returns a Set which has removed any values not also contained + * within `iterables`. + */ + intersect(...iterables: Iterable[]): Set; + intersect(...iterables: Array[]): Set; + + /** + * Returns a Set excluding any values contained within `iterables`. + */ + subtract(...iterables: Iterable[]): Set; + subtract(...iterables: Array[]): Set; + + + // Transient changes + + /** + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `add` may be used mutatively. + * + * @see `Map#withMutations` + */ + withMutations(mutator: (mutable: Set) => any): Set; + + /** + * @see `Map#asMutable` + */ + asMutable(): Set; + + /** + * @see `Map#asImmutable` + */ + asImmutable(): Set; + } + + + /** + * A type of Set that has the additional guarantee that the iteration order of + * values will be the order in which they were `add`ed. + * + * The iteration behavior of OrderedSet is the same as native ES6 Set. + * + * Note that `OrderedSet` are more expensive than non-ordered `Set` and may + * consume more memory. `OrderedSet#add` is amortized O(log32 N), but not + * stable. + */ + export module OrderedSet { + + /** + * True if the provided value is an OrderedSet. + */ + function isOrderedSet(maybeOrderedSet: any): boolean; + + /** + * Creates a new OrderedSet containing `values`. + */ + function of(...values: T[]): OrderedSet; + + /** + * `OrderedSet.fromKeys()` creates a new immutable OrderedSet containing + * the keys from this Iterable or JavaScript Object. + */ + function fromKeys(iter: Iterable): OrderedSet; + function fromKeys(obj: {[key: string]: any}): OrderedSet; + } + + /** + * Create a new immutable OrderedSet containing the values of the provided + * iterable-like. + */ + export function OrderedSet(): OrderedSet; + export function OrderedSet(iter: Iterable.Set): OrderedSet; + export function OrderedSet(iter: Iterable.Indexed): OrderedSet; + export function OrderedSet(iter: Iterable.Keyed): OrderedSet; + export function OrderedSet(array: Array): OrderedSet; + export function OrderedSet(iterator: Iterator): OrderedSet; + export function OrderedSet(iterable: /*Iterable*/Object): OrderedSet; + + export interface OrderedSet extends Set {} + + + /** + * Stacks are indexed collections which support very efficient O(1) addition + * and removal from the front using `unshift(v)` and `shift()`. + * + * For familiarity, Stack also provides `push(v)`, `pop()`, and `peek()`, but + * be aware that they also operate on the front of the list, unlike List or + * a JavaScript Array. + * + * Note: `reverse()` or any inherent reverse traversal (`reduceRight`, + * `lastIndexOf`, etc.) is not efficient with a Stack. + * + * Stack is implemented with a Single-Linked List. + */ + export module Stack { + + /** + * True if the provided value is a Stack + */ + function isStack(maybeStack: any): boolean; + + /** + * Creates a new Stack containing `values`. + */ + function of(...values: T[]): Stack; + } + + /** + * Create a new immutable Stack containing the values of the provided + * iterable-like. + * + * The iteration order of the provided iterable is preserved in the + * resulting `Stack`. + */ + export function Stack(): Stack; + export function Stack(iter: Iterable.Indexed): Stack; + export function Stack(iter: Iterable.Set): Stack; + export function Stack(iter: Iterable.Keyed): Stack; + export function Stack(array: Array): Stack; + export function Stack(iterator: Iterator): Stack; + export function Stack(iterable: /*Iterable*/Object): Stack; + + export interface Stack extends Collection.Indexed { + + // Reading values + + /** + * Alias for `Stack.first()`. + */ + peek(): T; + + + // Persistent changes + + /** + * Returns a new Stack with 0 size and no values. + */ + clear(): Stack; + + /** + * Returns a new Stack with the provided `values` prepended, shifting other + * values ahead to higher indices. + * + * This is very efficient for Stack. + */ + unshift(...values: T[]): Stack; + + /** + * Like `Stack#unshift`, but accepts a iterable rather than varargs. + */ + unshiftAll(iter: Iterable): Stack; + unshiftAll(iter: Array): Stack; + + /** + * Returns a new Stack with a size ones less than this Stack, excluding + * the first item in this Stack, shifting all other values to a lower index. + * + * Note: this differs from `Array#shift` because it returns a new + * Stack rather than the removed value. Use `first()` or `peek()` to get the + * first value in this Stack. + */ + shift(): Stack; + + /** + * Alias for `Stack#unshift` and is not equivalent to `List#push`. + */ + push(...values: T[]): Stack; + + /** + * Alias for `Stack#unshiftAll`. + */ + pushAll(iter: Iterable): Stack; + pushAll(iter: Array): Stack; + + /** + * Alias for `Stack#shift` and is not equivalent to `List#pop`. + */ + pop(): Stack; + + + // Transient changes + + /** + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set`, `push`, and `pop` may be used mutatively. + * + * @see `Map#withMutations` + */ + withMutations(mutator: (mutable: Stack) => any): Stack; + + /** + * @see `Map#asMutable` + */ + asMutable(): Stack; + + /** + * @see `Map#asImmutable` + */ + asImmutable(): Stack; + } + + + /** + * Returns a Seq.Indexed of numbers from `start` (inclusive) to `end` + * (exclusive), by `step`, where `start` defaults to 0, `step` to 1, and `end` to + * infinity. When `start` is equal to `end`, returns empty range. + * + * Range() // [0,1,2,3,...] + * Range(10) // [10,11,12,13,...] + * Range(10,15) // [10,11,12,13,14] + * Range(10,30,5) // [10,15,20,25] + * Range(30,10,5) // [30,25,20,15] + * Range(30,30,5) // [] + * + */ + export function Range(start?: number, end?: number, step?: number): Seq.Indexed; + + + /** + * Returns a Seq.Indexed of `value` repeated `times` times. When `times` is + * not defined, returns an infinite `Seq` of `value`. + * + * Repeat('foo') // ['foo','foo','foo',...] + * Repeat('bar',4) // ['bar','bar','bar','bar'] + * + */ + export function Repeat(value: T, times?: number): Seq.Indexed; + + + /** + * Creates a new Class which produces Record instances. A record is similar to + * a JS object, but enforce a specific set of allowed string keys, and have + * default values. + * + * var ABRecord = Record({a:1, b:2}) + * var myRecord = new ABRecord({b:3}) + * + * Records always have a value for the keys they define. `remove`ing a key + * from a record simply resets it to the default value for that key. + * + * myRecord.size // 2 + * myRecord.get('a') // 1 + * myRecord.get('b') // 3 + * myRecordWithoutB = myRecord.remove('b') + * myRecordWithoutB.get('b') // 2 + * myRecordWithoutB.size // 2 + * + * Values provided to the constructor not found in the Record type will + * be ignored. For example, in this case, ABRecord is provided a key "x" even + * though only "a" and "b" have been defined. The value for "x" will be + * ignored for this record. + * + * var myRecord = new ABRecord({b:3, x:10}) + * myRecord.get('x') // undefined + * + * Because Records have a known set of string keys, property get access works + * as expected, however property sets will throw an Error. + * + * Note: IE8 does not support property access. Only use `get()` when + * supporting IE8. + * + * myRecord.b // 3 + * myRecord.b = 5 // throws Error + * + * Record Classes can be extended as well, allowing for custom methods on your + * Record. This is not a common pattern in functional environments, but is in + * many JS programs. + * + * Note: TypeScript does not support this type of subclassing. + * + * class ABRecord extends Record({a:1,b:2}) { + * getAB() { + * return this.a + this.b; + * } + * } + * + * var myRecord = new ABRecord({b: 3}) + * myRecord.getAB() // 4 + * + */ + export module Record { + interface Class { + new (): Map; + new (values: {[key: string]: any}): Map; + new (values: Iterable): Map; // deprecated + + (): Map; + (values: {[key: string]: any}): Map; + (values: Iterable): Map; // deprecated + } + } + + export function Record( + defaultValues: {[key: string]: any}, name?: string + ): Record.Class; + + + /** + * Represents a sequence of values, but may not be backed by a concrete data + * structure. + * + * **Seq is immutable** — Once a Seq is created, it cannot be + * changed, appended to, rearranged or otherwise modified. Instead, any + * mutative method called on a `Seq` will return a new `Seq`. + * + * **Seq is lazy** — Seq does as little work as necessary to respond to any + * method call. Values are often created during iteration, including implicit + * iteration when reducing or converting to a concrete data structure such as + * a `List` or JavaScript `Array`. + * + * For example, the following performs no work, because the resulting + * Seq's values are never iterated: + * + * var oddSquares = Immutable.Seq.of(1,2,3,4,5,6,7,8) + * .filter(x => x % 2).map(x => x * x); + * + * Once the Seq is used, it performs only the work necessary. In this + * example, no intermediate data structures are ever created, filter is only + * called three times, and map is only called once: + * + * console.log(evenSquares.get(1)); // 9 + * + * Seq allows for the efficient chaining of operations, + * allowing for the expression of logic that can otherwise be very tedious: + * + * Immutable.Seq({a:1, b:1, c:1}) + * .flip().map(key => key.toUpperCase()).flip().toObject(); + * // Map { A: 1, B: 1, C: 1 } + * + * As well as expressing logic that would otherwise be memory or time limited: + * + * Immutable.Range(1, Infinity) + * .skip(1000) + * .map(n => -n) + * .filter(n => n % 2 === 0) + * .take(2) + * .reduce((r, n) => r * n, 1); + * // 1006008 + * + * Seq is often used to provide a rich collection API to JavaScript Object. + * + * Immutable.Seq({ x: 0, y: 1, z: 2 }).map(v => v * 2).toObject(); + * // { x: 0, y: 2, z: 4 } + */ + + export module Seq { + /** + * True if `maybeSeq` is a Seq, it is not backed by a concrete + * structure such as Map, List, or Set. + */ + function isSeq(maybeSeq: any): boolean; + + /** + * Returns a Seq of the values provided. Alias for `Seq.Indexed.of()`. + */ + function of(...values: T[]): Seq.Indexed; + + + /** + * `Seq` which represents key-value pairs. + */ + export module Keyed {} + + /** + * Always returns a Seq.Keyed, if input is not keyed, expects an + * iterable of [K, V] tuples. + */ + export function Keyed(): Seq.Keyed; + export function Keyed(seq: Iterable.Keyed): Seq.Keyed; + export function Keyed(seq: Iterable): Seq.Keyed; + export function Keyed(array: Array): Seq.Keyed; + export function Keyed(obj: {[key: string]: V}): Seq.Keyed; + export function Keyed(iterator: Iterator): Seq.Keyed; + export function Keyed(iterable: /*Iterable<[K,V]>*/Object): Seq.Keyed; + + export interface Keyed extends Seq, Iterable.Keyed { + + /** + * Returns itself + */ + toSeq(): /*this*/Seq.Keyed + } + + + /** + * `Seq` which represents an ordered indexed list of values. + */ + module Indexed { + + /** + * Provides an Seq.Indexed of the values provided. + */ + function of(...values: T[]): Seq.Indexed; + } + + /** + * Always returns Seq.Indexed, discarding associated keys and + * supplying incrementing indices. + */ + export function Indexed(): Seq.Indexed; + export function Indexed(seq: Iterable.Indexed): Seq.Indexed; + export function Indexed(seq: Iterable.Set): Seq.Indexed; + export function Indexed(seq: Iterable.Keyed): Seq.Indexed; + export function Indexed(array: Array): Seq.Indexed; + export function Indexed(iterator: Iterator): Seq.Indexed; + export function Indexed(iterable: /*Iterable*/Object): Seq.Indexed; + + export interface Indexed extends Seq, Iterable.Indexed { + + /** + * Returns itself + */ + toSeq(): /*this*/Seq.Indexed + } + + + /** + * `Seq` which represents a set of values. + * + * Because `Seq` are often lazy, `Seq.Set` does not provide the same guarantee + * of value uniqueness as the concrete `Set`. + */ + export module Set { + + /** + * Returns a Seq.Set of the provided values + */ + function of(...values: T[]): Seq.Set; + } + + /** + * Always returns a Seq.Set, discarding associated indices or keys. + */ + export function Set(): Seq.Set; + export function Set(seq: Iterable.Set): Seq.Set; + export function Set(seq: Iterable.Indexed): Seq.Set; + export function Set(seq: Iterable.Keyed): Seq.Set; + export function Set(array: Array): Seq.Set; + export function Set(iterator: Iterator): Seq.Set; + export function Set(iterable: /*Iterable*/Object): Seq.Set; + + export interface Set extends Seq, Iterable.Set { + + /** + * Returns itself + */ + toSeq(): /*this*/Seq.Set + } + + } + + /** + * Creates a Seq. + * + * Returns a particular kind of `Seq` based on the input. + * + * * If a `Seq`, that same `Seq`. + * * If an `Iterable`, a `Seq` of the same kind (Keyed, Indexed, or Set). + * * If an Array-like, an `Seq.Indexed`. + * * If an Object with an Iterator, an `Seq.Indexed`. + * * If an Iterator, an `Seq.Indexed`. + * * If an Object, a `Seq.Keyed`. + * + */ + export function Seq(): Seq; + export function Seq(seq: Seq): Seq; + export function Seq(iterable: Iterable): Seq; + export function Seq(array: Array): Seq.Indexed; + export function Seq(obj: {[key: string]: V}): Seq.Keyed; + export function Seq(iterator: Iterator): Seq.Indexed; + export function Seq(iterable: /*ES6Iterable*/Object): Seq.Indexed; + + export interface Seq extends Iterable { + + /** + * Some Seqs can describe their size lazily. When this is the case, + * size will be an integer. Otherwise it will be undefined. + * + * For example, Seqs returned from `map()` or `reverse()` + * preserve the size of the original `Seq` while `filter()` does not. + * + * Note: `Range`, `Repeat` and `Seq`s made from `Array`s and `Object`s will + * always have a size. + */ + size: number/*?*/; + + + // Force evaluation + + /** + * Because Sequences are lazy and designed to be chained together, they do + * not cache their results. For example, this map function is called a total + * of 6 times, as each `join` iterates the Seq of three values. + * + * var squares = Seq.of(1,2,3).map(x => x * x); + * squares.join() + squares.join(); + * + * If you know a `Seq` will be used multiple times, it may be more + * efficient to first cache it in memory. Here, the map function is called + * only 3 times. + * + * var squares = Seq.of(1,2,3).map(x => x * x).cacheResult(); + * squares.join() + squares.join(); + * + * Use this method judiciously, as it must fully evaluate a Seq which can be + * a burden on memory and possibly performance. + * + * Note: after calling `cacheResult`, a Seq will always have a `size`. + */ + cacheResult(): /*this*/Seq; + } + + /** + * The `Iterable` is a set of (key, value) entries which can be iterated, and + * is the base class for all collections in `immutable`, allowing them to + * make use of all the Iterable methods (such as `map` and `filter`). + * + * Note: An iterable is always iterated in the same order, however that order + * may not always be well defined, as is the case for the `Map` and `Set`. + */ + export module Iterable { + /** + * True if `maybeIterable` is an Iterable, or any of its subclasses. + */ + function isIterable(maybeIterable: any): boolean; + + /** + * True if `maybeKeyed` is an Iterable.Keyed, or any of its subclasses. + */ + function isKeyed(maybeKeyed: any): boolean; + + /** + * True if `maybeIndexed` is a Iterable.Indexed, or any of its subclasses. + */ + function isIndexed(maybeIndexed: any): boolean; + + /** + * True if `maybeAssociative` is either a keyed or indexed Iterable. + */ + function isAssociative(maybeAssociative: any): boolean; + + /** + * True if `maybeOrdered` is an Iterable where iteration order is well + * defined. True for Iterable.Indexed as well as OrderedMap and OrderedSet. + */ + function isOrdered(maybeOrdered: any): boolean; + + + /** + * Keyed Iterables have discrete keys tied to each value. + * + * When iterating `Iterable.Keyed`, each iteration will yield a `[K, V]` + * tuple, in other words, `Iterable#entries` is the default iterator for + * Keyed Iterables. + */ + export module Keyed {} + + /** + * Creates an Iterable.Keyed + * + * Similar to `Iterable()`, however it expects iterable-likes of [K, V] + * tuples if not constructed from a Iterable.Keyed or JS Object. + */ + export function Keyed(iter: Iterable.Keyed): Iterable.Keyed; + export function Keyed(iter: Iterable): Iterable.Keyed; + export function Keyed(array: Array): Iterable.Keyed; + export function Keyed(obj: {[key: string]: V}): Iterable.Keyed; + export function Keyed(iterator: Iterator): Iterable.Keyed; + export function Keyed(iterable: /*Iterable<[K,V]>*/Object): Iterable.Keyed; + + export interface Keyed extends Iterable { + + /** + * Returns Seq.Keyed. + * @override + */ + toSeq(): Seq.Keyed; + + + // Sequence functions + + /** + * Returns a new Iterable.Keyed of the same type where the keys and values + * have been flipped. + * + * Seq({ a: 'z', b: 'y' }).flip() // { z: 'a', y: 'b' } + * + */ + flip(): /*this*/Iterable.Keyed; + + /** + * Returns a new Iterable.Keyed of the same type with keys passed through + * a `mapper` function. + * + * Seq({ a: 1, b: 2 }) + * .mapKeys(x => x.toUpperCase()) + * // Seq { A: 1, B: 2 } + * + */ + mapKeys( + mapper: (key?: K, value?: V, iter?: /*this*/Iterable.Keyed) => M, + context?: any + ): /*this*/Iterable.Keyed; + + /** + * Returns a new Iterable.Keyed of the same type with entries + * ([key, value] tuples) passed through a `mapper` function. + * + * Seq({ a: 1, b: 2 }) + * .mapEntries(([k, v]) => [k.toUpperCase(), v * 2]) + * // Seq { A: 2, B: 4 } + * + */ + mapEntries( + mapper: ( + entry?: /*(K, V)*/Array, + index?: number, + iter?: /*this*/Iterable.Keyed + ) => /*[KM, VM]*/Array, + context?: any + ): /*this*/Iterable.Keyed; + + + // Search for value + + /** + * Returns the key associated with the search value, or undefined. + */ + keyOf(searchValue: V): K; + + /** + * Returns the last key associated with the search value, or undefined. + */ + lastKeyOf(searchValue: V): K; + + /** + * Returns the key for which the `predicate` returns true. + */ + findKey( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable.Keyed) => boolean, + context?: any + ): K; + + /** + * Returns the last key for which the `predicate` returns true. + * + * Note: `predicate` will be called for each entry in reverse. + */ + findLastKey( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable.Keyed) => boolean, + context?: any + ): K; + } + + + /** + * Indexed Iterables have incrementing numeric keys. They exhibit + * slightly different behavior than `Iterable.Keyed` for some methods in order + * to better mirror the behavior of JavaScript's `Array`, and add methods + * which do not make sense on non-indexed Iterables such as `indexOf`. + * + * Unlike JavaScript arrays, `Iterable.Indexed`s are always dense. "Unset" + * indices and `undefined` indices are indistinguishable, and all indices from + * 0 to `size` are visited when iterated. + * + * All Iterable.Indexed methods return re-indexed Iterables. In other words, + * indices always start at 0 and increment until size. If you wish to + * preserve indices, using them as keys, convert to a Iterable.Keyed by + * calling `toKeyedSeq`. + */ + export module Indexed {} + + /** + * Creates a new Iterable.Indexed. + */ + export function Indexed(iter: Iterable.Indexed): Iterable.Indexed; + export function Indexed(iter: Iterable.Set): Iterable.Indexed; + export function Indexed(iter: Iterable.Keyed): Iterable.Indexed; + export function Indexed(array: Array): Iterable.Indexed; + export function Indexed(iterator: Iterator): Iterable.Indexed; + export function Indexed(iterable: /*Iterable*/Object): Iterable.Indexed; + + export interface Indexed extends Iterable { + + // Reading values + + /** + * Returns the value associated with the provided index, or notSetValue if + * the index is beyond the bounds of the Iterable. + * + * `index` may be a negative number, which indexes back from the end of the + * Iterable. `s.get(-1)` gets the last item in the Iterable. + */ + get(index: number, notSetValue?: T): T; + + + // Conversion to Seq + + /** + * Returns Seq.Indexed. + * @override + */ + toSeq(): Seq.Indexed; + + /** + * If this is an iterable of [key, value] entry tuples, it will return a + * Seq.Keyed of those entries. + */ + fromEntrySeq(): Seq.Keyed; + + + // Combination + + /** + * Returns an Iterable of the same type with `separator` between each item + * in this Iterable. + */ + interpose(separator: T): /*this*/Iterable.Indexed; + + /** + * Returns an Iterable of the same type with the provided `iterables` + * interleaved into this iterable. + * + * The resulting Iterable includes the first item from each, then the + * second from each, etc. + * + * I.Seq.of(1,2,3).interleave(I.Seq.of('A','B','C')) + * // Seq [ 1, 'A', 2, 'B', 3, 'C' ] + * + * The shortest Iterable stops interleave. + * + * I.Seq.of(1,2,3).interleave( + * I.Seq.of('A','B'), + * I.Seq.of('X','Y','Z') + * ) + * // Seq [ 1, 'A', 'X', 2, 'B', 'Y' ] + */ + interleave(...iterables: Array>): /*this*/Iterable.Indexed; + + /** + * Splice returns a new indexed Iterable by replacing a region of this + * Iterable with new values. If values are not provided, it only skips the + * region to be removed. + * + * `index` may be a negative number, which indexes back from the end of the + * Iterable. `s.splice(-2)` splices after the second to last item. + * + * Seq(['a','b','c','d']).splice(1, 2, 'q', 'r', 's') + * // Seq ['a', 'q', 'r', 's', 'd'] + * + */ + splice( + index: number, + removeNum: number, + ...values: /*Array | T>*/any[] + ): /*this*/Iterable.Indexed; + + /** + * Returns an Iterable of the same type "zipped" with the provided + * iterables. + * + * Like `zipWith`, but using the default `zipper`: creating an `Array`. + * + * var a = Seq.of(1, 2, 3); + * var b = Seq.of(4, 5, 6); + * var c = a.zip(b); // Seq [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ] + * + */ + zip(...iterables: Array>): /*this*/Iterable.Indexed; + + /** + * Returns an Iterable of the same type "zipped" with the provided + * iterables by using a custom `zipper` function. + * + * var a = Seq.of(1, 2, 3); + * var b = Seq.of(4, 5, 6); + * var c = a.zipWith((a, b) => a + b, b); // Seq [ 5, 7, 9 ] + * + */ + zipWith( + zipper: (value: T, otherValue: U) => Z, + otherIterable: Iterable + ): Iterable.Indexed; + zipWith( + zipper: (value: T, otherValue: U, thirdValue: V) => Z, + otherIterable: Iterable, + thirdIterable: Iterable + ): Iterable.Indexed; + zipWith( + zipper: (...any: Array) => Z, + ...iterables: Array> + ): Iterable.Indexed; + + + // Search for value + + /** + * Returns the first index at which a given value can be found in the + * Iterable, or -1 if it is not present. + */ + indexOf(searchValue: T): number; + + /** + * Returns the last index at which a given value can be found in the + * Iterable, or -1 if it is not present. + */ + lastIndexOf(searchValue: T): number; + + /** + * Returns the first index in the Iterable where a value satisfies the + * provided predicate function. Otherwise -1 is returned. + */ + findIndex( + predicate: (value?: T, index?: number, iter?: /*this*/Iterable.Indexed) => boolean, + context?: any + ): number; + + /** + * Returns the last index in the Iterable where a value satisfies the + * provided predicate function. Otherwise -1 is returned. + */ + findLastIndex( + predicate: (value?: T, index?: number, iter?: /*this*/Iterable.Indexed) => boolean, + context?: any + ): number; + } + + + /** + * Set Iterables only represent values. They have no associated keys or + * indices. Duplicate values are possible in Seq.Sets, however the + * concrete `Set` does not allow duplicate values. + * + * Iterable methods on Iterable.Set such as `map` and `forEach` will provide + * the value as both the first and second arguments to the provided function. + * + * var seq = Seq.Set.of('A', 'B', 'C'); + * assert.equal(seq.every((v, k) => v === k), true); + * + */ + export module Set {} + + /** + * Similar to `Iterable()`, but always returns a Iterable.Set. + */ + export function Set(iter: Iterable.Set): Iterable.Set; + export function Set(iter: Iterable.Indexed): Iterable.Set; + export function Set(iter: Iterable.Keyed): Iterable.Set; + export function Set(array: Array): Iterable.Set; + export function Set(iterator: Iterator): Iterable.Set; + export function Set(iterable: /*Iterable*/Object): Iterable.Set; + + export interface Set extends Iterable { + + /** + * Returns Seq.Set. + * @override + */ + toSeq(): Seq.Set; + } + + } + + /** + * Creates an Iterable. + * + * The type of Iterable created is based on the input. + * + * * If an `Iterable`, that same `Iterable`. + * * If an Array-like, an `Iterable.Indexed`. + * * If an Object with an Iterator, an `Iterable.Indexed`. + * * If an Iterator, an `Iterable.Indexed`. + * * If an Object, an `Iterable.Keyed`. + * + * This methods forces the conversion of Objects and Strings to Iterables. + * If you want to ensure that a Iterable of one item is returned, use + * `Seq.of`. + */ + export function Iterable(iterable: Iterable): Iterable; + export function Iterable(array: Array): Iterable.Indexed; + export function Iterable(obj: {[key: string]: V}): Iterable.Keyed; + export function Iterable(iterator: Iterator): Iterable.Indexed; + export function Iterable(iterable: /*ES6Iterable*/Object): Iterable.Indexed; + export function Iterable(value: V): Iterable.Indexed; + + export interface Iterable { + + // Value equality + + /** + * True if this and the other Iterable have value equality, as defined + * by `Immutable.is()`. + * + * Note: This is equivalent to `Immutable.is(this, other)`, but provided to + * allow for chained expressions. + */ + equals(other: Iterable): boolean; + + /** + * Computes and returns the hashed identity for this Iterable. + * + * The `hashCode` of an Iterable is used to determine potential equality, + * and is used when adding this to a `Set` or as a key in a `Map`, enabling + * lookup via a different instance. + * + * var a = List.of(1, 2, 3); + * var b = List.of(1, 2, 3); + * assert(a !== b); // different instances + * var set = Set.of(a); + * assert(set.has(b) === true); + * + * If two values have the same `hashCode`, they are [not guaranteed + * to be equal][Hash Collision]. If two values have different `hashCode`s, + * they must not be equal. + * + * [Hash Collision]: http://en.wikipedia.org/wiki/Collision_(computer_science) + */ + hashCode(): number; + + + // Reading values + + /** + * Returns the value associated with the provided key, or notSetValue if + * the Iterable does not contain this key. + * + * Note: it is possible a key may be associated with an `undefined` value, + * so if `notSetValue` is not provided and this method returns `undefined`, + * that does not guarantee the key was not found. + */ + get(key: K, notSetValue?: V): V; + + /** + * True if a key exists within this `Iterable`. + */ + has(key: K): boolean; + + /** + * True if a value exists within this `Iterable`. + * @alias contains + */ + includes(value: V): boolean; + contains(value: V): boolean; + + /** + * The first value in the Iterable. + */ + first(): V; + + /** + * The last value in the Iterable. + */ + last(): V; + + + // Reading deep values + + /** + * Returns the value found by following a path of keys or indices through + * nested Iterables. + */ + getIn(searchKeyPath: Array, notSetValue?: any): any; + getIn(searchKeyPath: Iterable, notSetValue?: any): any; + + /** + * True if the result of following a path of keys or indices through nested + * Iterables results in a set value. + */ + hasIn(searchKeyPath: Array): boolean; + hasIn(searchKeyPath: Iterable): boolean; + + + // Conversion to JavaScript types + + /** + * Deeply converts this Iterable to equivalent JS. + * + * `Iterable.Indexeds`, and `Iterable.Sets` become Arrays, while + * `Iterable.Keyeds` become Objects. + * + * @alias toJSON + */ + toJS(): any; + + /** + * Shallowly converts this iterable to an Array, discarding keys. + */ + toArray(): Array; + + /** + * Shallowly converts this Iterable to an Object. + * + * Throws if keys are not strings. + */ + toObject(): { [key: string]: V }; + + + // Conversion to Collections + + /** + * Converts this Iterable to a Map, Throws if keys are not hashable. + * + * Note: This is equivalent to `Map(this.toKeyedSeq())`, but provided + * for convenience and to allow for chained expressions. + */ + toMap(): Map; + + /** + * Converts this Iterable to a Map, maintaining the order of iteration. + * + * Note: This is equivalent to `OrderedMap(this.toKeyedSeq())`, but + * provided for convenience and to allow for chained expressions. + */ + toOrderedMap(): Map; + + /** + * Converts this Iterable to a Set, discarding keys. Throws if values + * are not hashable. + * + * Note: This is equivalent to `Set(this)`, but provided to allow for + * chained expressions. + */ + toSet(): Set; + + /** + * Converts this Iterable to a Set, maintaining the order of iteration and + * discarding keys. + * + * Note: This is equivalent to `OrderedSet(this.valueSeq())`, but provided + * for convenience and to allow for chained expressions. + */ + toOrderedSet(): Set; + + /** + * Converts this Iterable to a List, discarding keys. + * + * Note: This is equivalent to `List(this)`, but provided to allow + * for chained expressions. + */ + toList(): List; + + /** + * Converts this Iterable to a Stack, discarding keys. Throws if values + * are not hashable. + * + * Note: This is equivalent to `Stack(this)`, but provided to allow for + * chained expressions. + */ + toStack(): Stack; + + + // Conversion to Seq + + /** + * Converts this Iterable to a Seq of the same kind (indexed, + * keyed, or set). + */ + toSeq(): Seq; + + /** + * Returns a Seq.Keyed from this Iterable where indices are treated as keys. + * + * This is useful if you want to operate on an + * Iterable.Indexed and preserve the [index, value] pairs. + * + * The returned Seq will have identical iteration order as + * this Iterable. + * + * Example: + * + * var indexedSeq = Immutable.Seq.of('A', 'B', 'C'); + * indexedSeq.filter(v => v === 'B').toString() // Seq [ 'B' ] + * var keyedSeq = indexedSeq.toKeyedSeq(); + * keyedSeq.filter(v => v === 'B').toString() // Seq { 1: 'B' } + * + */ + toKeyedSeq(): Seq.Keyed; + + /** + * Returns an Seq.Indexed of the values of this Iterable, discarding keys. + */ + toIndexedSeq(): Seq.Indexed; + + /** + * Returns a Seq.Set of the values of this Iterable, discarding keys. + */ + toSetSeq(): Seq.Set; + + + // Iterators + + /** + * An iterator of this `Iterable`'s keys. + */ + keys(): Iterator; + + /** + * An iterator of this `Iterable`'s values. + */ + values(): Iterator; + + /** + * An iterator of this `Iterable`'s entries as `[key, value]` tuples. + */ + entries(): Iterator>; + + + // Iterables (Seq) + + /** + * Returns a new Seq.Indexed of the keys of this Iterable, + * discarding values. + */ + keySeq(): Seq.Indexed; + + /** + * Returns an Seq.Indexed of the values of this Iterable, discarding keys. + */ + valueSeq(): Seq.Indexed; + + /** + * Returns a new Seq.Indexed of [key, value] tuples. + */ + entrySeq(): Seq.Indexed>; + + + // Sequence algorithms + + /** + * Returns a new Iterable of the same type with values passed through a + * `mapper` function. + * + * Seq({ a: 1, b: 2 }).map(x => 10 * x) + * // Seq { a: 10, b: 20 } + * + */ + map( + mapper: (value?: V, key?: K, iter?: /*this*/Iterable) => M, + context?: any + ): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type with only the entries for which + * the `predicate` function returns true. + * + * Seq({a:1,b:2,c:3,d:4}).filter(x => x % 2 === 0) + * // Seq { b: 2, d: 4 } + * + */ + filter( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any + ): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type with only the entries for which + * the `predicate` function returns false. + * + * Seq({a:1,b:2,c:3,d:4}).filterNot(x => x % 2 === 0) + * // Seq { a: 1, c: 3 } + * + */ + filterNot( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any + ): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type in reverse order. + */ + reverse(): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type which includes the same entries, + * stably sorted by using a `comparator`. + * + * If a `comparator` is not provided, a default comparator uses `<` and `>`. + * + * `comparator(valueA, valueB)`: + * + * * Returns `0` if the elements should not be swapped. + * * Returns `-1` (or any negative number) if `valueA` comes before `valueB` + * * Returns `1` (or any positive number) if `valueA` comes after `valueB` + * * Is pure, i.e. it must always return the same value for the same pair + * of values. + * + * When sorting collections which have no defined order, their ordered + * equivalents will be returned. e.g. `map.sort()` returns OrderedMap. + */ + sort(comparator?: (valueA: V, valueB: V) => number): /*this*/Iterable; + + /** + * Like `sort`, but also accepts a `comparatorValueMapper` which allows for + * sorting by more sophisticated means: + * + * hitters.sortBy(hitter => hitter.avgHits); + * + */ + sortBy( + comparatorValueMapper: (value?: V, key?: K, iter?: /*this*/Iterable) => C, + comparator?: (valueA: C, valueB: C) => number + ): /*this*/Iterable; + + /** + * Returns a `Iterable.Keyed` of `Iterable.Keyeds`, grouped by the return + * value of the `grouper` function. + * + * Note: This is always an eager operation. + */ + groupBy( + grouper: (value?: V, key?: K, iter?: /*this*/Iterable) => G, + context?: any + ): /*Map*/Seq.Keyed>; + + + // Side effects + + /** + * The `sideEffect` is executed for every entry in the Iterable. + * + * Unlike `Array#forEach`, if any call of `sideEffect` returns + * `false`, the iteration will stop. Returns the number of entries iterated + * (including the last iteration which returned false). + */ + forEach( + sideEffect: (value?: V, key?: K, iter?: /*this*/Iterable) => any, + context?: any + ): number; + + + // Creating subsets + + /** + * Returns a new Iterable of the same type representing a portion of this + * Iterable from start up to but not including end. + * + * If begin is negative, it is offset from the end of the Iterable. e.g. + * `slice(-2)` returns a Iterable of the last two entries. If it is not + * provided the new Iterable will begin at the beginning of this Iterable. + * + * If end is negative, it is offset from the end of the Iterable. e.g. + * `slice(0, -1)` returns an Iterable of everything but the last entry. If + * it is not provided, the new Iterable will continue through the end of + * this Iterable. + * + * If the requested slice is equivalent to the current Iterable, then it + * will return itself. + */ + slice(begin?: number, end?: number): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type containing all entries except + * the first. + */ + rest(): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type containing all entries except + * the last. + */ + butLast(): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type which excludes the first `amount` + * entries from this Iterable. + */ + skip(amount: number): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type which excludes the last `amount` + * entries from this Iterable. + */ + skipLast(amount: number): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type which includes entries starting + * from when `predicate` first returns false. + * + * Seq.of('dog','frog','cat','hat','god') + * .skipWhile(x => x.match(/g/)) + * // Seq [ 'cat', 'hat', 'god' ] + * + */ + skipWhile( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any + ): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type which includes entries starting + * from when `predicate` first returns true. + * + * Seq.of('dog','frog','cat','hat','god') + * .skipUntil(x => x.match(/hat/)) + * // Seq [ 'hat', 'god' ] + * + */ + skipUntil( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any + ): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type which includes the first `amount` + * entries from this Iterable. + */ + take(amount: number): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type which includes the last `amount` + * entries from this Iterable. + */ + takeLast(amount: number): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type which includes entries from this + * Iterable as long as the `predicate` returns true. + * + * Seq.of('dog','frog','cat','hat','god') + * .takeWhile(x => x.match(/o/)) + * // Seq [ 'dog', 'frog' ] + * + */ + takeWhile( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any + ): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type which includes entries from this + * Iterable as long as the `predicate` returns false. + * + * Seq.of('dog','frog','cat','hat','god').takeUntil(x => x.match(/at/)) + * // ['dog', 'frog'] + * + */ + takeUntil( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any + ): /*this*/Iterable; + + + // Combination + + /** + * Returns a new Iterable of the same type with other values and + * iterable-like concatenated to this one. + * + * For Seqs, all entries will be present in + * the resulting iterable, even if they have the same key. + */ + concat(...valuesOrIterables: /*Array|V*/any[]): /*this*/Iterable; + + /** + * Flattens nested Iterables. + * + * Will deeply flatten the Iterable by default, returning an Iterable of the + * same type, but a `depth` can be provided in the form of a number or + * boolean (where true means to shallowly flatten one level). A depth of 0 + * (or shallow: false) will deeply flatten. + * + * Flattens only others Iterable, not Arrays or Objects. + * + * Note: `flatten(true)` operates on Iterable> and + * returns Iterable + */ + flatten(depth?: number): /*this*/Iterable; + flatten(shallow?: boolean): /*this*/Iterable; + + /** + * Flat-maps the Iterable, returning an Iterable of the same type. + * + * Similar to `iter.map(...).flatten(true)`. + */ + flatMap( + mapper: (value?: V, key?: K, iter?: /*this*/Iterable) => Iterable, + context?: any + ): /*this*/Iterable; + flatMap( + mapper: (value?: V, key?: K, iter?: /*this*/Iterable) => /*iterable-like*/any, + context?: any + ): /*this*/Iterable; + + + // Reducing a value + + /** + * Reduces the Iterable to a value by calling the `reducer` for every entry + * in the Iterable and passing along the reduced value. + * + * If `initialReduction` is not provided, or is null, the first item in the + * Iterable will be used. + * + * @see `Array#reduce`. + */ + reduce( + reducer: (reduction?: R, value?: V, key?: K, iter?: /*this*/Iterable) => R, + initialReduction?: R, + context?: any + ): R; + + /** + * Reduces the Iterable in reverse (from the right side). + * + * Note: Similar to this.reverse().reduce(), and provided for parity + * with `Array#reduceRight`. + */ + reduceRight( + reducer: (reduction?: R, value?: V, key?: K, iter?: /*this*/Iterable) => R, + initialReduction?: R, + context?: any + ): R; + + /** + * True if `predicate` returns true for all entries in the Iterable. + */ + every( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any + ): boolean; + + /** + * True if `predicate` returns true for any entry in the Iterable. + */ + some( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any + ): boolean; + + /** + * Joins values together as a string, inserting a separator between each. + * The default separator is `","`. + */ + join(separator?: string): string; + + /** + * Returns true if this Iterable includes no values. + * + * For some lazy `Seq`, `isEmpty` might need to iterate to determine + * emptiness. At most one iteration will occur. + */ + isEmpty(): boolean; + + /** + * Returns the size of this Iterable. + * + * Regardless of if this Iterable can describe its size lazily (some Seqs + * cannot), this method will always return the correct size. E.g. it + * evaluates a lazy `Seq` if necessary. + * + * If `predicate` is provided, then this returns the count of entries in the + * Iterable for which the `predicate` returns true. + */ + count(): number; + count( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any + ): number; + + /** + * Returns a `Seq.Keyed` of counts, grouped by the return value of + * the `grouper` function. + * + * Note: This is not a lazy operation. + */ + countBy( + grouper: (value?: V, key?: K, iter?: /*this*/Iterable) => G, + context?: any + ): Map; + + + // Search for value + + /** + * Returns the value for which the `predicate` returns true. + */ + find( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any, + notSetValue?: V + ): V; + + /** + * Returns the last value for which the `predicate` returns true. + * + * Note: `predicate` will be called for each entry in reverse. + */ + findLast( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any, + notSetValue?: V + ): V; + + /** + * Returns the [key, value] entry for which the `predicate` returns true. + */ + findEntry( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any, + notSetValue?: V + ): /*[K, V]*/Array; + + /** + * Returns the last [key, value] entry for which the `predicate` + * returns true. + * + * Note: `predicate` will be called for each entry in reverse. + */ + findLastEntry( + predicate: (value?: V, key?: K, iter?: /*this*/Iterable) => boolean, + context?: any, + notSetValue?: V + ): /*[K, V]*/Array; + + /** + * Returns the maximum value in this collection. If any values are + * comparatively equivalent, the first one found will be returned. + * + * The `comparator` is used in the same way as `Iterable#sort`. If it is not + * provided, the default comparator is `>`. + * + * When two values are considered equivalent, the first encountered will be + * returned. Otherwise, `max` will operate independent of the order of input + * as long as the comparator is commutative. The default comparator `>` is + * commutative *only* when types do not differ. + * + * If `comparator` returns 0 and either value is NaN, undefined, or null, + * that value will be returned. + */ + max(comparator?: (valueA: V, valueB: V) => number): V; + + /** + * Like `max`, but also accepts a `comparatorValueMapper` which allows for + * comparing by more sophisticated means: + * + * hitters.maxBy(hitter => hitter.avgHits); + * + */ + maxBy( + comparatorValueMapper: (value?: V, key?: K, iter?: /*this*/Iterable) => C, + comparator?: (valueA: C, valueB: C) => number + ): V; + + /** + * Returns the minimum value in this collection. If any values are + * comparatively equivalent, the first one found will be returned. + * + * The `comparator` is used in the same way as `Iterable#sort`. If it is not + * provided, the default comparator is `<`. + * + * When two values are considered equivalent, the first encountered will be + * returned. Otherwise, `min` will operate independent of the order of input + * as long as the comparator is commutative. The default comparator `<` is + * commutative *only* when types do not differ. + * + * If `comparator` returns 0 and either value is NaN, undefined, or null, + * that value will be returned. + */ + min(comparator?: (valueA: V, valueB: V) => number): V; + + /** + * Like `min`, but also accepts a `comparatorValueMapper` which allows for + * comparing by more sophisticated means: + * + * hitters.minBy(hitter => hitter.avgHits); + * + */ + minBy( + comparatorValueMapper: (value?: V, key?: K, iter?: /*this*/Iterable) => C, + comparator?: (valueA: C, valueB: C) => number + ): V; + + + // Comparison + + /** + * True if `iter` includes every value in this Iterable. + */ + isSubset(iter: Iterable): boolean; + isSubset(iter: Array): boolean; + + /** + * True if this Iterable includes every value in `iter`. + */ + isSuperset(iter: Iterable): boolean; + isSuperset(iter: Array): boolean; + + + /** + * Note: this is here as a convenience to work around an issue with + * TypeScript https://github.com/Microsoft/TypeScript/issues/285, but + * Iterable does not define `size`, instead `Seq` defines `size` as + * nullable number, and `Collection` defines `size` as always a number. + * + * @ignore + */ + size: number; + } + + + /** + * Collection is the abstract base class for concrete data structures. It + * cannot be constructed directly. + * + * Implementations should extend one of the subclasses, `Collection.Keyed`, + * `Collection.Indexed`, or `Collection.Set`. + */ + export module Collection { + + + /** + * `Collection` which represents key-value pairs. + */ + export module Keyed {} + + export interface Keyed extends Collection, Iterable.Keyed { + + /** + * Returns Seq.Keyed. + * @override + */ + toSeq(): Seq.Keyed; + } + + + /** + * `Collection` which represents ordered indexed values. + */ + export module Indexed {} + + export interface Indexed extends Collection, Iterable.Indexed { + + /** + * Returns Seq.Indexed. + * @override + */ + toSeq(): Seq.Indexed; + } + + + /** + * `Collection` which represents values, unassociated with keys or indices. + * + * `Collection.Set` implementations should guarantee value uniqueness. + */ + export module Set {} + + export interface Set extends Collection, Iterable.Set { + + /** + * Returns Seq.Set. + * @override + */ + toSeq(): Seq.Set; + } + + } + + export interface Collection extends Iterable { + + /** + * All collections maintain their current `size` as an integer. + */ + size: number; + } + + + /** + * ES6 Iterator. + * + * This is not part of the Immutable library, but a common interface used by + * many types in ES6 JavaScript. + * + * @ignore + */ + export interface Iterator { + next(): { value: T; done: boolean; } + } + +} + +export = Immutable +} diff --git a/typings/modules/immutable/typings.json b/typings/modules/immutable/typings.json new file mode 100644 index 0000000000..16d3848f1f --- /dev/null +++ b/typings/modules/immutable/typings.json @@ -0,0 +1,12 @@ +{ + "resolution": "main", + "tree": { + "src": "https://raw.githubusercontent.com/alitaheri/immutable-unambient/3e5ef14e1677e2db90770b8263be889b71c4d444/typings.json", + "raw": "registry:npm/immutable#3.7.6+20160411060006", + "main": "immutable.d.ts", + "version": "3.7.6", + "global": false, + "name": "immutable", + "type": "typings" + } +} diff --git a/typings/modules/redux-immutable/index.d.ts b/typings/modules/redux-immutable/index.d.ts new file mode 100644 index 0000000000..6ffdc6c056 --- /dev/null +++ b/typings/modules/redux-immutable/index.d.ts @@ -0,0 +1,75 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/andrew-w-ross/typings-redux/2e0b57e18c6240d17fde045573d74e649762437b/redux.d.ts +declare module '~redux-immutable~redux' { +module redux { + //This should be extended + export interface IAction { + type: string | number; + } + + export interface IActionGeneric extends IAction { + payload?: TPayload; + error?: Error; + meta?: any; + } + + export interface IReducer { + (state: TState, action: IAction): TState; + } + + export interface IReducerMap { + [key: string]: IReducerMap | IReducer + } + + export interface IDispatch { + (action: IAction): IAction; + } + + export interface IMiddlewareStore { + getState(): TState; + + dispatch: IDispatch; + } + + export interface IStore extends IMiddlewareStore { + subscribe(listener: (state: TState) => any): () => void; + + replaceReducer(nextReducer: IReducer): void; + } + + export interface IMiddleware { + (middlewareStore: IMiddlewareStore): (next: IDispatch) => IDispatch; + } + + export interface ICreateStoreGeneric { + (reducer: IReducer, initialState?: TState): IStore; + } + + export interface IStoreEnhancerGeneric { + (createStore: ICreateStoreGeneric): ICreateStoreGeneric; + } + + export function createStore(reducer: IReducer, initialState?: TState): IStore; + + export function combineReducers(reducers: IReducerMap): IReducer; + export function combineReducers(reducers: IReducerMap): IReducer; + + export function applyMiddleware(...middlewares: IMiddleware[]): IStoreEnhancerGeneric; + + export function bindActionCreators(actionCreators: TActionCreator, dispatch: IDispatch): TActionCreator; + + export function compose(...functions: { (arg: TArg): TArg }[]): (arg: TArg) => TArg; + export function compose(...functions: { (arg: any): any }[]): (arg: any) => any; +} + +export = redux; +} + +// Generated by typings +// Source: https://raw.githubusercontent.com/asvetliakov/typings-redux-immutable/138394e6fc7fcfed7be7cb950f55f74a69ddf319/index.d.ts +declare module 'redux-immutable' { +import {IReducer, IReducerMap} from '~redux-immutable~redux'; + +export function combineReducers(reducers: IReducerMap): IReducer; +export function combineReducers(reducers: IReducerMap): IReducer; +} diff --git a/typings/modules/redux-immutable/typings.json b/typings/modules/redux-immutable/typings.json new file mode 100644 index 0000000000..3d45646799 --- /dev/null +++ b/typings/modules/redux-immutable/typings.json @@ -0,0 +1,21 @@ +{ + "resolution": "main", + "tree": { + "src": "https://raw.githubusercontent.com/asvetliakov/typings-redux-immutable/138394e6fc7fcfed7be7cb950f55f74a69ddf319/typings.json", + "raw": "registry:npm/redux-immutable#3.0.6+20160310030142", + "main": "index.d.ts", + "global": false, + "dependencies": { + "redux": { + "src": "https://raw.githubusercontent.com/andrew-w-ross/typings-redux/2e0b57e18c6240d17fde045573d74e649762437b/typings.json", + "raw": "github:andrew-w-ross/typings-redux#2e0b57e18c6240d17fde045573d74e649762437b", + "main": "redux.d.ts", + "global": false, + "name": "redux", + "type": "typings" + } + }, + "name": "redux-immutable", + "type": "typings" + } +}