Classes

node v6.17.1
version: 1.0.0
endpointsharetweet
// Write a class that represents a person. The class should take age, location, and name as inputs. The class should have methods to get each of these data points. // Solution class Person { constructor(age, location, name) { this.age = age; this.name = name; this.location = location; } getAge() { return this.age; } getLocation() { return this.location; } getName() { return this.name; } } ////////////////////////////////////////////////////////////////// // Write a class representing a database table/collection of persons. Your class should be able to allow the insertion, retrieving, updating, and deletion of persons. // Solution class PersonDatabase { constructor() { this.store = []; } delete(id) { this.store = this.store.filter((person) => person.id !== id); // Could be optimized } get(query) { return this.store.filter((person) => { for (let key in query) { if (!query.hasOwnProperty(key) || person[key] !== query[key]) { return false; } } return true; }) .slice(); } insert() { [...arguments].forEach((person) => { const id = date.now(); const personToStore = Object.assign({}, person, {id}); this.store.push(personToStore); }); } update(id, updates) { const personToUpdate = this.store.find((person) => person.id === id); const updatedPerson = Object.assign(personToUpdate, updates); return Object.assign({}, updatedPerson); } }
Loading…

no comments

    sign in to comment