Repository navigation
Expand file tree
/
Copy pathvalidation.js
More file actions
52 lines (45 loc) · 1.43 KB
/
Copy pathvalidation.js
File metadata and controls
52 lines (45 loc) · 1.43 KB
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
const { curry, curryN } = require("./core")
const { split, init, map, is } = require("./utils")
// handleType -> ({signature: String, f: (*, ...) -> b, validations: { String: * -> Bool }, args: [*] }) -> String -> Number -> void
const handleType = curry(
({ signature, f, validations, args }, expectedType, i) => {
const isValid = validations[expectedType]
const param = args[i]
if (!isValid(param)) {
throw new Error(
`the function ${f.name}
${f.toString()}
does not comply with the signature
"${signature}"
in param number ${i + 1}
with value "${args[i]}"
and type ${typeof args[i]}
`
)
}
}
)
const getBetween = curry((start, end, s) => {
return s.substring(s.lastIndexOf(start) + 1, s.lastIndexOf(end))
})
const getValidationTypes = signature => {
const validations = map(s => s.trim(), split("->", signature))
return init(validations)
}
// String -> (*, -> ... -> *) -> { String: (* -> Bool)} -> (* -> *)
const define = (signature, f, validations) => {
return curryN(f.length, (...args) => {
const paramTypes = getValidationTypes(signature)
paramTypes.forEach(handleType({ signature, f, validations, args }))
return f(...args)
})
}
// hasProps :: [String] -> Bool
const hasProps = curry((props, obj) =>
props.every(key => obj[key] !== undefined)
)
module.exports = {
define,
is,
hasProps
}