Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ parse('2e3s') // => 2000 * s

// custom output format
parse('1hr 20mins', 'm') // => 80
parse('1hr 20mins', 'MINS') // => 80, same matching rules as input units

// add units
parse.unit['μs'] = parse.unit.microsecond
Expand Down
17 changes: 14 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ parse.unit = en
// group/placeholder cleanup regex — rebuilt only when the locale strings change
let groupRE, placeholder = null, group

/**
* look up a unit name, ignoring case and a trailing plural `s`
*
* @param {object} unit
* @param {string} name
* @return {number|undefined}
*/
const lookupUnit = (unit, name) => {
name = String(name).toLowerCase()
return unit[name] ?? (name.endsWith('s') ? unit[name.slice(0, -1)] : undefined)
}

/**
* convert `str` to ms
*
Expand Down Expand Up @@ -35,12 +47,11 @@ export default function parse(str = '', format = 'ms') {
}
else units = format
}
else units = units.toLowerCase()

prevUnits = units = unit[units] || (units.endsWith('s') ? unit[units.slice(0, -1)] : undefined)
prevUnits = units = lookupUnit(unit, units)

if (typeof units == 'number') result = (result || 0) + m[1] * units
}

return result && ((result / (unit[format] || 1)) * (str.trimStart()[0] === '-' ? -1 : 1))
return result && ((result / (lookupUnit(unit, format) || 1)) * (str.trimStart()[0] === '-' ? -1 : 1))
}
17 changes: 17 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,23 @@ t('format', t => {
t.end()
})

t('format is matched like an input unit', t => {
// upper-case, exactly as accepted on the input side (`parse('2MIN')`)
t.equal(parse('2h', 'M'), 120)
t.equal(parse('2h', 'MIN'), 120)
t.equal(parse('2h', 'Hours'), 2)

// plural, matching `unit.endsWith('s')` handling on the input side
t.equal(parse('2h', 'mins'), 120)
t.equal(parse('2h', 'hrs'), 2)
t.equal(parse('2h', 'seconds'), 7200)

// an unknown format still falls back to ms
t.equal(parse('2h', 'bogus'), 7200000)

t.end()
})

t('unicode support', t => {
parse.unit['сек'] = parse.unit['s'] // ru seconds
t.equal(parse('5сек'), 5000)
Expand Down
Loading