Else Statement Does Not Stop Looping NodeJS - node.js

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

Related

extendscript after effects if else statement how do i fix this up

this is my code the else statement is not firing well.
just test it if you can type in any effect and name it. I am trying to get the else statement to work check=false so that I can add my other action code to it.
var effectNameCollection = app.effects;
var check = false;
for (var i = 0; i < effectNameCollection.length; i++) {
var name = effectNameCollection[i].displayName;
if (name == "Color Matcher") {
check = true;
alert ("INSTALLED");
}else{
alert ("not installed");
}
}
I'm not entirely sure what your question is. But I will happily lend some advice. First of all, you likely don't want to have your alert code to be inside of the the for-loop. The way you have it now, it will fire an alert on every loop. I have 428 effects installed on my After-Effects, so that is a lot of alerts!
var effectNameCollection = app.effects;
var check = false;
for (var i = 0; i < effectNameCollection.length; i++) {
var name = effectNameCollection[i].displayName;
$.writeln(name);
if (name == "Color Matcher") {
check = true;
}
}
var chckAlert = check ? "INSTALLED" : "not installed";
alert(chckAlert);
The code above will log all of your installed effects to the terminal using $.writeln (extendscript's version of a console.log) and then will alert you if an effect with the name of 'Color Matcher' is installed.
The line:
var chckAlert = check ? "INSTALLED" : "not installed";
is just a condensed version of an if-else statement and is equivalent to:
var chckAlert = '';
if (check) {
chckAlert = "INSTALLED";
} else {
chckAlert = "not installed";`
}

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'));

Nodejs while loop doesnt work

repeat(1000, function() {
console.log("REPEAT");
var i = 1;
var max = 1;
var mS = ini.parse(fs.readFileSync(__dirname + '/XXX/Temp/MS.ini', 'utf-8'));
var array = new Array();
while(i<=max){
if(typeof mS[i] != 'undefined'){
if(mS[i]['10'] == true){
array.push(i);
console.log(array);
}else{
console.log("ERROR");
}
i++;
max++;
}else{ //if undefined
if(mS[i+1] == 'undefined' && mS[i+2] == 'undefined') i++;
else{ i++; max++; }
}
}//while
});
It works without repeat function. (waitjs module)
Also repeat works without while loop.
I am trying to become reconciled to node.js (single thread). But i do not know, where is the mistake?
var i = 1;
var max = 1;
while(i<=max){
This condition is valid only once.
Update (due to #user949300 comments):
How many times your loop executes depends on your ini file. I recommend you to step into your code with a debugger.

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!

Compare two big variables in javascript

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.

Resources