Last active
August 29, 2015 14:09
-
-
Save scudelletti/5726ca931956695273f5 to your computer and use it in GitHub Desktop.
Composite Pattern
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
// How To Use | |
// var categories = CategoryModule.Category.all(); | |
// var categoryComposite = new CategoryModule.CategoryComposite('CategoryComposite', categories.categorias, null); | |
// | |
// var categoryComposities = categoryComposite.findByName('Bar'); | |
// | |
// var originalCategories = categoryComposities.map(function(item) { | |
// return item.original; | |
// }); | |
CategoryModule = (function(){ | |
var Category = { | |
all: function(){ | |
var responseText = $.ajax({ | |
type: "GET", | |
url: CONSOLE_HOST + '/widget_api/categorias', | |
async: false | |
}).responseText; | |
return JSON.parse(responseText); | |
} | |
}; | |
var ArrayHelper = { | |
thereIsArray: function (array){ | |
for(index = 0; index < array.length; index++){ | |
if($.isArray(array[index])){ | |
return true; | |
} | |
} | |
return false | |
}, | |
flatRecursiveArray: function(array){ | |
while(this.thereIsArray(array)) { | |
array = [].concat.apply([], array); | |
} | |
return array; | |
} | |
}; | |
var CategoryComposite = function(name, categories, original, parent){ | |
var buildComposities = function(categories, parent) { | |
var container = []; | |
categories.forEach(function(category){ | |
categoryComposite = new CategoryComposite(category.nome, category.categorias, category, parent); | |
container.push(categoryComposite); | |
}); | |
return container; | |
}; | |
var isEmpty = function(array) { | |
return array.length === 0 | |
}; | |
// Object Initialization | |
this.name = name; | |
this.categories = buildComposities(categories, this); | |
this.original = original; | |
this.parent = parent; | |
// Public Methods | |
this.findByName = function(name) { | |
if(isEmpty(this.categories) && this.name !== name) { | |
return [] | |
} | |
var container = []; | |
if(this.name === name) { | |
container = [this]; | |
} | |
this.categories.forEach(function(category) { | |
container.push(category.findByName(name)); | |
}); | |
return ArrayHelper.flatRecursiveArray(container); | |
}; | |
}; | |
return { | |
Category: Category, | |
CategoryComposite: CategoryComposite | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment