Sikau

Project: A JavaScript app · Day 3 · about 40 min

Quick orders: regex, Map and Set

Parse "2 momo, 1 chiya", tally the kitchen with a Map, find categories with a Set.

Type an order, get a cart

Regulars just type *2 momo, 1 chiya*. A regular expression pulls out the numbers and names; a Map counts dishes across many orders for the kitchen screen; a Set answers "which categories are in this order?" without duplicates.

Parsing with a pattern

function lookup(word) {
  return MENU.find((item) => item.id === word || item.name.toLowerCase() === word);
}

function parseOrder(text) {
  const order = [];
  for (const part of text.split(",")) {
    const m = part.trim().toLowerCase().match(/^(?:(\d+)\s*x?\s+)?([a-z ]+)$/);
    if (!m) continue;
    const item = lookup(m[2].trim());
    if (item) order.push({ id: item.id, qty: m[1] ? Number(m[1]) : 1 });
  }
  return order;
}

The rest of this lesson

  • Designing the patternexplain
  • Counting for the kitchenexplain
  • Map or object?predict
  • Tally two orderspredict
  • Parse and tallywrite code
  • Badge quizquiz
  • What you builtrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 6 lessons of Project: A JavaScript app