-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy path3-class.js
50 lines (46 loc) · 1.17 KB
/
3-class.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
'use strict';
const logable = fields => {
class Logable {
constructor(data) {
this.values = data;
}
toString() {
let result = this.constructor.name + '\t';
for (const key in fields) {
result += this.values[key] + '\t';
}
return result;
}
}
for (const key in fields) {
Object.defineProperty(Logable.prototype, key, {
get() {
console.log('Reading key:', key);
return this.values[key];
},
set(value) {
console.log('Writing key:', key, value);
const def = fields[key];
const valid = (
typeof value === def.type &&
def.validate(value)
);
if (valid) this.values[key] = value;
else console.log('Validation failed:', key, value);
}
});
}
return Logable;
};
// Usage
const Person = logable({
name: { type: 'string', validate: name => name.length > 0 },
born: { type: 'number', validate: born => !(born % 1) },
});
const p1 = new Person({ name: 'Marcus Aurelius', born: 121 });
console.log(p1.toString());
p1.born = 1923;
console.log(p1.born);
p1.born = 100.5;
p1.name = 'Victor Glushkov';
console.log(p1.toString());