Last active
August 29, 2015 14:27
-
-
Save kulakowka/aba96831e3e0b65bc016 to your computer and use it in GitHub Desktop.
This file contains 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 Item { | |
constructor(params) { | |
this.id = getItemId(); | |
this.params = params; | |
addItem(this); | |
} | |
destroy() { | |
destroyItem(this.id); | |
} | |
update(params) { | |
updateItem(this.id, params); | |
} | |
static destroy(id) { | |
destroyItem(id); | |
} | |
static create(params) { | |
return new Item(params); | |
} | |
static update(id, params) { | |
updateItem(id, params); | |
} | |
static get(id) { | |
return getItem(id); | |
} | |
static list() { | |
return getItems(); | |
} | |
} | |
export default Item; | |
// private data | |
let _items = []; | |
let _nextItemId = 0; | |
let _itemsIndex = {}; | |
// private methods | |
function addItem(item) { | |
_items.push(item); | |
_itemsIndex[item.id] = _items.length - 1; | |
} | |
function destroyItem(id) { | |
let index = _itemsIndex[id]; | |
delete _itemsIndex[id]; | |
_items.splice(index, 1); | |
} | |
function updateItem(id, params) { | |
let index = _itemsIndex[id]; | |
_items[index].params = Object.assign(_items[index].params, params); | |
} | |
function getItem(id) { | |
let index = _itemsIndex[id]; | |
return _items[index]; | |
} | |
function getItems() { | |
return _items; | |
} | |
function getItemId() { | |
return _nextItemId++; | |
} | |
// Debug | |
// import Item from './Item.js' | |
// new Item({title: 'Мой нулевой пост'}); | |
// Item.create({title: 'Мой первый пост'}); | |
// Item.create({title: 'Мой второй пост'}); | |
// Item.create({title: 'Мой третий пост'}); | |
// let items = Item.list(); | |
// items.forEach(item => { | |
// if (item.id === 2) item.destroy(); | |
// if (item.id === 1) item.update({title: 'Измененный пост id1'}); | |
// }); | |
// //Item.destroy(1); | |
// Item.create({title: 'Мой четвертый пост'}); | |
// Item.update(3, {title: 'Измененный пост id3'}); | |
// console.log(item); | |
// console.log('Item 3:::', Item.get(3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment