Move History

Fork Selected
  • Description

    Be careful! You were previously implicitly defining a global fact when you really should not have done that. A lot of these problems can be solved by including that "use strict"; at the start of a function, which is especially important when you're starting out. Also, factorial of 0 is 1, and factorial of negatives is undefined. It's also nice to have proper indentation to make programs a little easier to read.

    Code
    function factorial (n) {
      "use strict";
      if (n < 0) {
        return NaN
      }
      let i, fact
      i = fact = 1
      while (i <= n) { 
        fact *= i
        i++
      }
      return fact
    }
    Test Cases
    const chai = require("chai");
    const assert = chai.assert;
    
    describe("Solution", function() {
      it("should test for something", function() {
        assert(factorial(0), 1);
        assert(factorial(1), 1);
        assert(factorial(5), 120);
        assert(factorial(8),40320);
        assert(factorial(15),1307674368000);
      });
    });
    
  • Code
    • function factorial (n) {
    • if (n <= 0) return 0
    • let i = fact = 1
    • "use strict";
    • if (n < 0) {
    • return NaN
    • }
    • let i, fact
    • i = fact = 1
    • while (i <= n) {
    • fact *= i
    • i++
    • fact *= i
    • i++
    • }
    • return fact
    • }
    Test Cases
    • const chai = require("chai");
    • const assert = chai.assert;
    • describe("Solution", function() {
    • it("should test for something", function() {
    • assert(factorial(0), 1);
    • assert(factorial(1), 1);
    • assert(factorial(5), 120);
    • assert(factorial(8),40320);
    • assert(factorial(15),1307674368000);
    • });
    • });