Better way of setting default value - javascript

At the moment I'm setting my default values this way:
var ls = localStorage.get('app')
if (ls && typeof ls.installDate !== typeof undefined) { var installDate = ls.installDate } else { var installDate = false }
if (ls && typeof ls.settingsTab !== typeof undefined) { var settingsTab = ls.settingsTab } else { var settingsTab = '' }
if (ls && typeof ls.aboutTab !== typeof undefined) { var aboutTab = ls.aboutTab } else { var aboutTab = true }
plus extra 30 other values. I'm thinking if there is a better (shorter) way to solve this type of approach.

You can do the short cut in script as :
var ls = localStorage.get('app');
You can do like :
var installDate = (ls && ls.installDate) || false;
var settingsTab = (ls && ls.settingsTab) || false;
var aboutTab = (ls.aboutTab) || false;

Related

Cannot read property 'value' of null on simple var assignment: var goToThis = "";

I'm getting a javascript error Cannot read property 'value' of null on simple var assignment var goToThis = "";
// It is the second function that has the error.
function nextFocus(tLast) {
var goToThis = "";
var val = 0;
if(tLast === 'activity') {
if(document.getElementById('[Slip]Note').value === "") {
document.getElementById('[Slip]Note').value = document.getElementById('[Slip]Activity').value;
}
}
if((tLast === 'activity') && (fLedes === true)){
document.getElementById('[Slip]Task No').focus();
} else if((tLast === 'activity') && (fLedes === false)){
goToThis = 'billableHrs';
} else if(tLast === 'expense'){
goToThis = 'priceAdjustment';
} else if((tLast === 'task') && (initialSlipType === 'time')){
goToThis = 'billableHrs';
} else if((tLast === 'task') && (initialSlipType === 'expense')){
goToThis = 'priceAdjustment';
}
if(goToThis === 'billableHrs') {
val = getReal(document.getElementById("[Slip]Billable Hrs"));
if(val === 0) {
document.getElementById("[Slip]Billable Hrs").value = '';
//alert('[Slip]Billable Hrs: '+val);
}
document.getElementById('[Slip]Billable Hrs').focus();
} else if (goToThis === 'priceAdjustment') {
val = getReal(document.getElementById("[Slip]Price Adjustment"));
if(val === 0) {
document.getElementById("[Slip]Price Adjustment").value = '';
//alert('[Slip]Price Adjustment: '+val);
}
document.getElementById('[Slip]Price Adjustment').focus();
}
}
This error was solved by correcting the spelling of an HTML element involved with this function call.
Safari pointed to the correct error line.
Chrome would not point to the correct error line.
Check opening and closing curly braces {} on all functions of the page. Sometimes {} mismatch ,also gives weird errors. Also try '' instead of "";

if statements being skipped even when both expressions are true

I have a webpage that populates a table with arrays. It has a doClick function so that when a user clicks on a cell it passes the row and column of the cell to the function. Example cell: onclick="doClick(0,1)"
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if ((top != -1) && (cells[top][col].innerHTML = ""))
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && (cells[row][right].innerHTML = ""))
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML = ""))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((left != -1) && (cells[row][left].inn = ""))
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
. The problem is, even if both if expressions are true, the if statement is being skipped and it's falling through to the else statement. I've desk checked it and run it through the developer tools and checked values. A statement that was true on both expressions was skipped. Any suggestions?
cells[row][right].innerHTML = ""
is wrong. You are missing the double (triple) =.
The correct way should be...
cells[row][right].innerHTML === ""
It looks like maybe there are a few typos or misconceptions in your code.
A quick note about Conditions in an IF statement
A statement like (cells[top][col].innerHTML = "") as a condition will always return true as this is setting cells[top][col].innerHTML as "" or at least instantiating the variable. So, the proper condition to test absolutely true or false would be (cells[top][col].innerHTML === ""). However, you can get away with not even doing that and simply replace (cells[top][col].innerHTML = "") with cells[top][col].innerHTML. You may run into some other issues though is the variable is not instantiated already, either way. I would wrap the latter logic in an IF statement to check if cells[top][col].innerHTML is even instantiated.
To fix this, check out the following modifications I have made to your code.
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if(typeof cells[top][col].innerHTML !== 'undefined' $$ cells[top][col].innerHTML !== null)
{
if ((top != -1) && cells[top][col].innerHTML !== '')
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && cells[row][right].innerHTML !== '')
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
else if (typeof cells[row][left].inn !== 'undefined' && (left != -1) && cells[row][left].inn !== '')
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
An example working to demonstrate the above code
var testVar1 = '';
var testVar2 = 'Hello';
// var testVar3; <- Left this un-instantiated to test existance
// Testing if a var is empty but exists
if(typeof testVar1 !== 'undefined' && testVar1 !== null){
if(testVar1 !== ''){
alert('testVar1 has a value!');
}{
alert('testVar1 does not have a value!');
}
}
// Testing if a var is empty but exists
if(typeof testVar2 !== 'undefined' && testVar2 !== null){
if(testVar2 !== ''){
if(testVar2 === 'Hello'){
alert('testVar2 has a value! Value: ' + testVar2);
}{
alert('testVar2 has a value but it is not the one we expected.');
}
}{
alert('testVar2 does not have a value!');
}
}
// Test existance
if(typeof testVar3 !== 'undefined' && testVar3 !== null){
alert('testVar3 exists!');
}else{
alert('testVar3 does not exist!');
}

convert a string containing boolean values to a boolean

If I have this ;
var a = "(true && false) && true && false"
And if I want to evaluate this string , what are the options ?
If I say, this code will be generated in the browser but there will be absolutely no user input in it , would it be safe to use eval ?
If not, what is the most performant way of parsing it ?
EDIt :
By the way, the string is dynamic , so I can't gaurantee that it's always like above , so it could be :
var a = "(true && false) || (true && (true && false)) && true && false"
FIY :
I know I can use eval, all I'm asking is, why I shouldn't use eval, or is there any other options?
EDIT : the original problem :
var a = function(){ return false} // all of them always return a boolean
var b = function(){ return true}
var c = function(){ return true}
var d = function(){ return false}
var conditions = "(a && b) && c && d"
I can't change the above code , I need to parse it, I need the condition to be evaluated ;
function ExecuteJavascriptString() {
var n = 0;
var s = "(true || false) || (true || (true || false)) && true";
var ifstate = " if (" + s + ") { console.log('done'); } ";
setTimeout(ifstate, 1);
}
ExecuteJavascriptString()
I was thinking maybe you can atleast verify that the string contains what you think it should contain, before running eval on it, using the RegExp /(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g:
var validExp = "(true && false && true) || (true && (true && false)) && true";
var evilExp = "(true && false && true) || (true && (true && false)) && true function() { console.log('do evil stuff'); }";
console.log(evalBoolStr(validExp)); //false
console.log(evalBoolStr(evilExp)); //Invalid input
function evalBoolStr(str) {
if(str.match(/(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g).join('') === str) {
return eval(str);
}
return 'Invalid input';
}
An attempt at actually writing a parser for boolean strings:
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "(true && false) && true && false";
var exp3 = "(true && !false) && true && !false";
var exp4 = "(a && b) && c && d";
console.log(exp1 + ' = ' + parseBoolStr(exp1));
console.log(exp2 + ' = ' + parseBoolStr(exp2));
console.log(exp3 + ' = ' + parseBoolStr(exp3));
console.log(exp4 + ' = ' + parseBoolStr(exp4));
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
function a() {
return false;
}
function b() {
return true;
}
function c() {
return true;
}
function d() {
return false;
}
Usage would then simply be parseBoolStr('true && false'); //false

How to minimize the if statement in javascript

I have a very long if-conditional statement. How can I minimize it?
Here is my code,
if(this.refs.category.value.trim() != "" &&
this.refs.decisive_min.value.trim() != "" && this.refs.decisive_max.value.trim() != "" &&
this.refs.interactive_min.value.trim() != "" && this.refs.interactive_max.value.trim() != "" &&
this.refs.stabilizing_min.value.trim() != "" && this.refs.stabilizing_max.value.trim() != "" &&
this.refs.cautious_min.value.trim() != "" && this.refs.cautious_max.value.trim() != "" &&
this.refs.aesthetic_min.value.trim() != "" && this.refs.aesthetic_max.value.trim() != "" &&
this.refs.economic_min.value.trim() != "" && this.refs.economic_max.value.trim() != "" &&
this.refs.individualistic_min.value.trim() != "" && this.refs.individualistic_max.value.trim() != "" &&
this.refs.political_min.value.trim() != "" && this.refs.political_max.value.trim() != "" &&
this.refs.altruist_min.value.trim() != "" && this.refs.altruist_max.value.trim() != "" &&
this.refs.regulatory_min.value.trim() != "" && this.refs.regulatory_max.value.trim() != "" &&
this.refs.theoretical_min.value.trim() != "" && this.refs.theoretical_max.value.trim() != ""){
var data = {category:this.refs.category.value.trim()};
data.decisive_min = this.refs.decisive_min.value.trim();
data.decisive_max = this.refs.decisive_max.value.trim();
data.interactive_min = this.refs.interactive_min.value.trim();
data.interactive_max = this.refs.interactive_max.value.trim();
data.stabilizing_min = this.refs.stabilizing_min.value.trim();
data.stabilizing_max = this.refs.stabilizing_max.value.trim();
data.cautious_min = this.refs.cautious_min.value.trim();
data.cautious_max = this.refs.cautious_max.value.trim();
data.aesthetic_min = this.refs.aesthetic_min.value.trim();
data.aesthetic_max = this.refs.aesthetic_max.value.trim();
data.economic_min = this.refs.economic_min.value.trim();
data.economic_max = this.refs.economic_max.value.trim();
data.individualistic_max = this.refs.individualistic_max.value.trim();
data.individualistic_min = this.refs.individualistic_min.value.trim();
data.political_min = this.refs.political_min.value.trim();
data.political_max = this.refs.political_max.value.trim();
data.altruist_min = this.refs.altruist_min.value.trim();
data.altruist_max = this.refs.altruist_max.value.trim();
data.regulatory_min = this.refs.regulatory_min.value.trim();
data.regulatory_max = this.refs.regulatory_max.value.trim();
data.theoretical_min = this.refs.theoretical_min.value.trim();
data.theoretical_max = this.refs.theoretical_max.value.trim();
I just want to check all the values in the form if they are all not empty string.
I used refs by React JS in Meteor.
You could use an array with the wanted keys. Then take only one loop for assigning and checking.
If all values are truthy, data contains the trimmed values, otherwise it is undefined.
var keys = ['category', 'decisive_min', 'decisive_max', 'interactive_min', 'interactive_max', 'stabilizing_min', 'stabilizing_max', 'cautious_min', 'cautious_max', 'aesthetic_min', 'aesthetic_max', 'economic_min', 'economic_max', 'individualistic_min', 'individualistic_max', 'political_min', 'political_max', 'altruist_min', 'altruist_max', 'regulatory_min', 'regulatory_max', 'theoretical_min', 'theoretical_max'],
data = {};
data = keys.every(function (k) {
return data[k] = this.refs[k].value.trim();
}, this) && data || undefined;
Using ES2015, you can do something like that :
Inside your component
const fields = getFields(this.refs);
if (checkFieldsNotEmpty(fields)) {
const data = {category:this.refs.category.value.trim()};
fields.forEach(field => {
data[`${field.name}_min`] = field.valueMin;
data[`${field.name}_max`] = field.valueMax;
});
// ...
}
Outside your component (can be static methods)
const fieldNames = [
'decisive',
'interactive',
'stabilizing',
// ...
];
const getFields = refs => fieldNames.map(name => ({
name,
valueMin: refs[`${fieldName}_min`].value.trim(),
valueMax: refs[`${fieldName}_max`].value.trim()
}));
const checkFieldsNotEmpty = fields => {
for (let field of fields) {
if (field.valueMin === '' || field.valueMax === '') {
return false
}
}
return true;
};
Try using
for (var property in this.refs) {
if (this.refs.hasOwnProperty(property)) {
// perform a null check
if(this.refs[property]){
//perform operaion
data[property] = this.refs[property].trim();
}
}
}

How to optimize the 3 conditions if else if Statements

Hi i have to check the three conditions, is there any Way to optimize the code other than the if else if statements. if i am checking all the three combinations its going to more lines of code do we have any better option to check all the conditions. Please can anybody help me on this to optimize the code.
if (req.body.officeId === "null" && req.body.branchId === "null" && req.body.productId === "null") {
updatedTestData = _.omit(req.body, ['officeId', 'branchId', 'roomId']);
updatedTestData.officeId = null;
updatedTestData.office = {};
updatedTestData.branchId = null;
updatedTestData.branch = {};
updatedTestData.productId = null;
updatedTestData.product = {};
} else if (req.body.officeId === "null" && req.body.branchId === "null" && !req.body.productId === "null") {
updatedTestData = _.omit(req.body, ['officeId', 'branchId']);
updatedTestData.officeId = null;
updatedTestData.office = {};
updatedTestData.branchId = null;
updatedTestData.branch = {};
}
Use Array.prototype.every():
var condition = [ req.body.officeId, req.body.branchId, req.body.productId]
if (condition.every(item => item === "null") {
// do some work
}
if (condition.every(item => item !== "null") {
// do other work
}
every will automatically exit if it finds a false value, so you will only have to go through your conditions until they fail.
A slightly better version:
if(req.body.officeId === "null" && req.body.branchId === "null"){
if(req.body.productId === "null"){
//your first code block
}else{
//your second code block
}
}
This might help
if (req.body.officeId === "null" && req.body.branchId === "null") {
if (req.body.productId === "null"){
updatedTestData = _.omit(req.body, ['officeId', 'branchId', 'roomId']);
updatedTestData.officeId = null;
updatedTestData.office = {};
updatedTestData.branchId = null;
updatedTestData.branch = {};
updatedTestData.productId = null;
updatedTestData.product = {};
return
}
updatedTestData = _.omit(req.body, ['officeId', 'branchId']);
updatedTestData.officeId = null;
updatedTestData.office = {};
updatedTestData.branchId = null;
updatedTestData.branch = {};
}
2 of the checks are common to both the if and elseif so you could extract those to an outer if...
if (req.body.officeId === "null" && req.body.branchId === "null") {
if (req.body.productId === "null") {
updatedTestData = _.omit(req.body, ['officeId', 'branchId', 'roomId']);
updatedTestData.officeId = null;
updatedTestData.office = {};
updatedTestData.branchId = null;
updatedTestData.branch = {};
updatedTestData.productId = null;
updatedTestData.product = {};
} else {
updatedTestData = _.omit(req.body, ['officeId', 'branchId']);
updatedTestData.officeId = null;
updatedTestData.office = {};
updatedTestData.branchId = null;
updatedTestData.branch = {};
}
}
var array = ['officeId', 'branchId'];
var body = req.body;
var office = body.officeId;
var branch= body.branchId;
var product= body.productId;
if(office === 'null' && branch === 'null') {
if(product !== 'null') {
array.push('roomId');
updatedTestData = _.omit(body, array);
testChange(body, 'product', updatedTestData);
} else {
}
}
testChange(req.body, 'office', updatedTestData);
testChange(req.body, 'branch', updatedTestData);
function testChange(object, key, toChange) {
if(object[key] === 'null') {
toChange[key + 'Id'] = null;
toChange[key] = {};
}
}
One more approach in ES 5:
var isNull = function(items) {
if (items === null) return true;
if (items.length) {
return items.reduce(
function(p, c){
return ((c===null) && p);
}, true);
}
return false;
}
if (isNull([req.body.officeId,
req.body.branchId,
req.body.productId]))
{
//
}
else if (isNull([req.body.officeId,
req.body.branchId] && !isNull(req.body.productId))
{
//
}

Categories

Resources