import { describe, it, before } from "node:test" import assert from "node:assert" import { PlataGlobalRuntime } from "../libs/runtime" describe('PromiseAll', () => { const plataPromise = (async () => { const g = global as any g.Plata = new PlataGlobalRuntime() })() before(async () => { await plataPromise }) it('should resolve an array of promises (cold start)', async () => { const promises = [ Plata.FastPromise(async (): Promise<1> => 1), Plata.FastPromise(async (): Promise<2> => 2), Plata.FastPromise(async (): Promise<3> => 3), ] as const const result = await Plata.PromiseAll(promises) assert.strictEqual(result.errorID, undefined) const type: [ 1, 2, 3 ] = result assert.deepStrictEqual(result, [1, 2, 3]) }) it('should resolve an array of promises (hot start)', async () => { const promises = [ Plata.FastPromise(async (): Promise<1> => 1), Plata.FastPromise(async (): Promise<2> => 2), Plata.FastPromise(async (): Promise<3> => 3), ] as const const result = await Plata.PromiseAll(promises) assert.strictEqual(result.errorID, undefined) const type: [ 1, 2, 3 ] = result assert.deepStrictEqual(result, [1, 2, 3]) }) it('(stress) should resolve an array in order', async () => { const arrayAleatorio = new Array() const arrayPromises = new Array>() for (let i = 0; i < 3_000; i++) { arrayAleatorio.push(Math.random()) arrayPromises.push(Plata.FastPromise(() => Promise.resolve(arrayAleatorio[i]))) } const newArray = await Plata.PromiseAll(arrayPromises) assert.deepStrictEqual(newArray, arrayAleatorio) }) it('should return an empty array if input is an empty array', async () => { const promises: [] = [] const result = await Plata.PromiseAll(promises) assert.strictEqual(result.errorID, undefined) const type: unknown[] = result assert.deepStrictEqual(result, []) }) it('should handle promises that reject', async () => { const promises = [ Plata.FastPromise(() => Promise.resolve(1)), Plata.FastPromise(() => Promise.resolve(Plata.BuildPlataError({ errorID: 'a', msg: '', error: '' }))), Plata.FastPromise(() => Promise.resolve(3)), ] const result = await Plata.PromiseAll(promises) if (result.errorID === undefined) { const type: number[] = result } assert.strictEqual(result.errorID, 'a') }) it('should run in concurrency', async () => { const promises = [ Plata.FastPromise(() => new Promise(r => setTimeout(() => r(100), 100))), Plata.FastPromise(() => new Promise(r => setTimeout(() => r(200), 200))), Plata.FastPromise(() => new Promise(r => setTimeout(() => r(100), 100))), ] const startTime = performance.now() await Plata.PromiseAll(promises) const endTime = performance.now() assert.equal((endTime - startTime) < 400, true) }) })