EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

str62 #72

Open EdwardZZZ opened 4 years ago

EdwardZZZ commented 4 years ago
const chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ';
const radix = chars.length;

function intToStr62(n) {
    const arr = [];
    let qutient = +n;
    while (qutient) {
        mod = qutient % radix;
        qutient = (qutient - mod) / radix;
        arr.unshift(chars[mod]);
    }
    return arr.join('');
}

// function MathPow(x, y) {
//     if (y == 0) return 1n;

//     x = typeof x === 'bigint' ? x : BigInt(x);
//     let r = x;

//     while(y-- > 1) {
//         r *= x;
//     }

//     return r;
// }
function Pow(x, y) {
    console.log(x, y);
    if (y === 0) return typeof x === 'bigint' ? 1n : 1;
    if (y === 0n) return 1n;

    return x ** y;
}

function str62ToInt(str, isLong = false) {
    let strArr = String(str).split('').reverse();

    return strArr.reduce((prev, curr, idx) => {
        const currVal = chars.indexOf(curr || 0);

        return prev + Pow(isLong ? BigInt(radix) : radix, isLong ? BigInt(idx) : idx) * (isLong ? BigInt(currVal) : currVal);
    }, isLong ? 0n : 0);
}

const n = 123456789;
const str = intToStr62(n);
console.log(str);
console.log(str62ToInt(str, true));

如果需要考虑长整形,请参考 https://github.com/EdwardZZZ/articles/issues/42

EdwardZZZ commented 2 years ago
function str62ToBigInt(str) {
    let strArr = String(str).split('').reverse();

    return strArr.reduce((prev, curr, idx) => {
        return prev + BigInt(radix) ** BigInt(idx) * BigInt(chars.indexOf(curr || 0));
    }, 0n);
}