Breaking ternary operations to if, else in javascript - javascript

Hey guys i have a hard time in understanding multiple ternary conditions. Here is my code below
<div
className={
this.state.currentIndex == index
? "question-box bg-red-box"
: question.visited
? question.review
? "question-box review-box"
: question.selected_answer == null
? "question-box white-box"
: "question-box orange-box"
: "question-box"
}
>
How can i write this in if else (just for understanding). I know the conditions here would not be understable but just i want it in if else to get a clear understanding
Thanks !

The direct translation into if/else would be:
let temp;
if (this.state.currentIndex == index) {
temp = "question-box bg-red-box"
} else {
if (question.visited) {
if (question.review) {
temp = "question-box review-box";
} else {
if (question.selected_answer == null) {
temp = "question-box white-box"
} else {
temp = "question-box orange-box"
}
}
} else {
temp = "question-box"
}
}
// later:
<div className={temp} />
Neither version of the code is easy to understand. I would probably do something like the following instead:
let highlight = '';
if (this.state.currentIndex === index) {
highlight = "bg-red-box";
} else if (question.visited && question.review) {
highlight = "review-box";
} else if (question.visited && question.selected_answer === null) {
highlight = "white-box";
} else if (question.visited) {
highlight = "orange-box";
}
// ...
<div className={`question-box ${highlight}`} />

let currentIndex = 1;
let index = 2;
let question = {
visited: true,
review: false,
selected_answer: null
}
let output = '';
if(currentIndex == index){
output = 'question-box bg-red-box'
} else if (question.visited) {
if(question.review){
output = "question-box review-box"
} else if (question.selected_answer == null) {
output = "question-box white-box"
} else {
output = "question-box orange-box"
}
} else {
output = "question-box"
}
console.log(output)

Related

Text reversed on input

There is a email field where in if we access the site using chrome/IE/Firefox browser it works as expected, But if I access it using IPhone Safari browser the email field reverse the text I entered.
Example image here-
The code for the field Email is
<input
id="emal"
required
type="text"
maxlength="40"
onclick="this.focus();"
onfocus="if(this.value == this.dflt) { this.value='' }; this.onchange();"
onblur="if(this.value.length < 1) { this.value = this.dflt };"
onchange="this.ffoc = true; validate_email();"
onpaste="this.onchange();" oninput="this.onchange();"
onkeypress="this.onchange();">
Validation part of code -
function validate_email() {
if (document.loaded) {
$form[0].$emal.value = "";
$form[0].$emal.valid = null;
updateField($form[1].$emal, $form[1].$emal.value.replace(/\s/ig, ""));
if (isValidEmail($form[1].$emal.value) && $form[1].$emal.value != $form[
1].$emal.dflt) {
$form[0].$emal.value = $form[1].$emal.value;
$form[0].$emal.valid = true;
$form[1].$emal.setAttribute("valid", "true");
} else {
$form[1].$emal.setAttribute("valid", ($form[1].$emal.clik) ? ($form[
1].$emal.required) ? "false" : "warn" : "");
$form[0].$emal.valid = ($form[1].$emal.clik && !$form[1].$emal
.required) ? true : null;
}
$form[1].$emal.$wbox.style.display = ((/false|warn/i).test($form[1]
.$emal.getAttribute("valid"))) ? "block" : "none";
refresh();
}
}
function isValidEmail(str) {
var val = false;
if (str != null) {
var ddStr =
"aero%asia%biz%cat%com%coop%edu%gov%info%int%jobs%mil%mobi%museum%name%net%org%pro%tel%travel%ac%ad%ae%af%ag%cf%cg%ai%al%am%an%ao%aq%ar%as%at%au%aw%ax%az%ba%bb%bd%be%bf%bg%bh%bi%bj%bm%bn%bo%br%bs%bt%bv%bw%by%bz%ca%cc%cd%ch%ci%ck%cl%cm%cn%co%cr%cs%cu%cv%cx%cy%cz%dd%de%dj%dk%dm%do%dz%ec%ee%eg%eh%er%es%et%eu%fi%fj%fk%fm%fo%fr%ga%gb%gd%ge%gf%gg%gh%gi%gl%gm%gn%gp%gq%gr%gs%gt%gu%gw%gy%hk%hm%hn%hr%ht%hu%id%ie%il%im%in%io%iq%ir%is%it%je%jm%jo%jp%ke%kg%kh%ki%km%kn%kp%kr%kw%ky%kz%la%lb%lc%li%lk%lr%ls%lt%lu%lv%ly%ma%mc%md%me%mg%mh%mk%ml%mm%mn%mo%mp%mq%mr%ms%mt%mu%mv%mw%mx%my%mz%na%nc%ne%nf%ng%ni%nl%no%np%nr%nu%nz%om%pa%pe%pf%pg%ph%pk%pl%pm%pn%pr%ps%pt%pw%py%qa%re%ro%rs%ru%tw%tz%ua%ug%uk%us%uy%uz%va%vc%ve%vg%vi%vn%vu%wf%ws%ye%yt%yu%za%zm%zw",
ckStr = (ddStr).split("%");
if (str.length > 5 && (
/^\w+([\.\-\'\+]?\w+)*#\w+([\.\-]?\w+)*(\.\w+)+$/i).test(str)) {
for (var i = 0; i < ckStr.length; i++) {
if (str.substring(str.lastIndexOf(".") + 1) == ckStr[i]) {
val = true;
break;
}
}
}
}
return val
}
I really appreciate helping me sorting this or providing any references.

Using for loop to order dependency

var input = [ "KittenService: ", "Leetmeme: Cyberportal", "Cyberportal: Ice", "CamelCaser: KittenService", "Fraudstream: Leetmeme", "Ice: "];
var output = [];
function valid(input) {
for(var i = 0; i < input.length; i++) {
var array = input[i].trim().split(':');
var packageName = array[0].trim();
var dependencyName = array[1].trim();
if(array.length > 1 && dependencyName === '') {
if(output.indexOf(packageName) === -1) {
output.push(packageName);
}
else {
return;
}
}
else if(array.length > 1 && dependencyName !== '') {
if (output.indexOf(dependencyName) === -1) {
output.push(dependencyName);
if(output.indexOf(dependencyName) > -1) {
if(output.indexOf(packageName) > -1) {
continue;
}
else {
output.push(packageName);
}
}
}
else if(output.indexOf(dependencyName) > -1) {
output.push(packageName);
}
}
}
return output.join(', ');
}
valid(input);
I am trying to figure out way to make the output to become
"KittenService, Ice, Cyberportal, Leetmeme, CamelCaser, Fraudstream"
Right it logs
'KittenService, Cyberportal, Leetmeme, Ice, CamelCaser, Fraudstream'
I am not sure how to make all the input with dependencies to pushed before input with dependencies.
Problem was just that you were returning if no package name instead of using a continue.
var input =[ "KittenService: CamelCaser", "CamelCaser: " ]
var output = [];
function valid(input) {
for(var i = 0; i < input.length; i++) {
var array = input[i].trim().split(':');
var packageName = array[0].trim();
var dependencyName = array[1].trim();
if(array.length > 1 && dependencyName === '') {
if(output.indexOf(packageName) === -1) {
output.push(packageName);
}
else {
continue;
}
}
else if(array.length > 1 && dependencyName !== '') {
if (output.indexOf(dependencyName) === -1) {
output.push(dependencyName);
if(output.indexOf(dependencyName) > -1) {
output.push(packageName);
}
}
}
}
return output;
}
console.log(valid(input));

Sort array on string and boolean in javascript

I am having difficulty getting this sort to work.
Current always has precedence over name.
I can get it to sort on the values of either current or name but not both.
My array look like this.
var arr = [{current:true, name:"A name"},
{name:"A name"}, {name:"B name"},
{current:true, name:"B name"}];
arr.sort(sort_me)
Here's the sort function.
var sort_me = function(left, right){
var value = "name";
var sort_by_val = function(){
return left[value] == right[value] ? 0 : (left[value] < right[value] ? -1 : 1);
}
if(left.current===right.current) {
sort_by_val();
}else{
if(left.current===true){
return -1;
}else{
if(right.current===true){
return 1;
}else{
sort_by_val();
}
}
}
}
You're missing a return:
if(left.current===right.current) {
return sort_by_val();
}
Otherwise your return value will be undefined if both currents are set:
var sort_me = function(left, right){
var nameorder = left.name === right.name ? 0 : (left.name < right.name ? -1 : 1);
if(
(left.current && right.current) ||
(!left.current && !right.current)
) {
return nameorder;
} else if(left.current) {
return -1;
} else {
return 1;
}
}
Try
var sort_me = function(left, right) {
var value = "name";
var sort_by_val = function() {
return left[value] == right[value] ? 0 : (left[value] < right[value]
? -1
: 1);
}
if (left.current === right.current) {
return sort_by_val(); //missing return
} else {
if (left.current === true) {
return -1;
} else if (right.current === true) {
return 1;
} else {
return sort_by_val(); //missing return
}
}
}
Demo: Fiddle

Javascript code to convert serial numbers converted from PHP

These two Javascript functions are supposed to convert serial numbers (2-9999) for example into a number , but the functions below are not working for some reason .. they were originally written in PHP ... Works in PHP but not for Javascript.
<html>
<head>
<script type="text/javascript">
function my_isnum(str, negative=false, decimal=false)
{
var has_decimal = false;
var len = strlen(str);
if (len > 0) {
var valid = true;
for (var i=0; valid && i < len; i++) {
if (!(str[i] >= "0" && str[i] <= "9")) {
if (str[i] == "-") {
if (!negative || i != 0) {
valid = false;
}
} else if (str[i] == ".") {
if (!decimal || has_decimal) {
valid = false;
}
} else {
valid = false;
}
}
}
} else {
valid = false;
}
return valid;
}
function esn_to_num(esn) {
var tmp = [];
if ((tmp = esn.split("-")) {
if (tmp.length == 2
&& my_isnum(tmp[0])
&& my_isnum(tmp[1])
) {
esn = ((tmp[0] << 23) | tmp[1]);
} else {
esn = -1;
}
} else {
esn = -1;
}
return esn;
}
alert(2-9999);
</script> </head>
</html>
Original PHP functions
<?php
function my_isnum($str, $negative=false, $decimal=false)
{
$has_decimal = false;
$len = strlen($str);
if ($len > 0) {
$valid = true;
for ($i=0; $valid && $i<$len; $i++) {
if (!($str[$i] >= '0' && $str[$i] <= '9')) {
if ($str[$i] == '-') {
if (!$negative || $i != 0) {
$valid = false;
}
} else if ($str[$i] == '.') {
if (!$decimal || $has_decimal) {
$valid = false;
}
} else {
$valid = false;
}
}
}
} else {
$valid = false;
}
return $valid;
}
function esn_to_num($esn)
{
if (($tmp = explode('-', $esn))) {
if (sizeof($tmp) == 2
&& my_isnum($tmp[0])
&& my_isnum($tmp[1])
) {
$esn = (($tmp[0] << 23) | $tmp[1]);
} else {
$esn = -1;
}
} else {
$esn = -1;
}
return $esn;
}
?>
There is no such thing as strlen in Javascript. Use str.length instead.
Also, as Jason Sperske suggested below, change this:
function my_isnum(str, negative=false, decimal=false)
To this:
function my_isnum(str, negative, decimal)
{
if (typeof negative == "undefined") negative = false;
if (typeof decimal == "undefined") decimal = false;
....
}
These two javascript functions are supposed to convert serial numbers (2-9999) for example into a number.
Why not just get rid of the - and parse as a decimal number?
function padToFourDigits(_, digits) {
return "0000".substring(digits.length) + digits;
}
function serialToNum(serialNumStr) {
return +(serialNumStr.replace(/-(\d{1,4})/g, padToFourDigits));
}
Then
serialToNum('2-9999') === 29999
serialToNum('2-999') === 20999

how to make this javascript function output #value in the xpath?

The code below, produces Xpath. However, it doesn't display #value attribute/property. It is not working very well.
function getXPath(node, path, val) {
path = path || [];
if(node.parentNode) { path = getXPath(node.parentNode, path); }
if(node.previousSibling) {
var count = 1;
var sibling = node.previousSibling
do {
if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {count++;}
sibling = sibling.previousSibling;
} while(sibling);
if(count == 1) {count = null;}
} else if(node.nextSibling) {
var sibling = node.nextSibling;
do {
if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {
var count = 1;
sibling = null;
} else {
var count = null;
sibling = sibling.previousSibling;
}
} while(sibling);
}
if(node.nodeType == 1) {
if (val){
path.push(node.nodeName.toLowerCase() + (node.id ?
"[#id='"+node.id+"' #value='"+val+"']" :
count > 0 ? "["+count+"]" : ''));
}else{
path.push(node.nodeName.toLowerCase() + (node.id ?
"[#id='"+node.id+"']" : count > 0 ? "["+count+"]" : ''));
}
}
return path;
};
try:
http://mcc.id.au/xpathjs
or
http://xmljs.sourceforge.net/

Categories