4

I'm currently trying to do the following. I am using a Set to store objects. Now as Typescript uses SameZeroEquality for comparing Objects the default has will not work.

So I am trying to build an AdvancedSet that defines a custom has method. So far it looks somewhat like that

interface AdvancedSetOptions<T> {
    equal?: (a: T, b: T) => boolean;
}

const defaultOptions: AdvancedSetOptions<any> = {

}

export class AdvancedSet<T> extends Set<T>{

    constructor(Options: AdvancedSetOptions<T> = defaultOptions) {
        super();
        super.has = Options.equal ? this.getHasFromValidator(Options.equal) : super.has;
    }

    private getHasFromValidator(validator: ((a: T, b: T) => boolean)): (value: T) => boolean {

        return function(value: T): boolean {
            let found = false;
            let iterator = this.values();
            let entry = iterator.next();

            while (entry.value) {
                if (entry.value) {
                    if (validator(entry.value, value)) {
                        found = true;
                        break;
                    }
                }
                entry = iterator.next();
            }
            return found;
        }
    }
}

Now this will obviously not work as i am iterating through the set which will be painfully slow and I could have used an array in the first place.

Basically I will have to rewrite getHash and equals to achieve somthing that's working. Is this possible at all with set or do I basically have to build a class HashTable from scratch?

relief.melone
  • 3,042
  • 1
  • 28
  • 57
  • What do you mean by samezeroequality? – gatsbyz Nov 20 '18 at 16:19
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality Basically the same as === with the exception that it will also return true on comparing NaN with NaN – relief.melone Nov 20 '18 at 16:44

0 Answers0