UNPKG

8.98 kBMarkdownView Raw
1```
2________________________________
3___ |/ /_ __ \_ ___/__ __/
4__ /|_/ /_ / / /____ \__ /
5_ / / / / /_/ /____/ /_ /
6/_/ /_/ \____/______/ /_/
7```
8
9# Monadic streams for reactive programming
10
11[![Build Status](https://travis-ci.org/cujojs/most.svg?branch=master)](https://travis-ci.org/cujojs/most)
12[![Join the chat at https://gitter.im/cujojs/most](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/cujojs/most?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
13
14Most.js is a toolkit for reactive programming. It helps you compose asynchronous operations on streams of values and events, e.g. WebSocket messages, DOM events, etc, and on time-varying values, e.g. the "current value" of an <input>, without many of the hazards of side effects and mutable shared state.
15
16It features an ultra-high performance, low overhead architecture, APIs for easily creating event streams from existing sources, like DOM events, and a small but powerful set of operations for merging, filtering, transforming, and reducing event streams and time-varying values.
17
18## Learn more
19
20* [API docs](docs/api.md)
21* [Recipes](https://github.com/cujojs/most/wiki/Recipes)
22* [Examples](https://github.com/mostjs/examples)
23* [Get it](#get-it)
24* [Core & Community Packages](PACKAGES.md)
25
26## Simple example
27
28Here's a simple program that displays the result of adding two inputs. The result is reactive and updates whenever *either* input changes.
29
30First, the HTML fragment for the inputs and a place to display the live result:
31
32```html
33<form>
34 <input class="x"> + <input class="y"> = <span class="result"></span>
35</form>
36```
37
38Using most.js to make it reactive:
39
40```es6
41import { fromEvent, combine } from 'most'
42
43const xInput = document.querySelector('input.x')
44const yInput = document.querySelector('input.y')
45const resultNode = document.querySelector('.result')
46
47const add = (x, y) => x + y
48
49const toNumber = e => Number(e.target.value)
50
51const renderResult = result => {
52 resultNode.textContent = result
53}
54
55export const main = () => {
56 // x represents the current value of xInput
57 const x = fromEvent('input', xInput).map(toNumber)
58
59 // y represents the current value of yInput
60 const y = fromEvent('input', yInput).map(toNumber)
61
62 // result is the live current value of adding x and y
63 const result = combine(add, x, y)
64
65 // Observe the result value by rendering it to the resultNode
66 result.observe(renderResult)
67}
68```
69
70## More examples
71
72You can find the example above and others in the [Examples repo](https://github.com/mostjs/examples).
73
74## Get it
75
76### Requirements
77
78Most requires ES6 `Promise`. You can use your favorite polyfill, such as [creed](https://github.com/briancavalier/creed), [when](https://github.com/cujojs/when/blob/master/docs/es6-promise-shim.md), [bluebird](http://bluebirdjs.com/docs/getting-started.html), [es6-promise](https://github.com/jakearchibald/es6-promise), etc. Using a polyfill can be especially beneficial on platforms that don't yet have good unhandled rejection reporting capabilities.
79
80### Install
81
82As a module:
83
84```
85npm install --save most
86```
87
88```es6
89// ES6
90import { /* functions */ } from 'most'
91// or
92import * as most from 'most'
93```
94
95```js
96// ES5
97var most = require('most')
98```
99
100As `window.most`:
101
102```
103bower install --save most
104```
105
106```html
107<script src="most/dist/most.js"></script>
108```
109
110As a library via cdn :
111
112```html
113<!-- unminified -->
114<script src="https://unpkg.com/most/dist/most.js"></script>
115```
116
117```html
118<!-- minified -->
119<script src="https://unpkg.com/most/dist/most.min.js"></script>
120```
121
122### Typescript support
123
124Most.js works with typescript out of the box as it provides [local typings](https://github.com/cujojs/most/blob/master/type-definitions/most.d.ts) that will be read when you import Most.js in your code. You do not need to manually link an external `d.ts` file in your tsconfig.
125
126Most.js has a dependency on native Promises so a type definition for Promise must be available in your setup:
127 - If your tsconfig is targeting ES6, you do not need to do anything as typescript will include a definition for Promise by default.
128 - If your tsconfig is targeting ES5, you need to provide your own Promise definition. For instance [es6shim.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/es6-shim/es6-shim.d.ts)
129
130## Interoperability
131
132<a href="http://promises-aplus.github.com/promises-spec"><img width="82" height="82" alt="Promises/A+" src="https://promisesaplus.com/assets/logo-small.png"></a>
133<a href="https://github.com/fantasyland/fantasy-land"><img width="82" height="82" alt="Fantasy Land" src="https://raw.github.com/puffnfresh/fantasy-land/master/logo.png"></a>
134<a href="https://github.com/rpominov/static-land"><img width="131" height="82" src="https://raw.githubusercontent.com/rpominov/static-land/master/logo/logo.png" /></a>
135
136Most.js streams are [compatible with Promises/A+ and ES6 Promises](promises). They also implement [Fantasy Land](https://github.com/fantasyland/fantasy-land) and [Static Land](https://github.com/rpominov/static-land) (via [`most-static-land`](https://github.com/mostjs-community/most-static-land)) `Monoid`, `Functor`, `Applicative`, and `Monad`.
137
138## Reactive Programming
139
140[Reactive programming](https://github.com/cujojs/most/wiki/Concepts) is an important concept that provides a lot of advantages: it naturally handles asynchrony and provides a model for dealing with complex data and time flow while also lessening the need to resort to shared mutable state. It has many applications: interactive UIs and animation, client-server communication, robotics, IoT, sensor networks, etc.
141
142## Why most.js for Reactive Programming?
143
144### High performance
145
146A primary focus of most.js is performance. The [perf test results](test/perf) indicate that it is achieving its goals in this area. Our hope is that by publishing those numbers, and showing what is possible, other libs will improve as well.
147
148### Modular architecture
149
150Most.js is highly modularized. It's internal Stream/Source/Sink architecture and APIs are simple, concise, and well defined. Combinators are implemented entirely in terms of that API, and don't need to use any private details. This makes it easy to implement new combinators externally (ie in contrib repos, for example) while also guaranteeing they can still be high performance.
151
152### Simplicity
153
154Aside from making combinators less "obviously correct", complexity can also lead to performace and maintainability issues. We felt a simple implementation would lead to a more stable and performant lib overall.
155
156### Integration
157
158Most.js integrates with language features, such as promises, iterators, generators, and *asynchronous* generators.
159
160#### Promises
161
162Promises are a natural compliment to asynchronous reactive streams. The relationship between synchronous "sequence" and "value" is clear, and the asynchronous analogue needs to be clear, too. By taking the notion of a sequence and a value and lifting them into the asynchronous world, it seems clear that reducing an asynchronous sequence should produce a promise. Hence, most.js uses promises when a single value is the natural synchronous analogue.
163
164Most.js interoperates seamlessly with ES6 and Promises/A+ promises. For example, reducing a stream returns a promise for the final result:
165
166```es6
167import { from } from 'most'
168// After 1 second, logs 10
169from([1, 2, 3, 4])
170 .delay(1000)
171 .reduce((result, y) => result + y, 0)
172 .then(result => console.log(result))
173```
174
175You can also create a stream from a promise:
176
177```es6
178import { fromPromise } from 'most'
179// Logs "hello"
180fromPromise(Promise.resolve('hello'))
181 .observe(message => console.log(message))
182```
183
184#### Generators
185
186Conceptually, [generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) allow you to write a function that acts like an iterable sequence. Generators support the standard ES6 [Iterator interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol), so they can be iterated over using ES6 standard `for of` or the iterator's `next()` API.
187
188Most.js interoperates with ES6 generators and iterators. For example, you can create an event stream from any ES6 iterable:
189
190```es6
191import { from } from 'most'
192
193function* allTheIntegers() {
194 let i=0
195 while(true) {
196 yield i++
197 }
198}
199
200// Log the first 100 integers
201from(allTheIntegers())
202 .take(100)
203 .observe(x => console.log(x))
204```
205
206#### Asynchronous Generators
207
208You can also create an event stream from an *asynchronous generator*, a generator that yields promises:
209
210```es6
211import { generate } from 'most'
212
213function* allTheIntegers(interval) {
214 let i=0
215 while(true) {
216 yield delayPromise(interval, i++)
217 }
218}
219
220const delayPromise = (ms, value) =>
221 new Promise(resolve => setTimeout(() => resolve(value), ms))
222
223// Log the first 100 integers, at 1 second intervals
224generate(allTheIntegers, 1000)
225 .take(100)
226 .observe(x => console.log(x))
227```