Chain Formatting
Format a number as a combination of multiple units, which is very useful for formatting time, such as "1h30m30s".
Basic Usage
import SmartUnit from 'smart-unit'
const time = new SmartUnit(['ms', 1000, 's', 60, 'm', 60, 'h'])
console.log(time.formatChain(3661000)) // => "1h1m1s"Custom Separator
const length = new SmartUnit(['mm', 10, 'cm', 100, 'm'], {
// Separator, you can also specify it in the formatChain method
separator: ''
})
console.log(length.formatChain(1350)) // => "1m35cm"
console.log(length.formatChain(1350, ' ')) // => "1m 35cm"
console.log(length.formatChain(1350, ':')) // => "1m:35cm"If you want to add a space between the number and the unit, you should use
withConvertinstead ofseparator, which can only configure the separator between chain units.
Getting Chain Unit Array
Use the getChainUnit method to get the raw data, then format it however you want:
const time = new SmartUnit(['ms', 1000, 's', 60, 'm', 60, 'h'])
const chain = time.getChainUnit(3661000)
console.log(chain)
// [
// { num: 1, unit: 'h', numStr: '1' },
// { num: 1, unit: 'm', numStr: '1' },
// { num: 1, unit: 's', numStr: '1' }
// ]
// Completely custom formatting
const customFormat = chain.map(({ numStr, unit }) => {
const icons = { h: '⏰', m: '⏱️', s: '⏲️', ms: '' }
return `${icons[unit]}${numStr}${unit}`
}).join(' ')
console.log(customFormat) // => "⏰1h ⏱️1m ⏲️1s"Impact of fractionDigits
SmartUnit preserves decimals for the smallest unit, while other units don't display decimals, so they are not affected by the fractionDigits configuration.
Reverse Parsing
import SmartUnit from 'smart-unit'
const time = new SmartUnit(['ms', 1000, 's', 60, 'm', 60, 'h'])
console.log(time.parseChain('1h1m1s')) // => 3661000
console.log(time.parseChain('1h:1m:1s', ':')) // => 3661000Use the parseChain method to parse chain unit strings back to original values. This method takes the separator into account. It's best to specify the separator during initialization so you don't have to specify it every time you parse.
If you just want to split the number and unit, you can use the splitChainUnit method, which returns an array containing numbers and units without calculating the original value.
Internationalization Support
Reverse parsing supports internationalized strings. After using internationalization, only strings in the specific language can be correctly parsed. Original units will no longer be recognized.
Note
Reverse parsing only supports strings generated by or compatible with the formatChain method. If you use getChainUnit to get the unit and then manually format it, it's usually not supported.