88 lines
1.9 KiB
TypeScript
Raw Normal View History

2018-01-15 00:08:06 +01:00
// const prime1: u32 = 73;
// const prime2: u32 = 5009;
2017-12-16 17:54:53 +01:00
export class Set<T> {
2018-01-15 00:08:06 +01:00
private __memory: usize;
private __capacity: u32;
private __size: u32;
constructor() {
this.__memory = 0;
this.__capacity = this.__size = 0;
}
get size(): i32 {
return <i32>this.__size;
2018-01-15 00:08:06 +01:00
}
// FIXME: not a proper set implementation, just a filler
has(value: T): bool {
2018-01-28 06:18:27 +01:00
assert(this != null);
for (let index: usize = 0, limit: usize = this.__size; index < limit; ++index) {
2018-02-25 23:21:32 +01:00
if (load<T>(this.__memory + index * sizeof<T>()) == value) {
2018-01-15 00:08:06 +01:00
return true;
2018-02-25 23:21:32 +01:00
}
}
2018-01-15 00:08:06 +01:00
return false;
}
add(value: T): Set<T> {
2018-01-28 06:18:27 +01:00
assert(this != null);
2018-01-15 00:08:06 +01:00
if (this.__size >= this.__capacity) {
let newCapacity = max(this.__capacity << 1, 8);
let newMemory = allocate_memory(<usize>newCapacity * sizeof<T>());
2018-01-15 00:08:06 +01:00
if (this.__memory) {
move_memory(newMemory, this.__memory, <usize>this.__capacity * sizeof<T>());
free_memory(this.__memory);
}
this.__capacity = newCapacity;
this.__memory = newMemory;
}
store<T>(this.__memory + <usize>this.__size * sizeof<T>(), value);
++this.__size;
return this;
}
delete(value: T): bool {
2018-01-28 06:18:27 +01:00
assert(this != null);
for (let index: usize = 0, limit: usize = this.__size; index < limit; ++index) {
2018-01-15 00:08:06 +01:00
if (load<T>(this.__memory + index * sizeof<T>()) == value) {
if (index + 1 < limit) {
2018-02-25 23:21:32 +01:00
move_memory(
this.__memory + index * sizeof<T>(),
this.__memory + (index + 1) * sizeof<T>(),
limit - index - 1
2018-02-25 23:21:32 +01:00
);
}
2018-01-15 00:08:06 +01:00
--this.__size;
return true;
}
2018-02-25 23:21:32 +01:00
}
2018-01-15 00:08:06 +01:00
return false;
}
clear(): void {
2018-01-28 06:18:27 +01:00
assert(this != null);
2018-01-15 00:08:06 +01:00
this.__size = 0;
}
// TODO: think about iterators
2017-12-16 17:54:53 +01:00
}
2018-01-29 22:36:07 +01:00
// class SetIterator<T> extends Iterator<T> {
// get done(): bool {
// throw new Error("not implemented");
// }
// next(): T {
// throw new Error("not implemented");
// }
// }