Nodejs String to Ascii85 Convert toAscii85()

Here you can find the source of toAscii85()

Method Source Code

// 2kyu/*from  w w w  .  ja  v  a2  s. c  o m*/
// https://www.codewars.com/kata/5277dc3ff4bfbd9a36000c1c

String.prototype.toAscii85 = function() {
  var str = this, result = ''
  while (str.length) {
    let num = 0, j = 5, i = 4
    if (str.substr(0,4) == '\u0000\u0000\u0000\u0000') result += 'z'
    else {
      while (i--) {
        num += (str.charCodeAt(3-i) || 0)*Math.pow(2, 8*i)
      }
      while (j-- && str.length > 3-j) {
        result += String.fromCharCode(num/Math.pow(85, j) % 85 + 33)
      }
    }
    str = str.substr(4)
  }
  return `<~${result}~>`
}

Related

  1. toAscii85()
    String.prototype.toAscii85 = function() {
      var ret = "";
      for(var i=0; i<this.length; i+=4){
        var deficit = Math.max(0, 4+i-this.length);
        var nnn = 0;
        for(var j=0; j<4; j++){
          nnn = nnn*256 + (this.charCodeAt(i+j) || 0);
        var codes = [];
    ...
    
  2. toAscii85()
    String.prototype.toAscii85 = function() {
      var str = '';
      for(var i = 0, len = this.length; i < len; i+=4) {
        var bin = '';
        var zeroes = 0;
        for(var j = 0; j < 4; j++) {
          var char = this[i+j];
          bin += to8bit(char ? char.charCodeAt(0) : (zeroes++, 0));
        var n = parseInt(bin, 2);
        for(var j = 4; j >= 0; j--) {
          var c = Math.floor(n / Math.pow(85, j));
          n -= c*Math.pow(85, j);
          str += String.fromCharCode(c + 33);
        str = str.slice(0, zeroes > 0 ? -zeroes : undefined);
      return '<~' + str.replace(/!{5}/g, 'z') + '~>'
    
  3. toAscii85()
    String.prototype.toAscii85 = function() {
        let pad = '\0', addnum = 0, str = this, res = '', sum = 0;
        while (str.length % 4 !== 0)
            str += pad;
            addnum ++;
        for (let i = 0; i < str.length; i += 4)
            let e = '';
            let temp = str.substr(i, 4);
            for (let j = 0; j < 4; j++)
                let t = temp[j].charCodeAt().toString(2)
                while (t.length !== 8)
                    t = '0' + t;
                e += t;
            sum = parseInt(e, 2);
            let encode = [];
            for (let j = 0; j < 5; j++)
                encode.push(0);
            for (let j = 4; j >= 0; j--)
                encode[j] = sum % 85;
                sum = Math.floor(sum / 85);
            for (let j = 0; j < 5; j++)
                res += String.fromCharCode(encode[j] + 33);
        res = res.substr(0, res.length - addnum);
        let newres = '', i = 0;
        for (i = 0; i < res.length; i += 5)
            newres += res.substr(i, Math.min(5, res.length - i)) === '!!!!!' ? 'z' : res.substr(i, Math.min(5, res.length - i));
        return '<~' + newres + '~>';
    };