Skip to content

Commit 5c10132

Browse files
committed
Add prototype and class impelentation
1 parent ebeb8f0 commit 5c10132

2 files changed

Lines changed: 100 additions & 0 deletions

File tree

JavaScript/2-prototype.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
'use strict';
2+
3+
const logable = fields => {
4+
5+
function Logable(data) {
6+
this.values = data;
7+
}
8+
9+
for (const key in fields) {
10+
Object.defineProperty(Logable.prototype, key, {
11+
get: function() {
12+
console.log('Reading key:', key);
13+
return this.values[key];
14+
},
15+
set: function(value) {
16+
console.log('Writing key:', key, value);
17+
const def = fields[key];
18+
const valid = (
19+
typeof(value) === def.type &&
20+
def.validate(value)
21+
);
22+
if (valid) this.values[key] = value;
23+
else console.log('Validation failed:', key, value);
24+
}
25+
});
26+
}
27+
28+
Logable.prototype.toString = function() {
29+
let result = this.constructor.name + ': ';
30+
for (const key in fields) {
31+
result += this.values[key] + ' ';
32+
}
33+
return result;
34+
};
35+
36+
return Logable;
37+
38+
};
39+
40+
// Usage
41+
42+
const Person = logable({
43+
name: { type: 'string', validate: name => name.length > 0 },
44+
born: { type: 'number', validate: born => !(born % 1) },
45+
});
46+
47+
const p1 = new Person({ name: 'Marcus Aurelius', born: 121 });
48+
console.log(p1.toString());
49+
p1.born = 1923;
50+
console.log(p1.born);
51+
p1.born = 100.5;
52+
p1.name = 'Victor Glushkov';
53+
console.log(p1.toString());

JavaScript/3-class.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
'use strict';
2+
3+
const logable = fields => class Logable {
4+
constructor(data) {
5+
this.values = data;
6+
for (const key in fields) {
7+
Object.defineProperty(Logable.prototype, key, {
8+
get: function() {
9+
console.log('Reading key:', key);
10+
return this.values[key];
11+
},
12+
set: function(value) {
13+
console.log('Writing key:', key, value);
14+
const def = fields[key];
15+
const valid = (
16+
typeof(value) === def.type &&
17+
def.validate(value)
18+
);
19+
if (valid) this.values[key] = value;
20+
else console.log('Validation failed:', key, value);
21+
}
22+
});
23+
}
24+
}
25+
toString() {
26+
let result = this.constructor.name + '\t';
27+
for (const key in fields) {
28+
result += this.values[key] + '\t';
29+
}
30+
return result;
31+
}
32+
};
33+
34+
// Usage
35+
36+
const Person = logable({
37+
name: { type: 'string', validate: name => name.length > 0 },
38+
born: { type: 'number', validate: born => !(born % 1) },
39+
});
40+
41+
const p1 = new Person({ name: 'Marcus Aurelius', born: 121 });
42+
console.log(p1.toString());
43+
p1.born = 1923;
44+
console.log(p1.born);
45+
p1.born = 100.5;
46+
p1.name = 'Victor Glushkov';
47+
console.log(p1.toString());

0 commit comments

Comments
 (0)