-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
65 lines (44 loc) · 1.28 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
const R = require('ramda')
const PropsCheck = require('props-check')
const ERR = {
DNE : (name) => `Dependency does not exist ${name}`
, SUGGEST : (suggestions) => `\nDid you mean one of these: ${suggestions}`
}
const throwErrorIfNoSpec = R.when(
R.either(R.isEmpty, R.isNil)
, () => { throw new Error('Spec object is required') }
)
const throwError = R.curry((spec, name) => R.ifElse(
R.isEmpty
, () => { throw new Error(ERR.DNE(name))}
, (suggestions) => { throw new Error(ERR.DNE(name) + ERR.SUGGEST(suggestions)) }
))
const checkProps = R.curry((spec, name) => R.compose(
throwError(spec, name)
, R.prop(name)
, PropsCheck(spec)
, R.objOf(R.__, null)
)(name))
const throwErrorIfNotInSpec = (spec) => R.when(
R.compose(R.not, R.has(R.__, spec))
, checkProps(spec)
)
// Yaldic :: Spec -> Yaldic
const Yaldic = (spec) => {
const instances = {}
// createInstance :: String -> a
const createInstance = (name) => {
instances[name] = spec[name]()
return instances[name]
}
// getInstance :: String -> a
const getInstance = (name) => {
throwErrorIfNotInSpec(spec)(name)
if (instances[name])
return instances[name]
return createInstance(name)
}
throwErrorIfNoSpec(spec)
return { get : getInstance }
}
module.exports = Yaldic