Skip to content

Instantly share code, notes, and snippets.

@naosim
Created October 31, 2021 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naosim/01236b2159576c1f5ab53e72ed6390e5 to your computer and use it in GitHub Desktop.
Save naosim/01236b2159576c1f5ab53e72ed6390e5 to your computer and use it in GitHub Desktop.
簡易テーブル
class JsonTable {
constructor(data = {}, isSafetyMode = true) {
this.data = data;
this.isSafetyMode = isSafetyMode;
}
insert(id, obj) {
if(this.data[id]) {
throw new Error(`IDがすでに存在する: ${id}`);
}
this.data[id] = this.copyIfNeeded(obj)
}
findById(id) {
const result = this.data[id];
return this.copyIfNeeded(result);
}
findAll() {
return this.copyIfNeeded(Object.values(this.data))
}
copyIfNeeded(obj) {
if(!this.isSafetyMode) {
return obj;
}
return JSON.parse(JSON.stringify(obj))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment