易于理解的
type Values = number | string;
/** Not sorted array */
function compare<Values>(a1: Array<Values>, a2: Array<Values>): boolean {
if (a1.length !== a2.length) {
return false;
}
/** Unique values */
const set1 = new Set<Values>(a1);
const set2 = new Set<Values>(a2);
if (set1.size !== set2.size) {
return false;
}
return [...set1].every((value) => [...set2].includes(value));
}
compare([1, 2, 3], [1, 2, 3]); // true
compare([1, 2, 3], [1, 3, 2]); // true
compare([1, 1, 1], [1, 2, 3]); // false
compare([1, 1, 2, 3], [1, 2, 3]); // false
/** Sorted arrays, faster method */
function compareSorted<Values>(a1: Array<Values>, a2: Array<Values>): boolean {
if (a1.length !== a2.length) {
return false;
}
/** Unique values */
const set1 = new Set<Values>(a1);
const set2 = new Set<Values>(a2);
if (set1.size !== set2.size) {
return false;
}
return [...set1].every((value, index) => value === [...set2][index]);
}
compareSorted([1, 2, 3], [1, 2, 3]); // true
compareSorted([1, 2, 3], [1, 3, 2]); // false
compareSorted([1, 1, 1], [1, 2, 3]); // false
compareSorted([1, 1, 2, 3], [1, 2, 3]); // false