Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const menuState = (function() {
- class MenuData {
- constructor(attached = [], available = []) {
- // attached,available MUST be arrays!
- if ((!Array.isArray(attached)) || (!Array.isArray(available))) {
- throw TypeError("passed data MUST be in the form of Arrays!")
- }
- this.attached = attached;
- this.available = available;
- }
- add(entities) {
- // entities MUST be Array
- if (!Array.isArray(entities)) throw ReferenceError("entities must be array")
- // from here, we simply move from this.available to this.attached, the entities
- // but first, let's check if they're even available
- if (hasEntities(entities, this.available)) {
- // attach them
- this.attached = this.attached.concat(entities)
- // they are no longer available
- this.available= this.available
- .filter(excluderFactory(entities))
- }
- // if they're not attached, that is an error
- if (!hasEntities(entities, this.attached)) {
- throw Error('The entities you were trying to add were neither attached nor available')
- }
- }
- remove(entities) {
- // entities MUST be Array
- if (!Array.isArray(entities)) throw ReferenceError("entities must be array")
- // from here, we simply move from this.attached to this.available, the entities
- // but first, let's check if they're even attached
- if (hasEntities(entities, this.attached)) {
- // make them available
- this.available = this.available.concat(entities)
- // detach them
- this.attached = this.attached
- .filter(excluderFactory(entities))
- }
- // if they're not available, that is an error
- if (!hasEntities(entities, this.available)) {
- throw Error('The entities you were trying to remove were neither attached nor available')
- }
- }
- };
- let _categories = new MenuData(),
- _items = new MenuData()
- let _itemPool = [],
- _categoryItems = {}
- /**
- * Determines if an array has entities with an Id.
- * @param {Object[]} entities
- * @param {Object[]} arrayToCheck
- * @returns {boolean} whether arrayToCheck has objects with entities' Ids.
- */
- function hasEntities(entities, arrayToCheck) {
- for (let idx in entities) {
- if (arrayToCheck.find((element) => element.Id === entities[idx].Id)) {
- if (idx == entities.length - 1) {
- return true;
- }
- continue;
- }
- return false;
- }
- }
- /**
- * Returns a callback for the purpose of excluding entities
- * @param {Object[]} entities the entities to exclude
- */
- function excluderFactory(entities) {
- return function(model) {
- return !entities.find((entity) => entity.Id === model.Id)
- }
- }
- return {
- // some methods to expose to other parts of the page
- }
- })()
Add Comment
Please, Sign In to add comment