Skip to content

Commit

Permalink
Document moment
Browse files Browse the repository at this point in the history
  • Loading branch information
paldepind committed Jun 29, 2019
1 parent b962891 commit a3c45b4
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,66 @@ occurrence in `source` the function is applied to the current value of
the behaviour and the value of the occurrence, the returned value
becomes the next value of the behavior.

#### `moment<A>(f: (sample: <B>(b: Behavior<B>) => B) => A): Behavior<A>``

Constructs a behavior based on a function. At any point in time the value of
the behavior is equal to the result of applying the function to a sampling
function. The sampling function returns the current value of any behavior.

`moment` is a powerful function that can do many things and sometimes it can do
them in a way that is a lot easier than other functions. A typical usage of
`moment` has the following form.

```js
moment((at) => {
...
})
```

Above, the `at` function above can be applied to any behavior and it will
return the current value of the behavior. The following example adds together
the values of three behaviors of numbers.

```js
const sum = moment((at) => at(aBeh) + at(bBeh) + at(cBeh));
```

The above could also be achieved with `lift`. However, `moment` can do many
things that `lift` can't. For instance, `moment` can give better performance
when used with a function which dynamically switches which behaviors it depends
on.

```js
const showTime = moment((at) =>
at(timerActive) === true
? "Time left: " + timeToString(time)
: "Timer not active";
);
```

The `showTime` behavior only depends on `time` when `timerActive` is `true`.
When using `moment` the implementation can figure out when `time` is and isn't
used and it knows that there is no need to recompute `showTime` if `time`
changes while `timerActive` is `false`.

`moment` can also be very useful with behaviors nested inside behaviors. If
`persons` is a behavior of an array of persons and is of the type `Behavior<{
age: Behavior<number>, name: string }[]>` then the following code creates a
behavior that at any time is equal to the name of the first person in the array
whose age is greater than 20.

```js
const first = moment((at) => {
for (const person of at(persons)) {
if (at(person.age) > 20) {
return person.name;
}
}
});
```

Achieving something similar without `moment` would be quite tricky.

#### `time: Behavior<Time>`

A behavior whose value is the number of milliseconds elapsed since UNIX epoch.
Expand Down

0 comments on commit a3c45b4

Please sign in to comment.