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
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)
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.
You can use something that leverages an overridable function e.g. https://github.com/basarat/typescript-collections uses toString
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With