add Ox.codePointAt and Ox.fromCodePoint

This commit is contained in:
rolux 2013-12-04 09:46:16 +01:00
parent 779463072d
commit 828e814812

View file

@ -24,6 +24,27 @@ Ox.clean = function(string) {
})).join('\n');
};
/*@
Ox.codePointAt <f> Returns the code point at a given index
(string, index) -> <n> Code point
> Ox.codePointAt('\uD83D\uDCA9', 0)
0x1F4A9
@*/
Ox.codePointAt = function(string, index) {
var first, length = string.length, ret, second;
if (index >= 0 && index < length) {
first = string.charCodeAt(index);
if (first < 0xD800 || first > 0xDBFF || index == length - 1) {
ret = first;
} else {
second = string.charCodeAt(index + 1);
ret = second < 0xDC00 || second > 0xDFFF ? first
: ((first - 0xD800) * 0x400) + (second - 0xDC00) + 0x10000;
}
}
return ret;
};
/*@
Ox.endsWith <f> Tests if a string ends with a given substring
Equivalent to (but faster than)
@ -40,6 +61,31 @@ Ox.endsWith = function(string, substring) {
return string.slice(string.length - substring.length) == substring;
};
/*@
Ox.fromCodePoint <f> Returns a string for one or more given code points
(codePoint[, codePoint[, ...]]) -> <s> String
> Ox.fromCodePoint(102, 111, 111)
'foo'
> Ox.fromCodePoint(0x1F4A9)
'\uD83D\uDCA9'
@*/
Ox.fromCodePoint = function() {
var ret = '';
Ox.forEach(arguments, function(number) {
if (number < 0 || number > 0x10FFFF || !Ox.isInt(number)) {
throw new RangeError();
}
if (number < 0x10000) {
ret += String.fromCharCode(number);
} else {
number -= 0x10000;
ret += String.fromCharCode((number >> 10) + 0xD800)
+ String.fromCharCode((number % 0x400) + 0xDC00);
}
});
return ret;
};
/*@
Ox.isValidEmail <f> Tests if a string is a valid e-mail address
(str) -> <b> True if the string is a valid e-mail address