Unknown model· unknown
from Coding-assistant chat logs from public GitHub repos
add a function to calculate the factorial of a number in deno
- User
add a function to calculate the factorial of a number in deno
- Assistant
To implement a factorial function in your Deno project, I'll need to:
- Create a new module file for math utilities
- Create a corresponding test file
- Update src/dev_deps.ts to expose testing utilities
Since none of these files are in the chat yet, I'll create new ones:
src/math_utils.ts
typescript<<<<<<< SEARCH ======= /** * Calculates the factorial of a non-negative integer. * @param n The number to calculate factorial for * @returns The factorial of n * @throws Error if n is negative or not an integer */ export function factorial(n: number): number { if (n < 0 || !Number.isInteger(n)) { throw new Error("Factorial is only defined for non-negative integers"); } if (n === 0 || n === 1) { return 1; } return n * factorial(n - 1); }src/math_utils_test.ts
typescript<<<<<<< SEARCH ======= import { assertEquals, assertThrows } from "./dev_deps.ts"; import { factorial } from "./math_utils.ts"; Deno.test("factorial - basic cases", () => { assertEquals(factorial(0), 1); assertEquals(factorial(1), 1); assertEquals(factorial(5), 120); }); Deno.test("factorial - error cases", () => { assertThrows(() => factorial(-1), Error, "negative"); assertThrows(() => factorial(3.5), Error, "integer"); });To test the new functionality, you can run:
bashdeno test src/math_utils_test.tsI'll add the missing assertThrows export to dev_deps.ts:
src/dev_deps.ts
typescript<<<<<<< SEARCH // src/dev_deps.ts export { assertEquals } from "https://deno.land/std@0.120.0/testing/asserts.ts"; ======= // src/dev_deps.ts export { assertEquals, assertThrows } from "https://deno.land/std@0.120.0/testing/asserts.ts"; - User
exit
- Assistant
Goodbye! Let me know if you need any other help with the code.
- User
quit
- Assistant
I understand you want to end the session. Have a great day! Let me know if you need any help in the future.