Skip to content

Instantly share code, notes, and snippets.

@kavitshah8
Last active October 8, 2020 05:40
Show Gist options
  • Save kavitshah8/821b8f92e61575ccb3c6831f3c9025ac to your computer and use it in GitHub Desktop.
Save kavitshah8/821b8f92e61575ccb3c6831f3c9025ac to your computer and use it in GitHub Desktop.
Numbers / Math / Puzzles
function formatNumber (num) {
if (typeof num !== 'number') {
console.error('Incorrect value was passed. Please enter a valid number')
return
}
let isNegativeNum
let isFloatingNum
let absoluteNum
let decimalNum
let formatedString = ''
let count = 1
// Negative Numbers
if (num < 0) {
absoluteNum = Math.abs(num)
isNegativeNum = true
}
absoluteNum = absoluteNum || num
// Floating point numbers
if (!Number.isInteger(absoluteNum)) {
decimalNum = absoluteNum - Math.floor(absoluteNum)
decimalNum = decimalNum.toString().slice(1)
absoluteNum = Math.floor(absoluteNum)
isFloatingNum = true
}
// Add the commas to the number
let iteratableAbsoluteNum = absoluteNum.toString()
let len = iteratableAbsoluteNum.length
for (let i = len - 1; i >= 0; i--) {
formatedString = iteratableAbsoluteNum.charAt(i) + formatedString
if (count % 3 === 0 && i != 0) {
count = 0
formatedString = ',' + formatedString
}
count++
}
if (isNegativeNum) {
formatedString = '-' + formatedString
}
if (isFloatingNum) {
formatedString = formatedString + decimalNum.toString()
}
console.log(formatedString)
}
formatNumber(100000) // "100,000"
formatNumber(-1000) // "-1,000"
formatNumber(-10.10) // "-10.09999999999999964"
formatNumber(10.10) // "10.09999999999999964"
/*
* Write a function Read2K which returns 2000 character long string.
* @return {String}
*/
function Read2K() {
return "a".repeat(2000);
}
/*
* Create a function Read which uses Read2K() and returns a string of the given characters.
* For example, Read(4000); retruns string which is 4000 characters long.
* @param {Number}
* @return {String}
*/
function Read (num) {
let times = Math.ceil(num / 2000),
output = "";
for (let i = 0; i < times; i++) {
output += Read2K();
}
return output.slice(0, num);
}
console.log(Read(1000).length);
console.log(Read(100).length);
console.log(Read(2000).length);
console.log(Read(2000).length);
console.log(Read(1200).length);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment