diff --git a/solutions/21.js b/solutions/21.js new file mode 100644 index 0000000..1a4a6a4 --- /dev/null +++ b/solutions/21.js @@ -0,0 +1,35 @@ +// Rahul Kalra +// Return array of largest 3 values in descending order from a given array + +const max = (array) =>{ + let max = array[0]; + for(let i = 0; i < array.length; i++){ + if(max <= array[i+1]){ + max = array[i+1]; + } + } + return max; +}; + +const removeNum = (array, max) =>{ + let newArray = []; + for(let i = 0; i < array.length; i++){ + if(!(max === array[i])){ + newArray.push(array[i]); + } + } + return newArray; +}; + +const solution = (array) =>{ + let a = 0; + let newArray = []; + for(let i = 0; i < 3; i++){ + a = max(array);; + array = removeNum(array, a); + newArray.push(a); + } + return [newArray[0], newArray[1], newArray[2]]; +}; + +module.exports = {solution}; diff --git a/test/21.js b/test/21.js new file mode 100644 index 0000000..408d751 --- /dev/null +++ b/test/21.js @@ -0,0 +1,14 @@ +let expect = require('chai').expect; +let solution = require('../solutions/21').solution; + +describe('Return 3 top largest values of an array in a descending order', () =>{ + it('should return 3 top largest values of an array', () =>{ + expect(solution([8,1,4,2,12,6,7,19,2,9])).to.eql([19, 12, 9]); + }); +}); + +describe('Return 3 top largest values of an array in a descending order', () =>{ + it('should return 3 top largest values of an array', () =>{ + expect(solution([-8,-3,-7,-1,-20,-2])).to.eql([-1,-2,-3]); + }); +});