store a json object in ArrayBuffer

Viewed 13255

Want to store a json object in ArrayBuffer

function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
}
var str = {'x':'aaaa'},
    enc = stringToUint(str),
    dec = uintToString(enc);

console.log(dec.x);

console.log(dec.x); is printing `undefined. Am I doing it wrongly ? here is jsfiddle http://jsfiddle.net/DQJyX/137/

3 Answers

This code for stringToUint is ~40% faster, benchmark link

function stringToUint(string) {
  const str = btoa(unescape(encodeURIComponent(string)))
  const uintArray = []
  const len = str.length

  let i = -1

  while (++i < len) {
    uintArray[i] = str.charCodeAt(i)
  }

  return new Uint8Array(uintArray);
}
Related