Last active
June 20, 2017 08:41
-
-
Save mk-pmb/5e50c870ee0c055e0abb8b4f474536a0 to your computer and use it in GitHub Desktop.
JS: How to convert an Array-like list of character numbers to a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jslint indent: 2, maxlen: 80, browser: true */ | |
/* -*- tab-width: 2 -*- */ | |
'use strict'; | |
var bytes, s1, s2, arSlc = Array.prototype.slice; | |
// Let's assume the worst minimalistic buffer API ever imagined: | |
bytes = { length: 15, | |
'0': 72, '1': 101, '2': 108, '3': 108, '4': 111, '5': 32, | |
'6': 119, '7': 111, '8': 114, '9': 108, '10': 100, '11': 33, | |
'12': 32, '13': 9749, '14': 9774 }; | |
function dare(func, arg) { | |
try { | |
return func(arg); | |
} catch (err) { | |
return 'E: ' + String(err.message || err); | |
} | |
} | |
// version from https://github.com/Daplie/unibabel-js/blob/master/index.js#L50 | |
// License: Apache-2.0, https://opensource.org/licenses/Apache-2.0 | |
function bufferToBinaryString(buf) { | |
var binstr = Array.prototype.map.call(buf, function (ch) { | |
return String.fromCharCode(ch); | |
}).join(''); | |
return binstr; | |
} | |
s1 = dare(bufferToBinaryString, bytes); | |
// intuitive version: | |
function easyInFirefox(buf) { return String.fromCharCode.apply(null, buf); } | |
// MSIE 6 compatibility version: | |
function buf2binstr(buf) { | |
return String.fromCharCode.apply(null, | |
// If you target modern browsers, replace the next line with just "buf". | |
arSlc.call(buf) | |
// The array conversion wastes CPU in Node.js and Firefox since they | |
// can .apply() the original buf directly. However, if you try that | |
// in MSIE 6 it throws an Error("Array or arguments object expected") | |
); | |
} | |
s2 = dare(buf2binstr, bytes); | |
if ((typeof window === 'object') && (!window.console)) { | |
window.console = { log: function (arr) { | |
document.getElementsByTagName('body')[0].innerHTML = '<pre>' + | |
arr.join(' | ') + '</pre>\n'; | |
} }; | |
} | |
console.log([ s1, s2, (s1 === s2) ]); | |
// Output in Node.js v6.11.0 and Firefox v53.0: | |
// [ 'Hello world! ☕☮', 'Hello world! ☕☮', true ] | |
// Output in MSIE v6: | |
// E: 'Array.prototype.map' is null or not an object | Hello world! ☕☮ | false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment