loading...

re: Daily Challenge #248 - Chinese Numerals VIEW POST

FULL DISCUSSION
 

Add more test cases.

// 28901 二万八千九百零一
// 28911 二万八千九百一十一
// 20911 二万零九百一十一
// 20901 二万零九百零一
// 20001 二万零一
// 29000 二万九

let numberArray = [
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
  '',
]

let unitArray = ['', '', '', '', '']

const toChineseNumeral = input => {
  return input.toString().split('').map(
    (number, idx) => {
      return numberArray[parseInt(number)]
    }
  ).reduce(
    (acc, current) => {
      let last = acc[acc.length - 1]
      if (last == '' && current == '')
        acc[acc.length - 1] = ' '
      if (acc.length == (input.length - 1) && current == '')
        current = ''
      acc.push(current)
      return acc
    },
    []
  ).map(
    (elem, idx) => {
      if (elem == ' ' || elem == '')
        return elem.trim()
      return elem + unitArray[input.length-1 - idx]
    }
  ).join('').replace(/^一十/, '')
}

console.log(toChineseNumeral(29389))
console.log(toChineseNumeral(29000))
console.log(toChineseNumeral(20001))
console.log(toChineseNumeral(20901))

console.log([
    10,
    11,
    18,
    21,
    110,
    123,
    24681
].map(toChineseNumeral))
code of conduct - report abuse