Skip to content

Instantly share code, notes, and snippets.

@iahu
Created Mar 2, 2021
Embed
What would you like to do?
import memoize from 'lodash/memoize';
const supportLocaleCompare = typeof String.prototype.localeCompare === 'function';
const getShengmu = memoize((c: string) => {
const MAP = 'abcdefghjklmnopqrstwxyz';
const boundaryChar = '驁簿錯鵽樲鰒餜靃攟鬠纙鞪黁漚曝裠鶸蜶籜鶩鑂韻糳';
if (!supportLocaleCompare) {
return c;
}
if (c < '\u4E00' || c >= '\u9FFF') {
return c;
}
for (let i = 0; i < boundaryChar.length; i++) {
if (boundaryChar[i].localeCompare(c, 'pinyin') >= 0) {
return MAP[i];
}
}
return c;
});
const normalSort = (a: number, b: number) => {
if (a === b) {
return 0;
}
return a < b ? -1 : 1;
};
const moveChar = (c: string) => (c.charCodeAt(0) - 97 + 255) % 255;
const alphabetSort = (a: string, b: string) => {
const ca = a.charCodeAt(0);
const cb = b.charCodeAt(0);
if (ca > 255 || cb > 255) {
return normalSort(ca, cb);
}
const la = moveChar(a.toLowerCase());
const lb = moveChar(b.toLowerCase());
return normalSort(la, lb);
};
/**
* 汉字拼音首字母与英文字母混合排序,杂项排在末尾
*/
export const localeCompare = (a: string, b: string) => {
const la = a.toLowerCase();
const lb = b.toLowerCase();
const ca = getShengmu(la[0]);
const cb = getShengmu(lb[0]);
return alphabetSort(ca, cb);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment