瀏覽代碼

add fibonacci class

Richard Köhl 3 年之前
父節點
當前提交
41821bd1e2
共有 2 個文件被更改,包括 82 次插入0 次删除
  1. 31 0
      src/fibonacci.class.test.ts
  2. 51 0
      src/fibonacci.class.ts

+ 31 - 0
src/fibonacci.class.test.ts

@@ -0,0 +1,31 @@
+import { assertEquals } from "https://deno.land/std@0.161.0/testing/asserts.ts";
+import { Fibonacci } from "./fibonacci.class.ts";
+
+Deno.test("Fibonacci class", async (t) => {
+  await t.step("getter list()", async (t) => {
+    await t.step("returns a list of fibonacci numbers", () => {
+      const numbers = Fibonacci.list(150);
+      assertEquals(
+        [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144],
+        numbers,
+        "first fibonacci numbers up to 150",
+      );
+    });
+  });
+
+  await t.step("getter next()", async (t) => {
+    await t.step("returns next larger fibonacci number after input", () => {
+      const next = 89 + 144;
+      assertEquals(
+        Fibonacci.next(150),
+        next,
+        "next fibonacci number after 150",
+      );
+      assertEquals(
+        Fibonacci.next(next),
+        144 + next,
+        "second next fibonacci number after 150",
+      );
+    });
+  });
+});

+ 51 - 0
src/fibonacci.class.ts

@@ -0,0 +1,51 @@
+import { OrderedNumbers } from "./ordered-numbers.class.ts";
+
+export class Fibonacci {
+  private static values: OrderedNumbers = new OrderedNumbers([
+    0,
+    1,
+  ], false);
+
+  private static get lastKnown(): number {
+    return Fibonacci.values.max;
+  }
+
+  private static get findNextUnknown(): number {
+    const numbers = Fibonacci.values.list;
+    const next = numbers[numbers.length - 1] + numbers[numbers.length - 2];
+
+    Fibonacci.values.add(next);
+    return next;
+  }
+
+  public static next(number: number): number {
+    if (number < Fibonacci.lastKnown) {
+      const result = Fibonacci.values.findNextLargerValue(number);
+
+      if (result === undefined) {
+        throw new Error("does not exists. should not happen!");
+      }
+
+      return result;
+    }
+
+    let next: number;
+    do {
+      next = Fibonacci.findNextUnknown;
+    } while (next <= number);
+
+    return next;
+  }
+
+  public static list(to: number): number[] {
+    if (to < 0) {
+      return [];
+    }
+
+    const outOfLimit = Fibonacci.next(to);
+    return Fibonacci.values.list.slice(
+      0,
+      Fibonacci.values.list.indexOf(outOfLimit),
+    );
+  }
+}