Skip to content

Instantly share code, notes, and snippets.

@sscovil
Created January 3, 2022 06:14
Show Gist options
  • Select an option

  • Save sscovil/2bebfbcfcc071234ec0afe7ab3cb0612 to your computer and use it in GitHub Desktop.

Select an option

Save sscovil/2bebfbcfcc071234ec0afe7ab3cb0612 to your computer and use it in GitHub Desktop.
ES6 functions for calculating factorials and finding all possible combinations of an array
export function factorial(num) {
if (num < 0) return -1;
else if (num === 0) return 1;
return num * factorial(num - 1);
}
export function allPossibleCombos(list, size) {
if (size > list.length) return [];
const results = [];
const generate = (combo, index, count) => {
const isFullSet = count === 1;
for (index; index < list.length; index++) {
const next = [...combo, list[index]];
if (isFullSet) {
results.push(next);
} else {
generate(next, index + 1, count - 1);
}
}
};
generate([], 0, size);
return results;
}
import { factorial, allPossibleCombos } from "./utils.js";
describe("factorial", () => {
test("returns the product of all positive integers less than or equal to a given positive integer", () => {
const integers = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
const expected = [3628800, 362880, 40320, 5040, 720, 120, 24, 6, 2, 1];
for (let i = 0; i < integers.length; i++) {
const actual = factorial(integers[i]);
expect(actual).toBe(expected[i]);
}
});
});
describe("allPossibleCombos", () => {
test("Generates a list of all possible combinations of items in an array", () => {
const list = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
const size = 5;
const result = allPossibleCombos(list, size);
const possibilities =
factorial(list.length) /
(factorial(size) * factorial(list.length - size));
expect(result.length).toBe(possibilities);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment