Last active
January 20, 2019 14:18
-
-
Save archangel-irk/b51c48829f1b488e19bc9b236cc8ad55 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Float To Percent | |
// Complexity - 2n | |
// Memory - ? | |
// Input limit - 6e6 (6_000_000) elements | |
function floatToPercent(array) { | |
const total = array.reduce((acc, curr) => acc + parseFloat(curr), 0); | |
return array.map(value => { | |
return (parseFloat(value) / total * 100).toFixed(3); | |
}); | |
} | |
function assert(condition, message) { | |
if (!condition) { | |
throw new Error(message || 'Assertion failed'); | |
} | |
} | |
function isEquals(arr1, arr2) { | |
return JSON.stringify(arr1) == JSON.stringify(arr2); | |
} | |
async function test(name, func) { | |
try { | |
await func(); | |
console.log(name, ': passed') | |
} catch (exception) { | |
console.log(name, ': failed'); | |
console.error(exception); | |
} | |
} | |
test('Simple test', () => { | |
const data = [ | |
'1.5', | |
'3', | |
'6', | |
'1.5', | |
]; | |
const expect = [ | |
'12.500', | |
'25.000', | |
'50.000', | |
'12.500', | |
]; | |
assert(isEquals(floatToPercent(data), expect)); | |
}); | |
test('50/50 test', () => { | |
const data = [ | |
'1.5', | |
'1.5', | |
]; | |
const expect = [ | |
'50.000', | |
'50.000', | |
]; | |
assert(isEquals(floatToPercent(data), expect)); | |
}); | |
test('One element', () => { | |
const data = [ | |
'1.5', | |
]; | |
const expect = [ | |
'100.000', | |
]; | |
assert(isEquals(floatToPercent(data), expect)); | |
}); | |
test('Zero percent', () => { | |
const data = [ | |
'1.5', | |
'0', | |
]; | |
const expect = [ | |
'100.000', | |
'0.000', | |
]; | |
assert(isEquals(floatToPercent(data), expect)); | |
}); | |
// function genRandomFloat() { | |
// return (Math.random() * 40).toFixed(1); | |
// } | |
// | |
// function genRandomArray(length) { | |
// return Array.from({ length, }, genRandomFloat); | |
// } | |
// | |
// (function testMaxInput() { | |
// console.time('generateTime'); | |
// const testData = genRandomArray(6e6); | |
// console.timeEnd('generateTime'); | |
// | |
// console.time('calculateTime'); | |
// floatToPercent(testData); | |
// console.timeEnd('calculateTime'); | |
// })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment