-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
65 lines (55 loc) · 1.72 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var assert = require('assert')
var extend = require('xtend/mutable')
/**
* Create the `send` function by calling `sendAction`
*
* @name sendAction
* @param object options
* @param object options.state
* @param object options.actions
* @param function options.onChange
* @return {send}
*/
module.exports = function sendAction (options) {
assert(options && typeof options === 'object', 'options object is required')
assert(options.state && typeof options.state === 'object', 'options.state object is required')
assert(options.actions && typeof options.actions === 'object', 'options.actions object is required')
assert(options.onChange && typeof options.onChange === 'function', 'options.onChange function is required')
var state = options.state
var actions = options.actions
var onChange = options.onChange
/**
* Trigger actions with the `send` function
*
* @name send
* @param string actionName
* @param {*} data
* @return {null|object|Promise<(null|object)>}
*/
function send (actionName, data) {
var action = actions[actionName]
assert(action, 'action "' + actionName + '" not available')
assert(typeof action === 'function', 'action "' + actionName + '" must be a function')
var result = action(state, data)
if (!result) return
if (result.then) {
return result.then((newState) => {
if (newState) {
return change(newState, actionName)
}
})
}
return change(result, actionName)
}
function change (newState, actionName) {
extend(state, newState)
onChange(state, actionName)
return state
}
function setAction (actionName, action) {
actions[actionName] = action
}
send.action = setAction
send.state = state
return send
}