Skip to content

Main content

Quantity with Unit Parser Source Code

Browse the implementation files for Quantity with Unit Parser.
@tool.io/tools/parse/quantity source ↗
tool.ts typescript
import {
	NUMBER_FORMAT_OPTIONS,
	type NumberFormat
} from '../number/tool';
import { parseQuantity as parsePortableQuantity } from '@tool.io/tools/parse/quantity';

export type ParsedQuantity = {
	unit: string;
	value: number;
};

export const parseQuantity = (
	input: unknown,
	formatInput: unknown = 'plain'
): ParsedQuantity | null => {
	if (typeof input !== 'string') return null;

	if (typeof formatInput !== 'string') return null;
	return parsePortableQuantity(
		input,
		formatInput as NumberFormat
	);
};

export const normalizeQuantity = (
	input: unknown,
	formatInput: unknown = 'plain'
): string => {
	const result = parseQuantity(input, formatInput);
	return result === null ? '' : JSON.stringify(result);
};

export const Tool: TypeTool = {
	name: 'Quantity with Unit Parser',
	slug: 'parse/quantity',
	intro:
		'Parse a numeric value and its unit without performing a unit conversion.',
	tool: normalizeQuantity,
	i: [
		{
			example: '12.5 kg',
			help: 'Enter a number followed by a unit such as kg, m/s, °C, or ft.',
			label: 'Quantity',
			placeholder: 'Enter a value and unit',
			type: 'text'
		},
		{
			example: 'plain',
			label: 'Number Format',
			options: NUMBER_FORMAT_OPTIONS,
			placeholder: 'Choose a number format',
			type: 'select',
			value: 'plain'
		}
	],
	o: [
		{
			example: '{"unit":"kg","value":12.5}',
			help: 'The unit is preserved exactly and is not converted.',
			label: 'Parsed Quantity',
			placeholder: 'Parsed quantity will appear here...',
			render: 'textarea',
			type: 'text'
		}
	]
};

export default Tool;

Description

Browse the implementation files for Quantity with Unit Parser.

References

  1. Tool.io on GitHub
  2. Tool.io TypeScript tools library

Similar or alternative tools