面试题答案
一键面试class Collection<T> {
protected items: T[] = [];
add(item: T) {
this.items.push(item);
}
}
class SortedCollection<T extends Comparable<T>> extends Collection<T> {
add(item: T) {
let inserted = false;
for (let i = 0; i < this.items.length; i++) {
if (item.compareTo(this.items[i]) < 0) {
this.items.splice(i, 0, item);
inserted = true;
break;
}
}
if (!inserted) {
this.items.push(item);
}
}
}
interface Comparable<T> {
compareTo(other: T): number;
}