-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
65 lines (58 loc) · 1.44 KB
/
utils.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 xtend = require('xtend')
function addToJSON (error) {
error.toJSON || (error.toJSON = function () {
return {
message: this.message,
code: this.code || -32600,
data: this.data
}
})
return error
}
function cid () {
return Date.now() + Math.random()
}
function jsonrpc2 (...args) {
var jsonrpc = '2.0'
var id = null
return xtend({ jsonrpc, id }, ...args)
}
jsonrpc2.request = (method, params, ...args) => (
jsonrpc2({ method, params, id: cid() }, ...args)
)
jsonrpc2.response = (result, ...args) => (
jsonrpc2({ result }, ...args)
)
jsonrpc2.error = (error, ...args) => (
jsonrpc2({ error }, ...args)
)
function isNull (x) { return x === null }
function isBoolean (x) { return typeof x === 'boolean' }
function isString (x) { return typeof x === 'string' }
function isNumber (x) { return typeof x === 'number' && isFinite(x) }
function isArray (x) { return Array.isArray(x) }
function isObject (x) { return typeof x === 'object' && !isArray(x) && !isNull(x) }
function testType (target, prop, types) {
var TYPES = {
'null': isNull,
'boolean': isBoolean,
'number': isNumber,
'string': isString,
'array': isArray,
'object': isObject
}
return (
target == null
? !1
: !![].concat(types).some(type => TYPES[type](target[prop]))
)
}
function compose (...fs) {
return fs.reduce((a, b) => x => b(a(x)), x => (x))
}
module.exports = {
addToJSON,
jsonrpc2,
testType,
compose
}