Log-My-Food CLI app
unknown
javascript
3 years ago
4.5 kB
7
Indexable
#! /usr/bin/env node const { default: axios } = require('axios'); const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout, prompt: 'enter command > ' }) readline.prompt(); // Line event listener readline.on('line', async (line) => { switch (line.trim()) { case 'log': { const { data } = await axios.get(`http://localhost:3001/food`) const it = data[Symbol.iterator](); let actionIt; const actionIterator = { [Symbol.iterator]() { const positions = [...this.actions]; return { [Symbol.iterator]() { return this; }, next(...args) { if (positions.length > 0) { const position = positions.shift(); const result = position(...args); return { value: result, done: false } } else { return { done: true } } } } }, actions: [ askForServingSize, displayCalories ], }; function askForServingSize(food) { readline.question("How many servings did you eat? (enter as a decimal)", servingSize => { actionIt.next(servingSize, food) } ); } function displayCalories(servingSize, food) { const cals = food.calories console.log(`${food.name} with a serving size of ${servingSize} has ${Number.parseFloat(cals * parseFloat(servingSize)).toFixed(2)} calories.`) actionIt.next(); readline.prompt(); } readline.question(`What you would like to log today?`, async (item) => { let position = it.next(); // returns an object with a value property and a done property while (!position.done) { const food = position.value; if (food.name === item) { console.log(`${item} has ${food.calories} calories per ${food.serving_size} ${food.serving_size_units}`); actionIt = actionIterator[Symbol.iterator](); actionIt.next(food); } position = it.next() } console.log(`You have entered ${item}`) readline.prompt(); }); } break; case 'list vegan foods': { console.log('vegan food list') axios.get(`http://localhost:3001/food`).then(({ data }) => { const veganOnly = data.filter(food => { return food.dietary_preferences.includes('vegan'); }) let idx = 0; const veganIterable = { [Symbol.iterator]() { return { [Symbol.iterator]() { return this; }, next() { const current = veganOnly[idx]; idx++; if (current) { return { value: current, done: false }; } else { return { value: current, done: true }; } }, }; }, }; for (let val of veganIterable) { console.log(val.name); } readline.prompt() }); } break; } })
Editor is loading...