Question

I found an elegant code to converts ArrayBuffer into charCode.

But I need char, instead of charCode.

function ab2s (buf) {
  var view = new Uint8Array (buf);
  return Array.prototype.join.call (view, ",");
}

I tried

return Array.prototype.join.call (view, function() {String.fromCharCode(this)});

But this is crap.

Thanks for answers.

Was it helpful?

Solution

return Array.prototype.join.call (view, function() {String.fromCharCode(this)});

But this is crap.

Obviously, since Array::join does not take a callback to transform each element but only the separator by which the elements should be joined.

Instead, to transform every element before joining them you would use Array::map:

return Array.prototype.map.call(view, function(charcode) {
    return String.fromCharCode(charcode);
}).join('');

However, there is a much easier solution, as String.fromCharCode does take multiple arguments:

return String.fromCharCode.apply(String, view);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top