TypeScriptToLua icon indicating copy to clipboard operation
TypeScriptToLua copied to clipboard

Collections mutated during iteration don't affect it

Open ark120202 opened this issue 6 years ago • 1 comments

util.testFunction`
    const map = new Set([1, 2, 3, 4, 5]);
    const results: number[] = [];

    for (const value of map) {
        if (value === 3) map.clear();
        results.push(value);
    }

    return results;
`.expectToMatchJsResult();
    expect(received).toEqual(expected) // deep equality

    - Expected
    + Received

      Array [
        1,
        2,
        3,
    +   4,
    +   5,
      ]

ark120202 avatar Jan 21 '20 06:01 ark120202

It's also an issue for when you're adding new values into a set during iteration

util.testFunction`
    const set = new Set([1]);
    const results: number[] = [];

    for (const value of set) {
        if (value < 5) set.add(value + 1);
        results.push(value);
    }

    return results;
`.expectToMatchJsResult();

I was able to resolve this and .clear with

    public values(): IterableIterator<T> {
        let key: T | undefined = undefined;
        return {
            [Symbol.iterator](): IterableIterator<T> {
                return this;
            },
            next: () => {
                if (key === undefined) {
                    key = this.firstKey;
                } else {
                    key = this.nextKey.get(key);
                }

                return { done: !key, value: key };
            },
        };
    }

However it fails this test case

test("clear and add during iteration", () => {
    util.testFunction`
        const set = new Set([1, 2, 3]);
        const results: number[] = [];

        for (const value of set) {
            if (value === 2) {
                set.clear();
                set.add(10);
                set.add(11);
            }

            results.push(value);
        }

        return results;
    `.expectToMatchJsResult();
});

ark120202 avatar May 22 '20 23:05 ark120202