-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
58 lines (46 loc) · 1.16 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
var ObjectId = require('bson').ObjectId
ObjectId.prototype.equals = function (oidB) {
return equals(this, oidB)
}
var objIdPattern = /^[0-9a-fA-F]{24}$/;
var isValid = function (alleged) {
return (Boolean(alleged) && !Array.isArray(alleged) && objIdPattern.test(String(alleged)))
}
var equals = function (oidA, oidB) {
// curried
if (arguments.length === 1) {
return function (oidB) {
return equals(oidA, oidB)
}
}
if (oidA === oidB) { return true; }
if (!isValid(oidA) || !isValid(oidB)) { return false }
return (String(oidA) === String(oidB))
return false;
}
var tryParse = function (oid, out, as) {
if (!isValid(oid)) { return false }
try {
out[as] = Id(oid)
return true
} catch (e) {
return false
}
}
function Id(id) {
if (id instanceof ObjectId) { return id }
if (arguments.length === 0) {
return new ObjectId()
}
id = String(id)
if (isValid(id)) {
return new ObjectId(id)
} else {
throw new Error('Invalid ObjectId: ' + id)
}
}
module.exports = Id;
module.exports.constructor = ObjectId;
module.exports.tryParse = tryParse;
module.exports.equals = equals;
module.exports.isValid = isValid;