3.3Core reference
Units
Reference for the unit registry and the @recipe-book/core functions that look up units, convert quantities and temperatures, and find temperatures, durations, and quantities in step text.
Use these exports from @recipe-book/core to look up units, convert quantities between units and measurement systems, convert temperatures, and find temperatures, durations, and quantities in step text. For a walkthrough, see Convert units. In a React app, replace @recipe-book/core with @recipe-book/react/core in this page’s imports.
convert
function convert<A extends Amount, To extends UnitId>(
quantity: Quantity & { amount: A },
to: To,
): { amount: SameAmount<A>; unit: To }Converts a quantity to another unit of the same dimension: mass to mass, or volume to volume.
| Name | Type | Default | Description |
|---|---|---|---|
quantity |
Quantity & { amount: A } |
Required | The quantity to convert. It needs a unit; a quantity without one is a bare count. |
to |
To |
Required | The unit to convert to. It must measure the same dimension as quantity.unit, or be the same unit. |
Returns a new quantity in the to unit. Nothing is rounded, so the amount can be off in its last digit: 5 tbsp is 14.999999999999998 tsp. To show it, pass it to formatQuantity, which writes 15 tsp.
import { convert } from '@recipe-book/core'
convert({ amount: 1.25, unit: 'cup' }, 'ml') // { amount: 295.735295625, unit: 'ml' }
convert({ amount: { min: 2, max: 3 }, unit: 'tbsp' }, 'tsp') // { amount: { min: 6, max: 9 }, unit: 'tsp' }Throws a RecipeBookError with one of these codes:
incompatible_unitswhen the units measure different dimensions, such as cups to grams; when either unit is a count unit such ascloveand the units differ; or when the quantity has no unitunknown_unitwhentoorquantity.unitisn’t a unit ID, such as'cups'invalid_argumentwhenquantityisn’t a quantity object, when the amount isn’t a finite number greater than 0 or a range of them, when a range’sminis greater than itsmax, whenquantityhas amax, as aServingsorYieldhas, or when the result overflows toInfinity, or when the result underflows to 0, which only an amount above about 1e300 or below about 1e-300 can do
An error thrown by a getter or proxy in the input passes through.
A cup’s weight depends on the ingredient, so convert can’t turn cups into grams. Give the ingredient its weight as an equivalent instead, as Convert cups to grams shows.
When units come from data, check them with canConvert first.
canConvert
function canConvert(from: UnitId | undefined, to: UnitId | undefined): booleanChecks whether convert can convert between two units.
| Name | Type | Default | Description |
|---|---|---|---|
from |
UnitId | undefined |
Required | The unit to convert from. Pass undefined for a bare count. |
to |
UnitId | undefined |
Required | The unit to convert to. undefined, as findUnit returns for unknown text, gives false. |
Returns true when both are the same unit, or both are mass units, or both are volume units. Returns false otherwise, including for a bare count or a string that isn’t a unit ID.
import { canConvert } from '@recipe-book/core'
canConvert('cup', 'ml') // true
canConvert('cup', 'g') // false
canConvert(undefined, 'g') // falseNever throws, so it’s safe on data you don’t control. It checks units only: convert can still throw invalid_argument for the amount.
Convert units uses it to check units from users or a CMS before converting them.
toSystem
function toSystem<A extends Amount>(
quantity: Quantity & { amount: A },
system: System,
options?: ToSystemOptions,
): { amount: SameAmount<A>; unit?: UnitId | undefined }Expresses a quantity in a measurement system, choosing the unit from that system.
| Name | Type | Default | Description |
|---|---|---|---|
quantity |
Quantity & { amount: A } |
Required | The quantity to express. |
system |
System |
Required | The measurement system to use: 'metric' or 'us'. |
options |
ToSystemOptions |
{} |
Whether to keep the converted amount exact. |
Returns the same quantity object when its unit is already native to system, when it’s a count unit, or when it has no unit. tsp and tbsp are native to both systems. Otherwise, returns a new quantity in a unit from the system’s ladder:
| System | Dimension | Ladder, largest unit first |
|---|---|---|
| metric | mass | kg from 999.5 g, then g |
| metric | volume | l from 999.5 mL, then ml |
| US | mass | lb from 15.9375 oz, then oz |
| US | volume | cup from ¼ cup, then tbsp from 1 tbsp, then tsp |
For mass and metric volume, toSystem picks the largest unit whose threshold the quantity meets. kg, L, and lb start where the smaller unit would format the quantity as 1 of them: 999.5 g formats as 1000 g, so it’s 1 kg, while 998 g stays 998 g, and 15.9375 oz formats as 16 oz, so it’s 1 lb. Metric amounts and US weights aren’t rounded, so they can be off in their last digit, as with convert. To show one, pass it to formatQuantity, which writes the 354.88235475 mL below as 355 mL.
US volume lands on a cup or spoon measure, except a quantity or range end too small to land on ⅛ tsp, which stays exact, and a range whose ends convert to different amounts but would land on the same measure, which keeps those amounts. It takes the measure from the first of these sets of measuring cups or spoons that fits:
- Cups, on a multiple of ¼ or ⅓ cup less than 5% from the quantity.
- From 1 cup, cups on the nearest multiple of ⅛ or ⅓ cup, at most 1/16 cup (1 tbsp) off. In a range, an end below 1 cup lands as it would in set 1.
- From 1 tbsp, tbsp on a multiple of ½ tbsp less than 5% from the quantity.
- tsp, on ⅛ tsp or a multiple of ¼ tsp less than 5% from the quantity.
- tsp, on the nearest multiple of ⅛ tsp, at most 1/16 tsp off.
So 150 mL, 10.1442… tbsp, is 10 tbsp: ⅔ cup is 5.2% off, and ⅝ cup isn’t a measure below 1 cup. The smallest measure of each set is its threshold, and a quantity slightly below one lands on it when it’s less than 5% off: 14.2 mL (0.96 tbsp) is 1 tbsp, but 14.05 mL (0.95 tbsp) is 2 ¾ tsp. A quantity halfway between two measures lands on the larger, as formatQuantity rounds it, so 3/16 tsp is ¼ tsp and 1 1/16 cups is 1 ⅛ cups. For a range, each end lands on its own measure, and both must fit the same set, so a range never mixes units. An end below 1 cup that fits set 1 also fits set 2, so 180–270 mL is ¾–1 ⅛ cups. A range whose ends convert to different amounts but would land on the same measure keeps those amounts, so 14.8–15 mL is 1.0009–1.0144 tbsp, which formatQuantity writes as 1 tbsp. resolveRecipe lands the cups and spoons it scales or converts the same way. 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. Units off the ladders, such as fl-oz, quart, and dl, are never chosen.
import { toSystem } from '@recipe-book/core'
toSystem({ amount: 1.5, unit: 'cup' }, 'metric') // { amount: 354.88235475, unit: 'ml' }
toSystem({ amount: 150, unit: 'ml' }, 'us') // { amount: 10, unit: 'tbsp' }
toSystem({ amount: 3, unit: 'tbsp' }, 'metric') // { amount: 3, unit: 'tbsp' }
toSystem({ amount: 150, unit: 'ml' }, 'us', { exact: true }) // { amount: 10.1442068105529, unit: 'tbsp' }With exact: true, US volume takes the same unit but keeps its exact amount, as resolveRecipe’s exact does, so 150 mL is 10.1442… tbsp, which formatQuantity writes as 10 ⅛ tbsp. Any other exact, or options that isn’t an object, rounds as above.
Throws a RecipeBookError with one of these codes:
invalid_argumentwhensystemisn’t'metric'or'us', whenquantityisn’t a quantity object, when the amount isn’t a finite number greater than 0 or a range of them, when a range’sminis greater than itsmax, whenquantityhas amax, as aServingsorYieldhas, or when the result or the measure it lands on overflows toInfinity, or when the result underflows to 0, which only an amount above about 1e300 or below about 1e-300 can dounknown_unitwhenquantity.unitisn’t a unit ID
An error thrown by a getter or proxy in the input passes through.
Convert units uses it to switch a reader between systems.
findUnit
function findUnit<Alias extends UnitAlias>(text: Alias): UnitIdOf<Alias>
function findUnit<Alias extends UnitAlias>(text: `${Alias}.`): UnitIdOf<Alias>
function findUnit(text: string): UnitId | undefinedFinds the unit that author text names, such as 'cups' or 'T', and returns its ID.
| Name | Type | Default | Description |
|---|---|---|---|
text |
string |
Required | The text to look up. Surrounding whitespace is ignored, inner whitespace is collapsed, a period that ends a word is dropped, and case is ignored except for 'T' (tbsp), 't' (tsp), and 'c' (cup). |
Returns the unit ID, or undefined when the text names no unit in the registry. When you pass a string literal that is a UnitAlias, with or without a period after it, the return type is that unit’s ID: findUnit('tablespoons') and findUnit('tbsp.') have the type 'tbsp'.
import { findUnit } from '@recipe-book/core'
findUnit('Tablespoons') // 'tbsp'
findUnit('T') // 'tbsp'
findUnit('t') // 'tsp'
findUnit('fl oz') // 'fl-oz'
findUnit('fl. oz.') // 'fl-oz'
findUnit('c.') // 'cup'
findUnit('C') // undefined
findUnit('knob') // undefinedNever throws. It returns undefined for values that aren’t strings. Uppercase C isn’t a unit, because it usually means Celsius.
It takes no options, so 'cups' is always cup. To read cups or tablespoons in text as cup-metric or tbsp-au, pass units to a parser such as parseRecipe.
Convert units uses it to read units from users or a CMS.
getUnit
function getUnit<Id extends UnitId>(
id: Id,
): UnitDefinition & { readonly id: Id }Returns the registry entry for a unit ID.
| Name | Type | Default | Description |
|---|---|---|---|
id |
Id |
Required | The unit ID, such as 'cup'. Use findUnit to turn author text into an ID. |
Returns the frozen UnitDefinition for the unit, the same object as units[id].
import { getUnit } from '@recipe-book/core'
getUnit('cup').toBase // 236.5882365
getUnit('tbsp').systems // ['metric', 'us']Throws a RecipeBookError with the code unknown_unit when id isn’t a unit ID. When you pass an alias such as 'cups', the message names the ID to use.
units
const units: { readonly [Id in UnitId]: UnitDefinition & { readonly id: Id } }The unit registry: every supported unit for quantities, keyed by unit ID. Temperatures aren’t in it: convertTemperature converts between 'C' and 'F'. The registry and every entry in it are frozen.
import { units } from '@recipe-book/core'
units.cup.toBase // 236.5882365
Object.values(units).filter((unit) => unit.dimension === 'mass').length // 5The supported units for quantities by dimension, with their sizes in grams or milliliters (toBase):
| ID | Systems | Size (toBase) |
|---|---|---|
| Mass (g) | ||
mg | metric | 0.001 g |
g | metric | 1 g |
kg | metric | 1000 g |
oz | US | 28.349523125 g |
lb | US | 453.59237 g |
| Volume (mL) | ||
ml | metric | 1 mL |
cl | metric | 10 mL |
dl | metric | 100 mL |
l | metric | 1000 mL |
tsp | metric and US | 4.92892159375 mL |
tbsp | metric and US | 14.78676478125 mL |
tbsp-au | metric | 20 mL |
fl-oz | US | 29.5735295625 mL |
cup | US | 236.5882365 mL |
cup-metric | metric | 250 mL |
pint | US | 473.176473 mL |
quart | US | 946.352946 mL |
gallon | US | 3785.411784 mL |
| Count | ||
pinch | metric and US | None |
dash | metric and US | None |
clove | metric and US | None |
slice | metric and US | None |
piece | metric and US | None |
can | metric and US | None |
package | metric and US | None |
stick | metric and US | None |
sprig | metric and US | None |
bunch | metric and US | None |
head | metric and US | None |
bag | metric and US | None |
handful | metric and US | None |
jar | metric and US | None |
stalk | metric and US | None |
The sizes are exact, and all but cup-metric and tbsp-au are from NIST Handbook 44: 1 lb is 453.59237 g, and 1 tsp is 1/768 of a US gallon of 3785.411784 mL. So cups, pints, quarts, gallons, and fluid ounces are US sizes: cup is about 237 mL, not a 250 mL metric cup, and a pint is about 473 mL, not a 568 mL UK pint. For a recipe written with metric cups, use cup-metric, described below. For UK pints, give those quantities in milliliters.
Besides a unit’s ID, findUnit accepts its aliases:
mg:milligram,milligrams,milligramme,milligrammesg:gm,gms,gr,grs,gram,grams,gramme,grammeskg:kgs,kilo,kilos,kilogram,kilograms,kilogramme,kilogrammesoz:ozs,ounce,ounceslb:lbs,pound,poundsml:mL,krm,milliliter,milliliters,millilitre,millilitrescl:cL,centiliter,centiliters,centilitre,centilitresdl:dL,deciliter,deciliters,decilitre,decilitresl:L,lt,lts,ltr,ltrs,liter,liters,litre,litrestsp:t,tsps,tl,tsk,ts,teaspoon,teaspoonstbsp:T,tb,tbs,tbsps,el,msk,spsk,ss,tablespoon,tablespoonsfl-oz:fl oz,fluid ounce,fluid ouncescup:cups,cpint:pt,pts,pintsquart:qt,qts,quartsgallon:gal,gals,gallonspinch:pinches,nypa,prise,prisendash:dashesclove:clovesslice:slicespiece:pieces,pc,pcs,unit,units,pièce,pièces,stk,stückcan:canspackage:packages,pkg,pkgsstick:stickssprig:sprigsbunch:bunches,bundhead:headsbag:bagshandful:handfulsjar:jarsstalk:stalks
el and tl are the tablespoon and teaspoon as German recipes write them, EL and TL, and Dutch ones, el and tl. tsk is the teaspoon as Swedish and Danish recipes write it, and the tablespoon is msk in Swedish recipes and spsk in Danish ones.
ss and ts are the tablespoon and teaspoon as Norwegian recipes write them, and krm, the Swedish kryddmått, is a milliliter. stk, as Norwegian and Danish recipes write it, and the German Stück are a piece, the Swedish nypa and the German Prise and Prisen are a pinch, and the German Bund is a bunch. The Swedish st isn’t read as a piece, since it would read the St. in '3 St. Germain liqueur'.
cup-metric is the 250 mL cup of Australia, New Zealand, Canada, and South Africa, and tbsp-au the 20 mL Australian tablespoon. They have no aliases besides their IDs, so text such as '2 cups' names them only through the parsers’ units option, which reads every cup or tablespoon as one of them. They show the labels cup and tbsp, and round to fractions like US units.
convertTemperature
function convertTemperature(
temperature: Temperature,
to: TemperatureUnit,
): TemperatureConverts a temperature between Celsius and Fahrenheit.
| Name | Type | Default | Description |
|---|---|---|---|
temperature |
Temperature |
Required | The temperature to convert. |
to |
TemperatureUnit |
Required | The unit to convert to: 'C' or 'F'. |
Returns a new temperature in the to unit. Nothing is rounded, so the value can be off in its last digits: −18 °C is −0.3999999999999986 °F.
import { convertTemperature } from '@recipe-book/core'
convertTemperature({ value: 180, unit: 'C' }, 'F') // { value: 356, unit: 'F' }
convertTemperature({ value: 350, unit: 'F' }, 'C') // { value: 176.66666666666666, unit: 'C' }Throws a RecipeBookError with the code invalid_argument when the value isn’t a finite number, when either unit isn’t 'C' or 'F', or when a value beyond about ±2e307 °C is converted to °F or one beyond about ±3.6e307 °F is converted to °C, where the arithmetic overflows to Infinity or -Infinity even when the result itself would be finite. An error thrown by a getter or proxy in the input passes through.
Convert units shows it, and Display quantities rounds its result to an oven temperature a recipe would print, such as 180 °C.
segmentStepText
function segmentStepText(
text: string,
options?: SegmentStepTextOptions,
): StepSegment[]Splits step text into plain text and the temperatures and durations written in it.
| Name | Type | Default | Description |
|---|---|---|---|
text |
string |
Required | The step text, such as a Step’s text. |
options |
SegmentStepTextOptions |
None | Set assumeTemperatureUnit to read temperatures written with a degree sign or “degree” or “degrees” but no unit, as in Bake at 350°., or inferTemperatureUnit to read those of 275 or more as °F. |
Returns the segments in order. Joining every segment’s text gives back text exactly.
A temperature is a number followed by a unit, a degree sign and a unit, or “degree” or “degrees” and a unit: 350°F, 180 °C, 180C, 200℃, 350 degrees F, or 350 degrees Fahrenheit. A minus sign, written -, −, or –, makes it negative at the start of the text, after a space or an opening parenthesis, or right after ~, /, −, ⸺, ﹣, -, or a dash other than -, as in Freeze at -18°C. and Freeze at -18°C–-20°C., which has two readings. -- is a typed dash, so Preheat the oven--350°F. reads 350 °F. A - or – right after a number with no unit of its own, or with only a degree sign, as in 350 -375°F and 350° -375°F, is a dash that joins a range’s ends instead, and so is a − between two digits, as in 350−375°F. These rules decide the rest:
- A setting that the author already wrote more than one way is one segment, so it never gets a second conversion:
400 degrees F (200 degrees C),200C/180C fan forced, and190C/170C fan/gas 5. A gas mark stays in the segment’stextand isn’t read. - A temperature written after a gas mark and a slash or “or”, as in
gas 6/200Candgas mark 6 or 200C, is still read. The200Cis its owntemperaturesegment, and the gas mark stays in the text segment before it. - Readings pair only when a space, a slash, a comma, “or”, a dash, or parentheses join them, so
350°F 180°Cis one segment and350°F and 180°Cis two. A parenthesis may start with a hedge such as “about”, “approx.”, “around”, “ca.”, “i.e.”, “or”, or~, as in350°F (about 180°C). - Two readings for the same kind of oven pair only when they’re in different units and within 10 °C (18 °F) of each other, so they state one setting. So
350°F or 375°F,160°C, 180°C, and350°F or 200°Care separate segments. - A conventional setting and a fan setting pair whichever comes first, so
190°C (375°F) or 170°C fan (340°F)is one segment, as170°C fan (340°F) or 190°C (375°F)is. Otherwise, when a parenthesis restates a reading after the first, that reading starts its own segment.190°C or 160°C fan (350°F)is two segments, because 350 °F is a conventional setting, as below. So is190°C (375°F) or 170°C (340°F) Fan, whose second setting isn’t marked until after its parenthesis. - A fan or convection marker before or after a reading sets its
fan:170C fan,180C fan forced,fan-forced 180C,325°F (convection), andUmluft 180 °C. A marker after a closing parenthesis, as in170°C (340°F) Fan, sets it on every reading in the segment. Otherwise, a marker with other words between it and the reading, as in325°F for convection, isn’t read, so that reading hasfan: false, unless it restates a fan reading in parentheses, as below. - An unmarked reading in parentheses that restates a fan reading is for a fan oven too, so both readings in
170°C fan (340°F)havefan. In160°C fan (350°F), 350 °F is 177 °C, so it’s a conventional setting and keepsfan: false. - A number with only a degree sign or “degree” or “degrees”, as in
Bake at 350°.orBake in a 350-degree oven., stays text unless you setassumeTemperatureUnit, and so does a reading paired with it, as inBake at 350° (175°C).WithinferTemperatureUnitinstead, one of 275 or more is °F, since 275 °C is hotter than most home ovens go, soPreheat the oven to 425 degrees.reads 425 °F andWarm the plates at 200°.stays text. Even with either option, it counts only after a word such as “at”, “to”, or “bake”, before “oven”, or when it pairs with another reading, as inOven: 200° (180°C fan).and180°C fan (200°). Sorotate the pan 180 degreesstays text. It pairs with a reading before or after it across a space, a comma, a slash, “or”, or a dash, or in parentheses, wherever the same text with the unit written out would pair them, so with'F',Bake at 350°/175°C.is one segment, asBake at 350°F/175°C.is. WithinferTemperatureUnit, it pairs only with a reading after it, soBake at 400° (200°C).is one segment, but the400°inBake at 200°C (400°).stays text. When it doesn’t pair, a slash, “or”, a dash, “to”, “and”,&, or~followed by a number makes it the first end of a range, which stays text with its other end, as inBake at 350°–375°F.A number followed by a time word isn’t the other end, so the350°inBake at 350° – 25 minutes.is a temperature. - A range with its unit only on the second end, such as
350–375°F,350 to 375 degrees F, or350 or 375°F, stays text when a dash, a slash,&,~, “to”, “and”, or “or” joins its ends. A range with its unit only on the first end, such as350°F–375,175°C to 190, or-18°C to -20, stays text when a dash,~, or “to” joins them. The second end needs a minus sign, or has to be larger than a first end that isn’t below zero without restating it in °F. With a degree sign, it can’t have a fan marker or a parenthesis of its own, as in170°C fan – 190° (375°F). Without one, the end of the text,.,!,?,), “for”, “until”, “till”, “oven”, or a,or;that no other number follows has to follow it. So200°C – 400°reads 200 °C, and27°C – 60% humidity,180°C – 250 g flour,4 °C – 72 Stunden, and18°C – 30, 60, or 90 daysread 27 °C, 180 °C, 4 °C, and 18 °C. Otherwise only the end with the unit is a temperature, as with another word, such as “through” or “till”, between the ends, or with “or” in350°F or 375. A conversion then rewrites that end alone, soshowStepbelow turns350°F through 375into177 °C through 375. A range with a unit on each end, such as350°F to 375°F, is two segments. A range written in both units, as in350°F to 375°F (175°C to 190°C), is four segments, so a converted step shows the range twice. - A change in temperature, as in
lower the heat by 25°Forby about another 20°F, stays text. - A unit written as one letter needs a whole number of at least two digits, as in
180Cor350 F, soStep 12Creads as 12 °C and37.5Cstays text. A lowercasefneeds three digits, so90Fis a temperature and90 fisn’t. A lowercasec, or aCafter a space, could mean cups, so it needs three digits and a word such as “at” or “to” before it, “oven” after it, or another reading that it pairs with.2C,12 C bowl, andadd 100 c sugarstay text, whileheat to 180 c,a 180 C oven,a 180 C fan oven,Oven: 180 C (350 F), and350 F/180 Care temperatures.
A segment’s oven is true when the step says it’s an oven setting rather than the food’s, the oil’s, or another appliance’s temperature. That’s when a reading in the segment has fan or the segment has a gas mark; when “oven” comes right after it, as in a 200°C oven; when “oven”, “preheat”, “bake”, or “roast” comes before it in its sentence with no word such as “internal”, “thermometer”, “until”, “oil”, “air fryer”, or “grill” and no new clause between them; or, with no such word before it in its sentence, when one of those oven words comes after it with no new clause between them, as in At 180°C, bake for 20 minutes. So Roast until it registers 165°F. and Preheat your air fryer to 200°C. aren’t oven settings. A new clause starts at a comma or “and”, with or without “then” after it, before “heat”, “warm”, “bring”, or “cool” and an object other than “to”, “at”, or “it”. So in Preheat the oven to 220°C and heat the milk to 70°C. and Heat the milk to 70°C, then heat the oven to 220°C. only 220°C is an oven setting, but in Put a rack in the oven and heat to 350°F. 350°F is one. A Dutch oven is a pot, so Bake in a Dutch oven at 450°F. is an oven setting and Heat the oil in a Dutch oven to 350°F. isn’t. A dash, or one to three spaces or line breaks, can join the parts of “preheat” and “Dutch oven”, as in Pre heat to 350°F. and Heat a Dutch-oven to 350°F., but a dash with spaces around it can’t, as in Pre - heat to 350°F. A sentence ends at ., !, ?, or ; before a space, or at a line break. Only English words are read, besides the fan markers above. The words that rule a reading out were chosen by reading the steps in recipe-scrapers’ test data, and are scored on those same steps: there, 416 of the 418 segments that are English oven settings are marked, and 1 of the 417 marked isn’t one. Expect more misses and false hits on other text.
import { segmentStepText } from '@recipe-book/core'
segmentStepText('Bake at 350°F.').map((segment) => segment.text) // ['Bake at ', '350°F', '.']
segmentStepText('Heat oven to 200C/180C fan forced.')[1] // { type: 'temperature', text: '200C/180C fan forced', temperature: { value: 200, unit: 'C' }, fan: false, oven: true, alternatives: [{ temperature: { value: 180, unit: 'C' }, fan: true }] }
segmentStepText('Bake at 350 degrees.').length // 1
segmentStepText('Bake at 350 degrees.', { assumeTemperatureUnit: 'F' })[1] // { type: 'temperature', text: '350 degrees', temperature: { value: 350, unit: 'F' }, fan: false, oven: true, alternatives: [] }
segmentStepText('Preheat the oven to 425 degrees.', { inferTemperatureUnit: true })[1] // { type: 'temperature', text: '425 degrees', temperature: { value: 425, unit: 'F' }, fan: false, oven: true, alternatives: [] }
segmentStepText('Bake at 350°F until a thermometer reads 165°F.').flatMap((segment) => (segment.type === 'temperature' ? [segment.oven] : [])) // [true, false]A duration is a number or a range, then a time word: 20 minutes, 1.5 hours, 25–30 min, or 10 to 12 secs. After hours, it can go on to minutes, as in 1 hr 30 min. Its minutes never scale, since twice the batch doesn’t take twice as long, and formatDuration formats them. These rules decide the rest:
- The time words are “second”, “sec”, “minute”, “min”, “hour”, and “hr”, with or without an “s”, in any case. A period after one stays outside the segment, as in
10 min. - A dash, a tilde, “to”, “or”, or “and” joins a range’s ends, which share the time word, as in
10 to 12 min,10~12 min,25 or 30 minutes, andbetween 25 and 30 minutes. A range with equal ends, such as10-10 minutes, is one value. A reversed range, such as30-25 minutes, stays text, and so does a duration of 0. - Seconds are fractions of a minute, so
30 secondsis 0.5 minutes, and hours are 60 minutes, so1.5 hoursis 90 and.5 hoursis 30. - Before a minute or hour word, “a”, “an”, or “one” is 1, so
about a minuteis 1 andan hour and 15 minutesis 75. It doesn’t start a range, soPart one – 20 minutesis 20 minutes. Before “second”, it stays text, since there it usually means another, as ina second bowl. It stays text, too, at the end of a longer word, as inJamaican hour, and after “half” or “quarter”, as inhalf an hourandthree quarters of an hour. - Fractions, as in
1 ½ minutes,2 1/2 hours, and½–1 hour, decimal commas, as in1,5 hours, other number words, as in “two minutes”, hyphenated forms, as ina 5-minute rest, and single letters, as in1 h, stay text. A range that starts with a fraction, such as1½–2 hours, stays text whole. A comma, colon, or slash right before a number keeps its duration text too, as in200°C/20 minutes. - Hours, then minutes, with only spaces or “and” between them, are one duration:
1 hour 30 minutesand1 hr 30 minare 90, and1 hour and 15 minutesis 75. In a range, the minutes count for both ends, so1–2 hours 30 minutesis 90 to 150. Other pairs are two durations with text between them, as in1 hour, 30 minutesand5 minutes and 1 hour. A word before a number, as in “about 10 minutes”, stays in the text before it. - Temperatures are read first, and a dash between a temperature and a duration doesn’t join them, so
200°C – 20 minutesis a temperature, the text between them, and a duration. - A number after “gas”, “mark”, or “step” doesn’t start a range, so
gas 4 – 20 minutesandStep 2 – 20 minutesare each 20 minutes. Nor does a gas mark range’s high end, as ingas 4–5 – 20 minutes,gas 4 - 5 – 20 minutes, andgas 4 to 5 – 20 minutes. A high end is a mark above the low end, up to 9, sogas 4 – 10 – 12 minutesis 10 to 12. After a joiner with spaces before it, the joiner after the high end needs them too, sogas 5 – 8–10 minutesis 8 to 10.
import { segmentStepText } from '@recipe-book/core'
segmentStepText('Simmer for 25–30 minutes.')[1] // { type: 'duration', text: '25–30 minutes', minutes: 25, max: 30 }
segmentStepText('Whisk for 30 seconds.')[1] // { type: 'duration', text: '30 seconds', minutes: 0.5 }
segmentStepText('Roast for 1 hour and 15 minutes.')[1] // { type: 'duration', text: '1 hour and 15 minutes', minutes: 75 }
segmentStepText('Chill for about an hour.')[1] // { type: 'duration', text: 'an hour', minutes: 60 }
segmentStepText('Cook 30-25 minutes.').length // 1To show a step in the reader’s unit, show each kind of oven in a segment once. For the conventional setting and for the fan setting, take the reading of that kind that’s already in the reader’s unit, or else convert the first reading of that kind with convertTemperature. Then format that reading with formatTemperature: keep its value if it’s already in the reader’s unit. If you converted it, round it to oven steps when the segment’s oven is true, and to whole degrees otherwise. This function does that:
import {
convertTemperature,
formatTemperature,
segmentStepText,
type TemperatureUnit,
} from '@recipe-book/core'
function showStep(text: string, unit: TemperatureUnit): string {
return segmentStepText(text)
.map((segment) => {
if (segment.type !== 'temperature') {
return segment.text
}
const readings = [segment, ...segment.alternatives]
return [false, true]
.flatMap((fan) => {
const kind = readings.filter((reading) => reading.fan === fan)
const reading =
kind.find(({ temperature }) => temperature.unit === unit) ?? kind[0]
if (!reading) {
return []
}
const shown = formatTemperature(
convertTemperature(reading.temperature, unit),
{
rounding:
reading.temperature.unit === unit
? 'none'
: segment.oven
? 'oven'
: 'kitchen',
},
)
return [fan ? `${shown} fan` : shown]
})
.join(' / ')
})
.join('')
}
showStep('Preheat oven to 190°C (375°F) or 170°C fan (340°F).', 'F') // 'Preheat oven to 375 °F / 340 °F fan.'
showStep('Heat oven to 190C/170C fan/gas 5.', 'F') // 'Heat oven to 375 °F / 350 °F fan.'
showStep('Cook sous vide at 56.5°C.', 'C') // 'Cook sous vide at 56.5 °C.'
showStep('Cook sous vide at 56.5°C.', 'F') // 'Cook sous vide at 134 °F.'
showStep('Bake at 350°F until a thermometer reads 165°F.', 'C') // 'Bake at 180 °C until a thermometer reads 74 °C.'In the first step, both settings are already written in Fahrenheit, so a US reader sees the values the author wrote. They’re one segment, so a slash joins them in place of the author’s “or”. In the second, both are only in Celsius, so showStep converts them, rounds them to oven steps because they’re oven settings, and leaves out the gas mark. In React, <Recipe.StepText> shows a step this way, in <Recipe.Root>’s measurement system, and its inferTemperatureUnit prop passes that option. Its text differs from showStep’s in one way: a word joiner (U+2060) follows a dash or tilde between a duration’s ends when a number comes right after it, as in 25–30 minutes or 25~30 minutes, so the line doesn’t break there.
In the third step, a metric reader sees the 56.5 °C the author wrote. showStep uses formatTemperature’s oven rounding only for an oven setting, because a step can also give a food temperature: with oven rounding, a safe internal temperature of 165 °F would show as 70 °C rather than 74 °C. Sous vide isn’t an oven setting, so the fourth step converts to whole degrees. In the fifth, the oven setting rounds to 180 °C and the thermometer’s reading to 74 °C.
Throws a RecipeBookError with the code invalid_argument when text isn’t a string, or assumeTemperatureUnit isn’t 'C' or 'F'. An error thrown by a getter or proxy in the options passes through.
segmentStepQuantities
function segmentStepQuantities(text: string): StepQuantitySegment[]Finds the mass and volume quantities in step text, and splits the text around them so a page can show them in another measurement system.
| Name | Type | Default | Description |
|---|---|---|---|
text |
string |
Required | The step text, such as a Step’s text, or the text of a text segment from segmentStepText. |
Returns the segments in order. Joining every segment’s text gives back text exactly. It only finds quantities, and never converts or scales them.
A quantity is a whole number, a decimal with a point, a fraction, a mixed number, or a range, then a mass or volume unit that findUnit reads, after up to three spaces or none: 200 g, 180g, 1 ½ cups, 2¼ cups, 1/2 cup, 1.5 tbsp, 2-3 tablespoons, 1 to 2 cups, or 8 fl oz. These rules decide the rest:
- A quantity that the author already wrote another way is one segment, so it doesn’t get a second conversion:
200 g (7 oz),2 cups (about 480 ml),1 cup (240 ml, 8 fl oz),1 cup / 240 ml, and4 Tbsp or 60 ml. A segment holds five quantities at most, as in1 cup / 8 fl oz / 240 ml / 8 oz / 225 g, or six when the last two share a parenthesis, as in1 cup / 16 tbsp / 8 fl oz / 8 oz (240 ml, 225 g). The next quantity starts a new segment, so it can be converted again, unless a slash comes right before it with no space, which leaves it as text. The first quantity is the segment’squantity, and the others are itsalternatives. A restatement in the other dimension or the other system always counts, so8 oz (225 g)and2 tbsp (30 ml)are one segment each. Teaspoons and tablespoons count as US here. One in the same system counts only within 15% of the first quantity, so1 cup / 2 tbspis two segments. Quantities side by side, as in1 lb 2 ozand1 cup 2 tbsp, are a segment each and aren’t added together, unlikeparseIngredientLine, which reads1 lb 2 ozas one 1.125 lb quantity. - A period after an abbreviated unit is part of the segment when a lowercase word, a digit, or
(follows it, as in3 tbsp. sugar. A period aftercup,cups,pint,kilo,gram, or a unit word of five letters or more ends a sentence instead, so it stays outside, as in8 cups. - Counts and count units, as in
2 eggsand1 bunch, number words, as inone tablespoonanda cup, a size with a hyphen, as ina 2-quart dish, a decimal comma, as in1,5 litres, a number that starts with a point, as in.5 cup, an amount of 0, a reversed range, as in3-2 cups, and two numbers joined by “and” or “or”, as in1 and 1/2 cupsand1 or 2 tablespoons, stay text. - A lone
c,t, orTstays text, as inPreheat to 180c., since it more often means Celsius than cups. - A quantity in parentheses after a unit word stays text, since it restates a quantity that isn’t read:
one tablespoon (15 ml)anda 7-quart (6 ½ liters) slow cooker. - When a parenthesis after a quantity starts with a restatement but doesn’t close right after it or a second one, as in
600g (1lb 5oz),1½ cups (300 g, 2 rice cooker cups), and1 cup (240 ml, 8 fl oz, 16 tbsp), the quantity before it is a segment alone, and every quantity up to its)stays text, so none gets a second conversion. When it never closes, the rest of the text stays text. - The size of a scoop or of a measuring cup or spoon stays text, as in
1/4 cup scoopsanda 1/4 cup measuring cup. - An ounce is a weight unless it’s written as
fl ozorfluid ounces, so1 ½ ounces vodkareads as 1.5oz, as it does in an ingredient line. Only English words are read, and a cup is the US cup.
import { segmentStepQuantities } from '@recipe-book/core'
segmentStepQuantities('Stir in 1 ½ cups milk.').map((segment) => segment.text) // ['Stir in ', '1 ½ cups', ' milk.']
segmentStepQuantities('Whisk in 200 g (7 oz) sugar.')[1] // { type: 'quantity', text: '200 g (7 oz)', quantity: { amount: 200, unit: 'g' }, alternatives: [{ amount: 7, unit: 'oz' }] }
segmentStepQuantities('Add 1 cup / 2 tbsp milk.').filter((segment) => segment.type === 'quantity').length // 2
segmentStepQuantities('Add 2 eggs and a pinch of salt.').length // 1It doesn’t read temperatures or durations. To find those too, run it on the text segments of segmentStepText:
import {
type QuantitySegment,
segmentStepQuantities,
segmentStepText,
type StepSegment,
} from '@recipe-book/core'
segmentStepText('Bake at 180 C with 200 g sugar for 20 minutes.')
.flatMap<StepSegment | QuantitySegment>((segment) =>
segment.type === 'text' ? segmentStepQuantities(segment.text) : segment,
)
.map((segment) => segment.type) // ['text', 'temperature', 'text', 'quantity', 'text', 'duration', 'text']To show a step in the reader’s measurement system, keep a segment as written when any of its quantities is already in that system. Otherwise convert its quantity with toSystem and format it with formatQuantity, as an ingredient list does. This function does that:
import {
formatQuantity,
segmentStepQuantities,
type System,
toSystem,
} from '@recipe-book/core'
function showAmounts(text: string, system: System): string {
return segmentStepQuantities(text)
.map((segment) => {
if (segment.type === 'text') {
return segment.text
}
const written = [segment.quantity, ...segment.alternatives].some(
(quantity) => toSystem(quantity, system).unit === quantity.unit,
)
return written
? segment.text
: formatQuantity(toSystem(segment.quantity, system))
})
.join('')
}
showAmounts('Stir in 1 ½ cups milk.', 'metric') // 'Stir in 355 mL milk.'
showAmounts('Whisk in 200 g (7 oz) sugar.', 'us') // 'Whisk in 200 g (7 oz) sugar.'
showAmounts('Add 2 tbsp oil.', 'metric') // 'Add 2 tbsp oil.'Quantities in a step follow the measurement system only: scaling a recipe’s servings changes its ingredient list, not its steps.
Throws a RecipeBookError with the code invalid_argument when text isn’t a string.
Types
Quantity
type Quantity = {
amount: Amount
unit?: UnitId | undefined
max?: undefined
}An amount and an optional unit ID. A Servings or Yield writes its range as { amount, max }, so it isn’t a quantity: the functions that take a quantity throw invalid_argument for it. Print those with formatServings and formatYield.
| Name | Type | Description |
|---|---|---|
amount |
Amount |
A number, or a range as { min, max }. |
unit |
UnitId | undefined |
The unit’s ID, such as 'cup'. A quantity without a unit is a bare count, as in 2 eggs. |
max |
undefined |
Always left out or undefined, because a quantity’s range is its amount. |
import type { Quantity } from '@recipe-book/core'
const flour: Quantity = { amount: 1.5, unit: 'cup' }
const oil: Quantity = { amount: { min: 2, max: 3 }, unit: 'tbsp' }
const eggs: Quantity = { amount: 2 }Display quantities uses it to type a React component’s quantity prop.
Amount
type Amount = number | RangeA finite number greater than 0, or a Range. Functions that take a quantity throw invalid_argument for any other amount.
Range
type Range = { min: number; max: number }An inclusive range, such as 2–3 tbsp. convert, toSystem, and scaleQuantity can return equal ends for a range whose ends differ only in their last digit, and the functions that take a quantity accept them: formatQuantity writes one number.
| Name | Type | Description |
|---|---|---|
min |
number |
The low end, a finite number greater than 0. |
max |
number |
The high end, a finite number greater than or equal to min. |
SameAmount
type SameAmount<A extends Amount> = A extends number ? number : RangeThe amount that convert, toSystem, and scaleQuantity return for an amount of type A: a number for a number, and a Range for a range.
import { toSystem, type Amount, type Quantity, type SameAmount } from '@recipe-book/core'
function metricAmount<A extends Amount>(quantity: Quantity & { amount: A }): SameAmount<A> {
return toSystem(quantity, 'metric').amount
}
metricAmount({ amount: { min: 1, max: 2 }, unit: 'cup' }) // { min: 236.5882365, max: 473.176473 }UnitId
type UnitId =
| 'mg' | 'g' | 'kg' | 'oz' | 'lb'
| 'ml' | 'cl' | 'dl' | 'l' | 'tsp' | 'tbsp' | 'tbsp-au' | 'fl-oz' | 'cup' | 'cup-metric' | 'pint' | 'quart' | 'gallon'
| 'pinch' | 'dash' | 'clove' | 'slice' | 'piece' | 'can' | 'package' | 'stick' | 'sprig' | 'bunch' | 'head' | 'bag' | 'handful' | 'jar' | 'stalk'The ID of a unit in the registry. Quantities always store IDs; use findUnit to turn author text into one. The union may grow in minor releases, so a Record<UnitId, …> or an exhaustive switch of your own may need new entries after one.
UnitAlias
Any unit ID or alias, exactly as the registry lists it. findUnit also matches other cases (except 'T', 't', and 'c') and a trailing period at runtime, such as 'Cups' and 'tbsp.', but they aren’t part of this type.
import type { UnitAlias } from '@recipe-book/core'
const aliases: UnitAlias[] = ['cups', 'T', 'litre', 'fl oz']UnitIdOf
UnitIdOf<Alias extends UnitAlias> is the ID of the unit an alias names. UnitIdOf<'litres' | 'pound'> is 'l' | 'lb'.
import type { UnitIdOf } from '@recipe-book/core'
const tbsp: UnitIdOf<'tablespoons'> = 'tbsp'UnitDefinition
type UnitDefinition = {
readonly id: UnitId
readonly systems: readonly [System] | readonly ['metric', 'us']
readonly aliases: readonly UnitAlias[]
readonly labels: {
readonly short: { readonly one: string; readonly other: string }
readonly long: { readonly one: string; readonly other: string }
}
} & (
| { readonly dimension: 'mass' | 'volume'; readonly toBase: number }
| { readonly dimension: 'count'; readonly toBase?: undefined }
)One entry in the registry.
| Name | Type | Description |
|---|---|---|
id |
UnitId |
The unit’s ID. |
dimension |
Dimension |
What the unit measures. |
systems |
readonly [System] | readonly ['metric', 'us'] |
The measurement systems where the unit is native: one, or both in that order. |
toBase |
number | undefined |
The exact size in grams for mass units, or in milliliters for volume units. Count units don’t have it, so it’s a number once dimension is checked not to be 'count'. |
aliases |
readonly UnitAlias[] |
Every spelling findUnit accepts, starting with the ID, matched in any case except 'T', 't', and 'c'. See findUnit for the whitespace and periods it ignores. |
labels |
{ readonly short: { readonly one: string; readonly other: string }; readonly long: { readonly one: string; readonly other: string } } |
English names for one and for many, such as short: { one: 'tbsp', other: 'tbsp' } and long: { one: 'tablespoon', other: 'tablespoons' }. |
Dimension
type Dimension = 'mass' | 'volume' | 'count'What a unit measures. Count units, such as clove or pinch, have no fixed size, so they convert only to themselves.
System
type System = 'metric' | 'us'A measurement system: 'metric', or 'us' for US customary units.
ToSystemOptions
type ToSystemOptions = {
exact?: boolean | undefined
}Options for toSystem.
| Name | Type | Description |
|---|---|---|
exact |
boolean | undefined |
Pass true to keep the converted amount exact, so 150 mL in 'us' is 10.1442… tbsp, which formatQuantity writes as 10 ⅛ tbsp, rather than 10 tbsp. The unit is still the one a cook measures with. |
Temperature
type Temperature = { value: number; unit: TemperatureUnit }An oven or food temperature. Temperatures aren’t quantities, because converting them adds an offset: °F = °C × 9/5 + 32.
| Name | Type | Description |
|---|---|---|
value |
number |
The number of degrees, such as 350. |
unit |
TemperatureUnit |
'C' for Celsius or 'F' for Fahrenheit. |
TemperatureUnit
type TemperatureUnit = 'C' | 'F'Degrees Celsius or Fahrenheit.
StepSegment
type StepSegment = TextSegment | TemperatureSegment | DurationSegmentA piece of step text that segmentStepText returns. Check type before reading other fields. A minor release may add other kinds, so render a segment with an unknown type as its text.
TextSegment
type TextSegment = { type: 'text'; text: string }Step text with nothing recognized in it.
| Name | Type | Description |
|---|---|---|
type |
'text' |
Always 'text'. |
text |
string |
The text exactly as written. |
TemperatureSegment
type TemperatureSegment = {
type: 'temperature'
text: string
temperature: Temperature
fan: boolean
oven: boolean
alternatives: TemperatureReading[]
}A temperature in step text, or a setting that the author wrote more than one way. Code that builds one itself, such as a test fixture, has to set every property, including oven.
| Name | Type | Description |
|---|---|---|
type |
'temperature' |
Always 'temperature'. |
text |
string |
The text exactly as written, such as '350°F' or '190C/170C fan/gas 5', including any gas mark. |
temperature |
Temperature |
The first reading. |
fan |
boolean |
true when the text marks the first reading for a fan or convection oven, as in '170C fan'. |
oven |
boolean |
true when the step says that it’s an oven setting, as in 'Bake at 350°F', rather than a food temperature. segmentStepText says how it tells them apart. |
alternatives |
TemperatureReading[] |
The other readings, in the order written, such as the 200 °C in '400 degrees F (200 degrees C)'. Often empty. |
TemperatureReading
type TemperatureReading = { temperature: Temperature; fan: boolean }One reading in a TemperatureSegment’s alternatives. A TemperatureSegment is a reading too, of its first temperature, so [segment, ...segment.alternatives] lists every reading in it, as showStep does.
| Name | Type | Description |
|---|---|---|
temperature |
Temperature |
The temperature read from the text, such as { value: 350, unit: 'F' }. |
fan |
boolean |
true when the text marks the reading for a fan or convection oven, as in '170C fan'. |
DurationSegment
type DurationSegment = {
type: 'duration'
text: string
minutes: number
max?: number | undefined
}A duration in step text, such as '25–30 minutes' or '1 hour and 15 minutes'. It never scales. To show it in another form, format minutes, and max when it’s set, with formatDuration.
| Name | Type | Description |
|---|---|---|
type |
'duration' |
Always 'duration'. |
text |
string |
The text exactly as written, such as '25–30 minutes' or '1.5 hours'. |
minutes |
number |
The duration, or a range’s low end, in minutes. Seconds are fractions, so '30 seconds' is 0.5. |
max |
number | undefined |
A range’s high end, in minutes, such as 30 for '25–30 minutes'. Always greater than minutes when set. |
SegmentStepTextOptions
type SegmentStepTextOptions = {
assumeTemperatureUnit?: TemperatureUnit | undefined
inferTemperatureUnit?: boolean | undefined
}Options for segmentStepText.
| Name | Type | Description |
|---|---|---|
assumeTemperatureUnit |
TemperatureUnit | undefined |
The unit for a temperature written with a degree sign or “degree” or “degrees” but no unit, as in Bake at 350 degrees. When it’s absent, such temperatures stay text unless inferTemperatureUnit reads them. A number with neither, as in Preheat oven to 350., always stays text. |
inferTemperatureUnit |
boolean | undefined |
Whether such a temperature is °F when it’s 275 or more, as in Preheat the oven to 425 degrees. A lower one stays text, since it could be either. When it’s absent or false, or assumeTemperatureUnit is set, it does nothing. |
StepQuantitySegment
type StepQuantitySegment = TextSegment | QuantitySegmentA piece of step text that segmentStepQuantities returns. Check type before reading other fields.
QuantitySegment
type QuantitySegment = {
type: 'quantity'
text: string
quantity: Quantity
alternatives: Quantity[]
}A mass or volume quantity in step text, such as '200 g' or '1 ½ cups'. When the author already wrote it more than one way, as in '200 g (7 oz)' or '1 cup / 240 ml', the run is one segment, up to the bounds that segmentStepQuantities describes.
| Name | Type | Description |
|---|---|---|
type |
'quantity' |
Always 'quantity'. |
text |
string |
The text exactly as written, such as '200 g (7 oz)'. |
quantity |
Quantity |
The first quantity, such as { amount: 200, unit: 'g' }. Always has a mass or volume unit. |
alternatives |
Quantity[] |
The author’s other ways of writing it, in order, such as [{ amount: 7, unit: 'oz' }]. Often empty. |