From: Jay Freeman (saurik) Date: Wed, 26 Dec 2012 14:29:26 +0000 (+0000) Subject: Factor UTF-16 functions into their own module. X-Git-Url: https://git.saurik.com/utf16js.git/commitdiff_plain/5951f915abb80a3b18a89fed5ffbcb3c7dcf956e?ds=sidebyside Factor UTF-16 functions into their own module. --- 5951f915abb80a3b18a89fed5ffbcb3c7dcf956e diff --git a/utf16.js b/utf16.js new file mode 100644 index 0000000..89322ec --- /dev/null +++ b/utf16.js @@ -0,0 +1,44 @@ +if (typeof define !== 'function') { var define = require('amdefine')(module) } + +define(function(require) { + +var decode = function(array, string) { + for (var i = 0, e = string.length; i != e; ++i) { + var unit = string.charCodeAt(i); + var part = unit & 0xfc00; + if (part == 0xdc00) + return null; + else if (part != 0xd800) + array.push(unit); + else if (++i == e) + return null; + else { + var next = string.charCodeAt(i); + if ((next & 0xfc00) != 0xdc00) + return null; + array.push(0x10000 | (unit & 0x03ff) << 10 | next & 0x03ff); + } + } + + return array; +}; + +var encode = function(array) { + var units = []; + for (var i = 0, e = array.length; i != e; ++i) { + var point = array[i]; + if (point < 0x10000) + units.push(point); + else { + point -= 0x10000; + units.push(0xd800 | (0xffc00 & point) >> 10, 0xdc00 | 0x03ff & point); + } + } return String.fromCharCode.apply(String, units); +}; + +return { + decode: decode, + encode: encode, +}; + +});