### Build Leading Quantity Prefix Regex Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Demonstrates building a regex for approximation prefixes at the start of quantity expressions, allowing for optional whitespace.
```typescript
buildLeadingQuantityPrefixRegex(['about', 'ca.']);
// /^(?:(?:about)|(?:ca\.))\s*/iu
```
--------------------------------
### ESM Import Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/module-exports.md
Recommended way to import functions and types using ECMAScript Modules.
```typescript
import {
parseIngredient,
convertUnit,
identifyUnit,
unitsOfMeasure,
type Ingredient,
type ParseIngredientOptions,
} from 'parse-ingredient';
```
--------------------------------
### Example Unit Definitions
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/types.md
Provides an example of how to define units of measure, including volume and mass units with their respective conversion factors.
```typescript
{
cup: {
short: 'c',
plural: 'cups',
alternates: ['C', 'c.'] ,
type: 'volume',
conversionFactor: { us: 236.588, imperial: 284.131, metric: 250 }
},
gram: {
short: 'g',
plural: 'grams',
alternates: ['g.'] ,
type: 'mass',
conversionFactor: 1
}
}
```
--------------------------------
### Install parse-ingredient with npm
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Install the parse-ingredient package using npm. This command also applies to yarn, pnpm, and bun.
```shell
npm i parse-ingredient
# OR yarn add / pnpm add / bun add
```
--------------------------------
### Build Prefix Pattern Regex Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Demonstrates building a case-insensitive regex that matches specified patterns as whole words at the start of a string, followed by whitespace.
```typescript
buildPrefixPatternRegex(['For', 'Für']);
// /^(?:(?:For)|(?:Für))\s/iu
```
```typescript
buildPrefixPatternRegex([/^Pour\s/iu]);
// /^(?:(?:^Pour\s))/iu
```
--------------------------------
### Browser UMD Import Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/module-exports.md
Importing functions in a browser environment using a UMD bundle, making them available on a global object.
```html
```
--------------------------------
### Full i18n Example (German)
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Demonstrates parsing an ingredient list in German with custom unit definitions and range separators. This is useful for handling localized ingredient formats.
```javascript
parseIngredient(
`Für den Kuchen:
2 bis 3 Tassen Mehl
1 Tasse Zucker`,
{
groupHeaderPatterns: ['For', 'Für'],
rangeSeparators: ['to', 'or', 'bis', 'oder'],
decimalSeparator: ',',
additionalUOMs: {
tasse: {
short: 'T',
plural: 'Tassen',
alternates: ['Tasse'],
},
},
}
);
// [
// { description: 'Für den Kuchen:', isGroupHeader: true, ... },
// { quantity: 2, quantity2: 3, unitOfMeasure: 'Tassen', description: 'Mehl', ... },
// { quantity: 1, unitOfMeasure: 'Tasse', description: 'Zucker', ... }
// ]
```
--------------------------------
### Build Trailing Quantity Regex Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Provides an example of building a complex regex to capture trailing quantities and units, accommodating ranges and various separator formats.
```typescript
const regex = buildTrailingQuantityRegex(['to', 'or']);
// Matches patterns like:
// "3 lemons"
// "2-3 eggs"
// "1 x 400g"
// "juice of 3 lemons"
```
--------------------------------
### Build Strip Prefix Regex Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Illustrates creating a regex to remove specified prefixes from the beginning of a string, handling whole words followed by whitespace.
```typescript
buildStripPrefixRegex(['of', 'de']);
// /^(?:(?:of)|(?:de))\s+/iu
```
--------------------------------
### CommonJS Import Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/module-exports.md
Importing functions using the CommonJS module system, typically used in Node.js environments.
```javascript
const {
parseIngredient,
convertUnit,
identifyUnit,
unitsOfMeasure,
} = require('parse-ingredient');
```
--------------------------------
### Partial Unit Matching Example (Japanese)
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Enables partial unit matching for languages like Japanese where words are not space-separated. Requires defining additional units.
```javascript
parseIngredient('砂糖大さじ2', {
partialUnitMatching: true,
additionalUOMs: {
大さじ: { short: '大さじ', plural: '大さじ', alternates: [] },
}
});
// [
// {
// quantity: 2,
// quantity2: null,
// unitOfMeasure: '大さじ',
// unitOfMeasureID: '大さじ',
// description: '砂糖',
// isGroupHeader: false,
// }
// ]
```
--------------------------------
### Partial Unit Matching Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/unitLookup.md
Demonstrates how `collectUOMStrings` is used internally when `partialUnitMatching` is enabled. The parser scans the description for unit substrings.
```typescript
import { parseIngredient } from 'parse-ingredient';
// CJK example: word spacing not used
parseIngredient('砂糖大さじ2', {
partialUnitMatching: true,
additionalUOMs: {
大さじ: { short: '大さじ', plural: '大さじ', alternates: [] }
}
});
// The parser scans the description for '大さじ' substring
// and extracts it as the unit of measure
```
--------------------------------
### Build Range Separator Regex Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Shows how to construct a regex that matches common range separators, including dashes and custom word separators, with case-insensitivity.
```typescript
buildRangeSeparatorRegex(['to', 'or']);
// /^(-|–|—|(?:(?:to)|(?:or))\s)/iu
```
--------------------------------
### Build Trailing Context Regex Example
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Shows how to create a regex that matches specific context words at the end of a string, preceded by whitespace.
```typescript
buildTrailingContextRegex(['from', 'of']);
// /\s+(?:from|of)$/iu
```
--------------------------------
### Example: Normalize Unit of Measure
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/configuration.md
Demonstrates the effect of `normalizeUOM` on parsing unit strings. When `true`, units are converted to their singular canonical form.
```typescript
parseIngredient('2 c sugar', { normalizeUOM: false });
// unitOfMeasure: 'c'
parseIngredient('2 c sugar', { normalizeUOM: true });
// unitOfMeasure: 'cup'
```
--------------------------------
### Conversions with Custom Units
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/convertUnit.md
Integrate custom unit definitions using the 'additionalUOMs' option to enable conversions between non-standard and standard units. The example defines a 'bucket' unit.
```typescript
const result = convertUnit(1, 'bucket', 'liter', {
additionalUOMs: {
bucket: {
short: 'bkt',
plural: 'buckets',
alternates: [],
type: 'volume',
conversionFactor: 10000, // 10000 ml = 10 liters
},
},
}); // 10
```
--------------------------------
### Conversions with Different Measurement Systems
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/convertUnit.md
Specify measurement systems ('us', 'imperial', 'metric') for source and target units when conversion factors vary. For example, distinguishing between US and Imperial cups.
```typescript
convertUnit(1, 'cup', 'milliliter', { fromSystem: 'imperial' }); // ~284.131 (Imperial cup)
convertUnit(1, 'cup', 'cup', { fromSystem: 'us', toSystem: 'imperial' }); // ~0.833
convertUnit(1, 'tablespoon', 'teaspoon'); // 3 (metric system)
```
--------------------------------
### Strip Prefixes from Descriptions
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Use `descriptionStripPrefixes` to remove common words like 'of' or 'de' from the start of ingredient descriptions. This option is ignored if `allowLeadingOf` is true. Defaults to `['of']`.
```javascript
// Spanish "de" stripping
parseIngredient('2 tazas de azúcar', {
descriptionStripPrefixes: ['of', 'de'],
});
// [{ description: 'azúcar', ... }]
```
```javascript
// French with regex patterns for elisions/contractions
parseIngredient("2 tasses d'huile", {
descriptionStripPrefixes: [/de\s+la\s+/iu, /de\s+l'/iu, /d'/iu, 'de'],
});
// [{ description: 'huile', ... }]
```
--------------------------------
### Allow Leading 'of' in Descriptions
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Set `allowLeadingOf: true` to preserve descriptions that start with 'of '. By default, these are removed.
```javascript
parseIngredient('1 cup of sugar', { allowLeadingOf: true });
// [
// {
// quantity: 1,
// quantity2: null,
// unitOfMeasure: 'cup',
// unitOfMeasureID: 'cup',
// description: 'of sugar',
// isGroupHeader: false,
// }
// ]
```
--------------------------------
### Unit Conversions with System Options
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Perform conversions specifying source and target measurement systems. Defaults to 'us' if not provided.
```javascript
// Convert using different measurement systems
convertUnit(1, 'cup', 'milliliter', { fromSystem: 'imperial' }); // ~284.131
convertUnit(1, 'cup', 'cup', { fromSystem: 'us', toSystem: 'imperial' }); // ~0.833
```
--------------------------------
### buildPrefixPatternRegex
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Builds a regex that matches any of the provided patterns at the beginning of a string, followed by whitespace. It's useful for identifying specific prefixes in text.
```APIDOC
## buildPrefixPatternRegex
### Description
Builds a regex matching any of the given patterns at the start of a string, followed by whitespace.
### Parameters
#### Parameters
- **patterns** (Array) - Array of string or RegExp patterns. String patterns are treated as literal whole-word prefixes (escaped, followed by `\s`). RegExp patterns are used as-is with `(?:...)` grouping.
### Returns
RegExp (case-insensitive) or `null` if patterns array is empty
### Example:
```typescript
buildPrefixPatternRegex(['For', 'Für']);
// /^(?:(?:For)|(?:Für))\s/iu
buildPrefixPatternRegex([/^Pour\s/iu]);
// /^(?:(?:^Pour\s))/iu
```
```
--------------------------------
### Basic Ingredient Parsing
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/parseIngredient.md
Parses a single ingredient string with a fractional quantity and unit. Demonstrates basic conversion of '1 1/2 cups sugar'.
```typescript
import { parseIngredient } from 'parse-ingredient';
parseIngredient('1 1/2 cups sugar');
// [
// {
// quantity: 1.5,
// quantity2: null,
// unitOfMeasureID: 'cup',
// unitOfMeasure: 'cups',
// description: 'sugar',
// isGroupHeader: false,
// }
// ]
```
--------------------------------
### Parse a single ingredient string
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Use the `parseIngredient` function to parse a single ingredient string. This example shows parsing an ingredient with a range for quantity.
```javascript
import { parseIngredient } from 'parse-ingredient';
parseIngredient('1-2 pears');
// [
// {
// quantity: 1,
// quantity2: 2,
// unitOfMeasure: null,
// unitOfMeasureID: null,
// description: 'pears',
// isGroupHeader: false,
// }
// ]
```
--------------------------------
### Default Options and Units
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
Accessing default configuration options and the comprehensive list of built-in units of measure for the parsing library.
```javascript
import { defaultOptions, unitsOfMeasure } from "@/api-reference/constants.md";
```
--------------------------------
### Recipe Serialization with Options
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/README.md
Parse ingredients with options like normalizing units and including metadata, then serialize the result to JSON. This preserves structured ingredient data.
```typescript
const ingredients = parseIngredient(text, {
normalizeUOM: true,
includeMeta: true
});
const json = JSON.stringify(ingredients);
// Includes normalized units and source metadata
```
--------------------------------
### getDefaultUnitLookupMaps
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/unitLookup.md
Gets the cached default lookup maps, containing only default units without additional UOMs. This function is optimized for speed when custom units are not required.
```APIDOC
## getDefaultUnitLookupMaps
### Description
Gets the cached default lookup maps (only default units, no additionalUOMs).
### Signature
```typescript
getDefaultUnitLookupMaps(): UnitLookupMaps
```
### Return Type
`UnitLookupMaps` — Cached maps for all 60+ built-in units.
### Behavior
- Lazily initializes maps on first call
- Returns the same cached instance on subsequent calls
- Much faster than `buildUnitLookupMaps()` when no custom units needed
### Example
```typescript
import { getDefaultUnitLookupMaps } from 'parse-ingredient';
const maps = getDefaultUnitLookupMaps();
maps.caseSensitive.get('ml'); // 'milliliter'
maps.caseSensitive.get('tbsp'); // 'tablespoon'
```
```
--------------------------------
### buildLeadingQuantityPrefixRegex
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Creates a regex to match approximation or modifier prefixes that might appear before a quantity. It allows for optional whitespace, accommodating formats like 'ca.200g'.
```APIDOC
## buildLeadingQuantityPrefixRegex
### Description
Builds a regex matching approximation/modifier prefixes at the start of quantity expressions. Uses optional whitespace (`\s*`) instead of required whitespace, so "ca.200g" is recognized.
### Parameters
#### Parameters
- **patterns** (Array) - Array of string or RegExp patterns to match as prefixes.
### Returns
RegExp (case-insensitive) or `null` if patterns array is empty
### Example:
```typescript
buildLeadingQuantityPrefixRegex(['about', 'ca.']);
// /^(?:(?:about)|(?:ca\.))\s*/iu
```
```
--------------------------------
### System-Specific Unit Conversions
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/units-of-measure.md
Illustrates how to perform unit conversions between different measurement systems (US, Imperial, Metric) by specifying the `fromSystem` option in `convertUnit`.
```typescript
convertUnit(1, 'cup', 'ml', { fromSystem: 'us' }); // 236.588
convertUnit(1, 'cup', 'ml', { fromSystem: 'imperial' }); // 284.131
convertUnit(1, 'cup', 'ml', { fromSystem: 'metric' }); // 250
```
--------------------------------
### Default Leading Quantity Prefixes
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Contains the default approximation or modifier prefixes. This array is empty by default and requires explicit user enablement, for example, by adding `['about', 'ca.']`.
```typescript
const defaultLeadingQuantityPrefixes: readonly string[] = []
```
--------------------------------
### Partial Unit Matching with Mixed Languages
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Demonstrates partial unit matching with a mix of Japanese and English units. The parser correctly identifies units from both languages.
```javascript
parseIngredient('砂糖大さじ2\nバター10g\n1 cup flour', {
partialUnitMatching: true,
additionalUOMs: {
大さじ: { short: '大さじ', plural: '大さじ', alternates: [] },
}
});
// [
// { quantity: 2, unitOfMeasure: '大さじ', description: '砂糖', ... },
// { quantity: 10, unitOfMeasure: 'g', description: 'バター', ... },
// { quantity: 1, unitOfMeasure: 'cup', description: 'flour', ... },
// ]
```
--------------------------------
### Default Options for parse-ingredient
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/configuration.md
Lists the default configuration settings for the library, including normalization, unit handling, and parsing behaviors. These defaults can be overridden when initializing the parser.
```typescript
const defaultOptions = {
normalizeUOM: false,
additionalUOMs: {},
ignoreUOMs: [],
allowLeadingOf: false,
decimalSeparator: '.',
groupHeaderPatterns: ['For'],
rangeSeparators: ['or', 'to'],
descriptionStripPrefixes: ['of'],
trailingQuantityContext: ['from', 'of'],
leadingQuantityPrefixes: [],
includeMeta: false,
partialUnitMatching: false,
}
```
--------------------------------
### Default Group Header Patterns
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Specifies the default patterns for detecting group headers. Only lines starting with 'For ' trigger group header detection; lines ending with ':' always match.
```typescript
const defaultGroupHeaderPatterns: readonly string[] = ['For']
```
--------------------------------
### Get Default Unit Lookup Maps
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/unitLookup.md
Retrieves cached default unit lookup maps. This is faster than building maps when custom units are not needed. It lazily initializes and returns a cached instance.
```typescript
import { getDefaultUnitLookupMaps } from 'parse-ingredient';
const maps = getDefaultUnitLookupMaps();
maps.caseSensitive.get('ml'); // 'milliliter'
maps.caseSensitive.get('tbsp'); // 'tablespoon'
```
--------------------------------
### Include Metadata in Output
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Enable `includeMeta: true` to add a `meta` property to each ingredient object, containing `sourceText` and `sourceIndex`.
```javascript
parseIngredient('1 cup flour\n\n2 tbsp sugar', { includeMeta: true });
// [
// {
// quantity: 1,
// quantity2: null,
// unitOfMeasure: 'cup',
// unitOfMeasureID: 'cup',
// description: 'flour',
// isGroupHeader: false,
// meta: { sourceText: '1 cup flour', sourceIndex: 0 },
// },
// {
// quantity: 2,
// quantity2: null,
// unitOfMeasure: 'tbsp',
// unitOfMeasureID: 'tablespoon',
// description: 'sugar',
// isGroupHeader: false,
// meta: { sourceText: '2 tbsp sugar', sourceIndex: 2 },
// },
// ]
```
--------------------------------
### Main Entry Point Exports
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/module-exports.md
Re-exports all public members from core modules at the top level. This is the primary way to import functionality.
```typescript
export * from './constants';
export * from './convertUnit';
export * from './parseIngredient';
export * from './types';
```
--------------------------------
### US cup to metric/imperial conversions
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/configuration.md
Demonstrates converting US cups to milliliters using different system contexts. Shows how to specify source and target systems for accurate conversions.
```typescript
convertUnit(1, 'cup', 'ml', { fromSystem: 'us' }); // 236.588
```
```typescript
convertUnit(1, 'cup', 'ml', { fromSystem: 'imperial' }); // 284.131
```
```typescript
convertUnit(1, 'cup', 'cup', { fromSystem: 'us', toSystem: 'imperial' }); // 0.833
```
--------------------------------
### Configure Description Strip Prefixes
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/configuration.md
Define patterns to strip from the beginning of ingredient descriptions. Defaults to ['of']. Only applied when allowLeadingOf is false.
```typescript
descriptionStripPrefixes?: (string | RegExp)[]
```
```typescript
// English (default)
parseIngredient('1 cup of sugar');
// description: 'sugar'
```
```typescript
// Spanish
parseIngredient('2 tazas de azúcar', {
descriptionStripPrefixes: ['of', 'de'],
});
// description: 'azúcar'
```
```typescript
// French with elisions
parseIngredient("2 tasses d'huile", {
descriptionStripPrefixes: [/de\s+la\s+/iu, /de\s+l'/iu, /d'/iu, 'de'],
});
// description: 'huile'
```
--------------------------------
### Browser Usage with UMD Build
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/README.md
Include the library via a UMD build script tag and access its functions for parsing ingredients.
```html
```
--------------------------------
### buildStripPrefixRegex
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Constructs a regex designed to remove specific prefixes from the beginning of a string. This is useful for cleaning up text before further parsing.
```APIDOC
## buildStripPrefixRegex
### Description
Builds a regex matching prefixes to strip from the start of a string.
### Parameters
#### Parameters
- **patterns** (Array) - Array of string or RegExp patterns. String patterns are matched as whole words followed by whitespace. RegExp patterns are used as-is.
### Returns
RegExp (case-insensitive) or `null` if patterns array is empty
### Example:
```typescript
buildStripPrefixRegex(['of', 'de']);
// /^(?:(?:of)|(?:de))\s+/iu
```
```
--------------------------------
### Include Source Information
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/usage-patterns.md
Track the origin of each ingredient from the input string. The `sourceIndex` and `sourceText` are available in the metadata.
```typescript
const result = parseIngredient(
'1 cup flour\n\n2 eggs\n\n1 tsp vanilla',
{ includeMeta: true }
);
result.forEach(ing => {
console.log(`Line ${ing.meta.sourceIndex}: ${ing.meta.sourceText}`);
});
// Line 0: 1 cup flour
// Line 2: 2 eggs
// Line 4: 1 tsp vanilla
```
--------------------------------
### Batch Operations vs. Individual Parsing
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/usage-patterns.md
For better performance, parse all ingredients at once using `parseIngredient` with the full recipe text. Avoid parsing each ingredient line separately in a loop.
```typescript
// Good: parse all ingredients once
const allIngredients = parseIngredient(fullRecipeText);
// Not ideal: parse each ingredient separately
const ingredients = [];
for (const line of lines) {
const parsed = parseIngredient(line);
ingredients.push(...parsed);
}
```
--------------------------------
### Convert Units Using Conversion Factors
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/units-of-measure.md
Demonstrates converting '1 cup' to milliliters using the `convertUnit` function. The conversion relies on the formula: result = (value * fromConversionFactor) / toConversionFactor.
```typescript
// 1 cup to milliliters
// (1 * 236.588) / 1 = 236.588
convertUnit(1, 'cup', 'ml'); // 236.588
```
--------------------------------
### Build Custom Unit Lookup Maps
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/unitLookup.md
Demonstrates how to create a custom unit lookup map by extending the default maps with new unit definitions. This is useful for supporting locale-specific or non-standard units. The custom parser then uses these maps to identify units within an ingredient string.
```typescript
import { buildUnitLookupMaps, lookupUnit } from 'parse-ingredient';
function myCustomParser(ingredient) {
const maps = buildUnitLookupMaps({
tablespoon_de: {
short: 'EL',
plural: 'EL',
alternates: ['ELöffel'],
type: 'volume',
conversionFactor: { us: 14.787, metric: 15 },
}
});
const words = ingredient.split(' ');
for (const word of words) {
const unitID = lookupUnit(word, maps);
if (unitID) {
return { word, unitID };
}
}
return null;
}
myCustomParser('2 EL Zucker'); // { word: 'EL', unitID: 'tablespoon_de' }
```
--------------------------------
### Parsing with Unit Normalization Option
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/parseIngredient.md
Demonstrates parsing with the 'normalizeUOM' option enabled, which standardizes unit abbreviations like 'c' to 'cup'.
```typescript
parseIngredient('1 c sugar', { normalizeUOM: true });
// [
// {
// quantity: 1,
// unitOfMeasureID: 'cup',
// unitOfMeasure: 'cup', // normalized from 'c'
// description: 'sugar',
// isGroupHeader: false,
// }
// ]
```
--------------------------------
### Configure Leading Quantity Prefixes
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/configuration.md
Define words or patterns to strip from the beginning of quantity expressions. Longer/more-specific patterns should be listed first.
```typescript
leadingQuantityPrefixes?: (string | RegExp)[]
```
```typescript
// English
parseIngredient('about 2 cups sugar', {
leadingQuantityPrefixes: ['about'],
});
// quantity: 2
```
```typescript
// German
parseIngredient('ca. 200 g Mehl', {
leadingQuantityPrefixes: ['ca.'], // Note: longer pattern first
});
// quantity: 200
```
```typescript
parseIngredient('bis zu 3 EL Zucker', {
rangeSeparators: ['to', 'or', 'bis'],
leadingQuantityPrefixes: ['bis zu'],
});
// quantity: 3
```
--------------------------------
### buildUnitLookupMaps
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/unitLookup.md
Builds case-sensitive and case-insensitive lookup maps for efficient unit identification. It processes default and additional unit definitions to create maps where unit strings (ID, short, plural, or alternate) are associated with their canonical IDs.
```APIDOC
## buildUnitLookupMaps
### Description
Builds case-sensitive and case-insensitive lookup maps for efficient unit identification. It processes default and additional unit definitions to create maps where unit strings (ID, short, plural, or alternate) are associated with their canonical IDs.
### Function Signature
```typescript
buildUnitLookupMaps(
additionalUOMs?: UnitOfMeasureDefinitions
): UnitLookupMaps
```
### Parameters
#### Optional Parameters
- **additionalUOMs** (UnitOfMeasureDefinitions) - Optional - Custom unit definitions to merge with defaults. Custom units override defaults with the same ID.
### Return Type
```typescript
interface UnitLookupMaps {
caseSensitive: Map;
caseInsensitive: Map;
}
```
- **caseSensitive**: Map where each unit string (ID, short, plural, or alternate) maps to the canonical ID. Preserves case (e.g., 'T' vs 't').
- **caseInsensitive**: Map with lowercase keys for case-insensitive fallback lookup.
### Behavior
1. Processes default `unitsOfMeasure` first
2. Processes `additionalUOMs` second (overrides defaults)
3. For each unit definition, adds all versions to both maps:
- Unit ID itself (e.g., 'cup')
- Short form (e.g., 'c')
- Plural form (e.g., 'cups')
- All alternates (e.g., 'C', 'c.')
4. Case-sensitive map checked first during lookup; case-insensitive map used as fallback
### Example
```typescript
import { buildUnitLookupMaps } from 'parse-ingredient';
const maps = buildUnitLookupMaps({
bucket: {
short: 'bkt',
plural: 'buckets',
alternates: ['bk'],
}
});
maps.caseSensitive.get('cup'); // 'cup'
maps.caseSensitive.get('c'); // 'cup'
maps.caseSensitive.get('T'); // 'tablespoon'
maps.caseSensitive.get('t'); // 'teaspoon'
maps.caseSensitive.get('bucket'); // 'bucket'
maps.caseInsensitive.get('cup'); // 'cup'
maps.caseInsensitive.get('CUPS'); // 'cup'
maps.caseInsensitive.get('bucket'); // 'bucket'
```
```
--------------------------------
### Default Parsing Options
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Provides a complete set of default parsing options, with all values explicitly defined. Use this as a reference for default behavior or for resetting options.
```typescript
const defaultOptions: Required = {
additionalUOMs: {},
allowLeadingOf: false,
normalizeUOM: false,
ignoreUOMs: [],
decimalSeparator: '.',
groupHeaderPatterns: ['For'],
rangeSeparators: ['or', 'to'],
descriptionStripPrefixes: ['of'],
trailingQuantityContext: ['from', 'of'],
leadingQuantityPrefixes: [],
includeMeta: false,
partialUnitMatching: false,
}
```
--------------------------------
### Configure Trailing Quantity Context
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
The `trailingQuantityContext` option specifies words that indicate a trailing quantity extraction context, such as in 'Juice of 3 lemons'. Defaults to `['from', 'of']`.
```javascript
// German context word
parseIngredient('Saft von 3 Zitronen', {
trailingQuantityContext: ['from', 'of', 'von'],
});
// [{ quantity: 3, description: 'Saft von Zitronen', ... }]
```
--------------------------------
### Spaceless Language Parsing (CJK)
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/usage-patterns.md
Enable `partialUnitMatching` and define custom units like '大さじ' for languages like Japanese where units and descriptions may not have spaces.
```typescript
parseIngredient('砂糖大さじ2', {
partialUnitMatching: true,
additionalUOMs: {
大さじ: {
short: '大さじ',
plural: '大さじ',
alternates: [],
type: 'volume',
conversionFactor: 15,
},
},
});
// quantity: 2
// unitOfMeasureID: '大さじ'
// description: '砂糖'
```
--------------------------------
### Include parse-ingredient in Browser
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Include the parse-ingredient library in your HTML using a script tag. The `parseIngredient` function will be available on the global `ParseIngredient` object.
```html
```
--------------------------------
### Convert Recipe Ingredients to Metric Units
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/README.md
Convert parsed recipe ingredients to metric units (grams) using the `convertUnit` function. This is useful for standardizing measurements.
```typescript
const ingredients = parseIngredient(recipeText);
const metric = ingredients.map(ing => {
if (ing.unitOfMeasureID && ing.quantity !== null) {
const quantityG = convertUnit(ing.quantity, ing.unitOfMeasureID, 'gram');
if (quantityG) {
return { ...ing, quantity: quantityG, unitOfMeasure: 'g' };
}
}
return ing;
});
```
--------------------------------
### Perform System-Specific Unit Conversions
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/usage-patterns.md
Convert units between different systems (US, Imperial, metric) by specifying `fromSystem` and `toSystem` options. This is useful for cross-system comparisons.
```typescript
// US cup vs Imperial cup
convertUnit(1, 'cup', 'ml', { fromSystem: 'us' }); // 236.588
convertUnit(1, 'cup', 'ml', { fromSystem: 'imperial' }); // 284.131
convertUnit(1, 'cup', 'ml', { fromSystem: 'metric' }); // 250
// Cross-system conversion
convertUnit(1, 'cup', 'cup', { fromSystem: 'us', toSystem: 'imperial' }); // 0.833
```
--------------------------------
### Using Unit Aliases for Conversions
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/convertUnit.md
Utilize unit aliases and short forms (e.g., 'c' for 'cup', 'T' for 'tablespoon', 'fl oz' for 'fluid ounce') for concise unit specification in conversions.
```typescript
convertUnit(1, 'c', 'ml'); // 236.588 (c is short for cup)
convertUnit(1, 'T', 'tsp'); // 3 (T is tablespoon, tsp is teaspoon)
convertUnit(1, 'fl oz', 'ml'); // 29.573 (fluid ounce)
```
--------------------------------
### Configure Unit Conversion Options
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/types.md
Defines options for the `convertUnit` function, allowing specification of source and target measurement systems, and inclusion of custom unit definitions.
```typescript
interface ConvertUnitOptions {
fromSystem?: UnitSystem;
toSystem?: UnitSystem;
additionalUOMs?: UnitOfMeasureDefinitions;
}
```
--------------------------------
### constants
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
Access to various constants, including default options, patterns, and unit definitions.
```APIDOC
## Constants
### Description
Provides access to predefined constants used within the library, such as default configurations, pattern definitions, and a comprehensive list of units of measure.
### Constants Available
- **Default Options**: Default configuration settings.
- **Default Patterns**: Regular expressions and patterns for parsing.
- **unitsOfMeasure**: A collection of 60+ predefined unit definitions.
- **Regex Utilities**: Helper functions for regular expression manipulation.
- **Regex Builder Functions**: Functions to construct complex regular expressions.
- **escapeRegex()**: Utility to escape special characters in regex strings.
- **Deprecated Constants**: Constants that are no longer recommended, with alternatives provided.
```
--------------------------------
### Complete Recipe Processor
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/usage-patterns.md
This function parses a block of recipe text into structured sections and ingredients. It normalizes units of measure and includes metadata during parsing. It also attempts to convert ingredient quantities to grams where possible.
```typescript
import { parseIngredient, convertUnit } from 'parse-ingredient';
interface Recipe {
name: string;
sections: RecipeSection[];
}
interface RecipeSection {
title: string | null;
ingredients: ParsedIngredient[];
}
interface ParsedIngredient {
quantity: number | null;
quantity2: number | null;
unit: string | null;
unitID: string | null;
description: string;
quantityInGrams?: number; // after conversion
}
function parseRecipe(name: string, text: string): Recipe {
const parsed = parseIngredient(text, {
normalizeUOM: true,
includeMeta: true,
});
const sections: RecipeSection[] = [];
let currentSection: RecipeSection | null = null;
for (const ingredient of parsed) {
if (ingredient.isGroupHeader) {
if (currentSection) sections.push(currentSection);
currentSection = {
title: ingredient.description,
ingredients: [],
};
} else {
if (!currentSection) {
currentSection = { title: null, ingredients: [] };
}
const converted = tryConvertToGrams(ingredient);
currentSection.ingredients.push({
quantity: ingredient.quantity,
quantity2: ingredient.quantity2,
unit: ingredient.unitOfMeasure,
unitID: ingredient.unitOfMeasureID,
description: ingredient.description,
quantityInGrams: converted,
});
}
}
if (currentSection) sections.push(currentSection);
return { name, sections };
}
function tryConvertToGrams(ing) {
if (ing.quantity === null || !ing.unitOfMeasureID) return undefined;
return convertUnit(ing.quantity, ing.unitOfMeasureID, 'gram');
}
```
--------------------------------
### Parsing with Metadata Inclusion
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/parseIngredient.md
Parses multiple ingredients and includes source metadata for each ingredient when the 'includeMeta' option is true.
```typescript
parseIngredient('1 cup flour
2 tbsp sugar', { includeMeta: true });
// [
// {
// quantity: 1,
// unitOfMeasureID: 'cup',
// description: 'flour',
// meta: { sourceText: '1 cup flour', sourceIndex: 0 },
// ...
// },
// {
// quantity: 2,
// unitOfMeasureID: 'tablespoon',
// description: 'sugar',
// meta: { sourceText: '2 tbsp sugar', sourceIndex: 2 },
// ...
// }
// ]
```
--------------------------------
### Track Source Information for Parsed Ingredients
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/README.md
Include metadata about the source of each ingredient during parsing. This allows tracking the original line number and text.
```typescript
const result = parseIngredient(recipeText, { includeMeta: true });
result.forEach(ing => {
if (!ing.isGroupHeader) {
console.log(`Line ${ing.meta.sourceIndex}: ${ing.meta.sourceText}`);
}
});
```
--------------------------------
### Handle Trailing Quantities
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/usage-patterns.md
Parse ingredients where the quantity appears at the end of the description. The quantity is extracted, and the description is adjusted accordingly.
```typescript
parseIngredient('Juice of 3 lemons');
// quantity: 3, description: 'Juice of lemons'
parseIngredient('Zest from 2 limes');
// quantity: 2, description: 'Zest from limes'
```
--------------------------------
### Parsing Multiple Ingredients
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/parseIngredient.md
Parses a multi-line string containing multiple ingredients. Handles different fractional quantities and units for each ingredient.
```typescript
parseIngredient(`2/3 cup flour
1 tsp baking powder`);
// [
// { quantity: 0.667, unitOfMeasureID: 'cup', unitOfMeasure: 'cup', description: 'flour', ... },
// { quantity: 1, unitOfMeasureID: 'teaspoon', unitOfMeasure: 'tsp', description: 'baking powder', ... }
// ]
```
--------------------------------
### Batch Convert Quantities in Parsed Ingredients
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/usage-patterns.md
Iterate through parsed ingredients and use `convertUnit` to transform quantities to a target unit, such as grams. This is useful for standardizing recipes.
```typescript
const ingredients = parseIngredient(`
2 cups flour
1 tablespoon sugar
500 ml milk
`);
const toGrams = ingredients.map(ing => {
if (ing.unitOfMeasureID && ing.quantity !== null) {
const converted = convertUnit(ing.quantity, ing.unitOfMeasureID, 'gram');
if (converted !== null) {
return { ...ing, quantity: converted, unitOfMeasure: 'gram' };
}
}
return ing;
});
```
--------------------------------
### Configure Leading Quantity Prefixes
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Use `leadingQuantityPrefixes` to strip approximation prefixes like 'about' or 'ca.' from the beginning of quantity expressions. Defaults to `[]`.
```javascript
// English approximation prefix
parseIngredient('about 2 cups sugar', {
leadingQuantityPrefixes: ['about'],
});
// [{ quantity: 2, unitOfMeasure: 'cups', description: 'sugar', ... }]
```
```javascript
// German prefixes
parseIngredient('ca. 200 g Mehl', {
leadingQuantityPrefixes: ['ca.'],
});
// [{ quantity: 200, unitOfMeasure: 'g', description: 'Mehl', ... }]
```
```javascript
parseIngredient('bis zu 3 EL Zucker', {
rangeSeparators: ['to', 'or', 'bis'],
leadingQuantityPrefixes: ['bis zu'],
additionalUOMs: {
tablespoon_de: { short: 'EL', plural: 'EL', alternates: [] },
},
});
// [{ quantity: 3, unitOfMeasure: 'EL', description: 'Zucker', ... }]
```
--------------------------------
### Configure Group Header Patterns
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/configuration.md
Define patterns to identify group headers in ingredient lists. Defaults to ['For']. Lines ending with ':' are always matched.
```typescript
groupHeaderPatterns?: (string | RegExp)[]
```
```typescript
// German and English group headers
parseIngredient('Für den Teig:\n2 Tassen Mehl', {
groupHeaderPatterns: ['For', 'Für'],
});
```
```typescript
// French with regex for complex patterns
parseIngredient('Pour la pâte:\n2 tasses farine', {
groupHeaderPatterns: ['For', /^Pour\s/iu],
});
```
--------------------------------
### buildTrailingQuantityRegex
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
Constructs a complex regex to capture trailing quantities and units of measure, handling ranges and various numeric formats. It includes multiple capture groups for detailed parsing.
```APIDOC
## buildTrailingQuantityRegex
### Description
Builds a regex to capture trailing quantity and unit of measure, accounting for ranges and numeric patterns. Complex regex with 12+ capture groups for: Separator character (x, comma, colon, dash), First quantity (if range), Range separator, Second quantity, Unit of measure.
### Parameters
#### Parameters
- **rangeSeparators** (Array) - An array of strings or RegExp objects representing possible range separators.
### Returns
RegExp
### Example:
```typescript
const regex = buildTrailingQuantityRegex(['to', 'or']);
// Matches patterns like:
// "3 lemons"
// "2-3 eggs"
// "1 x 400g"
// "juice of 3 lemons"
```
```
--------------------------------
### First Word Regex for Unit Matching
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/constants.md
A regular expression designed to match the initial word in a description, identifying potential units of measure. It captures the unit itself and any remaining text.
```typescript
const firstWordRegEx: RegExp =
/^(fl(?:uid)?(?:\s+|-)(?:oz|ounces?)|[\p{L}\p{N}_]+(?:[./-][\p{L}\p{N}_]+|\([\p{L}\p{N}_]+\))*[-.]?)(.+)?/iu
```
--------------------------------
### Parse Japanese Recipe with Partial Unit Matching
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/README.md
Parse a Japanese ingredient string, enabling partial unit matching and defining custom units like '大さじ' (tablespoon).
```typescript
parseIngredient('砂糖大さじ2', {
partialUnitMatching: true,
additionalUOMs: {
大さじ: {
short: '大さじ',
plural: '大さじ',
alternates: [],
type: 'volume',
conversionFactor: 15,
},
},
});
```
--------------------------------
### Unit Conversions with Custom Units
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Integrate custom unit definitions for conversions by providing an `additionalUOMs` object. Ensure units have compatible types and conversion factors.
```javascript
// Use custom unit definitions
convertUnit(1, 'bucket', 'liter', {
additionalUOMs: {
bucket: {
short: 'bkt',
plural: 'buckets',
alternates: [],
type: 'volume',
conversionFactor: 10000, // 10000 ml = 10 liters
},
},
}); // 10
```
--------------------------------
### Basic Unit Conversions
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/convertUnit.md
Perform standard conversions between common units like cups to milliliters or pounds to grams. Accepts various forms of unit names (e.g., 'cup', 'cups', 'c').
```typescript
import { convertUnit } from 'parse-ingredient';
convertUnit(1, 'cup', 'milliliter'); // ~236.588 (US cup)
convertUnit(1, 'cups', 'ml'); // ~236.588 (same as above)
convertUnit(1, 'pound', 'gram'); // ~453.592
convertUnit(1, 'lbs', 'g'); // ~453.592
convertUnit(1, 'inch', 'centimeter'); // 2.54
```
--------------------------------
### Batch Unit Lookups
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/README.md
Efficiently look up units in batches by building lookup maps with additional units of measure. This is useful when processing a large number of ingredient strings.
```typescript
import { buildUnitLookupMaps, lookupUnit } from 'parse-ingredient';
const maps = buildUnitLookupMaps(additionalUOMs);
for (const unitString of unitStrings) {
const unitID = lookupUnit(unitString, maps);
}
```
--------------------------------
### Configure Group Header Patterns
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/README.md
Use `groupHeaderPatterns` to identify and parse group headers. This can include strings or RegExp patterns for flexible matching. Defaults to `['For']`.
```javascript
// German group headers
parseIngredient('Für den Teig:\n2 cups flour', {
groupHeaderPatterns: ['For', 'Für'],
});
// [
// { description: 'Für den Teig:', isGroupHeader: true, ... },
// { quantity: 2, unitOfMeasure: 'cups', description: 'flour', ... }
// ]
```
```javascript
// French with regex pattern (matches "Pour la", "Pour le", "Pour un", etc.)
parseIngredient('Pour la pâte:', {
groupHeaderPatterns: ['For', /^Pour\s/iu],
});
```
--------------------------------
### parseIngredient
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/README.md
Parses a single ingredient string or a multi-line string of ingredients into structured objects. It can handle quantities, units of measure, and descriptions.
```APIDOC
## parseIngredient
### Description
Parses a single ingredient string or a multi-line string of ingredients into structured objects. It can handle quantities, units of measure, and descriptions.
### Method
```typescript
parseIngredient(ingredientString: string, options?: ParseIngredientOptions)
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
const result = parseIngredient('1 1/2 cups sugar');
// Returns an array of Ingredient objects
const ingredients = parseIngredient(`
2 cups flour
1 tablespoon sugar
1/4 teaspoon salt
`);
// Returns an array of Ingredient objects
```
### Response
#### Success Response
An array of `Ingredient` objects, where each object represents a parsed ingredient.
```typescript
interface Ingredient {
quantity: number | null;
quantity2: number | null;
unitOfMeasureID: string | null;
unitOfMeasure: string | null;
description: string;
isGroupHeader: boolean;
meta?: IngredientMeta;
}
```
#### Response Example
```json
[
{
"quantity": 1.5,
"quantity2": null,
"unitOfMeasureID": "cup",
"unitOfMeasure": "cups",
"description": "sugar",
"isGroupHeader": false
}
]
```
```
--------------------------------
### Add Custom Unit Definition
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/units-of-measure.md
Define a custom unit like 'bucket' with its properties (short name, plural, alternates, type, and conversion factor) when parsing ingredients.
```typescript
parseIngredient('2 buckets water', {
additionalUOMs: {
bucket: {
short: 'bkt',
plural: 'buckets',
alternates: ['bk'],
type: 'volume',
conversionFactor: 10000, // 10 liters
}
}
});
```
--------------------------------
### Build Unit Lookup Maps
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/api-reference/unitLookup.md
Creates case-sensitive and case-insensitive maps for unit identification. Use this function to efficiently look up units of measure by their various forms (ID, short, plural, alternates). Custom units can be provided to override defaults.
```typescript
import { buildUnitLookupMaps } from 'parse-ingredient';
const maps = buildUnitLookupMaps({
bucket: {
short: 'bkt',
plural: 'buckets',
alternates: ['bk'],
}
});
maps.caseSensitive.get('cup'); // 'cup'
maps.caseSensitive.get('c'); // 'cup'
maps.caseSensitive.get('T'); // 'tablespoon'
maps.caseSensitive.get('t'); // 'teaspoon'
maps.caseSensitive.get('bucket'); // 'bucket'
maps.caseInsensitive.get('cup'); // 'cup'
maps.caseInsensitive.get('CUPS'); // 'cup'
maps.caseInsensitive.get('bucket'); // 'bucket'
```
--------------------------------
### Unit Lookup Functions
Source: https://github.com/jakeboone02/parse-ingredient/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
Functions for creating, retrieving, and using unit lookup maps for efficient unit identification and extraction.
```javascript
import { buildUnitLookupMaps, getDefaultUnitLookupMaps, lookupUnit, collectUOMStrings } from "@/api-reference/unitLookup.md";
```