空起床 senior 前端店面挂经

I was supposed to implement just the class, the interviewer provideed how the class was going to be used by what i added after the class implementation.

class StoreData {
  constructor() {
    this.data = {};
    this.events = {};
  }
  
  add(key, value) {
    if(this.data[key] && this.events[key]) {
      this.events[key].forEach((e)=>e(this.data[key],  value, key));
    }
    this.data[key]= value;
  }
  
  has(key) {
    return this.data[key] ? true : false
  }
  
  remove(key) {
    delete this.data[key]
  }
  
  on(event, func) {
    event = event.substring(event.indexOf(':') + 1) || event; //better way to do it??
    if(!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(func);
    
  }
  
}



let store= new StoreData();
store.add('name', 'joe');
store.add('age', 30);
console.log(store.has('age'));    // return true
console.log(store.has('animal')); // return false
store.add('name', 'emma');
store.on('change:name', (old_val, new_val, key)=>{console.log(`old ${key}: ${old_val}, new ${key}: ${new_val}`)});
store.add('name', 'john');
store.on('age', (old_val, new_val, key)=>{console.log(`old ${key}: ${old_val}, new ${key}: ${new_val}`)});
store.add('age', 26);
store.on('change:age', (old_val, new_val, key)=>{console.log(`${old_val > new_val ? 'older now' : ''}`)});
store.add('age', 28);
store.add('age', 45);

console.log('\n\n\n\n');

let data= new StoreData();
data.add('restaurant', 'food')
data.add('bar', 'drinks')
console.log(data.has('cost'))

....
....

Let’s start by saying that somehow i manage to fail this interview :frowning:
hopefully you guys find it helpful!