43 lines
1.2 KiB
JavaScript
43 lines
1.2 KiB
JavaScript
'use strict';
|
|
|
|
(function exposeWellFormedString(root, factory) {
|
|
const api = factory();
|
|
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
|
if (root) root.AptWellFormedString = api;
|
|
}(typeof window !== 'undefined' ? window : undefined, function wellFormedStringFactory() {
|
|
function manualToWellFormed(value) {
|
|
let result = '';
|
|
for (let index = 0; index < value.length; index += 1) {
|
|
const codeUnit = value.charCodeAt(index);
|
|
if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {
|
|
const next = value.charCodeAt(index + 1);
|
|
if (next >= 0xdc00 && next <= 0xdfff) {
|
|
result += value[index] + value[index + 1];
|
|
index += 1;
|
|
} else {
|
|
result += '\ufffd';
|
|
}
|
|
} else if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {
|
|
result += '\ufffd';
|
|
} else {
|
|
result += value[index];
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
function toWellFormedString(value, fallback = '') {
|
|
let string;
|
|
try {
|
|
string = String(value);
|
|
} catch {
|
|
string = String(fallback);
|
|
}
|
|
return typeof string.toWellFormed === 'function'
|
|
? string.toWellFormed()
|
|
: manualToWellFormed(string);
|
|
}
|
|
|
|
return Object.freeze({ toWellFormedString });
|
|
}));
|