Advertisement
valchak

Repository

Mar 15th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Repository {
  2.     constructor(props) {
  3.         this.props = props;
  4.         this.data = new Map();
  5.         this._id = 0;
  6.     }
  7.  
  8.     get count() {
  9.         return this.data.size;
  10.     }
  11.  
  12.     get id() {
  13.         return this._id++;
  14.     }
  15.  
  16.     add(entity) {
  17.         for (let property in this.props) {
  18.  
  19.             if (!entity.hasOwnProperty(property)) {
  20.                 throw new Error('Property ' + property + ' is missing from the entity!')
  21.             }
  22.  
  23.             let propsPropertyType = this.props[property];
  24.             let entityPropertyType = typeof entity[property];
  25.             if (propsPropertyType !== entityPropertyType) {
  26.                 throw new TypeError('Property ' + property + ' is of incorrect type!')
  27.             }
  28.         }
  29.  
  30.         let currentId = this.id;
  31.         this.data.set(currentId, entity);
  32.         return currentId
  33.     }
  34.  
  35.     get(idToReturn) {
  36.         if (!this.data.has(idToReturn)) {
  37.           throw new Error('Entity with id: ' + idToReturn + ' does not exist!');
  38.         }
  39.         return this.data.get(idToReturn);
  40.     }
  41.  
  42.     update(id, newEntity) {
  43.         if (!this.data.has(id)) {
  44.             throw new Error('Entity with id: ' + id + ' does not exist!')
  45.         }
  46.  
  47.         for (let property in this.props) {
  48.             if (!newEntity.hasOwnProperty(property)) {
  49.                 throw new Error('Property ' + property + ' is missing from the entity!')
  50.             }
  51.  
  52.             let propsPropertyType = this.props[property];
  53.             let entityPropertyType = typeof newEntity[property];
  54.             if (propsPropertyType !== entityPropertyType) {
  55.                 throw new TypeError('Property ' + property + ' is of incorrect type!')
  56.             }
  57.         }
  58.         this.data.set(id, newEntity);
  59.     }
  60.  
  61.     del(idToRemove) {
  62.         if (!this.data.has(idToRemove)) {
  63.             let result = 'Entity with id: ' + idToRemove + ' does not exist!';
  64.             // console.log(result)
  65.             throw new Error(result)
  66.         }
  67.         this.data.delete(idToRemove);
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement