Given input -> const s = ['2.1.1.a', '2.1.a', '2.1.1.d', 'A2.2', 'A2.1', 2.1.1.c', '2.1.b', '2.1.1.b']
Expected output after sorting -> const s = ['2.1.a', '2.1.b', '2.1.1.a', '2.1.1.b', '2.1.1.c', '2.1.1.d', 'A2.1', 'A2.2']
Output after sorting using the methods below -> const s = ['2.1.b', '2.1.a', '2.1.1.d', '2.1.1.c', '2.1.1.b', '2.1.1.a', 'A2.1', 'A2.2']
Below are the angular methods attempted to sort and the question of what may be wrong with the code:
private REGEXP_SPECIAL_CHAR = /^[A-Za-z]\d$/;
bubbleSort(collection: any[], property: string = 'code'): any[] {
let memo = null;
if (!collection.length) { return collection; }
for (let outer = 0; outer < collection.length; outer++) {
for (let inner = 0; inner < collection.length; inner++) {
if (this.compare(collection[outer][property], collection[inner][property]) === -1) {
memo = collection[outer];
collection[outer] = collection[inner];
collection[inner] = memo;
}
}
}
return collection;
}
private compare(v: any, w: any): number {
const vCollection = v.split('.');
const wCollection = w.split('.');
const depth = Math.min(vCollection.length, wCollection.length);
let res = 0;
for (let i = 0; i < depth; i++) {
const vElement = vCollection[i];
const wElement = wCollection[i];
const shouldCompareNumbers = !isNaN(Number(vElement)) && !isNaN(Number(wElement));
const shouldCompareChars = this.isSpecialSymbol(vElement, wElement) || (!isNaN(Number(vElement)) && !isNaN(Number(wElement)));
if (shouldCompareNumbers) {
if (Number(vElement) < Number(wElement)) {
res = -1;
break;
} else if (Number(vElement) > Number(wElement)) {
res = 1;
break;
}
} else if (shouldCompareChars) {
if (vElement < wElement) {
res = -1;
break;
} else if (vElement > wElement) {
res = 1;
break;
}
} else {
if (vElement < wElement) {
res = 1;
break;
} else if (vElement > wElement) {
res = -1;
break;
}
}
}
if (res === 0) {
// check depth
if (vCollection.length > wCollection.length) {
res = 1;
} else if (vCollection.length < wCollection.length) {
res = -1;
} else {
res = 0;
}
}
return res;
}
private isSpecialSymbol(v: string, w: string): boolean {
return this.REGEXP_SPECIAL_CHAR.test(v) || this.REGEXP_SPECIAL_CHAR.test(w);
}