DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Edited on

Advent of PBT 2021 - Day 2

Advent of PBT 2021 — Learn how to use property based testing and fast-check through examples

Our algorithm today is: decomposeIntoPrimes.
It comes with the following documentation and prototype:

/**
 * Decompose the received integer number into prime factors.
 * The numbers may come in any order in the output.
 *
 * @param n - Integer value to be decomposed into prime factors,
 * must be in range 2 (included) to 2**31-1 (included)
 *
 * @returns
 * The prime factors to build n.
 */
declare function decomposeIntoPrimes(n: number): number[];
Enter fullscreen mode Exit fullscreen mode

The definition of a prime number according to Wikipedia is the following:

A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.

In other words, the numbers 2, 3, 5, 7 are prime numbers whereas 4, 6, 8 or 9 are not.

In order to clarify our expectations, we already wrote some examples based tests for it:

it("should decompose a prime number into itself", () => {
  expect(sorted(decomposeIntoPrimes(5))).toEqual([5]);
});

it("should decompose a number product of two primes", () => {
  expect(sorted(decomposeIntoPrimes(10))).toEqual([2, 5]);
});

it("should decompose a number product of three primes", () => {
  expect(sorted(decomposeIntoPrimes(30))).toEqual([2, 3, 5]);
});

it("should decompose a number product of many times the same prime", () => {
  expect(sorted(decomposeIntoPrimes(8))).toEqual([2, 2, 2]);
});
Enter fullscreen mode Exit fullscreen mode

How would you cover it with Property Based Tests?

In order to ease your task we provide you with an already setup CodeSandbox, with examples based tests already written and a possible implementation of the algorithm: https://codesandbox.io/s/advent-of-pbt-day-2-pjpqx?file=/src/index.spec.ts&previewwindow=tests

You wanna see the solution? Here is the set of properties I came with to cover today's algorithm: https://dev.to/dubzzz/advent-of-pbt-2021-day-2-solution-367b


Back to "Advent of PBT 2021" to see topics covered during the other days and their solutions.

More about this serie on @ndubien or with the hashtag #AdventOfPBT.

Top comments (0)