All files diacritics.ts

100% Statements 74/74
100% Branches 23/23
100% Functions 15/15
100% Lines 69/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352            7x 7x     7x           7x                                                                                                                                                                                                                       7x                                                             7x 9943x         122x                                                                                                     7x   4792x 636x     4156x 44192x   4156x 3810x     346x               7x   312x   78x 78x 90x 90x 90x   90x 90x 90x     78x             7x   6x 6x   138x   5808x 5808x   5808x 2004x     3804x 234x     3804x 3804x 1872x     1932x       6x         876x 6x           6x 924x   234x 234x   324x 426x 420x   6x     324x     234x     6x               7x   3915x 6x     3915x   3915x   9199x 5172x       4027x 4027x 2690x       1337x 1337x 4x     1333x        
 
type TDiacraticList = {[key:string]:string};
 
// https://github.com/andrewrk/node-diacritics/blob/master/index.js
 
var latin_pat:RegExp;
const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}]'; // \u{2bc}
const accent_reg = new RegExp(accent_pat,'g');
var diacritic_patterns:TDiacraticList;
 
const latin_convert:TDiacraticList = {
	'æ': 'ae',
	'ⱥ': 'a',
	'ø': 'o',
};
 
const convert_pat = new RegExp(Object.keys(latin_convert).join('|'),'g');
 
 
export const DIACRITICS:TDiacraticList = {
	" ":" ",
	0:"߀",
	A:"ⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ",
	AA:"Ꜳ",
	AE:"ÆǼǢ",
	AO:"Ꜵ",
	AU:"Ꜷ",
	AV:"ꜸꜺ",
	AY:"Ꜽ",
	B:"ⒷBḂḄḆɃƁ",
	C:"ⒸCꜾḈĆCĈĊČÇƇȻ",
	D:"ⒹDḊĎḌḐḒḎĐƊƉᴅꝹ",
	Dh:"Ð",
	DZ:"DZDŽ",
	Dz:"DzDž",
	E:"ɛⒺEÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚƐƎᴇ",
	F:"ꝼⒻFḞƑꝻ",
	G:"ⒼGǴĜḠĞĠǦĢǤƓꞠꝽꝾɢ",
	H:"ⒽHĤḢḦȞḤḨḪĦⱧⱵꞍ",
	I:"ⒾIÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬƗ",
	J:"ⒿJĴɈȷ",
	K:"ⓀKḰǨḲĶḴƘⱩꝀꝂꝄꞢ",
	L:"ⓁLĿĹĽḶḸĻḼḺŁȽⱢⱠꝈꝆꞀ",
	LJ:"LJ",
	Lj:"Lj",
	M:"ⓂMḾṀṂⱮƜϻ",
	N:"ꞤȠⓃNǸŃÑṄŇṆŅṊṈƝꞐᴎ",
	NJ:"NJ",
	Nj:"Nj",
	O:"ⓄOÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘǪǬØǾƆƟꝊꝌ",
	OE:"Œ",
	OI:"Ƣ",
	OO:"Ꝏ",
	OU:"Ȣ",
	P:"ⓅPṔṖƤⱣꝐꝒꝔ",
	Q:"ⓆQꝖꝘɊ",
	R:"ⓇRŔṘŘȐȒṚṜŖṞɌⱤꝚꞦꞂ",
	S:"ⓈSẞŚṤŜṠŠṦṢṨȘŞⱾꞨꞄ",
	T:"ⓉTṪŤṬȚŢṰṮŦƬƮȾꞆ",
	Th:"Þ",
	TZ:"Ꜩ",
	U:"ⓊUÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴɄ",
	V:"ⓋVṼṾƲꝞɅ",
	VY:"Ꝡ",
	W:"ⓌWẀẂŴẆẄẈⱲ",
	X:"ⓍXẊẌ",
	Y:"ⓎYỲÝŶỸȲẎŸỶỴƳɎỾ",
	Z:"ⓏZŹẐŻŽẒẔƵȤⱿⱫꝢ",
	a:"ⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑ",
	aa:"ꜳ",
	ae:"æǽǣ",
	ao:"ꜵ",
	au:"ꜷ",
	av:"ꜹꜻ",
	ay:"ꜽ",
	b:"ⓑbḃḅḇƀƃɓƂ",
	c:"cⓒćĉċčçḉƈȼꜿↄ",
	d:"ⓓdḋďḍḑḓḏđƌɖɗƋᏧԁꞪ",
	dh:"ð",
	dz:"dzdž",
	e:"ⓔeèéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛɇǝ",
	f:"ⓕfḟƒ",
	ff:"ff",
	fi:"fi",
	fl:"fl",
	ffi:"ffi",
	ffl:"ffl",
	g:"ⓖgǵĝḡğġǧģǥɠꞡꝿᵹ",
	h:"ⓗhĥḣḧȟḥḩḫẖħⱨⱶɥ",
	hv:"ƕ",
	i:"ⓘiìíîĩīĭïḯỉǐȉȋịįḭɨı",
	j:"ⓙjĵǰɉ",
	k:"ⓚkḱǩḳķḵƙⱪꝁꝃꝅꞣ",
	l:"ⓛlŀĺľḷḹļḽḻſłƚɫⱡꝉꞁꝇɭ",
	lj:"lj",
	m:"ⓜmḿṁṃɱɯ",
	n:"ⓝnǹńñṅňṇņṋṉƞɲʼnꞑꞥлԉ",
	nj:"nj",
	o:"ⓞoòóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộǫǭøǿꝋꝍɵɔᴑ",
	oe:"œ",
	oi:"ƣ",
	oo:"ꝏ",
	ou:"ȣ",
	p:"ⓟpṕṗƥᵽꝑꝓꝕρ",
	q:"ⓠqɋꝗꝙ",
	r:"ⓡrŕṙřȑȓṛṝŗṟɍɽꝛꞧꞃ",
	s:"ⓢsśṥŝṡšṧṣṩșşȿꞩꞅẛʂ",
	ss:"ß",
	t:"ⓣtṫẗťṭțţṱṯŧƭʈⱦꞇ",
	th:"þ",
	tz:"ꜩ",
	u:"ⓤuùúûũṹūṻŭüǜǘǖǚủůűǔȕȗưừứữửựụṳųṷṵʉ",
	v:"ⓥvṽṿʋꝟʌ",
	vy:"ꝡ",
	w:"ⓦwẁẃŵẇẅẘẉⱳ",
	x:"ⓧxẋẍ",
	y:"ⓨyỳýŷỹȳẏÿỷẙỵƴɏỿ",
	z:"ⓩzźẑżžẓẕƶȥɀⱬꝣ"
}
 
/**
 * code points generated from toCodePoints();
 * removed 65339 to 65345
 */
export const code_points = [
	[ 67, 67 ],
	[ 160, 160 ],
	[ 192, 438 ],
	[ 452, 652 ],
	[ 961, 961 ],
	[ 1019, 1019 ],
	[ 1083, 1083 ],
	[ 1281, 1289 ],
	[ 1984, 1984 ],
	[ 5095, 5095 ],
	[ 7429, 7441 ],
	[ 7545, 7549 ],
	[ 7680, 7935 ],
	[ 8580, 8580 ],
	[ 9398, 9449 ],
	[ 11360, 11391 ],
	[ 42792, 42793 ],
	[ 42802, 42851 ],
	[ 42873, 42897 ],
	[ 42912, 42922 ],
	[ 64256, 64260 ],
	[ 65313, 65338 ],
	[ 65345, 65370 ]
];
 
/**
 * Remove accents
 * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
 *
 */
export const asciifold = (str:string):string => {
	return str
		.normalize('NFKD')
		.replace(accent_reg, '')
		.toLowerCase()
		.replace(convert_pat,function(foreignletter) {
			return latin_convert[foreignletter];
		});
};
 
 
/**
 * Convert list of diacritics to array of code points
 *
 */
// @ts-ignore
function toCodePoints(tolerance=8){
	var char_codes:number[] = [];
 
	for( let letter in DIACRITICS ){
		let _diacritics = DIACRITICS[letter];
		for( let n = 0; n < _diacritics.length; n++ ){
			var code_point = _diacritics.codePointAt(n);
			if( code_point ) char_codes.push( code_point );
		}
	}
 
	//https://stackoverflow.com/questions/40431572/is-there-a-simple-way-to-group-js-array-values-by-range
	char_codes.sort((a, b) => a - b);
	var accumulator: number[][] = [];
	char_codes.reduce(function (accumulator, currentValue, index, source) {
 
		if( !index ){
			accumulator.push( [currentValue,currentValue] );
 
		}else if( currentValue - source[index - 1] > tolerance ){
			accumulator.push( [currentValue,currentValue] );
 
		}else{
 
			let range = accumulator.pop();
			if( range ){
				accumulator.push( [range[0],currentValue]);
			}
		}
 
		return accumulator;
	}, accumulator);
 
}
 
/**
 * Convert array of strings to a regular expression
 *	ex ['ab','a'] => (?:ab|a)
 * 	ex ['a','b'] => [ab]
 *
 */
export const arrayToPattern = (chars:string[],glue:string='|'):string =>{
	
	if( chars.length == 1 ){
		return chars[0];
	}
	
	var longest = 1;
	chars.forEach((a)=>{longest = Math.max(longest,a.length)});
 
	if( longest == 1 ){
		return '['+chars.join('')+']';
	}
 
	return '(?:'+chars.join(glue)+')';	
};
 
/**
 * Get all possible combinations of substrings that add up to the given string
 * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
 *
 */
export const allSubstrings = (input:string):string[][] => {
 
    if( input.length === 1) return [[input]];
 
    var result:string[][] = [];
    allSubstrings(input.substring(1)).forEach(function(subresult) {
        var tmp = subresult.slice(0);
        tmp[0] = input.charAt(0) + tmp[0];
        result.push(tmp);
 
        tmp = subresult.slice(0);
        tmp.unshift(input.charAt(0));
        result.push(tmp);
    });
    
    return result;
}
 
/**
 * Generate a list of diacritics from the list of code points
 *
 */
export const generateDiacritics = ():TDiacraticList => {	
 
	var diacritics:{[key:string]:string[]} = {};
	code_points.forEach((code_range)=>{
 
		for(let i = code_range[0]; i <= code_range[1]; i++){
			
			let diacritic	= String.fromCharCode(i);
			let	latin		= asciifold(diacritic);
 
			if( latin == diacritic.toLowerCase() ){
				continue;
			}
 
			if( !(latin in diacritics) ){
				diacritics[latin] = [latin];
			}
			
			var patt = new RegExp( arrayToPattern(diacritics[latin]),'iu');
			if( diacritic.match(patt) ){
				continue;
			}
			
			diacritics[latin].push(diacritic);
		}
	});
		
	var latin_chars = Object.keys(diacritics);
	
	
	// latin character pattern
	// match longer substrings first
	latin_chars		= latin_chars.sort((a, b) => b.length - a.length );
	latin_pat		= new RegExp('('+ arrayToPattern(latin_chars) + accent_pat + '*)','g');
	
	
	// build diacritic patterns
	// ae needs: 
	//	(?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
	var diacritic_patterns:TDiacraticList = {};
	latin_chars.sort((a,b) => a.length -b.length).forEach((latin)=>{
		
		var substrings	= allSubstrings(latin);
		var pattern = substrings.map((sub_pat)=>{
			
			sub_pat = sub_pat.map((l)=>{
				if( diacritics.hasOwnProperty(l) ){
					return arrayToPattern(diacritics[l]);
				}
				return l;
			});
			
			return arrayToPattern(sub_pat,'');
		});
		
		diacritic_patterns[latin] = arrayToPattern(pattern);		
	});
			
	return diacritic_patterns;
}
 
/**
 * Expand a regular expression pattern to include diacritics
 * 	eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
 *
 */
export const diacriticRegexPoints = (regex:string):string => {
 
	if( diacritic_patterns === undefined ){
		diacritic_patterns = generateDiacritics();
	}
	
	const decomposed		= regex.normalize('NFKD').toLowerCase();
	
	return decomposed.split(latin_pat).map((part:string)=>{
		
		if( part == '' ){
			return '';
		}
		
		// "ffl" or "ffl"
		const no_accent = asciifold(part);				
		if( diacritic_patterns.hasOwnProperty(no_accent) ){
			return diacritic_patterns[no_accent];
		}
		
		// 'أهلا' (\u{623}\u{647}\u{644}\u{627}) or 'أهلا' (\u{627}\u{654}\u{647}\u{644}\u{627})
		const composed_part = part.normalize('NFC');
		if( composed_part != part ){
			return arrayToPattern([part,composed_part]);
		}
				
		return part;
	}).join('');
	
}