@bumble/stream v0.2.2
The Bumble Event Stream API
A simple API to work with events in the browser.
Compose callbacks using a familiar method chaining pattern.
BumbleStream
A configurable API with familiar methods that compose a callback function that can be passed to an event listener.
The attach function should return a clear function: a function that removes the listener.
Parameters
callback
Function Pass to an event listener.callback.direct
directCallback Use to directly configure a stream.
Examples
const listenToChromeEvent = (eventObject) => {
return BumbleStream(callback => {
// Add the composed callback to the event listeners.
eventObject.addListener(callback)
// Return a function to remove the callback
// from the event listener.
return () => eventObject.removeListener(callback)
})
}
function interval(time) {
const milliseconds = ms(time)
return BumbleStream(callback => {
// Create counter
let count = 0
// Start interval, pass count to callback, increment count
const id = setInterval(() => {
callback(count)
count++
}, milliseconds)
// Return function to stop interval
return () => clearInterval(id)
})
}
Returns BumbleStreamChain An object with familiar method names.
directCallback
Use to directly configure the BumbleStream. Used internally by the async method.
Type: Function
Parameters
payload
Object The value BumbleStream uses internally.
Examples
BumbleStream(({direct}) => {
// Immediately execute composed callback
direct({
result: 123,
args: [1, 2, 3],
use: true,
})
// Configure clearFn
return () => clear()
})
BumbleStreamChain
The BumbleStreamChain composes a callback using the familiar JS Array higher order function chain pattern.
Type: Object
map
Map changes result to the return value of mapFn.
Parameters
fn
Function The return value is passed to the next method.
Examples
interval('10s')
.map(() => 1)
.map((x) => x + 1)
.map((x) => {
console.log('This should be 2', x)
})
Returns BumbleStreamChain
forEach
Use for effects. ForEach does not pass its return value to the next function.
Parameters
fn
Function The return value is ignored.
Examples
interval('10s')
.map(() => 1)
.forEach((x) => {
const count = x + 1
console.log('This should be 2', count)
return count
})
.map((x) => {
console.log('This should be 1', x)
})
Returns methods BumbleStream methods object.
filter
Filter stops further mapping and returns the current value if the predicate returns false.
Parameters
predFn
Function Predicate.
Examples
interval('10s')
// This will skip the first 2 intervals
.filter((x) => x > 2)
.forEach((x) => {
console.log('This should be 3', x)
})
Returns Object BumbleStream methods object.
clear
Clear removes the event listener and continues down the map chain if the predicate returns true.
It calls the function returned by attachFn.
Parameters
predFn
Function? Predicate.
Examples
interval('10s')
// This will clear the interval on the 3rd time.
.clear((x) => x > 2)
.forEach(() => {
console.log('I will log three times.')
})
interval('10s')
// This will clear the interval immediately.
.clear()
.forEach(() => {
console.log('I will never log.')
})
const clear = interval('10s').clear
//This will clear the interval when something fails to load.
window.onerror = (e) => clear()
Returns Object BumbleStream methods object.
catch
Catch could cause a call to filter to be skipped. If this happens, the chain could begin to execute again.
Parameters
fn
Function Called when an error is encountered.
Examples
interval('10s')
.map(() => {
new Error('Boom!')
})
.catch((error) => {
console.log('The next line will say "Boom!"')
console.error(error.message)
})
Returns Object BumbleStream methods object.
await
Map a function that returns a Promise. Composes a new BumbleStream callback to pass to the returned Promise.then().
Parameters
asyncFn
Function Async Function.
Examples
listenTo(window, 'onload')
.map(() => 'https://www.google.com')
.await(fetch)
.map((response) => {
console.log(response.ok)
})
Returns Object The BumbleStreamChain object.
awaitFilter
Evaluates a function that returns a predicate Promise and stops further execution if the Promise resolves to false.
Parameters
asyncPredFn
function (any): boolean Async Predicate Function.
Examples
listenTo(window, 'onload')
.map(() => 'https://www.google.com')
.await.filter(fetch)
.map((response) => {
console.log(response.ok)
})
Returns Object The BumbleStreamChain object.
Bumble Stream Abstractions
Use common browser APIs with the BumbleStream API.
listenTo
Map responses to events. Uses BumbleStream internally.
Parameters
target
Object Either Chrome API Event or DOM Element.args
...any? Event string or additional arguments.
Examples
listenTo(chrome.runtime.onMessage).map(({greeting}) => {
if(greeting === 'hello') {
return ({greeting: 'goodbye'})
}
})
Returns Object Returns a BumbleStream object.
listenToChromeEvent
Listen to one or multiple events on a DOM Element.
Parameters
eventObject
Object A DOM Element.args
...any? Additional arguments to spread into Event.addListener().
Examples
const myDiv = document.querySelector('#mydiv')
listenToDomEvent(myDiv, 'click')
.map((event) => {})
const myDiv = document.querySelector('#mydiv')
listenToDomEvent(myDiv, ['click', 'keypress'])
.map((event) => {})
Returns Object Returns a BumbleStream object.
listenToDomEvent
Listen to one or multiple events on a DOM Element.
Parameters
target
Object A DOM Element.event
(string | Array<string>) An event string or an array of event strings.
Examples
const myDiv = document.querySelector('#mydiv')
listenToDomEvent(myDiv, 'click')
.map((event) => {})
const myDiv = document.querySelector('#mydiv')
listenToDomEvent(myDiv, ['click', 'keypress'])
.map((event) => {})
Returns Object Returns a BumbleStream object.
timeout
Thenable setTimeout. Uses Promise internally. The Promise resolves with undefined.
Parameters
Examples
timeout('10s').then(() => {
console.log('It has been 10 seconds!')
})
// Use argument defaults to pass
// values when the promise resolves.
timeout('10s').then((result = 5) => {
console.log('The result is', result)
}) // The result is 5
// Call resolve to resolve the promise immediately.
// The promise will resolve with the value you pass to it.
timeout('10s').then((result = 5) => {
console.log('The result is', result)
}).resolve(6) // The result is 6
Returns Object Returns a thenable object for chaining.
interval
Mappable setInterval. Uses BumbleStream internally.
Parameters
time
string Represents time between intervals.
Examples
interval('10s').forEach((x) => {
console.log(x, 'times')
})
Returns Object Returns a BumbleStreamChain object.
EventPromise
Resolves the first time the event occurs. The event listener is removed after the Promise resolves.
Parameters
args
...any
Examples
const eventPromise = EventPromise(chrome.someEvent)
eventPromise.then(() => {
// This will only be called
// the first time the event occurs.
})
Returns Promise<eventResults> Resolves with whatever the event passes the callback.
debounce
A Promise based debounce function that resolves with true only after the function has not been called for a certain amount of time. When the debouncer is called a second time, the first promise immediately resolves to false.
Parameters
fn
debounceCallback
(function (any): boolean | string | number) Callback for each time the debouncer is called.
Examples
// Debounce for 5ms
const debouncer = debounce(() => 5)
debouncer().then() // Resolves to false
debouncer().then() // Resolves to true
const debouncer = debounce(text => {
if (text === '') {
// Resolve both the pending promise
// and this one to false
return false
}
if (text.includes('\n')) {
// Resolve both promises to true
return true
} else {
// Resolve the prev promise to false
// And resolve the current promise in 5ms
return 5
}
})
debouncer('still typing') // Debounce
debouncer('') // Don't continue, no input
debouncer('done typing\n') // Resolve immediately
Returns function (any): TimeoutPromise<boolean> Returns a debouncer function.
throttle
Parameters
Examples
// Debounce for 5ms
const throttler = throttle(() => 5)
throttler().then() // Resolves to true after 5ms
throttler().then() // Resolves to false now
const throttler = throttle(text => {
if (text === '') {
// Resolve the previous to false now
// Resolve the current promise to false now
// Clear the timeout
return false
}
if (text.includes('\n')) {
// Resolve the previous promise to false now
// and the current promise to true now
// Clear the timeout
return true
} else {
// Resolve the previous promise to false now
// Resolve the current promise to true after 5ms
return 5
}
})
throttler('still typing') // Resolve every 5ms
throttler('') // Resolve both to false now
throttler('done typing\n') // Resolve both to true now
Returns function (any): TimeoutPromise<boolean> Returns a throttler function.
then
Add another function to the Promise chain.
Parameters
fn
Examples
timeout('5s').then(() => {
console.log('5 seconds have passed.')
})
Returns Object The methods object
catch
Catch a rejected promise.
Parameters
fn
Examples
timeout('5s')
.then(() => {
throw 'No, no quiero.'
})
.catch((error) => {
console.log('Just do it.')
})
Returns Object The methods object
clear
Stop the timer. The promise will remain pending, and can be resolved and rejected.
Examples
const timer = timeout('5s')
timer.clear()
timeoutId
The id returned by setTimeout
resolve
Clear the timeout and resolve the promise immediately with the parameter value.
Parameters
value
any The value to pass to resolve().
Examples
timeout('5s').resolve('Done!')
Returns undefined Returns undefined
reject
Clear the timeout and resolve the promise immediately with the parameter value.
Parameters
value
any The value to pass to reject().
Examples
timeout('5s').reject('No soup for you!')
Returns undefined Returns undefined
withPrev
Create a function that performs an operation on the first arguments from the current and previous calls. Note: The state maintained by this function means that it should be composed outside the final function.
Parameters
fn
function (a, b) CallbackinitialValue
Examples
// Set up withPrev to return true
// if previous and current arguments are not equal
const hasChanged = withPrev(not(isEqual))
// Previous call argument is undefined
hasChanged(5) // -> true
// Previous and current calls with same arguments
hasChanged(5) // -> true
hasChanged(5) // -> false
// Previous and current calls with different arguments
hasChanged(5) // -> true
hasChanged(6) // -> true
// Previous call argument is undefined
hasChanged(undefined) // -> false
Returns function (a) Calls the callback with both the first argument from the current and previous calls.
withPrevResult
Create a reducer function that performs an operation on the first current argument and previous result.
Parameters
fn
function (a, b) CallbackinitialValue
Examples
// Set up withPrev to return true
// if previous and current arguments are not equal
const sum = withPrevResult(add, 0)
// Add to initial value
sum(5) // -> 5
// Add to previous result
sum(6) // -> 11
Returns function (a) Calls the callback with both the current argument and the previous result
withPrevArgs
Create a function that performs an operation on the current and previous call arguments
Parameters
Examples
const logPrevAndCurrentArgs = withPrevArgs((prev, current) => {
console.log('previous args:', prev)
console.log('current args:', current)
}, [1, 2, 3])
listenTo(event)
.forEach(logPrevAndCurrentArgs)
// First event:
// previous args: [1, 2, 3]
// current args: [4, 5, 6]
// Second event:
// previous args: [4, 5, 6]
// current args: [7, 8, 9]
Returns Function Calls the callback with both the current and previous call arguments
composeHasChanged
Create a function that returns true if this call's argument is different than the last call. Maintains own state using a closure. Instantiate for each place you use it.
Parameters
fn
Examples
const hasChanged = createHasChanged()
Returns Function Instance of hasChanged