-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuniq-items.js
66 lines (50 loc) · 1.27 KB
/
uniq-items.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
66
import {Type, UniqRule} from 'typed-props'
class UniqItems extends UniqRule {
static ruleName = 'uniqueItems'
static format(key = 'id') {
return {key}
}
static check(items, {key}) {
const keys = new Set()
const issues = []
items.forEach((item, i) => {
const id = item[key]
if (! keys.has(id)) {
const issue = {
rule: this.ruleName,
path: [i],
details: {
reason: 'duplicate',
keyProp: key,
key: id,
},
}
issues.push(issue)
}
keys.set(id)
})
return issues
}
}
class MyType extends Type {
static uniqueItems(...args) {
const checks = UniqItems.create([], UniqItems.format(...args))
return new this(checks)
}
uniqueItems(...args) {
const checks = UniqItems.create(this.getChecks(), UniqItems.format(...args))
return new this.constructor(checks)
}
}
const type = MyType.object
.instanceOf(Array)
.uniqueItems('id')
const value = [
{id: 1},
{id: 2},
{id: 2}, // Duplicate
]
const issues = Type.check(value, type)
// issues array contain single issue for last element:
// {path: [2], rule: 'uniqueItems', details: {reason: 'duplicate', keyProp: 'id', key: 2}}
console.log(issues)