diff --git a/src/splitInteger.js b/src/splitInteger.js index d3da7485..e76644cf 100644 --- a/src/splitInteger.js +++ b/src/splitInteger.js @@ -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; diff --git a/src/splitInteger.test.js b/src/splitInteger.test.js index a610317d..268fd02a 100644 --- a/src/splitInteger.test.js +++ b/src/splitInteger.test.js @@ -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); + }); });