Created
October 31, 2021 06:28
-
-
Save naosim/01236b2159576c1f5ab53e72ed6390e5 to your computer and use it in GitHub Desktop.
簡易テーブル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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