import axios from 'axios'; import { key, proxy } from '../config'; export default class Recipe { constructor(id) { this.id = id; } async getRecipe() { try { const res = await axios(`${proxy}https://forkify-api.herokuapp.com/api/get?key=aaa${key}&rId=${this.id}`); this.title = res.data.recipe.title; this.author = res.data.recipe.publisher; this.img = res.data.recipe.image_url; this.url = res.data.recipe.source_url; this.ingredients = res.data.recipe.ingredients; } catch (error) { console.log(error); alert('sometihnd went wrong: ('); } } calcTime() { const numIng = this.ingredients.length; const periods = Math.ceil(numIng / 3); this.time = periods * 15; } calcServings() { this.servings = 4; } parseIngredients() { const unitsLong = ['tabelspoons', 'tablspoon', 'ounce', 'ounces', 'teaspoon', 'teaspoons', 'cups', 'pounds']; const unitsShort = ['tbsp', 'tbsp', 'oz', 'oz', 'tsp', 'tsp', 'cup', 'pound']; const newIngredients = this.ingredients.map(el => { // 1) uniform units let ingredient = el.toLowerCase();/*--大文字を小文字に変換する--*/ unitsLong.forEach((unit, i) => { ingredient = ingredient.replace(unit, unitsShort[i]); }); // 2) remove parenthese ingredient = ingredient.replace(/ *([^)]*) */g, ''); // 3) parse ingredients into count , unit and ingredient const arrIng = ingredient.split(' '); const unitIndex = arrIng.findIndex(el2 => unitsShort.includes(el2)); let objIng; if (unitIndex > -1) { // there is a unit // Ex 4 1/2 cups, arrCount is [4, 1/2] // Ex 4 cups ,arrCount is [4] const arrCount = arrIng.slice(0, unitIndex); let count; if (arrCount.length === 1) { count = eval(arrIng[0].replace('-', '+')); } else { count = eval(arrIng.slice(0, unitIndex).join('+')); } objIng = { count, unit: arrIng[unitIndex], ingredient: arrIng.slice(unitIndex + 1).join(' ') }; } else if (parseInt(arrIng[0], 10)) { // console.log(arrIng); // there is NO unit, but 1st element is number objIng = { count: parseInt(arrIng[0], 10), unit: '', ingredient: arrIng.slice(1).join('') } } else if (unitIndex === -1) { // there is not unit and NO number in 1s possition objIng = { count: 1, unit: '', ingredient } } return objIng; }); this.ingredients = newIngredients; } }
findIndexがあまり理解できていないので、ご教授していただければ幸いです。
また、 const unitIndex = arrIng.findIndex(el2 => unitsShort.includes(el2));
ここでいうel2はどこの部分を指しているのですか?
かなり初歩的な質問で大変恐縮なのですが、ご教授いただければ幸いです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/11/19 11:30