-
-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(transducers): add toggle() xform
- Loading branch information
1 parent
f644ecd
commit b5c744e
Showing
3 changed files
with
77 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import { Reducer, Transducer } from "../api"; | ||
import { iterator1 } from "../iterator"; | ||
|
||
/** | ||
* Stateful transducer which accepts any input and flips between given | ||
* `on` / `off` values for every value received. The `initial` state can | ||
* be optionally provided (default: false) and must be given if used as | ||
* an iterator. | ||
* | ||
* ``` | ||
* [...toggle(1, 0, false, [1, 2, 3, 4])] | ||
* // [ 1, 0, 1, 0 ] | ||
* | ||
* [...tx.toggle("on", "off", true, [1, 2, 3, 4])] | ||
* // [ 'off', 'on', 'off', 'on' ] | ||
* ``` | ||
* @param on result for "on" state | ||
* @param off result for "off" state | ||
* @param initial initial state | ||
*/ | ||
export function toggle<T>(on: T, off: T, initial?: boolean): Transducer<any, T>; | ||
export function toggle<T>( | ||
on: T, | ||
off: T, | ||
initial: boolean, | ||
src: Iterable<any> | ||
): IterableIterator<boolean>; | ||
export function toggle<T>( | ||
on: T, | ||
off: T, | ||
initial = false, | ||
src?: Iterable<any> | ||
): any { | ||
return src | ||
? iterator1(toggle(on, off, initial), src) | ||
: ([init, complete, reduce]: Reducer<any, T>) => { | ||
let state = initial; | ||
return [ | ||
init, | ||
complete, | ||
(acc) => reduce(acc, (state = !state) ? on : off) | ||
]; | ||
}; | ||
} |