gen-unit
A generic unit parser/formatter
Install
# Using npm
npm i gen-unit
# Using yarn
yarn add gen-unit
API
createParserfunctioncreateParseroptionsunitoptionmatchoptionmatchoption as a RegExpmatchoption as a stringmatchoption as a function
findoptionfindoption as a numberfindoption as an arrayfindoption as an objectfindoption as a function
createFormatterfunctioncreateFormatteroptionsunitoptionfindoptionfindoption as a numberfindoption as an arrayfindoption as an objectfindoption as a function
roundoptionroundoption as an objectroundoption as a numberroundoption as a functionroundoption as a boolean
outputoptionoutputoption as an objectoutputoption as a function
parsefunctionformatfunctionMICROconstant
The createParser function
Creates a parse function using the given options.
function createParser(options): Parser;
type Parser = (input: unknown) => number;
createParser options
The unit option
Defines the unit to be used during parsing.
unit: string;
Example
const parse = createParser({
unit: 'g',
});
parse('1'); // => 1
parse('1 g'); // => 1
parse('1 m'); // => 0.001
parse('1 mg'); // => 0.001
parse('1 k'); // => 1000
parse('1 kg'); // => 1000
parse('1 ms'); // => NaN because "s" is not recognized as unit
Precedence
This option takes precedence over any prefix or prefixed unit.
Examples
const parseMeter = createParser({
unit: 'm', // Meter
});
parseMeter('1 m'); // returns 1 (1 meter)
parseMeter('1 mm'); // returns 0.001 (1 millimeter)
const parseSecond = createParser({
unit: 's' // Seconds
});
parseSecond('1 m'); // returns 0.001 (1 millisecond)
parseSecond('1 ms'); // returns 0.001 (1 millisecond)
const parse = createParser({
unit: 'eg', // assuming "eg" is the unit... for some reason
});
parse('1 meg'); // => 0.001 (not 1000000), it's interpreted as 1 milli-eg
parse('1 megeg'); // => 1000000, it's interpreted as 1 mega-eg
parse('1 Meg'); // => 1000000, it's interpreted as 1 mega-eg because capital "M" parses as mega
The match option
match: RegExp | string | MatchFunction;
type MatchFunction = (input: string) => [value: string, unit: string] | null | undefined;
default /^\s*(-?\d*\.?\d*(?:e[+-]?\d+)?)\s*([a-z\xb5]*)\s*$/i
Defines the first step in the parse process, it takes the input and should turn it into an array with two elements with the value, and the unit to be process further down the road, or null (or undefined) if the input can't be parsed.
match option as a RegExp
match: RegExp;
default /^\s*(-?\d*\.?\d*(?:e[+-]?\d+)?)\s*([a-z\xb5]*)\s*$/i
A RegExp with two capturing groups, the first to be used as value and the second as unit. If the RegExp has less than two capturing groups, parse function will throw.
Example
const parse = createParser({
match: /^\s*([\d.]+)\s*([a-z]*)\s*$/i,
});
parse('1 m'); // => 0.001
parse('1 k'); // => 1000
match option as a string
match: string;
A string to be used to create a RegExp. It is expected to have two capturing groups, the first to be used as value and the second as unit.
Example
const parse = createParser({
match: '^\\s*([\\d.]+)\\s*([a-z]*)\\s*
match option as a function
match: (input: string) => [value: string, unit: string] | null | undefined;
A function which will receive the input and should return an array of two elements, the first to be used as value and the second as unit, or null (or undefined) if the input can't be parsed.
Example
const parse = createParser({
match(input) {
return [input, 'k']
},
});
parse('1'); // => 1000
parse('2'); // => 2000
The find option
The find option describes how to find the multiplier which is the number by which the parsed value should be multiplied.
find option as a number
find: number;
A number to be used as base during parsing.
Example
const parse = createParser({
find: 1024,
});
parse('2'); // => 2
parse('2 k'); // => 2048
parse('2 M'); // => 2097152
parse('2 G'); // => 2147483648
find option as an array
find: Array<{ pre: string; exp: number }>;
An array of objects describing prefixes and exponents to use with the default base (1000) to find the multiplier to be used during parsing. Every item should have a unique pre, if there are duplicates createParser will throw.
notes
Note that empty prefix ({ pre: '', exp: 0 }) is not necessary, as an empty prefix will result in multiplier = 1
Example
const parse = createParser({
find: [
{ pre: 'k', exp: 1 },
{ pre: 'M', exp: 2 },
],
});
parse('1.3'); // => 1.3
parse('1.3 k'); // => 1300
parse('1.3 M'); // => 1300000
parse('1.3 G'); // => NaN because prefix "G" can't be found
find option as an object
find: {
base?: number;
items?: Array<{ pre: string; exp: number }>;
};
default: {
base: 1000,
items: [
{ pre: 'a', exp: -6 },
{ pre: 'f', exp: -5 },
{ pre: 'p', exp: -4 },
{ pre: 'n', exp: -3 },
{ pre: 'u', exp: -2 },
{ pre: 'µ', exp: -2 },
{ pre: 'm', exp: -1 },
{ pre: 'k', exp: 1 },
{ pre: 'K', exp: 1 },
{ pre: 'meg', exp: 2 },
{ pre: 'M', exp: 2 },
{ pre: 'G', exp: 3 },
{ pre: 'T', exp: 4 },
{ pre: 'P', exp: 5 },
{ pre: 'E', exp: 6 },
],
}
An object describing the base and a series of objects describing prefixes and exponents to find the multiplier to be used during parsing. Every item in items array should have a unique pre, if there are duplicates createParser will throw.
Notes
Note that empty prefix ({ pre: '', exp: 0 }) is not necessary, as an empty prefix will result in multiplier = 1
Example
const parse = createParser({
find: {
base: 1024,
items: [
{ pre: 'K', exp: 1 },
{ pre: 'M', exp: 2 },
],
},
});
parse('1'); // => 1
parse('1 K'); // => 1024
parse('1 M'); // => 1048576
parse('1 G'); // => NaN
find option as a function
find: (pre: string) => number | null | undefined;
A function that should return a non-zero number by which the parsed value should be multiplied based on the captured prefix. Return null (or undefined) if multiplier can't be determined. It will cause the parse function to return NaN. If your function returns zero, negative number or any other invalid multiplier, parse function will throw a TypeError.
Example
const parse = createParser({
find: (unit) => {
if (unit === 'K' || unit === 'k') {
return 1024;
} else if (unit === 'M') {
return 1024 ** 2;
}
// next line can be omitted
// as it will return undefined anyway
return null;
},
});
parse('2'); // => 2
parse('2 k'); // => 2048
parse('2 K'); // => 2048
parse('2 M'); // => 2097152
parse('2 G'); // => NaN
Notes
Previous version of this library allow this function to return an object { mul: number } containing the multiplier. This behavior has been removed, it will throw instead.
The createFormatter function
Creates a format function using the given options.
function createFormatter(options): Formatter;
type Formatter = (input: number) => string;
createFormatter options
The unit option
A string to be used as main unit during formatting.
unit: string;
Example
const format = createFormatter({
unit: 'm',
});
format(100); // => '100 m'
format(0.0012); // => '1.2 mm'
format(1200); // => '1.2 Km'
The find option
Describes how to find the unit prefix and divider based on input value.
find option as a number
find: number;
A number to be used as base during formatting.
Example
const format = createFormatter({
find: 1024,
});
format(100); // => '100'
format(2048); // => '2 k'
format(2097152); // => '2 M'
find option as an array
find: Array<{ pre: string; exp: number }>;
An array of objects describing prefixes and exponents to use with the default base (1000) to find the prefix and multiplier to be used during formatting. Every item should have a unique exp, if there are duplicates createFormatter will throw.
Example
const format = createFormatter({
find: [
{ exp: 0, pre: '' },
{ exp: 1, pre: 'K' },
],
});
format(2); // => '2'
format(2000); // => '2 K'
format(2000000); // => '2000 K'
find option as an object
find: {
base?: number;
items?: Array<{ exp: number; pre: string }>;
}
default: {
base: 1000,
items: [
{ exp: -6, pre: 'a' },
{ exp: -5, pre: 'f' },
{ exp: -4, pre: 'p' },
{ exp: -3, pre: 'n' },
{ exp: -2, pre: 'µ' },
{ exp: -1, pre: 'm' },
{ exp: 0, pre: '' },
{ exp: 1, pre: 'k' },
{ exp: 2, pre: 'M' },
{ exp: 3, pre: 'G' },
{ exp: 4, pre: 'T' },
{ exp: 5, pre: 'P' },
{ exp: 6, pre: 'E' },
],
}
An object describing the base and a series of objects describing prefixes and exponents to find the prefix and multiplier to be used during formatting. Every item in items array should have a unique exp, if there are duplicates createFormatter will throw.
Example
const format = createFormatter({
find: {
base: 1024,
items: [
{ exp: 0, pre: '' },
{ exp: 1, pre: 'K' },
],
},
});
format(100); // => '100'
format(2048); // => '2 K'
format(2097152); // => '2048 K'
find option as a function
find: (value: number) => { pre: string; mul: number };
A function that returns an object describing the unit prefix (pre) and multiplier (mul).
Example
const format = createFormatter({
find: (value) => {
if (value >= 1000) {
return { pre: 'K', mul: 1000 };
} else {
return { pre: '', mul: 1 };
}
},
});
format(0.2); // => '0.2'
format(2); // => '2'
format(2000); // => '2 K'
format(2000000); // => '2000 K'
The round option
Describes how to round the output value before final format.
round option as an object
round: {
dec?: number;
fixed?: boolean;
};
default: {
dec: 2,
fixed: false,
};
An object describing how to round the value before final format. Describes the number of decimal (dec) and whether or not the output should have a fixed number of decimal (fixed).
Example
const format = createFormatter({
round: {
dec: 3,
fixed: true,
},
});
format(1.23); // => '1.230'
format(1230); // => '1.230 k'
format(0.00123); // => '1.230 m'
round option as a number
round: number;
A number defining the number of decimal places to round to.
Example
const format = createFormatter({
round: 1,
});
format(1.23); // => '1.2'
format(1.28); // => '1.3'
format(1230); // => '1.2 k'
format(0.00123); // => '1.2 m'
round option as a function
round: (num: number) => (string | number);
A function which returns the rounded value.
Example
const format = createFormatter({
round: Math.round,
});
format(1.23); // => '1'
format(1.75); // => '2'
format(1230); // => '1 k'
format(0.00123); // => '1 m'
round option as a boolean
round: boolean;
A boolean defining wether or not to round the number. If true is passed, the default rounder will be used (2 decimals). If false is passed, rounding will be disabled.
Example
const format = createFormatter({
round: true,
});
format(1.231); // => '1.23'
format(1.238); // => '1.24'
format(1200); // => '1.2 k'
format(0.001234); // => '1.23 m'
const format = createFormatter({
round: false,
});
format(1.234); // => '1.234'
format(1.28); // => '1.28'
format(1233); // => '1.233 k'
format(0.0012); // => '1.2 m'
Keep in mind disabling the rounder will case the the output to receive the value in it's raw form and you might get unpredictable results, see example...
Example
const format = createFormatter({});
const formatWithoutRounding = createFormatter({ round: false });
const pointThree = 0.1 + 0.2; // in javascript 0.1 + 0.2 = 0.30000000000000004
format(pointThree); // => '0.3'
formatWithoutRounding(pointThree); // => '0.30000000000000004'
const threeThousand = pointThree * 10000; // 3000.0000000000005
format(threeThousand); // => '3 k'
formatWithoutRounding(threeThousand); // => '3000.0000000000005 k'
The output option
Describes the final output format.
output: FormatOutputFunction | FormatOutputAdvancedOption;
type FormatOutputFunction = (value: string | number, prefix: string, unit: string) => string;
interface FormatOutputAdvancedOption {
space: string;
}
output option as an object
output: {
space?: string;
}
default {
space: ' ';
}
Example
const format = createFormatter({
output: {
space: '-', // unrealistic, for demonstration only
},
})
format(1.23); // => '1.23'
format(1230); // => '1.23-k'
format(0.00123); // => '1.23-m'
output option as a function
A function to format the final output.
output: (value: string | number, prefix: string, unit: string) => string;
Example
const format = createFormatter({
unit: 'x',
output: (value, pre) => {
// ignore original unit and hardcode one
return `${value}${pre}s`;
},
});
format(1.23); // => '1.23s'
format(1230); // => '1.23ks'
format(0.00123); // => '1.23ms'
The parse function
A convenient function to parse an input in one step. I will internally call createParser then will call the newly created parser. See createParser options.
function parse(input, options): number;
The format function
A convenient function to format a number in one step. It wil internally call createFormatter then will call the newly created formatter. See createFormatter options.
function format(input, options): string;
The MICRO constant
A constant containing the micro symbol ("µ"). Used internally, exported for convenience.
License
MIT 2019-2024 Manuel Fernández
,
});
parse('1 m'); // => 0.001
parse('1 k'); // => 1000
__INLINE_CODE_58__ option as a function
__CODE_BLOCK_12__A function which will receive the __INLINE_CODE_59__ and should return an __INLINE_CODE_60__ of __INLINE_CODE_61__, the first to be used as __INLINE_CODE_62__ and the second as __INLINE_CODE_63__, or __INLINE_CODE_64__ (or __INLINE_CODE_65__) if the input can't be parsed.
Example
__CODE_BLOCK_13__The __INLINE_CODE_66__ option
The __INLINE_CODE_67__ option describes how to find the multiplier which is the __INLINE_CODE_68__ by which the parsed value should be multiplied.
__INLINE_CODE_69__ option as a number
__CODE_BLOCK_14__A number to be used as __INLINE_CODE_70__ during parsing.
Example
__CODE_BLOCK_15____INLINE_CODE_71__ option as an array
__CODE_BLOCK_16__An __INLINE_CODE_72__ of __INLINE_CODE_73__ describing __INLINE_CODE_74__ and __INLINE_CODE_75__ to use with the default __INLINE_CODE_76__ (1000) to find the __INLINE_CODE_77__ to be used during parsing. Every item should have a unique __INLINE_CODE_78__, if there are duplicates __INLINE_CODE_79__ will __INLINE_CODE_80__.
notes
Note that __INLINE_CODE_81__ (__INLINE_CODE_82__) is not necessary, as an __INLINE_CODE_83__ will result in __INLINE_CODE_84__
Example
__CODE_BLOCK_17____INLINE_CODE_85__ option as an object
__CODE_BLOCK_18__An object describing the __INLINE_CODE_86__ and a series of __INLINE_CODE_87__ describing __INLINE_CODE_88__ and __INLINE_CODE_89__ to find the __INLINE_CODE_90__ to be used during parsing. Every item in __INLINE_CODE_91__ array should have a unique __INLINE_CODE_92__, if there are duplicates __INLINE_CODE_93__ will __INLINE_CODE_94__.
Notes
Note that __INLINE_CODE_95__ (__INLINE_CODE_96__) is not necessary, as an __INLINE_CODE_97__ will result in __INLINE_CODE_98__
Example
__CODE_BLOCK_19____INLINE_CODE_99__ option as a function
__CODE_BLOCK_20__A function that should return a non-zero __INLINE_CODE_100__ by which the parsed value should be multiplied based on the captured prefix. Return __INLINE_CODE_101__ (or __INLINE_CODE_102__) if multiplier can't be determined. It will cause the parse function to return __INLINE_CODE_103__. If your function returns __INLINE_CODE_104__, __INLINE_CODE_105__ or any other invalid multiplier, parse function will throw a __INLINE_CODE_106__.
Example
__CODE_BLOCK_21__Notes
Previous version of this library allow this function to return an object __INLINE_CODE_107__ containing the multiplier. This behavior has been removed, it will __INLINE_CODE_108__ instead.
The __INLINE_CODE_109__ function
Creates a __INLINE_CODE_110__ function using the given options.
__CODE_BLOCK_22____INLINE_CODE_111__ options
The __INLINE_CODE_112__ option
A __INLINE_CODE_113__ to be used as main __INLINE_CODE_114__ during formatting.
__CODE_BLOCK_23__Example
__CODE_BLOCK_24__The __INLINE_CODE_115__ option
Describes how to find the unit __INLINE_CODE_116__ and __INLINE_CODE_117__ based on input value.
__INLINE_CODE_118__ option as a number
__CODE_BLOCK_25__A __INLINE_CODE_119__ to be used as __INLINE_CODE_120__ during formatting.
Example
__CODE_BLOCK_26____INLINE_CODE_121__ option as an array
__CODE_BLOCK_27__An __INLINE_CODE_122__ of __INLINE_CODE_123__ describing __INLINE_CODE_124__ and __INLINE_CODE_125__ to use with the default __INLINE_CODE_126__ (1000) to find the __INLINE_CODE_127__ and __INLINE_CODE_128__ to be used during formatting. Every item should have a unique __INLINE_CODE_129__, if there are duplicates __INLINE_CODE_130__ will __INLINE_CODE_131__.
Example
__CODE_BLOCK_28____INLINE_CODE_132__ option as an object
__CODE_BLOCK_29__An object describing the __INLINE_CODE_133__ and a series of __INLINE_CODE_134__ describing __INLINE_CODE_135__ and __INLINE_CODE_136__ to find the __INLINE_CODE_137__ and __INLINE_CODE_138__ to be used during formatting. Every item in __INLINE_CODE_139__ array should have a unique __INLINE_CODE_140__, if there are duplicates __INLINE_CODE_141__ will __INLINE_CODE_142__.
Example
__CODE_BLOCK_30____INLINE_CODE_143__ option as a function
__CODE_BLOCK_31__A __INLINE_CODE_144__ that __INLINE_CODE_145__ an __INLINE_CODE_146__ describing the unit __INLINE_CODE_147__ (__INLINE_CODE_148__) and __INLINE_CODE_149__ (__INLINE_CODE_150__).
Example
__CODE_BLOCK_32__The __INLINE_CODE_151__ option
Describes how to __INLINE_CODE_152__ the output value before final __INLINE_CODE_153__.
__INLINE_CODE_154__ option as an object
__CODE_BLOCK_33__An __INLINE_CODE_155__ describing how to __INLINE_CODE_156__ the value before final format. Describes the number of decimal (__INLINE_CODE_157__) and whether or not the output should have a fixed number of decimal (__INLINE_CODE_158__).
Example
__CODE_BLOCK_34____INLINE_CODE_159__ option as a number
__CODE_BLOCK_35__A __INLINE_CODE_160__ defining the number of decimal places to round to.
Example
__CODE_BLOCK_36____INLINE_CODE_161__ option as a function
__CODE_BLOCK_37__A __INLINE_CODE_162__ which __INLINE_CODE_163__ the rounded value.
Example
__CODE_BLOCK_38____INLINE_CODE_164__ option as a boolean
__CODE_BLOCK_39__A __INLINE_CODE_165__ defining wether or not to round the number. If __INLINE_CODE_166__ is passed, the default rounder will be used (2 decimals). If __INLINE_CODE_167__ is passed, rounding will be disabled.
Example
__CODE_BLOCK_40__ __CODE_BLOCK_41__Keep in mind disabling the rounder will case the the output to receive the value in it's raw form and you might get unpredictable results, see example...
Example
__CODE_BLOCK_42__The __INLINE_CODE_168__ option
Describes the final output format.
__CODE_BLOCK_43____INLINE_CODE_169__ option as an object
__CODE_BLOCK_44__Example
__CODE_BLOCK_45____INLINE_CODE_170__ option as a function
A __INLINE_CODE_171__ to format the final output.
__CODE_BLOCK_46__Example
__CODE_BLOCK_47__The __INLINE_CODE_172__ function
A convenient function to parse an __INLINE_CODE_173__ in one step. I will internally call __INLINE_CODE_174__ then will call the newly created parser. See __INLINE_CODE_175__ options.
__CODE_BLOCK_48__The __INLINE_CODE_176__ function
A convenient function to format a __INLINE_CODE_177__ in one step. It wil internally call __INLINE_CODE_178__ then will call the newly created formatter. See __INLINE_CODE_179__ options.
__CODE_BLOCK_49__The __INLINE_CODE_180__ constant
A constant containing the micro symbol ("µ"). Used internally, exported for convenience.
License
MIT 2019-2024 Manuel Fernández