Recipe Book0.6.0

2.2Guides

Scale a recipe

Scale quantities, resolve a recipe in metric or US units to a number of servings or by a multiplier, and display its ingredients, servings, and yield.

§ 2.210 min readView as Markdown

Scale one quantity with scaleQuantity, or resolve a whole recipe with resolveRecipe to scale it to a number of servings, or by 2× or 3×, in the reader’s measurement system. In a React app, replace @recipe-book/core with @recipe-book/react/core in this page’s imports. To scale a quantity, pass it and the factor to multiply by:

TypeScript
import { scaleQuantity } from '@recipe-book/core'

scaleQuantity({ amount: 1.5, unit: 'cup' }, 2) // { amount: 3, unit: 'cup' }
scaleQuantity({ amount: { min: 2, max: 3 }, unit: 'tbsp' }, 0.5) // { amount: { min: 1, max: 1.5 }, unit: 'tbsp' }

scaleQuantity keeps the unit and doesn’t round, so 3 tsp doubled is 6 tsp. To get 2 tbsp, pass an ingredient from a parsed recipe, or a line from parseIngredientLine, to resolveIngredient with the scale and the reader’s measurement system.

Resolve a recipe for display

resolveRecipe takes a recipe from parseRecipe and returns each ingredient with the quantity to show. These examples use the sample recipe from examples/node-script:

recipe.ts
import type { RecipeInput } from '@recipe-book/core'

export const pancakes = {
  name: 'Buttermilk pancakes',
  servings: 4,
  times: { prep: 10, cook: 15 },
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cups', equivalents: ['190 g'] },
    { name: 'sugar', quantity: '2 tbsp', equivalents: ['25 g'] },
    { name: 'baking powder', quantity: '2 tsp' },
    { name: 'buttermilk', quantity: '1 ¼ cups' },
    { name: 'egg', plural: 'eggs', quantity: 2 },
    {
      name: 'butter',
      quantity: '3 tbsp',
      note: 'melted',
      equivalents: ['42 g'],
    },
    { name: 'maple syrup', note: 'to serve' },
  ],
  steps: [
    'Whisk the dry ingredients in a large bowl.',
    'Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.',
    'Cook ¼-cup portions on a buttered griddle, 2–3 minutes per side.',
  ],
} satisfies RecipeInput

Pass the measurement system the reader wants:

TypeScript
import { parseRecipe, resolveRecipe } from '@recipe-book/core'
import { pancakes } from './recipe.ts'

const result = parseRecipe(pancakes)
if (!result.success) throw result.error

const resolved = resolveRecipe(result.data, { system: 'metric' })

for (const section of resolved.ingredients) {
  for (const { ingredient, quantity, origin } of section.items) {
    console.log(ingredient.name, quantity, origin)
  }
}

Each ingredient’s origin says where its quantity comes from:

Authored quantity origin
1 ½ cups all-purpose flour, or 190 g { amount: 190, unit: 'g' } 'equivalent'
2 tbsp sugar, or 25 g { amount: 2, unit: 'tbsp' } 'authored'
2 tsp baking powder { amount: 2, unit: 'tsp' } 'authored'
1 ¼ cups buttermilk { amount: 295.735295625, unit: 'ml' } 'converted'
2 eggs { amount: 2 } 'authored'
3 tbsp butter, or 42 g { amount: 3, unit: 'tbsp' } 'authored'
maple syrup undefined 'authored'

tsp and tbsp belong to both systems, so the sugar and butter keep their authored quantities. The author gave no metric quantity for the buttermilk, so resolveRecipe converts it. Without system, resolveRecipe uses the recipe’s authored system, else the one parseRecipe infers from its units, else 'metric'. Equivalents don’t count, so resolveRecipe uses 'us' for the sample recipe, which has no authored system: its flour and buttermilk are in cups, and its grams are all equivalents.

Before you offer a choice of system, check resolved.canConvert. It’s true when an ingredient’s quantity, or any equivalent of a quantity in a count unit, such as the size of a can, has a unit that belongs to only one system. A count unit’s equivalents count because they give the size the reader sees, and each of them counts, not only the one that shows. An equivalent of any other quantity doesn’t count. Step temperatures and step quantities don’t count toward it either, so if you convert them with segmentStepText and segmentStepQuantities, treat any temperature segment as convertible too, and any quantity segment in a unit of only one system, unless the author also wrote it in the other.

Scale to a number of servings

Pass servings to scale every quantity. The sample recipe has servings: 4, so 8 servings doubles it:

TypeScript
import { parseRecipe, resolveRecipe } from '@recipe-book/core'
import { pancakes } from './recipe.ts'

const result = parseRecipe(pancakes)
if (!result.success) throw result.error

const resolved = resolveRecipe(result.data, { servings: 8, system: 'us' })
const [flour, sugar] = resolved.ingredients[0]?.items ?? []

resolved.scale // 2
resolved.servings // { amount: 8 }
flour?.quantity // { amount: 3, unit: 'cup' }
sugar?.quantity // { amount: 0.25, unit: 'cup' }

When the scale is more than 1e-9 from 1, a quantity in a unit on one of the toSystem ladders also moves to the unit on that ladder a cook measures with, within the measurement system: 2 tbsp of sugar doubled is ¼ cup in US units, and 4 tbsp in metric because cups aren’t metric. Unless you pass exact, teaspoons and tablespoons land on a measure too, in either system, and so do cups in US units, even when they keep their unit. An amount too small to land on ⅛ tsp stays exact, though, and so does a range whose ends would land on the same measure. The metric cup and the Australian tablespoon of regional recipes are on no ladder, so in metric they’re only scaled. At a scale within 1e-9 of 1, a quantity that doesn’t convert shows as written. Counts, such as the eggs, and units off the ladders, such as cloves and pints, keep their unit. The rebalance option turns this off, but a converted quantity, such as the buttermilk in metric, always gets the unit that fits it.

resolveRecipe doesn’t scale step text: resolved.steps holds each step as written. That’s right for the sample recipe’s “Cook ¼-cup portions”, since each pancake is still ¼ cup at 8 servings, but a step such as “Add 1 cup of the flour” would still say 1 cup after the flour doubles. Write a share in the step, such as “Stir in half the flour”, and keep the quantity in ingredients.

Times, equipment, notes, and nutrition don’t scale either. Read them from resolved.recipe, the recipe you passed. In React, <Recipe.Times>, <Recipe.Equipment>, <Recipe.Notes>, and <Recipe.Nutrition> show them as written at any servings.

Servings and yield

A recipe’s servings is how many servings it makes, and its yield is what a batch makes, such as 24 cookies. A recipe can have either, both, or neither. invalid_recipe lists the issues parseRecipe gives for values it can’t read.

resolveRecipe divides the servings option by the recipe’s scaling base. For a recipe with a yield and no servings, that’s the yield’s amount, so 48 doubles a recipe that makes 24 cookies:

TypeScript
import { parseRecipe, resolveRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Sugar cookies',
  yield: { amount: 24, unit: 'cookie', plural: 'cookies' },
  ingredients: [{ name: 'flour', quantity: '2 cups' }],
  steps: ['Bake for 10 minutes.'],
})
if (!result.success) throw result.error

const resolved = resolveRecipe(result.data, { servings: 48 })
resolved.scale // 2
resolved.yield // { amount: 48, unit: 'cookie', plural: 'cookies' }

When a recipe has both, the servings option counts servings, so for a recipe with 4 servings and a yield of 24 cookies, servings: 48 scales it by 12, to 288 cookies. For 48 cookies, pass scale as 48 divided by the yield’s amount.

A recipe with neither has a scaling base of 1, so servings: 8 gives a scale of 8, and the resolved recipe still has no servings to print. Before you offer a number of servings, check that the recipe has servings or yield. For a recipe with neither, offer multiplier buttons instead.

Scale by a multiplier

For 1×, 2×, and 3× buttons, pass scale instead. It multiplies every quantity directly, whatever the recipe’s servings or yield:

TypeScript
import { parseRecipe, resolveRecipe } from '@recipe-book/core'
import { pancakes } from './recipe.ts'

const result = parseRecipe(pancakes)
if (!result.success) throw result.error

const tripled = resolveRecipe(result.data, { scale: 3 })
tripled.scale // 3
tripled.servings // { amount: 12 }

resolveRecipe(result.data, { scale: 3, servings: 8 }).scale // 3
resolveRecipe(result.data, { scale: 0, servings: 8 }).scale // 2

To halve a recipe, pass scale: 0.5, or halve its servings, such as servings: 2 for the sample recipe.

Scale a range

Servings and yields can be ranges, such as servings: '6–8' or yield: '12–16 rolls'. When the servings option sets a scale more than 1e-9 from 1, the resolved servings or yield, whichever is the scaling base, is exactly that number, with no max. Every other range scales at both ends, as ResolvedRecipe describes:

TypeScript
import { parseRecipe, resolveRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Dinner rolls',
  servings: '6–8',
  yield: '12–16 rolls',
  ingredients: [{ name: 'bread flour', quantity: '3 cups' }],
  steps: ['Shape the dough into rolls and bake.'],
})
if (!result.success) throw result.error

const doubled = resolveRecipe(result.data, { scale: 2 })
doubled.servings // { amount: 12, max: 16 }
doubled.yield // { amount: 24, unit: 'roll', plural: 'rolls', max: 32 }

const forTwelve = resolveRecipe(result.data, { servings: 12 })
forTwelve.servings // { amount: 12 }
forTwelve.yield // { amount: 24, unit: 'roll', plural: 'rolls', max: 32 }

resolveRecipe(result.data, { servings: 6 }).servings // { amount: 6, max: 8 }
resolveRecipe(result.data, { servings: 8 }).scale // 1.3333333333333333

The scaling base is a range’s low end. At a scale within 1e-9 of 1, the resolved servings and yield are the recipe’s own objects, so don’t modify them.

Display scaled ingredients

For 3 servings of the sample recipe in metric, the buttermilk is { amount: 221.80147171875, unit: 'ml' }. Print each ingredient with formatIngredient, which rounds its quantity the way formatQuantity does:

TypeScript
import { formatIngredient, parseRecipe, resolveRecipe } from '@recipe-book/core'
import { pancakes } from './recipe.ts'

const result = parseRecipe(pancakes)
if (!result.success) throw result.error

const resolved = resolveRecipe(result.data, { servings: 3, system: 'us' })

for (const section of resolved.ingredients) {
  for (const item of section.items) {
    console.log(formatIngredient(item, { system: resolved.system }).text)
  }
}
Output
1 ⅛ cups all-purpose flour
1 ½ tbsp sugar
1 ½ tsp baking powder
15 tbsp buttermilk
1 ½ eggs
6 ¾ tsp butter, melted
maple syrup, to serve

Counts and both ends of a range scale like any other amount, and nothing rounds a count to a whole number, so the 2 eggs are 1 ½ eggs for 3 servings and ½ egg for 1. formatQuantity rounds a count to the nearest ¼ or ⅓ and writes one below ¼ as a decimal, so 1 egg in a recipe with 12 servings prints as 0.1 eggs for 1 serving. Passing the resolved system shows the size of a can, package, jar, or bag in it too. A per-unit size reads the same at any scale where the count shows as it is: at 2×, 1 (28 oz) can crushed tomatoes reads 2 cans (28 oz each) crushed tomatoes, and 2 cans (794 g each) crushed tomatoes in metric. The count shows rounded, though, so the size shows as a total when that rounding puts the per-unit figure more than 2% off: in a recipe with 6 servings, the can is ⅚ can for 5 servings, which shows as ¾, and the line reads ¾ can (23 ⅓ oz total) crushed tomatoes in US. A size also shows as a total when the per-unit figure isn’t clean or a range’s ends disagree, and a total scales with the count, so at 2× 6 slices (5 oz) bacon reads 12 slices (10 oz total) bacon in US. An ingredient with no quantity, such as the maple syrup or salt to taste, has none at any scale, and its note prints as written.

Display servings and yield

Scale with resolveRecipe, and print with formatServings and formatYield, not formatQuantity. formatServings returns only the number or range, so your UI adds the word. To write it after the number, choose it as formatYield chooses the yield’s word: serving when formatServings returns 1 or a fraction below 1, such as ½, and servings otherwise, including decimals and ranges, as in 0.2 servings, 1 ½ servings, and 2–3 servings. formatYield adds the yield’s word after a no-break space (U+00A0):

TypeScript
import {
  formatServings,
  formatYield,
  parseRecipe,
  resolveRecipe,
  type ResolvedRecipe,
} from '@recipe-book/core'

const result = parseRecipe({
  name: 'Dinner rolls',
  servings: '6–8',
  yield: '12–16 rolls',
  ingredients: [{ name: 'bread flour', quantity: '3 cups' }],
  steps: ['Shape the dough into rolls and bake.'],
})
if (!result.success) throw result.error

function summary({ servings, yield: makes }: ResolvedRecipe) {
  const parts: string[] = []
  if (servings) parts.push(`Servings: ${formatServings(servings)}`)
  if (makes) parts.push(`Yield: ${formatYield(makes)}`)
  return parts.join(' · ')
}

summary(resolveRecipe(result.data)) // 'Servings: 6–8 · Yield: 12–16 rolls'
summary(resolveRecipe(result.data, { scale: 2 })) // 'Servings: 12–16 · Yield: 24–32 rolls'
summary(resolveRecipe(result.data, { servings: 9 })) // 'Servings: 9 · Yield: 18–24 rolls'

A yield written as text, such as '12–16 rolls', keeps its words, and one of them, usually the last, is made singular or plural to match the scaled number as printed, as formatYield describes. So yield: '1 sheet cake' doubled prints 2 sheet cakes, but '1 cup sauce' prints 2 cup sauces, and you write '1 cup of sauce' to get 2 cups of sauce. Text with a second number outside parentheses, such as '24 cookies or 12 bars', is an invalid_quantity issue, because only the number or range in front would scale. A number in parentheses, as in '1 loaf (about 8 slices)', stays as written. YieldInput has every rule.

In React, <Recipe.ServingsText> and <Recipe.YieldText> show the servings and the yield at <Recipe.Root>’s servings, each with its word.

Take servings from user input

resolveRecipe doesn’t throw for an option value it can’t use, and uses that option’s default instead. To scale to servings from a URL, a form, or a cookie, pass the raw values to readRecipeView, which validates them and keeps only the ones resolveRecipe accepts, and pass its result on:

TypeScript
import { parseRecipe, readRecipeView, resolveRecipe } from '@recipe-book/core'
import { pancakes } from './recipe.ts'

const result = parseRecipe(pancakes)
if (!result.success) throw result.error

const params = new URLSearchParams('?servings=twelve&system=us')
const view = readRecipeView(result.data, {
  servings: params.get('servings'),
  system: params.get('system'),
})

view // { system: 'us' }
resolveRecipe(result.data, view).scale // 1

Besides 'twelve', the view leaves out text that Number would read, such as ' 8' and '0x8', and servings outside the recipe’s servings window. ResolveRecipeOptions lists the values resolveRecipe ignores.

Reference

  • Resolving documents resolveRecipe, scaleQuantity, readRecipeView, which reads servings and a system from untrusted input, and resolveIngredient, which resolves one ingredient at a scale you choose.
  • Servings and Yield describe the parsed servings and yield, and ServingsInput and YieldInput the forms authors can write them in.
  • Formatting documents formatIngredient, formatServings, and formatYield, with their options, rounding rules, and errors.
  • toSystem lists the unit ladders that conversion and rebalancing use.
  • invalid_argument explains the error that scaleQuantity and resolveIngredient throw.
Contents