js 模拟haskell 字符串转数字

haskell

-- 只载入 Data.Char 中的 digitToInt 函数
import Data.Char (digitToInt)

asInt xs = loop 0 xs

loop :: Int -> String -> Int
loop acc [] = acc
loop acc (x:xs) = let acc' = acc * 10 + digitToInt x
                  in loop acc' xs

js

function asInt(str, num=0) {
    try{
        if(str !== '' && isNaN(parseInt(str[0]))){
            throw "Parameter is not a number!"
        }
        return str[0] ? asInt(str.slice(1), num * 10 + parseInt(str[0])) : num
    }catch(e){
        console.error(e)
    }   
}
console.log(asInt('3332'))

你可能感兴趣的:(js 模拟haskell 字符串转数字)