@applicaster/zapp-react-native-utils
Version:
Applicaster Zapp React Native utilities package
74 lines (56 loc) • 2.19 kB
text/typescript
import { mapAccum } from "../mapAccum";
describe("mapAccum", () => {
it("using standard ramda test", () => {
const digits = ["1", "2", "3", "4"];
const appender = (a, b) => [a + b, a + b];
const [acc, result] = mapAccum(appender, 0, digits); //= > ['01234', ['01', '012', '0123', '01234']]
expect(acc).toBe("01234");
expect(result).toEqual(["01", "012", "0123", "01234"]);
});
it("maps and accumulates over an array", () => {
const fn = (acc, x) => [acc + x, x * 2];
const [acc, result] = mapAccum(fn, 0, [1, 2, 3]);
expect(acc).toBe(6); // final accumulator (0 + 1 + 2 + 3)
expect(result).toEqual([2, 4, 6]); // mapped values (acc + x*2 at each step)
});
it("returns initial accumulator for empty array", () => {
const fn = (acc, x) => [acc + x, acc * x];
const [acc, result] = mapAccum(fn, 10, []);
expect(acc).toBe(10);
expect(result).toEqual([]);
});
it("accumulates strings correctly", () => {
const fn = (acc, x) => [acc + x, acc + x];
const [acc, result] = mapAccum(fn, "A", ["B", "C", "D"]);
expect(acc).toBe("ABCD");
expect(result).toEqual(["AB", "ABC", "ABCD"]);
});
it("works with objects as accumulator", () => {
const fn = (acc, x) => {
const newAcc = { sum: acc.sum + x };
return [newAcc, newAcc.sum];
};
const [acc, result] = mapAccum(fn, { sum: 0 }, [1, 2, 3]);
expect(acc).toEqual({ sum: 6 });
expect(result).toEqual([1, 3, 6]);
});
it("is curried", () => {
const fn = (acc, x) => [acc + x, x * 2];
const mapWithFn = mapAccum(fn);
const withInit = mapWithFn(2);
const [acc, result] = withInit([1, 2, 3]);
expect(acc).toBe(8);
expect(result).toEqual([2, 4, 6]);
});
it("does not mutate the original array", () => {
const arr = [1, 2, 3];
mapAccum((acc, x) => [acc + x, acc + x], 0, arr);
expect(arr).toEqual([1, 2, 3]);
});
it("handles mixed types in accumulator and result", () => {
const fn = (acc, x) => [acc + x.length, acc + "-" + x];
const [acc, result] = mapAccum(fn, 0, ["a", "bb", "ccc"]);
expect(acc).toBe(6);
expect(result).toEqual(["0-a", "1-bb", "3-ccc"]);
});
});