Skip to content

Instantly share code, notes, and snippets.

@iamandrewluca
Last active April 22, 2022 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamandrewluca/a9161c18cf0115ff980e69b334501176 to your computer and use it in GitHub Desktop.
Save iamandrewluca/a9161c18cf0115ff980e69b334501176 to your computer and use it in GitHub Desktop.
let unit = `5" x 5' x 1-3/16"`
unit.split('x')
.map((v) => v.trim())
.map((v) => ({ value: removeUnit(v), unit: getUnit(v) }))
.map(({ unit, value }) => ({ unit, value: value.split('-') }))
.map(({ unit, value: [whole, fraction] }) => ({ unit, whole, fraction: splitFraction(fraction) }))
.map(({ unit, whole, fraction }) => ({ unit, value: parseInt(whole) + divideTuple(fraction) }))
.map(o => convertToInch(o))
.reduce((product, o) => product * o.value, 1)
let getUnit = (v: string) => v.includes('"') ? 'inch' : v.includes(`'`) ? 'feet' : undefined
let removeUnit = (v: string) => v.replace(/['"]/g, '')
let splitFraction = (v: string = '0/1') => v.split('/') as [string, string]
let divideTuple = ([numerator = '0', denominator = '1'] = ['0', '1']) => parseInt(numerator) / parseInt(denominator)
let convertToInch = (o: { unit: string, value: number }) => o.unit === 'inch' ? o : ({ unit: 'inch', value: o.value * 12 })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment