/**
* Module Dependencies
*/
var assign = require('object-assign')
var isObject = require('./is-object')
var isError = require('./is-error')
/**
* Export `fold`
*/
module.exports = fold
/**
* Fold the arguments into an action
*/
function fold (action) {
if (action.length === 1 && isObject(action[0])) {
action[0].payload = action[0].payload || {}
return isError(action[0].payload)
? assign(action[0], error(action[0].payload))
: action[0]
} else {
return action.reduce(folder, { payload: {} })
}
}
function folder (action, value) {
if (typeof value === 'string' && !action.type) {
action.type = value
} else if (isObject(value)) {
action.payload = assign(action.payload || {}, value)
} else if (isError(value)) {
action = assign(action, error(value))
} else {
action.payload = value
}
return action
}
/**
* Create an object from an error
*/
function error (err) {
return {
error: true,
payload: {
message: err.message,
stack: err.stack,
name: err.name,
code: err.code
}
}
}
|