diff --git a/src/includes/util.js b/src/includes/util.js new file mode 100644 index 0000000..4ae5c4b --- /dev/null +++ b/src/includes/util.js @@ -0,0 +1,73 @@ +const getClientLocale = () => { + return navigator.languages.length > 0 ? navigator.languages[0] : 'en-US'; +}; + +const getAge = (dateOfBirth) => { + const today = new Date(); + + const thisYear = today.getFullYear(); + const thisMonth = today.getMonth(); + const thisDay = today.getDate(); + + const dobYear = dateOfBirth.getFullYear(); + const dobMonth = dateOfBirth.getMonth(); + const dobDay = dateOfBirth.getDate(); + + let age = thisYear - dobYear; + + if (thisMonth < dobMonth) age--; + if (thisMonth === dobMonth && thisDay < dobDay) age--; + + return age; +}; + +const toImperial = (cm) => { + const realFeet = (cm * 0.3937) / 12; + const feet = Math.floor(realFeet); + const inches = Math.round((realFeet - feet) * 12); + + return `${feet}'${inches}"`; +}; + +const toInch = (cm) => { + return `${Math.round(cm / 2.45)} in`; +}; + +const toLbs = (kg) => { + const nearExact = kg / 0.45359237; + const lbs = Math.floor(nearExact); + + return lbs; +}; + +const toFahrenheit = (celsius) => { + return celsius * 1.8 + 32; +}; + +const dateFormat = new Intl.DateTimeFormat(getClientLocale(), { + year: 'numeric', + month: 'long', + day: '2-digit' +}); + +const getFullName = (...names) => names.join(' '); +const getDateOfBirth = (dob) => `${dateFormat.format(dob)} (${getAge(dob)})`; +const getHeight = (height) => `${height} cm (${toImperial(height)})`; +const getWeight = (weight) => `${weight} kg (${toLbs(weight)} lbs)`; +const getTailLength = (length) => `${length / 100} m (${toImperial(length)})`; +const getWingspan = (wingspan) => `${wingspan / 100} m (${toImperial(wingspan)})`; + +export { + getAge, + toImperial, + toInch, + toLbs, + toFahrenheit, + dateFormat, + getFullName, + getDateOfBirth, + getHeight, + getWeight, + getTailLength, + getWingspan +}; diff --git a/src/index.webc b/src/index.webc index 61caeaa..cff532f 100644 --- a/src/index.webc +++ b/src/index.webc @@ -1,7 +1,7 @@