Francis2.1.0

Installation

NPM

npm i --save francis

Yarn

yarn add francis

CDN

<script type="text/javascript" src="https://unpkg.com/francis@2.1.0/dist/francis.min.js"></script>

Usage

Francis can be used by using either ES6 module syntax or normal CommonJS module syntax. Note that francis package is 100% tree shakeable so if you're using ES6 module syntax, modern bundlers with UglifyJS (such as Webpack) include only the used functions to your application!

// ES6 wildcard
import * as F from "francis"

// ES6 named imports
import {map, combineAsArray} from "francis"

// CommonJS
const F = require("francis")
const {map, combineAsArray} = require("francis")

Every operator in Francis is curried. Francis offers a built-in convenience function called pipe that allows to "chain" different operators in a type-safe manner:

import * as F from "francis"

F.pipe(
  F.interval(1000, "!"),
  F.scan("Francis", (s, x) => s + x),
  F.map(s => "Hello " + s.toUpperCase()),
  F.skip(2),
  F.take(2),
  F.onValue(console.log),
)

Functions

asEventStream
(observable: Observable<T>) => EventStream<T>

Restores the given observables type information. Fails if the observable's runtime type is not EventSTream.

Params

observable

Observable whose type information will be restored

Returns EventStream<T>

asProperty
(observable: Observable<T>) => Property<T>

Restores the given observables type information. Fails if the observable's runtime type is not Property.

Params

observable

Observable whose type information will be restored

Returns Property<T>

awaiting
(toWait: Observable<any>, obs: Observable<any>) => Property<boolean>
(toWait: Observable<any>) => (obs: Observable<any>) => Property<boolean>

Creates a Property that indicates whether observable is awaiting the other observable, i.e. has produced a value after the latest value from the other. This is handy for keeping track whether we are currently awaiting an AJAX response

Params

toWait

Observable whose value is waited after each event of obs

obs

Observable who is waiting toWait

Returns Property<boolean>

Example

const searchReq = F.map(toRequest, searchTextChange)
const searchRes = F.flatMapLatest(sendRequest, searchReq)
const isRequestPending = F.awaiting(searchRes, searchReq)
bus
() => Bus<ValueType>

Creates a new Bus instance.

Params

None

Returns Bus<ValueType>

constant
(val: ValueType) => Property<ValueType>

Creates a constant Property with the given value.

Params

val

Property's value

Returns Property<ValueType>

Example

const message = F.constant("Tsers!")
filter
(predicateOrProperty: Predicate<ValueType> | Property<any>, observable: In<ObsType, ValueType>) => Out<ObsType, ValueType>
(predicateOrProperty: Predicate<ValueType> | Property<any>) => (observable: In<ObsType, ValueType>) => Out<ObsType, ValueType>

Filters Observable's values using the given predicate function. Supports also filtering by Property - values are passed only when the property has truthy value.

Params

predicateOrProperty

Predicate function x => boolean or Property which is used to filter out value events

observable

Source observable

Returns Out<ObsType, ValueType>

An Observable whose values pass the given predicate.

Example

// Filtering by predicate function
F.pipe(F.fromArray([1, 2, 3, 4]),
 F.filter(x => x % 2 === 0),
 F.log("Result"))
// logs: 2, 4, <end>

// Filtering by Property
const isLoading: Property<boolean> = getLoading(document)
const clicksWhenNotLoading =
 F.pipe(F.fromEvents(document.getElementById("myButton"), "click"),
  F.filter(F.not(isLoading)))
first
(observable: In<ObsType, ValueType>) => Out<ObsType, ValueType>

Params

observable

Returns Out<ObsType, ValueType>

firstToCustomPromise
(ctor: PromiseConstructor, obs: Observable<ValueType>) => Promise<ValueType>
(ctor: PromiseConstructor) => (obs: Observable<ValueType>) => Promise<ValueType>

Works same as firstToPromise but offers way to use custom promise implementation instead.

Params

ctor

Constructor to the custom promise implementation

obs

Observable whose first event/error will be resolved to the promise

Returns Promise<ValueType>

See also

firstToPromisetoPromisetoCustomPromise

Example

import * as Promise from "bluebird"
const bluebirdPromise = F.firstToCustomPromise(Promise, F.later(100, "tsers!"))
firstToPromise
(obs: Observable<ValueType>) => Promise<ValueType>

Returns a Promise which will be resolved with the first event (or error) coming from an Observable. Uses global ES6 promise implementation to construct the promise.

Params

obs

Observable whose first event/error will be resolved to the promise

Returns Promise<ValueType>

See also

firstToCustomPromisetoPromisetoCustomPromise

Example

F.firstToPromise(F.sequentially(100, [1, 2, 3])).then(console.log)
// => 1
fromArray
(events: Array<ValueType | AnyEvent<ValueType>>) => EventStream<ValueType>

Creates an EventStream that produces events from the given array. Once the stream is activated, all events are emitted at the same tick. You can also send errors by using F.Error event in the given array.

Params

events

Events to be emitted to the subscribers

Returns EventStream<ValueType>

Example

const events = F.fromArray(["foo", new F.Error("fail"), "bar"])
fromBinder
(subscribe: Subscribe<ValueType>) => EventStream<ValueType>

When the last subscriber unsubscribes from this stream, subscriber function gets disposed and the (optional) disposer function gets called.

Params

subscribe

Subscriber function that is called at the stream activation

Returns EventStream<ValueType>

See also

Subscribe

Example

const events = F.fromBinder(sink => {
  sink("Hello")
  sink(new F.Error("oops"))
  const id = setTimeout(() => sink("world!"), 1000)
  return () => {
    clearTimeout(id)
  }
})
fromCallback
(f: AsyncCallback<ValueType>) => EventStream<ValueType>

Creates an EventStream from a function that accepts a callback. The function is supposed to call its callback just once.

Params

f

Function that gets called at the stream activation

Returns EventStream<ValueType>

Example

const resultStream = F.fromCallback(cb => {
  callSomeLongTask(result => {
    cb(processResult(result))
  })
})
fromEvent
(target: EventTarget, event: string, args: any[]) => EventStream<ValueType>
(target: EventTarget) => (event: string, args: any[]) => EventStream<ValueType>

Creates an EventStream from events on EventTarget or EventEmitter object, or an object that supports event listeners using on/off methods.

Params

target

EventTarget object whose events will be listened

event

Name of the listened event

args

Extra args passed to the addListener / on function

Returns EventStream<ValueType>

Example

const bubbleClicks = F.fromEvent(document.querySelector("#my-button"), "click")
const captureClicks = F.fromEvent(document.querySelector("#my-button"), "click", true)
fromNodeCallback
(f: AsyncNodeCallback<ValueType>) => EventStream<ValueType>

Behaves the same way as fromCallback, except that it expects the callback to be called in the Node.js convention: callback(error, data), where error is null if everything is fine.

Params

f

Function that gets called at the stream activation

Returns EventStream<ValueType>

See also

fromCallback

Example

const fileContent = F.fromNodeCallback(cb => {
  fs.readFile("myFile.txt", cb)
})
fromPoll
(interval: number, f: function) => EventStream<ValueType>
(interval: number) => (f: function) => EventStream<T>

Polls given function with given interval. Function should return plain values or F.Event objects. Polling occurs only when there are subscribers to the stream. Polling ends permanently when f returns F.End.

Params

interval

Polling interval in milliseconds

f

Function that will be called on each tick

Returns EventStream<ValueType>

Example

const nowEverySec = F.fromPoll(1000, () => Date.now())
fromPromise
(promise: Promise<ValueType>, abort: boolean) => EventStream<ValueType>

Returns a single-value EventStream from the given promise. If promise is rejected, an error event will be emitted instead of value.

Params

promise

Promise to follow

abort

Optional flag whether or not to call promise.abort if all subscribers have been removed from the created stream.

Returns EventStream<ValueType>

Example

const response = F.fromPromise(fetch("/my-api.json"))
interval
(period: number, value: ValueType) => EventStream<ValueType>
(period: number) => (value: ValueType) => EventStream<ValueType>

Repeats the single element indefinitely with the given interval

Params

period

Inverval in milliseconds

value

Repeated value

Returns EventStream<ValueType>

Example

const messages = F.inverval(1000, "Tsers!")
isObservable
(x: any) => boolean

Test whether the given value is Francis observable or not

Params

x

Value to be tested

Returns boolean

later
(delay: number, value: ValueType) => EventStream<ValueType>
(delay: number) => (value: ValueType) => EventStream<ValueType>

Creates a single-element stream that emits the given value after given delay.

Params

delay

Initial delay in milliseconds

value

Value to emit

Returns EventStream<ValueType>

Example

const message = F.later(10000, "Wait for it!")
map
(project: Projection<InType, OutType>, observable: In<ObsType, InType>) => Out<ObsType, OutType>
(project: Projection<InType, OutType>) => (observable: In<ObsType, InType>) => Out<ObsType, OutType>

Maps the Observable's values using the given projection function.

Params

project

Projection function in => out

observable

Source observable

Returns Out<ObsType, OutType>

An Observable having project function applied to its values

Example

F.pipe(F.fromArray([1, 2, 3]),
 F.map(x => x + 1),
 F.log("Result"))
// logs: 2, 3, 4, <end>
never
() => EventStream<ValueType>

Creates an EventStream that immediately ends

Params

None

Returns EventStream<ValueType>

Example

const emptyNum = F.never<number>()
once
(val: ValueType) => EventStream<ValueType>

Creates a single-event EventStream with the given value. Stream ends immediately after the value has been emitted.

Params

val

Stream's value

Returns EventStream<ValueType>

Example

const message = F.once("Tsers!")
repeat
(generator: Generator<ValueType>) => EventStream<ValueType>

Calls generator function which is expected to return an observable. When the spawned observable ends, the generator is called again to spawn a new observable. If generator returns a falsy value, the stream ends.

Params

generator

Generator function that's supposed to return an observable or null to end the stream

Returns EventStream<ValueType>

See also

Generator

Example

const events = F.repeat(i => i < 10 && F.fromArray([...Array(i).keys()].map(_ => i)))
repeatedly
(interval: number, events: Array<ValueType | AnyEvent<ValueType>>) => EventStream<ValueType>
(interval: number) => (events: Array<ValueType | AnyEvent<ValueType>>) => EventStream<ValueType>

Repeats given elements indefinitely with the given interval.

Params

interval

Interval in milliseconds

events

Event sequence to repeat indefinitely

Returns EventStream<ValueType>

Example

const lolbal = F.repeatedly(10, ["lol", "bal"])
scan
(seed: StateType, acc: Accum<StateType, ValueType>, observable: Observable<ValueType>) => Property<StateType>
(seed: StateType, acc: Accum<StateType, ValueType>) => (observable: Observable<ValueType>) => Property<StateType>
(seed: StateType) => (acc: Accum<StateType, ValueType>) => (observable: Observable<ValueType>) => Property<StateType>
(seed: StateType) => (acc: Accum<StateType, ValueType>, observable: Observable<ValueType>) => Property<StateType>

Scans EventStream or Property with given seed value and accumulator function, resulting to a Property. The seed value is used as an initial value for the result property.

Params

seed

Seed value to use for the accumulation

acc

Accumulator function (state, value) => state

observable

Source observable

Returns Property<StateType>

Example

F.pipe(F.fromArray(["!", "!"]),
 F.scan("Hello Francis", (state, value) => state + value),
 F.log("Greeting:"))
// logs: "Hello Francis", "Hello Francis!", "Hello Francis!!", <end>
sequentially
(interval: number, events: Array<ValueType | AnyEvent<ValueType>>) => EventStream<ValueType>
(interval: number) => (events: Array<ValueType | AnyEvent<ValueType>>) => EventStream<ValueType>

Creates an EventStream containing the given values emitted with the given interval.

Params

interval

Interval in milliseconds

events

Events to emit

Returns EventStream<ValueType>

Some shit

Example

const numEvery100ms = F.sequentially(100, [1, 2, 3])
startWith
(value: ValueType, observable: In<ObsType, ValueType>) => Out<ObsType, ValueType>
(value: ValueType) => (observable: In<ObsType, ValueType>) => Out<ObsType, ValueType>

For EventStream, this operator adds an extra event with the given value to the beginning of the stream.

Params

value

Value to be added to the stream / property's initial value

observable

Source observable

Returns Out<ObsType, ValueType>

Example

F.pipe(F.once(1),
 F.startWith(2),
 F.startWith(3),
 F.log("EventStream"))
// logs: 3, 2, 1, <end>

F.pipe(F.constant(1),
 F.startWith(2),
 F.startWith(3),
 F.log("Property"))
// logs: 1, <end>
toCustomPromise
(ctor: PromiseConstructor, obs: Observable<ValueType>) => Promise<ValueType>
(ctor: PromiseConstructor) => (obs: Observable<ValueType>) => Promise<ValueType>

Works same as toPromise but offers way to use custom promise implementation instead.

Params

ctor

Constructor to the custom promise implementation

obs

Observable whose last event/error will be resolved to the promise

Returns Promise<ValueType>

See also

toPromisefirstToPromisefirstToCustomPromise

Example

import * as Promise from "bluebird"
const bluebirdPromise = F.toCustomPromise(Promise, F.later(100, "tsers!"))
toPromise
(obs: Observable<ValueType>) => Promise<ValueType>

Returns a Promise which will be resolved with the last event (or first error) coming from an Observable. Uses global ES6 promise implementation to construct the promise.

Params

obs

Observable whose last event/error will be resolved to the promise

Returns Promise<ValueType>

See also

toCustomPromisefirstToPromisefirstToCustomPromise

Example

F.firstToPromise(F.sequentially(100, [1, 2, 3])).then(console.log)
// => 3

Installation

Usage

Functions

asEventStreamasPropertyawaitingbusconstantfilterfirstfirstToCustomPromisefirstToPromisefromArrayfromBinderfromCallbackfromEventfromNodeCallbackfromPollfromPromiseintervalisObservablelatermapneveroncerepeatrepeatedlyscansequentiallystartWithtoCustomPromisetoPromiseNo matches