Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  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() {
  9. console.log('Reading key:', key);
  10. return this.values[key];
  11. },
  12. set(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. configurable: true
  23. });
  24. }
  25. }
  26.  
  27. toString() {
  28. let result = this.constructor.name + '\t';
  29. for (const key in fields) {
  30. result += this.values[key] + '\t';
  31. }
  32. return result;
  33. }
  34. };
  35.  
  36. // Usage
  37.  
  38. const Person = logable({
  39. name: { type: 'string', validate: name => name.length > 0 },
  40. born: { type: 'number', validate: born => !(born % 1) },
  41. });
  42.  
  43. const p1 = new Person({ name: 'Marcus Aurelius', born: 121 });
  44. console.log(p1.toString());
  45. p1.born = 1923;
  46. console.log(p1.born);
  47. p1.born = 100.5;
  48. p1.name = 'Victor Glushkov';
  49. console.log(p1.toString());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement