Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
Improve this question
I have a task to filter out a number which is bigger than 9e+65 (65 zeros).
As input I have a number and as output I need to return a boolean value. The function can accept regular formatted numbers (42342) and any scientific notation (1e5).
My approach is:
const 65zerosCheck = (num: number):boolean =>
num.toString().includes("e+")
: Number(value.toString().split('e+')[1]) > 65
: false
It looks dirty and the reviewer didn't accept it.
To quote MDN:
In JavaScript, numbers are implemented in double-precision 64-bit binary format IEEE 754 (i.e., a number between ±2^−1022 and ±2^+1023, or about ±10^−308 to ±10^+308, with a numeric precision of 53 bits). Integer values up to ±2^53 − 1 can be represented exactly.
You do not have to worry about such huge numbers. I have added a link to MDN quote above at the end of this snippet where it is discussed in details about how Javascript handles Numbers.
const HUGE_NUMBER_THRESHOLD = 9e+65;
const checkHugeNumbers = (num) => num > HUGE_NUMBER_THRESHOLD;
let myTestNum = 9000000000000000000000000000000000000000000000000000000000000000000;
console.log(checkHugeNumbers(myTestNum));
// OUTPUT:
// true
For further study, here is the reference link.
There doesn't seem to be anything logically wrong with your approach, but if your reviewer is asking for a cleaner approach, this is my suggestion.
It does the same thing, but is more readable and its easy to add on to, in the future. Splitting up the logic and results into descriptive variables makes it easier to read, and catch any errors or oversights that may be encountered.
Also you can save a step by directly getting the index, without using split and creating three types (array, string, and number), that can make it confusing to follow. This approach keeps everything between strings and numbers
const checkOver65Zeros = (num: number) =>{
const numString = num.toString()
const idxOfZeros = numString.indexOf("e+")
if(idxOfZeros!== -1)
return Number(numString.substring(idxOfZeros + 2)) > 65
return false
}
console.log(checkOver65Zeros(900000000000000000000000000000000000000))
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have built a function that formats a number using commas, similar to what the toLocaleString method does. To achieve that, I used a regular expression and recursion. However, I have a feeling that this could've been done better.
I did some research but was not able to find the answer I'm looking for. So, my question is...Is there a better way to do this?
function transform(value) {
const pureNumber = parseInt(value);
const numberParts = [];
function format(val) {
let formatted = val.toString().split(/(\d{3})$/).filter(i => !!i).join(",");
const splitted = formatted.split(",");
if(splitted.length > 1){
numberParts.unshift(splitted[1]);
return format(splitted[0]);
}
numberParts.unshift(splitted[0]);
return numberParts.join(",");
}
return format(pureNumber.toString());
}
const data = "1234567890";
const result = transform(data);
console.log(result);
What I need you to note is that I used a regular expression to split the string, however, I was wondering if there is a way to only use regular expressions to avoid the recursion? I.e., Is there a way to use the regular expression starting at the end of the string and repeating towards left?
This can be accomplished much simpler using a single Regex expression:
function transform(value) {
return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// Works with string
console.log(transform("0123456789"));
// And numbers
console.log(transform(1234567890));
This regex will look in the string for any point that has 3 digits in a row after it and will make sure that point only has exactly multiples of 3 digits.
This was discovered in the first part of a post:
How to print a number with commas as thousands separators in JavaScript
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have been trying a coding challenge but could not think of the logic for it.
The question was like in a function you were given and arguement which was an
array containing info like
[ 56 , 011000 ]
so when we run this function the output was 1 as only 1 digit needs to be changed in binary (i,e 011000) to make that equivalent to 56.
Similarily the other test case was
[ 44 , 111111 ]
which expected output to be 3 as only 3 digits needs to be changes in binary number to make it equivalent to 44.
I could not even think of the logic so would be better if someone helps me out :)
There are two parts to this question:
Convert the decimal number to binary
Find the number of differing digits between the two binary strings
For the first part, you can use the toString(2) method as described here. For example:
console.log(Number(22).toString(2)); // prints "10110"
Or you can write your own function for that. One way to do that is, for a decimal number n, keep finding the highest power of 2 that is less than or equal to n, and then subtract that from n.
For the second part, you can iterate over both strings as follows:
let binaryString1 = "101";
let binaryString2 = Number(22).toString(2); // "10110"
const maxLen = Math.max(binaryString1.length, binaryString2.length); // get the length of the longer string
// make sure both strings are of the same length
binaryString1 = binaryString1.padStart(maxLen, "0");
binaryString2 = binaryString2.padStart(maxLen, "0");
let diff = 0;
for (let i=0; i < maxLen; i++) {
if (binaryString1.charAt(i) !== binaryString2.charAt(i)) {
diff++;
}
}
console.log(diff); // prints the number of differing chars
I guess you are looking for this?
(there is a lack of information in your message)
for information 01100 represent an octal value
01100 === 0o1100 === 576 === 0b1001000000000
this is just 5 lines of code...
function pairTest (arr2v)
{
let v0 = [...arr2v[0].toString(2)].reverse() // make 2 binary string reverse array
, v1 = [...arr2v[1].toString(10)].reverse() // for Right to Left testing
return v0.reduce((d,v,i)=>
d +((!!v1[i])?v!==v1[i]:1) // test digits, if exist in v1 otherwise add 1
,Math.max(0, v1.length-v0.length)) // if v1 is longer, the start value is the difference
}
console.log( pairTest([ 56 , 11000 ]) ) // -> 1
console.log( pairTest([ 44 , 111111 ]) ) // -> 3
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What is the best possible way to create a function that transforms a string of upvote counts into an array of numbers. Each k represents a thousand.
transformUpvotes("6.8k 13.5k") ➞ [6800, 13500]
transformUpvotes("5.5k 8.9k 32") ➞ [5500, 8900, 32]
transformUpvotes("20.3k 3.8k 7.7k 992") ➞ [20300, 3800, 7700, 992]
Return the upvotes as an array.
Now i tried to do this myself with or without regex, the pattern i used was this /\.\d(k)/g
I first converted the string into a javascript array using array.split(' '); but i don't know how to replace the k with zeroes properly so that the k after floating point get two zeroes and a k without floating point get three zeroes.
function transformUpvotes(upvotes) {
return upvotes.split(" ").map(x => {
parsed = parseFloat(x);
return x.endsWith("k") ? parsed * 1000 : parsed;
});
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm using this function to generate random int values :
var r = function(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
};
It works perfectly but makes me wonder ... why there is no randomInt and randomFloat in javascript?
JavaScript has a Number type which is a 64-bit float; there is no Integer type per se. Math.random by itself gives you a random Number, which is already a 64-bit float. I don't see why there couldn't be a Math.randomInt (internally it could either truncate, floor, or ceil the value). There is no good answer as to why the language doesn't have it; you would have to ask Brendan Eich. However, you can emulate what you want using Math.ceil or Math.floor. This will give you back a whole number, which isn't really an Integer typewise, but is still a Number type.
Because Javascript doesn't have those types. Pure javascript only has a generic number type.
More info on Javascript types may be found here and here.
You may also want to look into this question: Integers in JavaScript
The marked answer says, and I quote:
There are really only a few data types in Javascript: Objects, numbers, and strings. As you read, JS numbers are all 64-bit floats. There are no ints.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
var ratings = 3193;
var reviews = 9;
var average = parseFloat(ratings) / reviews; //I want a floating point number at the end.
Is this the right way to do it?
All numbers in JavaScript are double-precision 64-bit binary format IEEE 754. There is no need to typecast "integers" into "floats" as you would expect it from C/C++ and other languages. You need parse* only if you handle strings.
See also:
Number value
primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value
parseInt, parseFloat (both take a string as parameter)
The conversion isn't necessary. JavaScript automatically converts between types. And numbers are not actually represented as integers internally. They're all floating point anyway.
So, the simplest solution should have the desired effect:
var ratings = 3193;
var reviews = 9;
var average = ratings/reviews;
What you have in your example causes the engine to convert ratings to a String and parse that string as a double (theoretically resulting in the value it had to begin with) before treating it as the numerator in your calculation.