import { mapIterable, peerIdFromString } from "./util.js";
/**
 * We can't use PeerIds as set entries because set entries are
 * compared using same-value-zero equality, so this is just
 * a map that stringifies the PeerIds before storing them.
 *
 * PeerIds cache stringified versions of themselves so this
 * should be a cheap operation.
 *
 * @example
 *
 * ```TypeScript
 * import { peerSet } from '@libp2p/peer-collections'
 *
 * const set = peerSet()
 * set.add(peerId)
 * ```
 */
export class PeerSet {
    set;
    constructor(set) {
        this.set = new Set();
        if (set != null) {
            for (const key of set) {
                this.set.add(key.toString());
            }
        }
    }
    get size() {
        return this.set.size;
    }
    [Symbol.iterator]() {
        return this.values();
    }
    add(peer) {
        this.set.add(peer.toString());
    }
    clear() {
        this.set.clear();
    }
    delete(peer) {
        this.set.delete(peer.toString());
    }
    entries() {
        return mapIterable(this.set.entries(), (val) => {
            const peerId = peerIdFromString(val[0]);
            return [peerId, peerId];
        });
    }
    forEach(predicate) {
        this.set.forEach((str) => {
            const peerId = peerIdFromString(str);
            predicate(peerId, peerId, this);
        });
    }
    has(peer) {
        return this.set.has(peer.toString());
    }
    values() {
        return mapIterable(this.set.values(), (val) => {
            return peerIdFromString(val);
        });
    }
    intersection(other) {
        const output = new PeerSet();
        for (const peerId of other) {
            if (this.has(peerId)) {
                output.add(peerId);
            }
        }
        return output;
    }
    difference(other) {
        const output = new PeerSet();
        for (const peerId of this) {
            if (!other.has(peerId)) {
                output.add(peerId);
            }
        }
        return output;
    }
    union(other) {
        const output = new PeerSet();
        for (const peerId of other) {
            output.add(peerId);
        }
        for (const peerId of this) {
            output.add(peerId);
        }
        return output;
    }
}
export function peerSet() {
    return new PeerSet();
}
//# sourceMappingURL=set.js.map