Created
February 16, 2023 07:58
-
-
Save joseph-abell/407674a55a5403b6889b85823dbca677 to your computer and use it in GitHub Desktop.
Chat GPT's attempt at Scott's Tech Test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const convertNumbersToWords = (num: number): string => { | |
const words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; | |
const tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; | |
if (num < 20) { | |
return words[num]; | |
} else if (num < 100) { | |
return tens[Math.floor(num / 10)] + (num % 10 !== 0 ? " " : "") + words[num % 10]; | |
} else if (num < 1000) { | |
return words[Math.floor(num / 100)] + " hundred" + (num % 100 !== 0 ? " and " : "") + convertNumberToWords(num % 100); | |
} else if (num < 1000000) { | |
return convertNumberToWords(Math.floor(num / 1000)) + " thousand" + (num % 1000 !== 0 ? " " : "") + convertNumberToWords(num % 1000); | |
} else { | |
return convertNumberToWords(Math.floor(num / 1000000)) + " million" + (num % 1000000 !== 0 ? " " : "") + convertNumberToWords(num % 1000000); | |
} | |
}; | |
const convertCurrencyToWords = (amount: number): string => { | |
const dollars = Math.floor(amount); | |
const cents = Math.round((amount - dollars) * 100); | |
const dollarsText = dollars === 0 ? "zero dollars" : convertNumberToWords(dollars) + " dollars"; | |
const centsText = cents === 0 ? "zero cents" : convertNumberToWords(cents) + " cents"; | |
if (dollars === 0) { | |
return centsText; | |
} else if (cents === 0) { | |
return dollarsText; | |
} else { | |
return dollarsText + " and " + centsText; | |
} | |
}; | |
console.log(convertCurrencyToWords(1234.56)); // outputs "one thousand two hundred and thirty-four dollars and fifty-six cents" | |
console.log(convertCurrencyToWords(100)); // outputs "one hundred dollars" | |
console.log(convertCurrencyToWords(0.01)); // outputs "one cent" | |
// Tests Cases to use during testing | |
const testCases: [number, string][] = [ | |
[0, "zero dollars"], | |
[0.01, "one cent"], | |
[0.99, "ninety-nine cents"], | |
[1, "one dollar"], | |
[1.01, "one dollar and one cent"], | |
[100, "one hundred dollars"], | |
[100.01, "one hundred dollars and one cent"], | |
[1234.56, "one thousand two hundred and thirty-four dollars and fifty-six cents"], | |
[999999.99, "nine hundred and ninety-nine thousand nine hundred and ninety-nine dollars and ninety-nine cents"], | |
[1000000, "one million dollars"], | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment