Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions src/splitInteger.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,19 @@
/**
* @param {number} value
* @param {number} numberOfParts
*
* @returns {number[]}
*/
function splitInteger(value, numberOfParts) {
const parts = [];
let rest = value;
const base = Math.floor(value / numberOfParts);
const remainder = value % numberOfParts;

for (let partsLeft = numberOfParts; partsLeft > 0; partsLeft--) {
const part = Math.floor(rest / partsLeft);
const result = Array(numberOfParts).fill(base);

parts.push(part);
rest -= part;
for (let i = 0; i < remainder; i++) {
result[numberOfParts - 1 - i] += 1;
}

return parts;
return result.sort((a, b) => a - b);
}

module.exports = splitInteger;
41 changes: 32 additions & 9 deletions src/splitInteger.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,43 @@

const splitInteger = require('./splitInteger');

test(`should split a number into equal parts
if a value is divisible by a numberOfParts`, () => {
describe('splitInteger', () => {
it('should be a function', () => {
expect(typeof splitInteger).toBe('function');
});

});
it('returns [8] when value is 8 and parts is 1', () => {
expect(splitInteger(8, 1)).toEqual([8]);
});

test(`should return a part equals to a value
when splitting into 1 part`, () => {
it('returns [3, 3] when value is 6 and parts is 2', () => {
expect(splitInteger(6, 2)).toEqual([3, 3]);
});

});
it('returns [4, 4, 4, 5] when value is 17 and parts is 4', () => {
expect(splitInteger(17, 4)).toEqual([4, 4, 4, 5]);
});

test('should sort parts ascending if they are not equal', () => {
it('returns [5, 5, 5, 5, 6, 6] when value is 32 and parts is 6', () => {
expect(splitInteger(32, 6)).toEqual([5, 5, 5, 5, 6, 6]);
});

});
it('should return array of correct length', () => {
expect(splitInteger(10, 5)).toHaveLength(5);
});

it('should have max difference between min and max <= 1', () => {
const result = splitInteger(100, 6);
const min = Math.min(...result);
const max = Math.max(...result);

expect(max - min).toBeLessThanOrEqual(1);
});

test('should add zeros if value < numberOfParts', () => {
it('should be sorted ascending', () => {
const result = splitInteger(13, 4);
const sorted = [...result].sort((a, b) => a - b);

expect(result).toEqual(sorted);
});
});