3.2Core reference
Resolving
Reference for resolveRecipe, readRecipeView, resolveIngredient, and scaleQuantity, which scale quantities, express a recipe in one measurement system, and read servings and a system from a link or storage.
Use these exports from @recipe-book/core to scale quantities and to resolve a parsed recipe for display, with every ingredient scaled and in one measurement system. For a walkthrough, see Scale a recipe. In a React app, replace @recipe-book/core with @recipe-book/react/core in this page’s imports.
resolveRecipe
function resolveRecipe(
recipe: Recipe,
options?: ResolveRecipeOptions,
): ResolvedRecipeScales a recipe to a number of servings, or by a multiplier, and expresses each ingredient in one measurement system.
| Name | Type | Default | Description |
|---|---|---|---|
recipe |
Recipe |
Required | A recipe from parseRecipe. |
options |
ResolveRecipeOptions |
{} |
The servings or scale, measurement system, and rebalancing to use. |
Returns a ResolvedRecipe. Each ingredient resolves as resolveIngredient describes, at the scale that scale or servings sets. Format for display.
import { parseRecipe, resolveRecipe } from '@recipe-book/core'
const result = parseRecipe({
name: 'Pancakes',
servings: '4–6',
ingredients: [
{ name: 'flour', quantity: '1 ½ cups', equivalents: ['190 g'] },
{ name: 'buttermilk', quantity: '1 ¼ cups' },
],
steps: ['Whisk the flour and buttermilk.', 'Cook on a hot griddle.'],
})
if (!result.success) throw result.error
const resolved = resolveRecipe(result.data, { system: 'metric' })
resolved.ingredients[0]?.items[0]?.quantity // { amount: 190, unit: 'g' }
resolved.ingredients[0]?.items[1]?.quantity // { amount: 295.735295625, unit: 'ml' }
resolved.steps[0]?.items[1]?.number // 2
resolveRecipe(result.data, { servings: 8 }).servings // { amount: 8 }
resolveRecipe(result.data, { servings: 4 }).servings // { amount: 4, max: 6 }
resolveRecipe(result.data, { scale: 2 }).servings // { amount: 8, max: 12 }Never throws for an unchanged recipe from parseRecipe, so it’s safe with options from a URL or a form. An error thrown by a getter or proxy in the options passes through. A recipe that’s null, undefined, or a primitive, such as a string, throws a TypeError.
readRecipeView
function readRecipeView(recipe: Recipe, input: RecipeViewInput): RecipeViewReads a number of servings and a measurement system from values you don’t control, such as search params, a cookie, or storage. It keeps each one only if resolveRecipe and <Recipe.Root> accept it.
| Name | Type | Default | Description |
|---|---|---|---|
recipe |
Recipe |
Required | The recipe the servings are for, from parseRecipe. Its scaling base sets which servings are kept. |
input |
RecipeViewInput |
Required | The values to read, such as { servings: url.searchParams.get('servings') }. |
Returns a new RecipeView with each value that’s valid. An invalid value is left out, so pass the view to resolveRecipe as its options, or its values to <Recipe.Root>’s defaultServings and defaultSystem, and the default applies.
| Value | Kept when |
|---|---|
| Servings as a number | It’s from a millionth to a million times the recipe’s scaling base, including both ends: its servings amount, else its yield amount, else 1. That’s the servings window that resolveRecipe and <Recipe.Root> accept. It isn’t clamped or rounded. |
| Servings as a string | It’s digits, optionally followed by a decimal point and digits, then optionally e+ or e- and digits, and the number it reads as is in the window above. That pattern covers every string String() writes for a finite number greater than 0, such as '8', '1.5', or '5e-7', and also '007' and '8.0'. '', ' 8', '+8', '-3', '8.', '.5', '0x8', '1,5', 'Infinity', and '8 servings' don’t match it, and neither does '1e3', whose exponent has no sign. |
| A system | It’s 'metric' or 'us'. 'Metric', 'US', and 'imperial' aren’t. |
| An array | Its first item is kept when a row above keeps it, the way URLSearchParams.get reads only a repeated key’s first value. Next.js passes a repeated search param as an array. Later items aren’t read, so ['twelve', '8'] is left out, and so are an empty array and an array whose first item is another array. |
| Anything else | Never: undefined, null, booleans, objects, and bigints are left out. An input that isn’t an object reads as {}. |
import { parseRecipe, readRecipeView, resolveRecipe } from '@recipe-book/core'
const result = parseRecipe({
name: 'Pancakes',
servings: '4–6',
ingredients: [{ name: 'flour', quantity: '1 ½ cups', equivalents: ['190 g'] }],
steps: ['Whisk the flour.', 'Cook on a hot griddle.'],
})
if (!result.success) throw result.error
const url = new URL('https://example.com/pancakes?servings=8&system=us')
const view = readRecipeView(result.data, {
servings: url.searchParams.get('servings'),
system: url.searchParams.get('system'),
})
view // { servings: 8, system: 'us' }
resolveRecipe(result.data, view).scale // 2
readRecipeView(result.data, { servings: ['2', '6'] }) // { servings: 2 }
readRecipeView(result.data, { servings: '4000000' }) // { servings: 4000000 }
readRecipeView(result.data, { servings: '4000001', system: 'Metric' }) // {}
readRecipeView(result.data, { servings: ' 8' }) // {}Doesn’t throw, warn, or log for any value in input when recipe is an object. An error thrown by a getter or proxy in input or recipe passes through, and a recipe of undefined or null throws a TypeError. Share servings in a link and Remember the reader’s choice use it to start a <Recipe.Root> from the URL or a cookie.
resolveIngredient
function resolveIngredient(
ingredient: Ingredient,
options?: ResolveIngredientOptions,
): ResolvedIngredient
function resolveIngredient(
ingredient: IngredientLine,
options?: ResolveIngredientOptions,
): Omit<ResolvedIngredient, 'id' | 'ingredient'> & { ingredient: IngredientLine }Resolves one ingredient the way resolveRecipe does, at a scale you choose.
| Name | Type | Default | Description |
|---|---|---|---|
ingredient |
Ingredient | IngredientLine |
Required | An ingredient from a parsed recipe, or a line from parseIngredientLine. A line’s missing equivalents count as none. |
options |
ResolveIngredientOptions |
{} |
The scale, measurement system, and rebalancing to use. |
Returns a ResolvedIngredient whose quantity is the first of these that applies. For a line from parseIngredientLine, which has no id, the result has no id either, and its ingredient is the line.
- The ingredient’s
quantity, when its unit belongs tosystem, with the origin'authored'. A bare count, tsp, tbsp, and count units such asclovebelong to both systems, and a unit that isn’t a unit ID belongs to neither. - The first of its
equivalentswhose unit belongs tosystem, with the origin'equivalent'. - When
systemis'metric', the first weight among itsquantityandequivalents, converted tosystemthe waytoSystemconverts it, with the origin'converted'. It’s scaled before it’s converted, so the unit fits the scaled quantity. Fluid ounces are a volume, not a weight. - Its
quantity, scaled and converted the same way, with the origin'converted'. A US reader gets this one rather than a weight, so a volume stays a volume. When its unit isn’t a unit ID, which only a recipe you build can have, it’s only scaled, and keeps the origin'authored'.
So 1 ½ cups of flour with a 6.7 oz equivalent stays 1 ½ cups for a reader who wants US units, and becomes about 189.94 g for one who wants metric. 250 mL of flour with a 125 g equivalent becomes 1 cup for a reader who wants US units, not ounces.
At any scale more than 1e-9 from 1, an authored or equivalent quantity is scaled, then moves to the best unit on its own ladder that belongs to system. Teaspoons and tablespoons can land on a measure in either system, and cups in 'us', even when they keep their unit. A quantity or range end too small to land on ⅛ tsp stays exact, so ⅛ tsp at a scale of 0.6 is 0.075 tsp, and a range whose ends would land on the same measure keeps its amounts, so '2-2.03 tsp' at a scale of 1.1 is 2.2–2.233 tsp. With exact: true, the quantity still moves to the best unit but keeps its exact amount, and with rebalance: false, it keeps its unit and its exact amount: 3 tsp at a scale of 2.1 in 'us' is 2 tbsp, but 2.1 tbsp with exact and 6.3 tsp with rebalance: false. mg, cl, dl, cup-metric, and tbsp-au are on no ladder, so in 'metric' they’re only scaled: 500 mg at a scale of 4 is 2000 mg, not 2 g, and 1 cup-metric at a scale of 0.05 is 0.05 cup-metric, which shows as 0.1 cups. At a scale within 1e-9 of 1, it shows as written. toSystem lists the thresholds and measures.
| Quantity | scale |
system |
Result | Why |
|---|---|---|---|---|
| 3 tsp | 8 | US | ½ cup | 24 tsp is ½ cup |
| 3 tsp | 8 | metric | 8 tbsp | Cups aren’t metric |
| 1 tbsp | 0.5 | either | 1 ½ tsp | Less than 1 tbsp |
| 6 tbsp | 1.6 | US | 9 ½ tbsp | 9.6 tbsp is 1% from 9 ½ tbsp |
| ⅜ tsp | 0.5 | either | ¼ tsp | 3/16 tsp is halfway, which rounds up |
| 8 oz | 2 | US | 1 lb | 16 oz is 1 lb |
| 3–4 tsp | 2 | US | 6–8 tsp | 8 tsp isn’t near a multiple of ½ tbsp |
| 1 pint | 4 | US | 4 pints | Pints aren’t on a ladder |
| 2 cloves | 2 | either | 4 cloves | Count units never change |
Between two scales more than 1e-9 from 1, a scaled quantity that isn’t a range never goes down as the scale grows. Either end of a range can go down: by less than 2/21 (about 9.5%) when the range moves to another measure set, and by less than 5%, 1/16 cup or 1/16 tsp when its ends start or stop landing on one measure. A range lands on the first measure set both its ends fit, where an end below 1 cup that fits the ¼-cup set also fits the from-1-cup set. So 1–2.209 tsp is 1–2 tbsp at 2.8573× and 2 ¾–6 ¼ tsp at 2.8607×. A range whose ends scale or convert to different amounts but would land on the same measure keeps those amounts, so 0.999–1.001 tsp is 0.1871127–0.1874873 tsp at 0.1873× and ⅛–¼ tsp at 0.18752×, while 1–1 tsp is ⅛ tsp at 0.1873×. An amount or range end too small to land on ⅛ tsp stays exact, so 1 tsp is 0.1 tsp at 0.1×, and 1–2 tsp is 0.1–¼ tsp. Within 1e-9 of 1, an authored or equivalent quantity in its own system and unit shows as written rather than landing on a measure, so it can be up to half a measure step from where it lands at a nearby scale: in US units, 1 ⅜ cups shows as 1 ⅜ cups at 1× and as 1 ⅓ cups at 1.000000002×, and in metric, 5.244 tbsp shows as 5 ¼ tbsp at 1× and as 5 tbsp at 1.000001×.
import { resolveIngredient, type Ingredient } from '@recipe-book/core'
const salt: Ingredient = {
id: 'salt',
name: 'salt',
quantity: { amount: 3, unit: 'tsp' },
equivalents: [],
optional: false,
}
resolveIngredient(salt, { scale: 2, system: 'us' }).quantity // { amount: 2, unit: 'tbsp' }
resolveIngredient(salt, { scale: 2, system: 'us', rebalance: false }).quantity // { amount: 6, unit: 'tsp' }A line from parseIngredientLine resolves without first going through parseRecipe:
import { parseIngredientLine, resolveIngredient } from '@recipe-book/core'
const line = parseIngredientLine('1 cup milk')
if (!line.success) throw line.error
resolveIngredient(line.data).quantity // { amount: 236.5882365, unit: 'ml' }
resolveIngredient(line.data, { scale: 2, system: 'us' }).quantity // { amount: 2, unit: 'cup' }Throws a RecipeBookError with the code invalid_argument when scale is set and isn’t a finite number greater than 0, system is set and isn’t 'metric' or 'us', or the ingredient has a quantity and it or one of its equivalents is a quantity that scaleQuantity rejects. It doesn’t check units or the rest of the ingredient, so pass one from a parsed recipe or parseIngredientLine. An ingredient that’s null or a primitive, such as a string, throws a TypeError. With a quantity, so does an equivalents that’s neither undefined, null, nor iterable, such as 5 or {}; the items of any other iterable, such as a string’s characters, a Set’s values, or a Map’s entries, are checked as quantities. Unlike resolveRecipe, it doesn’t limit the scale to 1e-6 to 1e6, so a huge scale can overflow an amount to Infinity and a tiny one can underflow it to 0, which the format functions reject. An error thrown by a getter or proxy in the input or options passes through.
scaleQuantity
function scaleQuantity<A extends Amount>(
quantity: Quantity & { amount: A },
factor: number,
): { amount: SameAmount<A>; unit?: UnitId | undefined }Multiplies a quantity’s amount by a factor.
| Name | Type | Default | Description |
|---|---|---|---|
quantity |
Quantity & { amount: A } |
Required | The quantity to scale. |
factor |
number |
Required | The number to multiply by, such as 2 to double or 0.5 to halve. It must be a finite number greater than 0. |
Returns a new quantity with the same unit, so 3 tsp doubled is 6 tsp; resolveIngredient moves it to 2 tbsp. Nothing is rounded.
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' }Throws a RecipeBookError with the code invalid_argument when factor isn’t a finite number greater than 0, when quantity isn’t a quantity object, when the amount isn’t a finite number greater than 0 or a range of them, when a range’s min is greater than its max, or when quantity has a max, as a Servings or Yield has. Scale servings and yields with resolveRecipe. It also throws invalid_argument when an end times factor overflows to Infinity or underflows to 0: past about 1.8e308, or below about 2.5e-324, where it rounds to 0 rather than up to the smallest number, 5e-324. An error thrown by a getter or proxy in the input passes through.
Types
ResolvedRecipe
type ResolvedRecipe = {
recipe: Recipe
scale: number
servings?: Servings | undefined
yield?: Yield | undefined
system: System
canConvert: boolean
ingredients: Array<{
id: string
title?: string | undefined
items: ResolvedIngredient[]
}>
steps: Array<{
id: string
title?: string | undefined
items: Array<Step & { number: number }>
}>
}What resolveRecipe returns: the recipe at one scale, in one measurement system, unformatted.
| Name | Type | Description |
|---|---|---|
recipe |
Recipe |
The recipe you passed, unchanged. It’s the same object, not a copy, so don’t modify it. |
scale |
number |
The factor every quantity is multiplied by: a valid scale option, or else the servings option divided by the recipe’s scaling base (its servings amount, else its yield amount, else 1). So servings: 8 gives 2 for a recipe with 4 servings. It’s 1 when you leave out both options or neither is valid. For a factor within 1e-9 of 1, resolveRecipe multiplies nothing, so quantities, servings, and yield come back the same as at a scale of 1. |
servings |
Servings | undefined |
The recipe’s servings at this scale, absent when it has none. When the servings are the scaling base and the servings option sets a scale more than 1e-9 from 1, it’s exactly that number, with no max. Otherwise both ends of a range scale. The servings are the base unless their amount isn’t a finite number greater than 0, which only a recipe you build can have. With such an amount, at a scale more than 1e-9 from 1, a max that isn’t greater than it is dropped, which is every max when amount is NaN or Infinity. When amount is a finite number greater than 0, a max that isn’t greater than it, which only a recipe you build can have, is kept and scaled, even with the servings option, so formatServings throws invalid_argument at every scale. At a scale of 1, it’s the same object as recipe.servings, so don’t modify it. |
yield |
Yield | undefined |
The recipe’s yield at this scale, absent when it has none. When the servings aren’t the scaling base and the servings option sets a scale more than 1e-9 from 1, it’s exactly that number, with no max, even when the yield’s own amount isn’t a finite number greater than 0, which only a recipe you build can have. Otherwise both ends of a range scale. With such an amount, at a scale more than 1e-9 from 1, a max that isn’t greater than it is dropped, which is every max when amount is NaN or Infinity. When amount is a finite number greater than 0, a max that isn’t greater than it, which only a recipe you build can have, is kept and scaled, even with the servings option, so formatYield throws invalid_argument at every scale. At a scale of 1, it’s the same object as recipe.yield, so don’t modify it. |
system |
System |
The measurement system the quantities are in: the system option, else recipe.system, else 'metric'. |
canConvert |
boolean |
false when the recipe is system-neutral: no ingredient’s quantity, nor 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, such as cup or g. Each of a count unit’s equivalents counts, not only the one formatIngredient shows as the size. Step temperatures and step quantities don’t count, 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. |
ingredients |
Array<{ id: string; title?: string | undefined; items: ResolvedIngredient[] }> |
The ingredient sections in order, each with its id, its title if it has one, and its ingredients as ResolvedIngredient objects. |
steps |
Array<{ id: string; title?: string | undefined; items: Array<Step & { number: number }> }> |
The step sections in order. Each step is the recipe’s Step with a display number, counting from 1 across sections. |
Scale a recipe uses it to print the servings and yield at each scale.
ResolvedIngredient
type ResolvedIngredient = {
id: string
ingredient: Ingredient
quantity?: Quantity | undefined
origin: QuantityOrigin
}One ingredient, scaled and in one measurement system.
| Name | Type | Description |
|---|---|---|
id |
string |
The ingredient’s id. |
ingredient |
Ingredient |
The ingredient as authored and unscaled, for its name, plural, and note. It’s the same object, not a copy, so don’t modify it. |
quantity |
Quantity | undefined |
The quantity to show. It’s absent for an ingredient without one. A range whose min is greater than its max, or whose max is missing, null, or NaN, which only a recipe you build can have, is kept and scaled. formatIngredient throws invalid_argument for it at every scale. Where scaling or converting makes the range’s ends equal, it gives one amount instead. At a scale of 1, quantity can be the same object as on the ingredient, so don’t modify it. |
origin |
QuantityOrigin |
Where quantity comes from. |
Scale a recipe uses it to list each ingredient with the quantity to show.
QuantityOrigin
type QuantityOrigin = 'authored' | 'equivalent' | 'converted'Where a resolved quantity comes from. The union may grow in minor releases.
| Value | When |
|---|---|
'authored' |
The ingredient’s quantity belongs to the measurement system, or is used with a unit that isn’t a unit ID, or the ingredient has none. Rebalancing keeps this origin: 3 tsp shown as 2 tbsp is still 'authored'. |
'equivalent' |
The ingredient’s quantity doesn’t belong to the system, and one of its equivalents does. The first one that does is used. |
'converted' |
Neither the ingredient’s quantity nor any of its equivalents belongs to the system, so the first weight is converted for a metric reader, else quantity when its unit is a unit ID. |
Scale a recipe shows the origin of each ingredient in a sample recipe.
ResolveRecipeOptions
type ResolveRecipeOptions = {
servings?: number | undefined
scale?: number | undefined
system?: System | undefined
rebalance?: boolean | undefined
exact?: boolean | undefined
}Options for resolveRecipe. An option that isn’t valid uses its default.
| Name | Type | Description |
|---|---|---|
servings |
number | undefined |
The number of servings to show. The recipe scales by servings divided by its servings amount, else its yield amount, else 1. So for a recipe with a yield and no servings, it counts the yield’s unit, such as cookies. A valid scale takes precedence. Without either, the scale is 1. A value that isn’t a finite number greater than 0, or that’s outside a millionth to a million times the number it’s divided by, is ignored. |
scale |
number | undefined |
A direct multiplier, such as 2 for a 2× button. A scale that isn’t a number from 1e-6 to 1e6 is ignored, so servings applies. |
system |
System | undefined |
The measurement system to show quantities in. Defaults to recipe.system, then 'metric'. |
rebalance |
boolean | undefined |
Whether to move a scaled authored or equivalent quantity to the best unit on its own ladder, such as 6 tsp to 2 tbsp. Defaults to true. Pass false to keep the unit it was written in. A converted quantity always gets the unit that fits it. |
exact |
boolean | undefined |
Pass true to keep converted and rebalanced amounts exact, so 150 mL in 'us' is 10.1442… tbsp, which formatIngredient writes as 10 ⅛ tbsp, rather than 10 tbsp. The unit is still the one a cook measures with. |
ResolveIngredientOptions
type ResolveIngredientOptions = {
scale?: number | undefined
system?: System | undefined
rebalance?: boolean | undefined
exact?: boolean | undefined
}Options for resolveIngredient. The defaults match resolveRecipe’s for a recipe with no system. Unlike ResolveRecipeOptions, scale and system are checked, and invalid values throw rather than use the default.
| Name | Type | Description |
|---|---|---|
scale |
number | undefined |
The factor to multiply the quantity by. Defaults to 1. When set, it must be a finite number greater than 0. |
system |
System | undefined |
The measurement system to show the quantity in: 'metric' or 'us'. Defaults to 'metric'. |
rebalance |
boolean | undefined |
Whether to move a scaled authored or equivalent quantity to the best unit on its own ladder, such as 6 tsp to 2 tbsp. Defaults to true. Pass false to keep the unit it was written in. A converted quantity always gets the unit that fits it. |
exact |
boolean | undefined |
Pass true to keep converted and rebalanced amounts exact, so 150 mL in 'us' is 10.1442… tbsp, which formatIngredient writes as 10 ⅛ tbsp, rather than 10 tbsp. The unit is still the one a cook measures with. |
RecipeViewInput
type RecipeViewInput = {
servings?: unknown
system?: unknown
}The values readRecipeView reads. Nothing in them is trusted.
| Name | Type | Description |
|---|---|---|
servings |
unknown |
A number of servings, a string such as url.searchParams.get('servings') returns, or an array of them, such as Next.js’s searchParams holds for a repeated key. |
system |
unknown |
A measurement system, such as a cookie’s value, or an array whose first item is one. |
RecipeView
type RecipeView = {
servings?: number | undefined
system?: System | undefined
}What readRecipeView returns.
| Name | Type | Description |
|---|---|---|
servings |
number | undefined |
The servings from the input, when they’re in the recipe’s servings window. Otherwise the key is left out. |
system |
System | undefined |
The measurement system from the input, when it’s 'metric' or 'us'. Otherwise the key is left out. |