String comparison seems not to work - javascript

I have strings that I have to insert in a db but I want to first modify their value if they fall under certain conditions.
For example I have the strings Epatite, Epatite B, EpatiteáB, EpB3 that I want them to be changed to EP B before being inserted into the db.
This is piece of my code:
// vaccines[index] is the string to compare
var vac = makeUniform(vaccines[index]);
const queryInsert = {
text: 'INSERT INTO coverages (vaccine) VALUES ($1) ON CONFLICT DO NOTHING;',
values: [vac]
}
var printText = '[INSERT Italy IN coverages]';
promises.push(postgreSQLlib.query(queryInsert, printText, false));
function makeUniform(val) {
if(val === 'DIF' || val === 'Difterite') {
return 'DIPH'; // diphtheria
}
else if(val === 'Epatite' || val === 'Epatite B' || val === 'EpatiteáB' || val === 'EpB3') {
return 'EP B'; // hepatitis B
}
else if(val === 'HIB' || val === 'Hib3' || val === 'Hib') {
return 'HIB'; // haemophilus influenzae B
}
else {
return val;
}
}
Whene I execute SELECT DISTINCT vaccine FROM coverages ORDER BY vaccine; on psql shell, I get:
DIPH
DT-DTP3
DTP3
EP A
EP B
EpatiteáB
Hib
HIB
M-MPR1
M-MPR1-MPRV ...
There is EpatiteáB which theoretically should have changed in EP B.
Why it doesn't work?
EDIT 1
vaccines[index] comes from an online pdf of which I did web scraping using the textract package of Node.js.
Thanks

Try to clean your development database first with this:
UPDATE coverages set vaccine = 'EP B' WHERE vaccine LIKE 'Epatite%' OR vaccine = 'EpB3';
Do something similar for the others.

Try this added one more condition = (val==="Epatite%E1B%21")
function makeUniform(val) {
if(val === 'DIF' || val === 'Difterite') {
return 'DIPH'; // diphtheria
}
else if(val === 'Epatite' || val === 'Epatite B' || val==="Epatite%E1B%21" || val === 'EpatiteáB' || val === 'EpB3') {
return 'EP B'; // hepatitis B
}
else if(val === 'HIB' || val === 'Hib3' || val === 'Hib') {
return 'HIB'; // haemophilus influenzae B
}
else {
return val;
}
}

Related

Changing javascript eval method to another solution

I try to get rid of an ugly javscript eval method (Cause we all know it is unsecure).
I have the following problem. I build a dynamic searchstring.
Depends on the TLD a user decided to search for.
Here is my code:
if (tld == 0) {
var searchString = 'value.tld != ""';
}
if (tld == 1) {
var searchString = 'value.tld == "de"';
}
if (tld == 2) {
var searchString = 'value.tld == "com" || value.tld == "net" || value.tld == "org" || value.tld == "info" || value.tld == "biz"';
}
if (tld == 3) {
var searchString = 'value.tld == "io"';
}
Depending on the search parameter 'searchstring', I build this routine with eval:
if (eval(searchString)) {
// Do something special, depends on the tld variable
}
How can i rebuild this without using 'eval'. The premission is, that the first part of the code is beeing untouched.
Thanks in advance
Nick
How about:
let choices = {
1: ['de'],
2: ['com', 'net', 'org', 'info', 'biz'],
3: ['io']
};
function check(tldparam) {
if (tld === 0) {
return value.tld !== "";
} else {
return tld === tldparam && choices[tldparam].includes(value.tld);
}
}
And we test it like:
// Got this value from somewhere
let tld = 2;
let value = {tld: 'net'};
// This is my checking criterion
let tldparam = 2;
if (check(tldparam)) {
// Do something special, depends on the tld variable
}
Does it serve your purpose?

If block not hitting when enum matches

I'm trying to convert a string value to number based on an enum.But even when the enum matches.The if block is never hit.This is the code
let item = this.gaparameterlist.find(x => x.key === globalparameter);
if (globalparameter == enums.IASamplingGlobalParameters.PercentageTolerance || globalparameter == enums.IASamplingGlobalParameters.MarkDifferenceMethodThreshold || globalparameter == enums.IASamplingGlobalParameters.TailedThreshold, globalparameter == enums.IASamplingGlobalParameters.AvergaeDiffMethodTolerance || globalparameter == enums.IASamplingGlobalParameters.ModerationTest2Tolerance) {
var numericvalue = +textvalue;
numericvalue = numericvalue / 100;
textvalue = String(numericvalue);
}
This is the output from debugger

how to handle an array with filter().map in react js

I'm trying to make a search engine for my database.
I start with mapping all the elements and then I have a filter for some of the things in each elements like this:
const filteredCars = (carsGet.filter(item => {
const filter = (item.make.toLowerCase().includes(searchfield.toLowerCase()) ||
item.make.toLowerCase().includes(searchfield.toLowerCase()) === '')
&& (item.year > min || min === '')
&& (item.year < max || max === '')
&& (item.color === color || color === '');
console.log(filter);
return filter
}))
The filter works fine as long as it's just one item, but as soon as I send an array to color it returns false, if I set initialState to color: [] and change color === '' to color === [] they return false from start.
I have created a handler for the color:
handleChange (e) {
var options = e.target.options;
var value = [];
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
value.push(options[i].value);
}
}
console.log(value)
this.setState({color: value});
}
The console.log returns ["guld", "red"] but the filter returns false for all elements even if i only select one color
You can check if color is an array or a string and return a boolean accordingly.
const filteredCars = (carsGet.filter(item => {
const checkColor = () => {
if(Array.isArray(color)) {
return (color.length === 0) || color.includes(item.color);
} else {
return (color === '') || (color === item.color);
}
}
const filter = (item.make.toLowerCase().includes(searchfield.toLowerCase()) ||
item.make.toLowerCase().includes(searchfield.toLowerCase()) === '')
&& (item.year > min || min === '')
&& (item.year < max || max === '')
&& checkColor();
console.log(filter);
return filter
}))

Adding conditions to filter() dynamically in Javascript

I want to add conditions in JavaScript filter() method dynamically.
I have the code below:
let condition = '';
let a = ['empEmail', 'employeeAction', 'transactionNo', 'deviceListName', 'projectName'];
if (this.selectedEmployeeAlias != undefined) {
condition += '&& a => a.empEmail === this.selectedEmployeeAlias';
}
if (this.employeeStatusList != undefined) {
condition += '&& a.employeeAction === this.employeeStatusList'
}
if (this.selectedTransactionNo != undefined) {
condition += '&& a.transactionNo === this.selectedTransactionNo';
}
if (this.selectedDeviceList != undefined) {
condition += ' && a.deviceListName == this.selectedDeviceList';
}
if (this.selectedProjectName != undefined) {
condition += '&& a.projectName == this.selectedProjectName';
}
var finalCondition = condition.substring(2, condition.length);
var fArray = arrayDetails.filter(finalCondition);
The code is returning an error as:
finalCondition is not a function.
Could you please let me know how can I add conditions to filter() dynamically.
You could take an array of functions with conditions. Then iterate with every.
var conditions = [];
if (this.selectedEmployeeAlias !== undefined) {
conditions.push(a => a.empEmail === this.selectedEmployeeAlias);
}
if (this.employeeStatusList !== undefined) {
conditions.push(a => a.employeeAction === this.employeeStatusList);
}
if (this.selectedTransactionNo !== undefined) {
conditions.push(a => a.transactionNo === this.selectedTransactionNo);
}
if (this.selectedDeviceList !== undefined) {
conditions.push(a => a.deviceListName == this.selectedDeviceList);
}
if (this.selectedProjectName !== undefined) {
conditions.push(a => a.projectName == this.selectedProjectName);
}
var fArray = arrayDetails.filter(o => conditions.every(c => c(o)));
As you got the nakes of the keys, just loop over them and check for undefineds:
const keys = ['empEmail', 'employeeAction', 'transactionNo', 'deviceListName', 'projectName'];
const result = arrayDetails.filter(el => {
for(const key of keys) {
if(this[key] === undefined) continue;
if(this[key] !== el[key]) return false;
}
return true;
});
eval to the Rescue!
While it's generally advised against, eval does exactly what you want here.
Just pass your condition variable to eval inside the .filter method and voila!
let condition='';
let a = ['empEmail', 'employeeAction', 'transactionNo', 'deviceListName', 'projectName'];
if (this.selectedEmployeeAlias != undefined) {
condition += '&& a => a.empEmail === this.selectedEmployeeAlias';
}
if (this.employeeStatusList != undefined) {
condition += '&& a.employeeAction === this.employeeStatusList'
}
if (this.selectedTransactionNo != undefined) {
condition += '&& a.transactionNo === this.selectedTransactionNo';
}
if (this.selectedDeviceList != undefined) {
condition += ' && a.deviceListName == this.selectedDeviceList';
}
if (this.selectedProjectName != undefined) {
condition += '&& a.projectName == this.selectedProjectName';
}
var finalCondition=condition.substring(2, condition.length);
var fArray=arrayDetails.filter(stuff => eval(finalCondition));

JavaScript: Parsing a string Boolean value? [duplicate]

This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 4 years ago.
JavaScript has parseInt() and parseFloat(), but there's no parseBool or parseBoolean method in the global scope, as far as I'm aware.
I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean.
Here's my implementation:
function parseBool(value) {
return (typeof value === "undefined") ?
false :
// trim using jQuery.trim()'s source
value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
Is this a good function? Please give me your feedback.
Thanks!
I would be inclined to do a one liner with a ternary if.
var bool_value = value == "true" ? true : false
Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:
var bool_value = value == 'true';
This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.
You can use JSON.parse for that:
JSON.parse("true"); //returns boolean true
It depends how you wish the function to work.
If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:
function parseBoolean(str) {
return /true/i.test(str);
}
If you wish to assure that the entire string is the word true you could do this:
function parseBoolean(str) {
return /^true$/i.test(str);
}
You can try the following:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:
function test (input) {
try {
return !!$.parseJSON(input.toLowerCase());
} catch (e) { }
}
last but not least, a simple and efficient way to do it with a default value :
ES5
function parseBool(value, defaultValue) {
return (value == 'true' || value == 'false' || value === true || value === false) && JSON.parse(value) || defaultValue;
}
ES6 , a shorter one liner
const parseBool = (value, defaultValue) => ['true', 'false', true, false].includes(value) && JSON.parse(value) || defaultValue
JSON.parse is efficient to parse booleans
Personally I think it's not good, that your function "hides" invalid values as false and - depending on your use cases - doesn't return true for "1".
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0" and "1".
(Maybe there is a way to compare only once against "true", but I couldn't think of something right now.)
Why not keep it simple?
var parseBool = function(str) {
if (typeof str === 'string' && str.toLowerCase() == 'true')
return true;
return (parseInt(str) > 0);
}
You can add this code:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
Wood-eye be careful.
After looking at all this code, I feel obligated to post:
Let's start with the shortest, but very strict way:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
var parseBool = function(str)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
return false;
if (typeof str === 'boolean')
{
if(str === true)
return true;
return false;
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out params. In JavaScript it can be implemented in the following manner:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);
stringjs has a toBoolean() method:
http://stringjs.com/#methods/toboolean-tobool
S('true').toBoolean() //true
S('false').toBoolean() //false
S('hello').toBoolean() //false
S(true).toBoolean() //true
S('on').toBoolean() //true
S('yes').toBoolean() //true
S('TRUE').toBoolean() //true
S('TrUe').toBoolean() //true
S('YES').toBoolean() //true
S('ON').toBoolean() //true
S('').toBoolean() //false
S(undefined).toBoolean() //false
S('undefined').toBoolean() //false
S(null).toBoolean() //false
S(false).toBoolean() //false
S({}).toBoolean() //false
S(1).toBoolean() //true
S(-1).toBoolean() //false
S(0).toBoolean() //false
I shamelessly converted Apache Common's toBoolean to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {
if (str == "true") {
return true;
}
if (!str) {
return false;
}
switch (str.length) {
case 1: {
var ch0 = str.charAt(0);
if (ch0 == 'y' || ch0 == 'Y' ||
ch0 == 't' || ch0 == 'T' ||
ch0 == '1') {
return true;
}
if (ch0 == 'n' || ch0 == 'N' ||
ch0 == 'f' || ch0 == 'F' ||
ch0 == '0') {
return false;
}
break;
}
case 2: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'n' || ch1 == 'N') ) {
return true;
}
if ((ch0 == 'n' || ch0 == 'N') &&
(ch1 == 'o' || ch1 == 'O') ) {
return false;
}
break;
}
case 3: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
if ((ch0 == 'y' || ch0 == 'Y') &&
(ch1 == 'e' || ch1 == 'E') &&
(ch2 == 's' || ch2 == 'S') ) {
return true;
}
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'f' || ch1 == 'F') &&
(ch2 == 'f' || ch2 == 'F') ) {
return false;
}
break;
}
case 4: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
if ((ch0 == 't' || ch0 == 'T') &&
(ch1 == 'r' || ch1 == 'R') &&
(ch2 == 'u' || ch2 == 'U') &&
(ch3 == 'e' || ch3 == 'E') ) {
return true;
}
break;
}
case 5: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
var ch4 = str.charAt(4);
if ((ch0 == 'f' || ch0 == 'F') &&
(ch1 == 'a' || ch1 == 'A') &&
(ch2 == 'l' || ch2 == 'L') &&
(ch3 == 's' || ch3 == 'S') &&
(ch4 == 'e' || ch4 == 'E') ) {
return false;
}
break;
}
default:
break;
}
return false;
}
console.log(toBoolean("yEs")); // true
console.log(toBoolean("yES")); // true
console.log(toBoolean("no")); // false
console.log(toBoolean("NO")); // false
console.log(toBoolean("on")); // true
console.log(toBoolean("oFf")); // false
Inspect this element, and view the console output.
Enough to using eval javascript function to convert string to boolean
eval('true')
eval('false')

Categories