Skip to content

Instantly share code, notes, and snippets.

@cagcak
Created September 29, 2019 09:27
Show Gist options
  • Save cagcak/1ddf9bde4395ee1ebe8518ce757c9466 to your computer and use it in GitHub Desktop.
Save cagcak/1ddf9bde4395ee1ebe8518ce757c9466 to your computer and use it in GitHub Desktop.
A function that converts a number to words in Turkish
const turkish_NumberToWords = (number = 0) => {
/*
* Assign spelling words in seperate arrays
*/
const steps = ['', 'bir', 'iki', 'üç', 'dört', 'beş', 'altı', 'yedi', 'sekiz', 'dokuz']
const tens = ['', 'on', 'yirmi', 'otuz', 'kırk', 'elli', 'altmış', 'yetmiş', 'seksen', 'doksan']
const hundreds = ['', 'yüz', 'ikiyüz', 'üçyüz', 'dörtyüz', 'beşyüz', 'altıyüz', 'yediyüz', 'sekizyüz', 'dokuzyüz']
const nS = ['', 'bin', 'milyon', 'milyar', 'trilyon', 'katrilyon', 'kentilyon', 'seksilyon', 'septilyon', 'oktilyon']
/*
* Maximum number step is 30
*/
const max = 30
/*
* Completing number if it has step length which are bigger than 3
*/
const completer = ['', '00', '0']
/*
* Variables which hold data temporary
*/
let index
let backer
let triples
let result = ''
/*
* Combining less-thousands input to words
* Ex: > turkish_NumberToWords('134')
* > 'yüz' + 'otuz' + 'dört'
*/
const getUntilThousands = triple => `${hundreds[triple[0]]} ${tens[triple[1]]} ${steps[triple[2]]}`
/*
* Handling string parameter errors before calculation
*/
const errorHandlers = () => {
if (number.toString().length > max) {
throw new RangeError `Girilen hesaplanamayacak kadar çok büyük. Sayı en fazla ${max} basamak olmalıdır`
}
if (typeof number != 'string') {
throw new TypeError('Parametre string olmalıdır')
}
for (let index = 0; index < number.length; ++index) {
console.log(number[index])
if (number[index] < '0' || number[index] > '9') {
throw new Error('Sayı sadece rakamlardan oluşmalıdır')
}
}
}
errorHandlers()
/*
* Seperating triples as a word from end edge
*/
number = completer[number.length % 3] + number
/*
* Iterating over seperated triple length
*/
for ( index = number.length, backer = 0; index > 0; index -= 3, ++backer ) {
/*
* Reigstering next triple to calculate
*/
triples = getUntilThousands(number.substr(index - 3, 3))
/*
* If the last triple hasn't reached yet,
* extend the resulted and combined words to the right
*/
if (triples !== '') {
result = `${triples} ${nS[backer]} ${result}`
}
}
/*
* There is no one thousand or a thousand in turkish,
* just returning last word
*/
if (result.substr(0, 7) === 'bir bin') {
return result.substr(4)
} else if (result === '') {
return 'sıfır'
} else {
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment