Commit 55cc3f0b authored by Fernando Basso's avatar Fernando Basso
Browse files

algdsts: Add calcSubtotals() example

parent c38bacb6
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -6,6 +6,7 @@
  "deno.importMap": "./src/codewars/typescript/import-map.json",
  "esbonio.sphinx.confDir": "",
  "cSpell.words": [
    "algdsts",
    "Codewars",
    "devel",
    "hackerrank",
+15 −0
Original line number Diff line number Diff line
@@ -69,3 +69,18 @@ As the length grows, the space complexity grows.

For both objects and arrays, it is O(n), `n` being the number of keys in the object or the length for arrays.

## Code Examples

### calcSubtotals()

#### Unit Tests

```{literalinclude} /../src/algdsts/src/02-bigO-notation/calcSubtotals.test.ts
:language: typescript
```

#### Implementation

```{literalinclude} /../src/algdsts/src/02-bigO-notation/calcSubtotals-v1.ts
:language: typescript
```
+5 −5
Original line number Diff line number Diff line
@@ -16,14 +16,14 @@
 * next element in turn. For example, the array `[1, 2, 3, 4]` has these
 * subtotals:
 *
 * ```text
 * ```
 *  1 → sum of just the first element.
 *  3 → sum of 1 and 2.
 *  6 → sum of 1, 2 and 3.
 * 10 → sum of 1, 2, 3 and 4.
 * ```
 *
 * So, `[1, 2, 3]` produces `[1, 3, 6]
 * So, for example, the sum of `[1, 2, 3]` produces `[1, 3, 6].
 */
function calcSubtotals(xs: number[]): number[] {
  const subtotals = [];
+16 −16
Original line number Diff line number Diff line
@@ -4,20 +4,20 @@ import { calcSubtotals } from './calcSubtotals-v1.ts';
Deno.test('calcSubtotals()', async (t) => {
  await t.step('should produce correct subtotals', () => {
    assertEquals(calcSubtotals([0, 1, 2, 3]), [
			0,
			0 + 1,
			0 + 1 + 2,
			0 + 1 + 2 + 3,
      0,             // → 0
      0 + 1,         // → 1
      0 + 1 + 2,     // → 3
      0 + 1 + 2 + 3, // → 6
    ]);
    assertEquals(calcSubtotals([10, 20, 30]), [
      10,
      10 + 20,
      10 + 20 + 30
      10,           // → 10
      10 + 20,      // → 30
      10 + 20 + 30, // → 60
    ]);
    assertEquals(calcSubtotals([-3, -7, -11]), [
      -3,
      -3 + -7,
      -3 + -7 + -11
      -3,            // → -3
      -3 + -7,       // → -10
      -3 + -7 + -11, // → -21
    ]);
  });
});