Samtech
Samtech

Reputation: 339

Javascript How to check the length of multiple variables and return the result in an efficient way?

At the moment I have an if the condition that checks if any of the string variable lengths is greater than 2 if true check for another condition, else console.log the output.

var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
// check for changes
if (
    previous_data_change.length >= 2 ||
    current_data_start.length >= 2 ||
    current_data_end.length >= 2 ||
    current_data_profile.length >= 2
) {
  if (previous_data_change.includes("last_changed")) {
    console.log(`last change comments: ${previous_data_change}`)
  } 
} else {
    console.log(`no change in previous record`)
}

i have tried refactoring it using some,

var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";

var filter_col = [
  previous_data_change,
  current_data_change,
  current_data_end,
  current_data_profile
];
change_boolean = filter_col.some((element) => element.length >= 2);
if (change_boolean && previous_data_change.includes("last_changed")) {
  console.log(`last change comments: ${previous_data_change}`);
} else {
  console.log("no change in previous record");
}


is there any way to shorten it further?

Upvotes: 0

Views: 824

Answers (1)

Raghav Garg
Raghav Garg

Reputation: 3707

Since you want any of them to be length greater than 2. You can simply merge them instead of writing 4 if conditions.

var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";

var string_to_check = previous_data_change + current_data_start + current_data_end + current_data_profile;

// check for changes
if (string_to_check.length < 2) {
    console.log(`no change in previous record`)
    return false;
}

if (previous_data_change.includes("last_changed")) {
    console.log(`last change comments: ${previous_data_change}`)
    return true;
}

Upvotes: 1

Related Questions