function toNumber(str) {
const num = [‘零‘,‘一‘,‘二‘,‘三‘,‘四‘,‘五‘,‘六‘,‘七‘,‘八‘,‘九‘].indexOf(str)
return num >=0 ? num : str
}
function isUnit(str) {
switch (str) {
case ‘十‘:
return 10
case ‘百‘:
return 100
case ‘千‘:
return 1000
case ‘万‘:
return 10000
case ‘亿‘:
return 100000000
default:
return 0
}
}
function cs2(arr, i) {
let total = 0;
for (;i >= 0;i-- ){
const c = arr[i]
if (!isUnit(c)) total += c
else break
}
return total || 1
}
function cs1(arr) {
const p = arr.reduce((p, v, i) => {
if (isUnit(v)) {
if(!i || !isUnit(arr[i - 1])) p.push(cs2(arr,i-1)*isUnit(v))
else p.push(v)
} else if (i===arr.length-1 && !isUnit(v)) {
p.push(cs2(arr,i))
}
return p
}, [])
return p.some(s => isUnit(s)) ? cs1(p) : p.reduce((t, v) => t += v,0);
}
function cs(str) {
const arr = str.split(‘‘).map(s => toNumber(s))
return cs1(arr)
}
原文:https://www.cnblogs.com/qq3279338858/p/13825692.html