Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add generic Heap #15

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/collections/HeapArray.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
enum HeapType { MIN, MAX };

abstract class Comparable<X> {
private value: X;

constructor(value: X) {
this.value = value;
}

public getValue(): X {
return this.value;
}

/**
* Return true if this object value is strictly greater than the specified item's value.
*
* @param item the "comparable" object.
*/
public abstract gt(item: Comparable<X>): boolean;
/**
* Return true if this object value is strictly less than the specified item's value.
*
* @param item the "comparable" object.
*/
public abstract lt(item: Comparable<X>): boolean;
}

class TheNumber extends Comparable<number> {
gt(item: Comparable<number>): boolean {
return this.getValue() > item.getValue();
}

lt(item: Comparable<number>): boolean {
return this.getValue() < item.getValue();
}
}

class Person extends Comparable<number> {
private name: string;

constructor(name: string, age: number = 0) {
super(age);
this.name = name;
}

public getName(): string {
return this.name;
}

public gt(item: Comparable<number>): boolean {
return this.getValue() > item.getValue();
}

public lt(item: Comparable<number>): boolean {
return this.getValue() < item.getValue();
}
}

class HeapArray<T extends Comparable<X>, X> {
private heap: Array<T>;
private heapType: HeapType;

constructor(heap: Array<T> = [], heapType: HeapType = HeapType.MAX) {
this.heap = heap;
this.heapType = heapType;
}

public get(): Comparable<X> {
if (this.heap.length === 0) return undefined;

let mu = this.heap[0];
for (let i = 1; i < this.heap.length; i++) {
if (this.heapType === HeapType.MAX && this.heap[i].gt(mu)) {
mu = this.heap[i];
}

if (this.heapType === HeapType.MIN && this.heap[i].lt(mu)) {
mu = this.heap[i];
}
}

return mu;
}
}

// const a = new TheNumber(3);
// const b = new TheNumber(11);

// const h: Heap<TheNumber, number> = new Heap([a, b], HeapType.MAX);
// console.log(h.get());

const a = new Person('Simone', 38);
const b = new Person('Lalla', 40);

const h: HeapArray<Person, number> = new HeapArray([a, b], HeapType.MAX);
console.log((h.get() as Person).getName());