|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import { enUS } from './systems';
- import { StringifySystem } from './common';
-
- type StringifyValue = string | number | bigint;
-
- export interface StringifyOptions {
- system?: StringifySystem;
- makeGroupOptions?: Record<string, unknown>;
- }
-
- export const stringify = (
- valueRaw: StringifyValue,
- options = {} as StringifyOptions,
- ): string => {
- if (!(['bigint', 'number', 'string'].includes(typeof (valueRaw as unknown)))) {
- throw new TypeError('value must be a string, number, or bigint');
- }
-
- const value = valueRaw.toString().replace(/\s/g, '');
- const { system = enUS, makeGroupOptions } = options;
-
- if (value.startsWith('-')) {
- return system.makeNegative(stringify(value.slice(1), options));
- }
-
- const groups = system
- .group(value)
- .map(([group, place]) => (
- system.makeGroup(group, place, makeGroupOptions)
- ));
-
- return system.finalize(groups);
- };
-
- type ParseType = 'string' | 'number' | 'bigint';
-
- export interface ParseOptions {
- system?: StringifySystem;
- type?: ParseType;
- }
-
- export const parse = (value: string, options = {} as ParseOptions) => {
- const { system = enUS, type = 'string' } = options;
-
- const tokens = system.tokenize(value);
- const groups = system.parseGroups(tokens);
- const stringValue = system.combineGroups(groups);
-
- switch (type) {
- case 'number':
- return Number(stringValue);
- case 'bigint':
- return BigInt(stringValue);
- default:
- break;
- }
-
- return stringValue;
- };
|