recipe-ts-runtime
Version:
TypeScript run-time library for the Recipe framework
113 lines • 4.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const Ingredient_1 = require("./Ingredient");
class Recipe extends Ingredient_1.Ingredient {
constructor(...ingredients) {
super("Recipe");
this.context = null;
this.ingredients = [];
for (const ingredient of ingredients) {
if (ingredient instanceof Recipe && !ingredient.getContext()) {
this.ingredients.push(...ingredient.ingredients);
}
else {
this.ingredients.push(ingredient);
}
}
}
static prepare(...ingredients) {
return new Recipe(...ingredients);
}
static context(context, ...ingredients) {
let recipe;
if (typeof context === "string") {
recipe = Recipe.prepare(...ingredients);
recipe.context = context;
}
else {
const contextKey = context.getKey();
if (contextKey) {
recipe = Recipe.prepare(context, Recipe.context(contextKey, ...ingredients));
}
else {
recipe = Recipe.prepare(context, ...ingredients);
}
}
return recipe;
}
getIngredients() {
return this.ingredients;
}
getContext() {
return this.context;
}
segment() {
const segments = [];
const recipeStack = [];
recipeStack.push(this);
this._segment(new Recipe(), recipeStack, null, segments);
return segments;
}
_segment(currRecipe, recipeStack, currDomain, segments) {
for (const ingredient of recipeStack[0].ingredients) {
if (ingredient instanceof Recipe) {
let recipe = new Recipe();
recipe.context = ingredient.context;
recipeStack.unshift(ingredient);
this._segment(recipe, recipeStack, currDomain, segments);
if (recipe.ingredients.length !== 0) {
currRecipe.ingredients.push(recipe);
}
}
else {
if (ingredient.getDomain() !== currDomain) {
//copy recipe structure
let outerRecipe = null;
let recipe = null;
for (const r of recipeStack) {
if (recipe === null) {
outerRecipe = new Recipe();
recipe = outerRecipe;
}
else {
outerRecipe = Recipe.prepare(outerRecipe);
}
outerRecipe.context = r.context;
}
const segmented = {
domain: ingredient.getDomain(),
recipe: outerRecipe
};
segments.push(segmented);
currRecipe = recipe;
currDomain = ingredient.getDomain();
}
currRecipe.ingredients.push(ingredient);
}
}
recipeStack.unshift();
}
toJSON() {
const jsonObj = super.toJSON();
jsonObj[this.getIngredientType()].ingredients = this.ingredients;
if (this.context) {
jsonObj[this.getIngredientType()].context = this.context;
}
return jsonObj;
}
static fromJSON(json, ingredientTypes) {
ingredientTypes["Recipe"] = Recipe;
const context = json.Recipe.context || null;
const ingredients = json.Recipe.ingredients.map((ingredient) => {
return "Recipe" in ingredient
? Recipe.fromJSON(ingredient, ingredientTypes)
: Ingredient_1.Ingredient.fromJSON(ingredient, ingredientTypes);
});
return Object.assign(new Recipe(), {
context,
ingredients
});
}
}
exports.Recipe = Recipe;
//# sourceMappingURL=Recipe.js.map