I checked the MDN for both flatMap/map but still cannot understand why the third test fails:
describe("mysterious flatMap", () => {
it("an array will be mapped to an array of `undefined` when its element NOT set", () => {
const mapped = new Array(1).map(() => "x");
expect(mapped.length).toBe(1); //OK
expect(mapped[0]).toBe(undefined); // OK
});
it("flatMap can join array of `undefined`", () => {
const flat = [undefined].flatMap((_) => [undefined]);
expect(flat.length).toBe(1); // OK
expect(flat[0]).toBe(undefined); //OK
});
it("but flatMap can NOT join the array which is created without elements set, why ??", () => {
const flat = [undefined].flatMap((_) => new Array(1).map(() => "x"));
expect(flat.length).toBe(1); // Error, Received: 0
expect(flat[0]).toBe("x");
});
});
I also created an online test on codesandbox