练习TS泛型简单的案例
小于 1 分钟
练习TS泛型简单的案例
小小排序加函数重载
function isChinese(arr: any[]): Boolean {
let pattern = /^(?:[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/
return arr.some((item) => {
return pattern.test(item)
})
}
// 这里兼顾了英文和中文的排序
function quiteSort<T>(arr: Array<T>): Array<T> {
if (arr.length < 2) { return arr }
let left: Array<any> = [];
var right: Array<any> = [];
let mid = arr.splice(Math.floor(arr.length / 2), 1)[0];
for (var i = 0; i < arr.length; i++) {
if (arr[i] < mid) {
left.push(arr[i]);
} else {
right.push(arr[i])
}
}
return quiteSort(left).concat(mid, quiteSort(right))
}
// 排序中文
function sortChinese<T>(arr: any[]): any[] {
return arr.sort((i, o) => {
return (i.localeCompare(o, 'zh-CN'))
})
}
// 排序数字
function sortNum(arr: number[]): number[] {
return arr.sort((i, o) => i - o)
}
// 函数重载
// function allSort(arr: string): string
function allSort<T>(arr: T): T
function allSort(arr: any): any {
if (typeof arr === 'string') {
return quiteSort(arr.split("")).join("")
}
if (arr instanceof Array) {
if (isChinese(arr)) {
return sortChinese(arr)
}
let newArr = arr.map(item => {
return typeof item === 'string' ? quiteSort(item.split("")).join("") : item;
})
return quiteSort(newArr as any);
}
return quiteSort(arr);
}
let chi = ["刘德华", "刘亦菲", "周杰伦", "成都"]
let yinwen = ["abadf", "b", "cccdd", 'bdadg']
let num = [1, 34, 4, 44, 5, 6, 2]
let str = "asdfasdgagasgjlk"
console.log(allSort(chi));
console.log(allSort(num));
console.log(allSort(str));
let newYi = allSort<string[]>(yinwen);
let newStr = allSort(str)
console.log(newYi);