Skip to content

Commit

Permalink
feat: implement and test new sort function
Browse files Browse the repository at this point in the history
  • Loading branch information
matejchalk committed Jun 14, 2024
1 parent 7ed39db commit 86d581b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,13 @@ export function sum(values) {
export function average(values) {
return sum(values) / values.length;
}

/**
* Sort array by numeric values.
* @param {number[]} values Numbers to sort.
* @param {'asc' | 'desc'} order Ascending (default) or descending order.
* @returns {number[]} Sorted array.
*/
export function sort(values, order = 'asc') {
return [...values].sort((a, b) => (order === 'desc' ? b - a : a - b));
}
12 changes: 11 additions & 1 deletion test/index.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from 'node:assert';
import { describe, it } from 'node:test';
import { average, sum } from '../src/index.js';
import { average, sort, sum } from '../src/index.js';

describe('sum', () => {
it('should sum all numbers', () => {
Expand All @@ -17,3 +17,13 @@ describe('average', () => {
assert.strictEqual(average([1, 2, 3, 4]), 2.5);
});
});

describe('sort', () => {
it('should sort numbers in ascending order by default', () => {
assert.deepEqual(sort([4, 2, 1, 3]), [1, 2, 3, 4]);
});

it('should sort numbers in descending order if specified', () => {
assert.deepEqual(sort([4, 2, 1, 3], 'desc'), [4, 3, 2, 1]);
});
});

0 comments on commit 86d581b

Please sign in to comment.