Skip to content

Instantly share code, notes, and snippets.

@JCloudYu
Last active October 19, 2018 05:10
Show Gist options
  • Save JCloudYu/4f4c0cfad355029700c6c6c7acc72e21 to your computer and use it in GitHub Desktop.
Save JCloudYu/4f4c0cfad355029700c6c6c7acc72e21 to your computer and use it in GitHub Desktop.
Add unicode_length to count the correct number of characters in the string and fix incorrect index problem of codePointAt api
/**
ISC License
Copyright (c) 2018, JCloudYu
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
**/
Object.defineProperty(String.prototype, '_codePointAt', {value:String.prototype.codePointAt, enumerable:false});
String.prototype.codePointAt = function(index){
let _cur_index = 0, _code_point = undefined;
for( let i=0; i<this.length; i++ ) {
let codePoint = this._codePointAt(i);
if ( _cur_index === index ) {
_code_point = codePoint;
break;
}
_cur_index++;
// If the code point requires surrogate pairs, then skip the up coming byte
if ( codePoint > 0xFFFF ) { i++; }
}
return _code_point;
};
Object.defineProperty(String.prototype, 'unicode_length', { get:function(){
let _char_length = 0;
for( let i=0; i<this.length; i++ ) {
_char_length++;
let codePoint = this._codePointAt(i);
// If the code point requires surrogate pairs, then skip the up coming byte
if ( codePoint > 0xFFFF ) { i++; }
}
return _char_length;
}, enumerable:true, configurable:true });
/*
//Testing code
let char = '012𠮷45我6789ABCDE𠁎';
for( let i=0; i<char.unicode_length; i++ ) {
console.log(`${i}: ${char.codePointAt(i)}`);
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment