-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
86 lines (73 loc) · 2.43 KB
/
Copy pathindex.js
File metadata and controls
86 lines (73 loc) · 2.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"use strict";
// Require Third-party Dependencies
const is = require("@slimio/is");
/**
* @function getObjectType
* @param {any} value any javascript value
* @returns {string}
*/
function getObjectType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
/**
* @function seal
* @param {!object} target target
* @returns {object}
*
* @throws {TypeError}
*/
function seal(target) {
if (!is.plainObject(target)) {
throw new TypeError("target must be a plain Object");
}
if (Object.isFrozen(target)) {
throw new Error("Unable to handle freezed Object");
}
const ref = Object.isSealed(target) ? target : Object.seal(target);
return new Proxy(ref, {
get(target, propertyKey) {
if (!Reflect.has(ref, propertyKey)) {
throw new Error(`Unable to found propertyKey ${propertyKey} on ${getObjectType(target)}`);
}
return ref[propertyKey];
},
set(target, propertyKey, propertyValue) {
if (!Reflect.has(ref, propertyKey)) {
throw new Error(`Unable to found propertyKey ${propertyKey} on ${getObjectType(target)}`);
}
const propertyType = getObjectType(propertyValue);
const currType = getObjectType(ref[propertyKey]);
if (propertyType !== currType) {
throw new TypeError(`Unable to cast ${currType} to ${propertyType} for propertyKey ${propertyKey}`);
}
Reflect.set(ref, propertyKey, propertyValue);
return true;
}
});
}
/**
* @function freezedProperty
* @description Define a private (non-enumable, non-configurable) property on the target
* @param {!object} target target object
* @param {!string | symbol} propertyKey The name of the property we want to define in target
* @param {*} [value=null] The property value
* @returns {void}
*
* @throws {Error}
* @throws {TypeError}
*/
function freezedProperty(target, propertyKey, value = null) {
if (!is.symbol(propertyKey) && !is.string(propertyKey)) {
throw new TypeError("propertyKey must be a symbol or a string");
}
const ok = Reflect.defineProperty(target, propertyKey, {
value,
enumerable: false,
configurable: false,
writable: false
});
if (!ok) {
throw new Error(`Unable to define propertyKey ${propertyKey}`);
}
}
module.exports = { seal, freezedProperty };