Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript set of objects

I am new in angular2 and typescript. I have a problem in creating an unique collection like Set<>. I want to avoid duplicate objects in a collection, for that purpose, try to use a set dataType like following code:

private cardItems = new Set<MyBean>([]);

MyBean is an object.

export class MyBean  {

  id:integer
  ownerId:integer
  ownerName:string
  img: string;

constructor() {

}
public equals(obj: MyBean) {
    console.log(obj.id);
    if (this.id == obj.id) {
        console.log(obj.id);
        return true;
    }
    if (obj == null)
        return false;

    return true;
}

public hashCode(obj: MyBean) {
    return obj.id
}

}

but equals and hashCode does not run in this way.and I have duplicate objects in set.

What is the solution for implementing Set?

Many thanks

like image 384
mary Avatar asked Oct 10 '16 02:10

mary


2 Answers

How about extending the Set class and then overriding the add method:

interface SetItem {
    equals(other: SetItem): boolean;
}

class MySet<T extends SetItem> extends Set<T> {
    add(value: T): this {
        let found = false;
        this.forEach(item => {
            if (value.equals(item)) {
                found = true;
            }
        });

        if (!found) {
            super.add(value);
        }

        return this;
    }
}

(code in playground)

like image 92
Nitzan Tomer Avatar answered Sep 28 '22 05:09

Nitzan Tomer


What is the solution for implementing Set

The JavaScript Set uses the same algorithm as === and there is no way to override that in your JavaScript class.

Solution

You can use something that leverages an overridable function e.g. https://github.com/basarat/typescript-collections uses toString.

like image 26
basarat Avatar answered Sep 28 '22 06:09

basarat