Compare two big variables in javascript - string

I have 2 big variables, and I need to compare like:
var a = 15000000000000000000000001 // integer
var b = "15000000000000000000000000" // string
In all my test comparisons get wrong results.
eg:
Convert var b into a integer
var a = 15000000000000000000000001
var b = 15000000000000000000000000
a > b // return false and is wrong
Convert var a into a string
var a = "1500000000000000000000001"
var b = "15000000000000000000000000"
a > b // return true and is wrong
My solution:
function compareCheck(a,b){
if (a.length > b.length) {
return true;
}
else if (a.length == b.length) {
if (a.localeCompare(b) > 0) {
return true
}
else return false;
}
else return false;
}
var a = "15000000000000000000000001"
var b = "15000000000000000000000000"
compareCheck(a,b) // return true and is correct
var a = "1500000000000000000000001"
var b = "15000000000000000000000000"
compareCheck(a,b) // return false and is correct
My question is whether the solution found is the correct one, or will have problems in the future?

Here the standard practice I believe is to subtract one number from another and compare it with an epsilon value.

Related

How to make a string shift backward each letter

I am finishing some functions in a flutter project.
void code_shift_backward() {
var input_string = controller.text;
List<String> output_list = [];
var input_runes = input_string.runes.toList();
for (var rune in input_runes) {
var mutatedRune = rune--;
output_list.add(String.fromCharCode(mutatedRune));
}
var output_string = output_list.join("");
setState(() {
text_in_tree = output_string;
});
}
I give it the word wiggle and I expect vhffkd but it keeps giving wiggle
You have to change:
var mutatedRune = rune--;
to:
var mutatedRune = --rune;
Explanation:
rune-- assigns the value of rune to mutatedRune first, then reduces the value by one. It means mutatedRune and rune has the same value.
--rune reduces the value first, then assigns.
Read about Dart arithmetic operators for more details.
You can fix this by moving the -- to the front of rune.. This happens because putting the -- after the variable only updates the variable after that line.
void code_shift_backward() {
var input_string = controller.text;
List<String> output_list = [];
var input_runes = input_string.runes.toList();
for (var rune in input_runes) {
var mutatedRune = --rune;
output_list.add(String.fromCharCode(mutatedRune));
}
var output_string = output_list.join("");
setState(() {
text_in_tree = output_string;
});
}
For size, maybe:
String shiftBack(String input) =>
String.fromCharCodes([for (var c in input.runes) c - 1]);

Else Statement Does Not Stop Looping NodeJS

I have been working on this code to read through a PDF file and grab the keywords of company names and display them. It all works fine except for one part where the else if statement outputs one line (which is what I want) but the else statement that comes last, which is supposed to output "Not Found" loops 20 times where I only want it to display the output only once instead of 20 times.
I have tried numerous ways by going through the internet to change my code, most recommended that forEach is not a proper way to do things and that I should use for instead but when I do, I just can't seem to get it right.
l.forEach(function(element) {
var j = element['fullTextAnnotation']['text'];
var sd = 'SDN. BHD.';
var bd = 'BHD.';
var et = 'Enterprise';
var inc = 'Incorporated';
var regtoken = new natural.RegexpTokenizer({pattern:/\n/});
var f = regtoken.tokenize(jsondata);
for(o = 0 ; o < f.length; o++){
var arrayline1 = natural.LevenshteinDistance(sd,f[o],{search:true});
var arrayline2 = natural.LevenshteinDistance(bd,f[o],{search:true});
var arrayline3 = natural.LevenshteinDistance(et,f[o],{search:true});
var arrayline4 = natural.LevenshteinDistance(inc,f[o],{search:true});
var arrayline5 = natural.LevenshteinDistance(nf,f[o],{search:false});
var onedata1 = arrayline1['substring'];
var onedata2 = arrayline2['substring'];
var onedata3 = arrayline3['substring'];
var onedata4 = arrayline4['substring'];
var onedata5 = arrayline5['substring'];
if (onedata1 === sd)
{
tokends = f[o];
break;
} else if(onedata3 === et)
{
tokends = f[o];
break;
} else if(onedata2 === bd)
{
tokends = f[o];
console.log(tokends);
break;
} else if(onedata4 === inc)
{
tokends = f[o];
console.log(tokends);
break;
} else{
console.log("Not Found");
return false;
}
}
});
I wish to get only one "Not Found" output for the else statement rather than it looping it for 20 times over. Hopefully I could get some insight to this problem. Thank you.
You are actually using the .forEach Array's method which actually take a function in parameter.
The keywork return breaks actually the loop of the current function executed.
For example :
const data = ['Toto', 'Tata', 'Titi'];
data.forEach(function(element) {
console.log(element);
if (element === 'Tata') {
return false;
}
});
// Will print everything :
// Print Toto
// Print Tata
// Print Titi
for (let element of data) {
console.log(element);
if (element === 'Tata') {
return false;
}
}
// Will print :
// Print Toto
// Print Tata

How to manipulate a string representing a raw number (e.g. 130000.1293) into a formatted string (e.g. 130,000.13)?

In apps script I want to obtain formatted 'number' strings. The input is an unformatted number. With an earlier answer posted by #slandau, I thought I had found a solution by modifying his code (see code snippet). It works in codepen, but not when I am using apps script.
1. Does anyone know what went wrong here?
2. I noticed this code works except when entering a number ending in .0, in that case the return value is also .0 but should be .00. I would like some help fixing that too.
Thanks!
I have tried to look for type coercion issues, but wasn't able to get it down. I am fairly new to coding.
function commaFormatted(amount)
{
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2);
var preD = a[1]/(Math.pow(10,a[1].length-2));
var d = Math.round(preD);
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
console.log(commaFormatted('100000.3532'))
The expected result would be 100,000.35.
I am getting this in the IDE of codepen, but in GAS IDE is stops at the .split() method => not a function. When converting var a to a string = I am not getting ["100000", "3532"] when logging var a. Instead I am getting 100000 and was expecting 3532.
Based on this answer, your function can be rewritten to
function commaFormatted(amount)
{
var inputAmount;
if (typeof(amount) == 'string') {
inputAmount = amount;
} else if (typeof(amount) == 'float') {
inputAmount = amount.toString();
}
//--- we expect the input amount is a String
// to make is easier, round the decimal part first
var roundedAmount = parseFloat(amount).toFixed(2);
//--- now split it and add the commas
var parts = roundedAmount.split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
console.log(commaFormatted(100000.3532));
console.log(commaFormatted('1234567.3532'));

Iterating with Q

I have this collection in MongoDB (I'm omitting _ids for brevity):
test> db.entries.find();
{
"val": 1
}
{
"val": 2
}
{
"val": 3
}
{
"val": 4
}
{
"val": 5
}
I need to perform some processing on each document which I cannot do with db.update(). So, in a nutshell, what I need to do is retrieving one document at a time, process it in Node and save it back to Mongo.
I'm using the Monk library, and Q for promises. Here's what I've done — I didn't include the processing/save bit for brevity:
var q = require('q');
var db = require('monk')('localhost/test');
var entries = db.get('entries');
var i = 1;
var total;
var f = function (entry) {
console.log('i = ' + i);
console.log(entry.val);
i++;
if (i <= total) {
var promise = entries.findOne({ val: i });
loop.then(function (p) {
return f(p);
});
return promise;
}
};
var loop = q.fcall(function () {
return entries.count({});
}).then(function (r) {
total = r;
return entries.findOne({ val: i });
}).then(f);
I would expect this code to print out:
i = 1
1
i = 2
2
i = 3
3
i = 4
4
i = 5
5
but it actually prints out:
i = 1
1
i = 2
2
i = 3
2
i = 4
2
i = 5
2
What am I doing wrong?
In your code, loop is one and only one promise. It is executed only once. It is not a function.
Inside f, loop.then(f) just trigger f with the result of the promise (it has already been executed so it is not executed again).
You actually want to create several promises.
What you are looking for is something that should looks like:
var q = require('q');
var db = require('monk')('localhost/test');
var entries = db.get('entries');
var i = 1;
var total;
var f = function (entry) {
console.log('i = ' + i);
console.log(entry.val);
i++;
if (i <= total) {
// I am not sure why you put entries.findOne here (looks like a mistake,
// its returned value isn't used) but if you really need it to be done
// before loop, then you must pipe it before loop
return entries.findOne({ val: i }).then(loop);
// do not pipe f again here, it is already appended at the end of loop
}
};
function loop(){
return q.fcall(function () {
return entries.count({});
}).then(function (r) {
total = r;
return entries.findOne({ val: i });
}).then(f);
}
loop();
If you are interested, here is a very nice article about promises.

How to remove duplicates from a string except it's first occurence

I've been given the following exercise but can't seem to get it working.
//Remove duplicate characters in a
// given string keeping only the first occurrences.
// For example, if the input is ‘tree traversal’
// the output will be "tre avsl".
// ---------------------
var params = 'tree traversal word';
var removeDuplicates = function (string) {
return string;
};
// This function runs the application
// ---------------------
var run = function() {
// We execute the function returned here,
// passing params as arguments
return removeDuplicates;
};
What I've done -
var removeDuplicates = function (string) {
var word ='';
for(var i=0; i < string.length; i++){
if(string[i] == " "){
word += string[i] + " ";
}
else if(string.lastIndexOf(string[i]) == string.indexOf(string[i]))
{
word += string[i];
}
}
return word;
};
I'm not allowed to use replaceAll and when I create an inner for loop it doesn't work.
<script>
function removeDuplicates(string)
{
var result = [];
var i = null;
var length = string.length;
for (i = 0; i < length; i += 1)
{
var current = string.charAt(i);
if (result.indexOf(current) === -1)
{
result.push(current);
}
}
return result.join("");
}
function removeDuplicatesRegex(string)
{
return string.replace(/(.)(?=\1)/g, "");
}
var str = "tree traversal";
alert(removeDuplicates(str));
</script>
First of all, the run function should be returning removeDuplicates(params), right?
You're on the right lines, but need to think about this condition again:
else if(string.lastIndexOf(string[i]) == string.indexOf(string[i]))
With i = 0 and taking 'tree traversal word' as the example, lastIndexOf() is going to be returning 5 (the index of the 2nd 't'), whereas indexOf() will be returning 0.
Obviously this isn't what you want, because 't' hasn't yet been appended to word yet (but it is a repeated character, which is what your condition does actually test for).
Because you're gradually building up word, think about testing to see if the character string[i] exists in word already for each iteration of your for loop. If it doesn't, append it.
(maybe this will come in handy: http://www.w3schools.com/jsref/jsref_search.asp)
Good luck!

Resources