samedi 22 décembre 2018

JS How to make a function that returns a factorial

Ian new to coding and have been given this question that I cannot seem to get right;

The question is;

Create a function that takes an array of positive integers and returns an array of the factorials of these numbers.

  E.g. [4, 3, 2] => [24, 6, 2]

The factorial of a number is the product of that number and all the integers below it.

  E.g. the factorial of 4 is 4 * 3 * 2 * 1 = 24

If the number is less than 0, reject it.

The code that I have created is this;

function getFactorials(nums) {
   if (nums === 0 || nums === 1)
      return 1;
   for (var i = nums - 1; i >= 1; i--) {
      nums *= i;
   }
   return nums;
} 

The code is being run against this test;

describe("getFactorials", () => {
  it("returns [] when passed []", () => {
    expect(getFactorials([])).to.eql([]);
  });
  it("returns one factorial", () => {
    expect(getFactorials([3])).to.eql([6]);
  });
  it("returns multiple factorials", () => {
    expect(getFactorials([3, 4, 5])).to.eql([6, 24, 120]);
  });
  it("returns largest factorials", () => {
    expect(getFactorials([3, 8, 9, 10])).to.eql([6, 40320, 362880, 3628800]);
  });
});

Dose anyone have an idea of how to make this code work?

Aucun commentaire:

Enregistrer un commentaire