diff2html/src/utils.ts

55 lines
1,020 B
TypeScript
Raw Normal View History

2019-10-12 21:45:49 +00:00
const specials = [
// Order matters for these
2019-12-29 22:31:32 +00:00
'-',
'[',
']',
2019-10-12 21:45:49 +00:00
// Order doesn't matter for any of these
2019-12-29 22:31:32 +00:00
'/',
'{',
'}',
'(',
')',
'*',
'+',
'?',
'.',
'\\',
'^',
'$',
'|',
2019-10-12 21:45:49 +00:00
];
// All characters will be escaped with '\'
// even though only some strictly require it when inside of []
2019-12-29 22:31:32 +00:00
const regex = RegExp('[' + specials.join('\\') + ']', 'g');
2019-10-12 21:45:49 +00:00
/**
* Escapes all required characters for safe usage inside a RegExp
*/
export function escapeForRegExp(str: string): string {
2019-12-29 22:31:32 +00:00
return str.replace(regex, '\\$&');
2019-10-12 21:45:49 +00:00
}
/**
* Converts all '\' in @path to unix style '/'
*/
export function unifyPath(path: string): string {
2019-12-29 22:31:32 +00:00
return path ? path.replace(/\\/g, '/') : path;
2019-10-12 21:45:49 +00:00
}
/**
* Create unique number identifier for @text
*/
export function hashCode(text: string): number {
let i, chr, len;
let hash = 0;
for (i = 0, len = text.length; i < len; i++) {
chr = text.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}