Repository: marpple/FxTS (ts)

Issue:
Add `scan` function
# Suggestion

<!--
  Please fill in each section completely. Thank you!
-->

## ⭐ Suggestion

<!-- What would you like to be added? -->

## 💻 Use Cases

<!-- What do you want to use this for? -->

```ts
const iter = scan((acc, cur) => acc * cur, 1, [1, 2, 3, 4 ]);
iter.next(); // {value: 1, done:false}
iter.next(); // {value: 1, done:false}
iter.next(); // {value: 2, done:false}
iter.next(); // {value: 6, done:false}
iter.next(); // {value: 24, done:false}
iter.next(); // {value: undefined, done: true}
```


Pull request description:
feat: add `scan` function
Fixes #87 


Patch:
diff --git a/src/Lazy/index.ts b/src/Lazy/index.ts
index 03364915..7a43d6fe 100644
--- a/src/Lazy/index.ts
+++ b/src/Lazy/index.ts
@@ -22,6 +22,7 @@ import range from "./range";
 import reject from "./reject";
 import repeat from "./repeat";
 import reverse from "./reverse";
+import scan from "./scan";
 import split from "./split";
 import take from "./take";
 import takeUntil from "./takeUntil";
@@ -58,6 +59,7 @@ export {
   reject,
   repeat,
   reverse,
+  scan,
   split,
   take,
   takeUntil,
diff --git a/src/Lazy/scan.ts b/src/Lazy/scan.ts
new file mode 100644
index 00000000..387f139b
--- /dev/null
+++ b/src/Lazy/scan.ts
@@ -0,0 +1,202 @@
+import pipe1 from "../pipe1";
+import Arrow from "../types/Arrow";
+import Awaited from "../types/Awaited";
+import IterableInfer from "../types/IterableInfer";
+import ReturnIterableIteratorType from "../types/ReturnIterableIteratorType";
+import { empty, isAsyncIterable, isIterable } from "../_internal/utils";
+import concurrent, { isConcurrent } from "./concurrent";
+import head from "../head";
+
+function* sync<A, B>(
+  f: (a: B, b: A) => B,
+  acc: B,
+  iterable: Iterable<A>,
+): IterableIterator<B> {
+  yield acc;
+  for (const a of iterable) {
+    yield (acc = f(acc, a));
+  }
+}
+
+async function* asyncSequential<A, B>(
+  f: (a: B, b: A) => B,
+  acc: Promise<B>,
+  iterable: AsyncIterable<A>,
+): AsyncIterableIterator<B> {
+  yield acc;
+  for await (const a of iterable) {
+    yield (acc = pipe1(acc, (acc) => f(acc as B, a)));
+  }
+}
+
+function async<A, B>(
+  f: (a: B, b: A) => B,
+  acc: Promise<B>,
+  iterable: AsyncIterable<A>,
+): AsyncIterableIterator<B> {
+  let _iterator: AsyncIterator<B>;
+  return {
+    async next(_concurrent: any) {
+      if (_iterator === undefined) {
+        _iterator = isConcurrent(_concurrent)
+          ? asyncSequential(f, acc, concurrent(_concurrent.length, iterable))
+          : asyncSequential(f, acc, iterable);
+      }
+      return _iterator.next(_concurrent);
+    },
+    [Symbol.asyncIterator]() {
+      return this;
+    },
+  };
+}
+
+function asyncWithoutSeed<A, B>(
+  f: (a: B, b: A) => B,
+  iterable: AsyncIterable<A>,
+): AsyncIterableIterator<B> {
+  let _iterator: AsyncIterator<B>;
+  return {
+    async next(_concurrent: any) {
+      if (_iterator === undefined) {
+        if (isConcurrent(_concurrent)) {
+          const _iterable = concurrent(_concurrent.length, iterable);
+          _iterator = asyncSequential(f, head(_iterable) as any, _iterable);
+        } else {
+          _iterator = asyncSequential(f, head(iterable) as any, iterable);
+        }
+      }
+      return _iterator.next(_concurrent);
+    },
+    [Symbol.asyncIterator]() {
+      return this;
+    },
+  };
+}
+
+/**
+ * Returns a Iterable/AsyncIterable of successively reduced values from the left.
+ * It's similar to reduce
+ *
+ * @example
+ * ```ts
+ * const iter = scan((acc, cur) => acc * cur, 1, [1, 2, 3, 4 ]);
+ * iter.next(); // {value: 1, done:false}
+ * iter.next(); // {value: 1, done:false}
+ * iter.next(); // {value: 2, done:false}
+ * iter.next(); // {value: 6, done:false}
+ * iter.next(); // {value: 24, done:false}
+ * iter.next(); // {value: undefined, done: true}
+ *
+ * // with pipe
+ * pipe(
+ *   [1, 2, 3, 4],
+ *   scan,
+ *   toArray,
+ * ); // [1, 2, 6, 24]
+ * ```
+ */
+function scan<A extends readonly []>(
+  f: Arrow,
+  iterable: A,
+): IterableIterator<never>;
+
+function scan<A extends readonly [], B>(
+  f: Arrow,
+  seed: B,
+  iterable: A,
+): IterableIterator<B>;
+
+function scan<A>(
+  f: (a: A, b: A) => A,
+  iterable: Iterable<A>,
+): IterableIterator<A>;
+
+function scan<A, B>(
+  f: (a: B, b: A) => B,
+  seed: B,
+  iterable: Iterable<A>,
+): IterableIterator<B>;
+
+function scan<A, B>(
+  f: (a: B, b: A) => B,
+  iterable: Iterable<A>,
+): IterableIterator<B>;
+
+function scan<A>(
+  f: (a: A, b: A) => A | Promise<A>,
+  iterable: AsyncIterable<A>,
+): AsyncIterableIterator<A>;
+
+function scan<A, B>(
+  f: (a: Awaited<B>, b: A) => B | Promise<B>,
+  seed: B | Promise<B>,
+  iterable: AsyncIterable<A>,
+): AsyncIterableIterator<B>;
+
+function scan<A, B>(
+  f: (a: Awaited<B>, b: A) => B | Promise<B>,
+  iterable: AsyncIterable<A>,
+): AsyncIterableIterator<Awaited<B>>;
+
+function scan<A extends Iterable<unknown> | AsyncIterable<unknown>>(
+  f: (
+    a: IterableInfer<A>,
+    b: IterableInfer<A>,
+  ) => IterableInfer<A> | Promise<IterableInfer<A>>,
+): (iterable: A) => ReturnIterableIteratorType<A, IterableInfer<A>>;
+
+function scan<A extends Iterable<unknown> | AsyncIterable<unknown>, B>(
+  f: (a: B, b: IterableInfer<A>) => B | Promise<B>,
+): (iterable: A) => ReturnIterableIteratorType<A, B>;
+
+function scan<A extends Iterable<unknown> | AsyncIterable<unknown>, B>(
+  f: (a: B, b: IterableInfer<A>) => B,
+  seed?: B | Iterable<IterableInfer<A>> | AsyncIterable<IterableInfer<A>>,
+  iterable?: Iterable<IterableInfer<A>> | AsyncIterable<IterableInfer<A>>,
+):
+  | IterableIterator<B>
+  | AsyncIterableIterator<B>
+  | ((iterable: A) => ReturnIterableIteratorType<A, B>) {
+  if (iterable === undefined) {
+    if (seed === undefined) {
+      return (iterable: A) => {
+        return scan(
+          f,
+          iterable as any,
+        ) as unknown as ReturnIterableIteratorType<A, B>;
+      };
+    }
+
+    if (isIterable(seed)) {
+      const iterator = seed[Symbol.iterator]();
+      const { done, value } = iterator.next();
+      if (done) {
+        return empty() as IterableIterator<B>;
+      }
+
+      return sync(f, value, {
+        [Symbol.iterator]() {
+          return iterator;
+        },
+      });
+    }
+
+    if (isAsyncIterable(seed)) {
+      return asyncWithoutSeed(f, seed);
+    }
+
+    throw new TypeError("'iterable' must be type of Iterable or AsyncIterable");
+  }
+
+  if (isIterable(iterable)) {
+    return sync(f, seed as B, iterable);
+  }
+
+  if (isAsyncIterable(iterable)) {
+    return async(f, Promise.resolve(seed as B), iterable);
+  }
+
+  throw new TypeError("'iterable' must be type of Iterable or AsyncIterable");
+}
+
+export default scan;


Test patch:
diff --git a/test/Lazy/scan.spec.ts b/test/Lazy/scan.spec.ts
new file mode 100644
index 00000000..2e78c974
--- /dev/null
+++ b/test/Lazy/scan.spec.ts
@@ -0,0 +1,149 @@
+import { delay, map, pipe, range, toArray, toAsync } from "../../src";
+import concurrent, { Concurrent } from "../../src/Lazy/concurrent";
+import scan from "../../src/Lazy/scan";
+import { callFuncAfterTime, generatorMock } from "../utils";
+
+describe("scan", function () {
+  describe("sync", function () {
+    it.each([
+      [(a: number, b: number) => a * b, 1, [1, 2, 3, 4], [1, 1, 2, 6, 24]],
+      [(a: string, b: string) => a + b, "a", ["b", "c"], ["a", "ab", "abc"]],
+    ])(
+      "should return value that is reduced given elements successively %s %s %s",
+      function (f, seed, iterable, result) {
+        expect(toArray(scan(f, seed, iterable as any))).toEqual(result);
+      },
+    );
+
+    it.each([
+      [(a: number, b: number) => a * b, [1, 2, 3, 4], [1, 2, 6, 24]],
+      [(a: string, b: string) => a + b, ["a", "b", "c"], ["a", "ab", "abc"]],
+    ])(
+      "should reduce given elements successively without seed %s %s %s",
+      function (f, iterable, result) {
+        expect(toArray(scan(f, iterable as any))).toEqual(result);
+      },
+    );
+
+    it("should be able to be used as a curried function in the pipeline", function () {
+      const res = pipe(
+        [1, 2, 3, 4],
+        scan((a, b) => a * b),
+        toArray,
+      );
+
+      expect(res).toEqual([1, 2, 6, 24]);
+    });
+  });
+
+  describe("async", function () {
+    it.each([
+      [(a: number, b: number) => a * b, 1, [1, 2, 3, 4], [1, 1, 2, 6, 24]],
+      [(a: string, b: string) => a + b, "a", ["b", "c"], ["a", "ab", "abc"]],
+    ])(
+      "should return value that is reduced given elements successively %s %s %s",
+      async function (f, seed, iterable, result) {
+        expect(
+          await toArray(scan(f, seed, toAsync(iterable as any) as any)),
+        ).toEqual(result);
+      },
+    );
+
+    it.each([
+      [(a: number, b: number) => a * b, 1, [1, 2, 3, 4], [1, 1, 2, 6, 24]],
+      [(a: string, b: string) => a + b, "a", ["b", "c"], ["a", "ab", "abc"]],
+    ])(
+      "should reduce given elements successively when seed is Promise %s %s %s",
+      async function (f, seed, iterable, result) {
+        expect(
+          await toArray(
+            scan(f, Promise.resolve(seed), toAsync(iterable as any) as any),
+          ),
+        ).toEqual(result);
+      },
+    );
+
+    it.each([
+      [(a: number, b: number) => a * b, [1, 2, 3, 4], [1, 2, 6, 24]],
+      [(a: string, b: string) => a + b, ["a", "b", "c"], ["a", "ab", "abc"]],
+    ])(
+      "should reduce given elements successively without seed %s %s %s",
+      async function (f, iterable, result) {
+        expect(await toArray(scan(f, toAsync(iterable as any) as any))).toEqual(
+          result,
+        );
+      },
+    );
+
+    it("should be able to be used as a curried function in the pipeline", async function () {
+      const res = await pipe(
+        [1, 2, 3, 4],
+        toAsync,
+        scan((a, b) => a * b),
+        toArray,
+      );
+
+      expect(res).toEqual([1, 2, 6, 24]);
+    });
+
+    it("should be passed concurrent object when job works concurrently", async function () {
+      const mock = generatorMock();
+      const iter = scan((a) => a, mock);
+      const concurrent = Concurrent.of(2) as any;
+
+      await iter.next(concurrent);
+      expect((mock as any).getConcurrent()).toEqual(concurrent);
+    });
+
+    it("should be handled concurrently", async function () {
+      const fn = jest.fn();
+      callFuncAfterTime(fn, 600);
+
+      const res = await pipe(
+        [1, 2, 3, 4, 5, 6, 7, 8, 9],
+        toAsync,
+        map((a) => delay(200, a)),
+        (nums) => scan((a, b) => a * b, 1, nums),
+        concurrent(3),
+        toArray,
+      );
+
+      expect(fn).toBeCalled();
+      expect(res).toEqual([1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]);
+    }, 650);
+
+    it("should be handled concurrently without seed", async function () {
+      const fn = jest.fn();
+      callFuncAfterTime(fn, 600);
+
+      const res = await pipe(
+        [1, 2, 3, 4, 5, 6, 7, 8, 9],
+        toAsync,
+        map((a) => delay(200, a)),
+        scan((a, b) => a * b),
+        concurrent(3),
+        toArray,
+      );
+
+      expect(fn).toBeCalled();
+      expect(res).toEqual([1, 2, 6, 24, 120, 720, 5040, 40320, 362880]);
+    }, 650);
+
+    it("should be able to handle an error when working concurrent", async function () {
+      await expect(
+        pipe(
+          toAsync(range(1, 21)),
+          map((a) => delay(100, a)),
+          scan((a, b) => {
+            if (a * b === 24) {
+              throw new Error("err");
+            }
+            return a * b;
+          }),
+          concurrent(2),
+          toArray,
+        ),
+      ).rejects.toThrow("err");
+    });
+  });
+});
diff --git a/type-check/Lazy/scan.test.ts b/type-check/Lazy/scan.test.ts
new file mode 100644
index 00000000..c45c9642
--- /dev/null
+++ b/type-check/Lazy/scan.test.ts
@@ -0,0 +1,81 @@
+import * as Test from "../../src/types/Test";
+import { pipe, scan, toAsync } from "../../src";
+
+const { checks, check } = Test;
+
+const res1 = scan((a, b) => a + b, []);
+const res2 = scan((a, b) => a + b, "seed", []);
+const res3 = scan((a, b) => a + b, 0, [1, 2, 3]);
+const res4 = scan((a, b) => a + b, [1, 2, 3]);
+const res5 = scan((a, b) => a + b, "0", [1, 2, 3]);
+const res6 = scan((a: string, b) => String(Number(a) + Number(b)), [1, 2, 3]);
+const res7 = scan((a, b) => a + b, toAsync([1, 2, 3]));
+const res8 = scan((a, b) => a + b, 0, toAsync([1, 2, 3]));
+const res9 = scan((a, b) => a + b, Promise.resolve(0), toAsync([1, 2, 3]));
+const res10 = scan(
+  (a: string, b) => String(Number(a) + Number(b)),
+  toAsync([1, 2, 3]),
+);
+const res11 = scan(
+  (a: string, b) => Promise.resolve(String(Number(a) + Number(b))),
+  toAsync([1, 2, 3]),
+);
+
+const res12 = pipe(
+  [1, 2, 3],
+  scan((a, b) => a + b),
+);
+
+const res13 = pipe(
+  [1, 2, 3],
+  scan((a: string, b) => String(Number(a) + Number(b))),
+);
+
+const res14 = pipe(
+  [1, 2, 3],
+  toAsync,
+  scan((a, b) => a + b),
+);
+
+const res15 = pipe(
+  [1, 2, 3],
+  toAsync,
+  scan((a, b) => Promise.resolve(a + b)),
+);
+
+const res16 = pipe(
+  [1, 2, 3],
+  toAsync,
+  scan((a: string, b) => String(Number(a) + Number(b))),
+);
+
+const res17 = pipe(
+  [1, 2, 3],
+  toAsync,
+  scan((a: string, b) => Promise.resolve(String(Number(a) + Number(b)))),
+);
+
+const res18 = pipe([1, 2, 3], toAsync, (res) =>
+  scan((a, b) => Promise.resolve(a + b), 0, res),
+);
+
+checks([
+  check<typeof res1, IterableIterator<never>, Test.Pass>(),
+  check<typeof res2, IterableIterator<string>, Test.Pass>(),
+  check<typeof res3, IterableIterator<number>, Test.Pass>(),
+  check<typeof res4, IterableIterator<number>, Test.Pass>(),
+  check<typeof res5, IterableIterator<string>, Test.Pass>(),
+  check<typeof res6, IterableIterator<string>, Test.Pass>(),
+  check<typeof res7, AsyncIterableIterator<number>, Test.Pass>(),
+  check<typeof res8, AsyncIterableIterator<number>, Test.Pass>(),
+  check<typeof res9, AsyncIterableIterator<number>, Test.Pass>(),
+  check<typeof res10, AsyncIterableIterator<string>, Test.Pass>(),
+  check<typeof res11, AsyncIterableIterator<string>, Test.Pass>(),
+  check<typeof res12, IterableIterator<number>, Test.Pass>(),
+  check<typeof res13, IterableIterator<string>, Test.Pass>(),
+  check<typeof res14, AsyncIterableIterator<number>, Test.Pass>(),
+  check<typeof res15, AsyncIterableIterator<number>, Test.Pass>(),
+  check<typeof res16, AsyncIterableIterator<string>, Test.Pass>(),
+  check<typeof res17, AsyncIterableIterator<string>, Test.Pass>(),
+  check<typeof res18, AsyncIterableIterator<number>, Test.Pass>(),
+]);