var dataBase = new DataBase();
dataBase.addById({
id : 1,
name : "hello"
});
dataBase.updateById({
id : 1,
name: "你好"
})
dataBase.getById(1);
dataBase.deleteById(1);
class DataBase {
list = [];
idIndex = {};
primary = 'id';
setPrimary(primary) {
this.primary = primary;
}
init(list) {
for (let i = 0; i < list.length; i++) {
this.list[i] = list[i];
this.idIndex[list[this.primary]] = list[i];
}
}
addById(data) {
let id = data[this.primary];
if (this.idIndex[id] !== undefined && this.idIndex[id] !== -1) {
this.updateById(data);
return;
}
this.idIndex[id] = this.list.push(data) - 1;
}
deleteById(id) {
let index = this.idIndex[id];
this.idIndex[id] = -1;
this.list[index] = false;
}
updateById(data) {
let id = data[this.primary];
this.list[this.idIndex[id]] = data;
}
getById(id) {
return this.list[this.idIndex[id]];
}
getAll() {
let res = [];
for (let i = 0; i < this.list.length; i++) {
if (this.list[i]) {
res.push(this.list[i]);
}
}
return res;
}
getAllIds() {
let res = [];
for (let i = 0; i < this.list.length; i++) {
if (this.list[i]) {
res.push(this.list[i][this.primary]);
}
}
return res;
}
clear() {
this.idIndex = {};
this.list = [];
}
}