Is possible to make function from code and make it shorter? - javascript

I have this lines of code
let value = productDetails.recentPurchaseDate;
if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) {
value = false;
}
if (!productDetails.presentEstimatedValue) {
value = true;
}
Is it possible to refactor, I need to make it function and this two IF? Thanks in advance

You can do it like this
function getValue({
salesPrice,
recentPurchaseDate,
presentEstimatedValue
}) {
if (!salesPrice && !recentPurchaseDate) return false;
if (!presentEstimatedValue) return true
return recentPurchaseDate
}
and then
let value = getValue(productDetails);

Something like that?
const value = yourNewFn();
function yourNewFn() {
if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) {
value = false;
}
if (!productDetails.presentEstimatedValue) {
value = true;
}
return value;
}

Generally I don't think it is well designed if-conditions, but I don't know your business requirements. Let's try with something like this
let value = productHasRecentPurchaseDate(productDetails); //name should math your business goal
function productHasRecentPurchaseDate(productDetails) {
if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) {
return false;
}
else if (!productDetails.presentEstimatedValue) {
return true;
}
else {
return /*you need all if statement path to return some value, this is last one, please provide what those statements should return if both previous conditions fail*/;
}
}

Then use this
if (!productDetails.salesPrice && !productDetails.recentPurchaseDate && !productDetails.presentEstimatedValue ) : value = false ? value = true;

Related

How to simplify this two JS function coding?

Background: Below coding work fine, and i am able to use both function and return the expected value.
Question: Is there any way to simplify below function coding?
red_messages_disabled_p1() {
let s = this.status;
if (s.red_messages[0] === null) {
return 'none';
} else {
return 'inline-block';
}
},
red_messages_disabled_p2() {
let s = this.status;
if (s.red_messages[1] === null) {
return 'none';
} else {
return 'inline-block';
}
},
What did I try?
I tried to figure it out but no idea, guessing it's not possbile to simplify any more, am i correct?
Expecting?
I expecting there maybe simplify way for this coding.
First option :
red_messages_disabled_p(i) {
return this.status.red_messages[i-1] === null ? 'none' : 'inline-block';
}
Second option :
red_messages_disabled_p(i) {
return this.status.red_messages[i-1] ? 'inline-block' : 'none';
}
Get rid of code duplication. Both of your functions contain the same logic. So move that logic into a separate method as shown below:
class MyClass {
status = {red_messages: []}
redMsgDisplayStyle(msg) {
if (msg === null) {
return 'none';
}
return 'inline-block';
}
red_messages_disabled_p1() {
return this.redMsgDisplayStyle(this.status.red_messages[0])
}
red_messages_disabled_p2() {
return this.redMsgDisplayStyle(this.status.red_messages[1])
}
}
This will not only simplify the code, but also make it less error prone in case of you decide to change the logic in the future.
Also, replacing if-else with a ternary operator is probably not a good idea because: 1) it doesn't actually simplify the logic, just a different syntax and 2) ternary operator is less readable.
use a parameterized function
red_messages_disabled(index) {
let s = this.status;
if (s.red_messages[index] === null) {
return 'none';
} else {
return 'inline-block';
}
}
red_messages_disabled_p1() {
return this.red_messages_disabled(0);
};
red_messages_disabled_p2() {
return this.red_messages_disabled(1);
};
Use a ternary operator
red_messages_disabled_p1() {
let s = this.status;
return s.red_messages[0] === null ? 'none' : 'inline-block';
}
red_messages_disabled_p2() {
let s = this.status;
return s.red_messages[1] === null ? 'none' : 'inline-block';
}
There are already lots of good answers for this question, but I wanted to submit my own solution.
const redMessageDisabled => (index) {
return (s.red_messages[index] === null)?"none":"inline-block";
}
However, I think you can just pass s.red_messages[index] to the function
const redMessageDisabled => (data) {
return (data === null) ? "none" : "inline-block";
}

Evaluate passed value using .filter in JavaScript

I have a method that takes a language abbreviation and matches it using a .constant dictionary, and returns the matching language name.
How can I do an evaluation with .filter to check whether the passed isoCode/language abbreviation exists?
Here is my method:
angular.module('portalDashboardApp')
.service('ISOtoLanguageService', ['Languages', function(Languages) {
this.returnLanguage = function(isoCode) {
var categoryObject = Languages.filter(function ( categoryObject ) {
return categoryObject.code === isoCode;
})[0];
return categoryObject.name;
};
}]);
Here is the method with some error catching I have tried:
angular.module('portalDashboardApp')
.service('ISOtoLanguageService', ['Languages', function(Languages) {
this.returnLanguage = function(isoCode) {
var categoryObject = Languages.filter(function (categoryObject) {
if (isoCode != null || isoCode != undefined) {
return categoryObject.code === isoCode;
}
else {
return categoryObject.code === 'und';
}
})[0];
if (categoryObject.name != undefined || categoryObject.name != null) {
return categoryObject.name;
}
else {
return "undefined";
}
};
}]);
Thank you!
I would recommend you organize your data at Languagesin an object or map, it'll be much faster and simpler when you fetch your translation by an abbreviation. A short example:
angular.module('portalDashboardApp')
.factory('Languages', function(){
var dictionary = {
ISO: {name: 'International Organization for Standardization'}
};
return {
get: function(abbr){
return dict[abbr];
}
};
}).service('ISOtoLanguageService', ['Languages', function(Languages) {
this.returnLanguage = function(isoCode) {
if(!isoCode) {
return "Answer for empty isoCode";
}
var categoryObject = Languages.get(isoCode);
return (categoryObject || {}).name || "I don't know this abbr";
};
}]);
I'm not sure that this JS works without any syntax error (I've not try to launch it) but idea is that you don't need array and filter on big dictionaries and you are able to get any abbreviation from dict with O(1) complexity even with huge dictionary.
If you don't want to have a refactoring with your code you can do something like this:
angular.module('portalDashboardApp')
.service('ISOtoLanguageService', ['Languages', function(Languages) {
this.returnLanguage = function(isoCode) {
if (!isoCode) {
return;
}
var resultAbbrs = Languages.filter(function (categoryObject) {
return categoryObject.code === isoCode;
});
if (resultAbbrs.length > 0) {
return resultAbbrs[0].name;
}
};
}]);
In this case if isoCode is null, undefined or empty string or this key is not found in dictionary return undefined will be by default. Outside you should check a result of this function with if (result === undefined) ...
I hope it helped you)

jQuery returning multiple functions doesn't work

I am working a simple form validation and I have 3 functions where I check the input text fields, a select field and 2 radio buttons. For each group I have made a function, so 3 functions.
I have tested the functions on its own and they are working. But if I use them all 3 together at the end of my script, only one of them works.
Can anyone tell me what I need to do?
// Form validation
$(function() {
function wz_validation() {
var ok = true;
$('input[validate="true"]').each(function() {
if($(this).val() == '') {
ok = false;
$(this).addClass('red_border');
}
else $(this).removeClass('red_border');
});
return ok;
}
// Check Bank select box on checkout page
function wz_val_select() {
if($(".payment select")) {
if($(".payment select option:selected").val() == "") {
$(".payment select").addClass('red_border');
return false;
}
else{
$(".payment select").removeClass('red_border');
return true;
}
}
}
function wz_radio_shipping() {
var form = $("#shipping_form");
if(form.length) {
if(form.find('input[name=wz_shipping]:checked').length == 0) {
$("#checkout_shipping").addClass('red_border');
return false;
}
else{
$("#checkout_shipping").removeClass('red_border');
return true;
}
}
}
var wz_form = $('#wz_form1, #wz_form2, #wz_form3, #wz_form7');
$(wz_form).submit(function() {
return wz_validation() && wz_radio_shipping() && wz_val_select();
});
});
&& is a short circuit operator. It prevents the evaluation of b in a && b when a is falsy.
If you want to have all three functions called even when some of them return false, and if you only return boolean values, use &. As & makes 0 or 1, you might want to convert the result to a boolean with !! :
return !!(wz_validation() & wz_radio_shipping() & wz_val_select());
You might also want to write it more explicitly :
$(wz_form).submit(function(e) {
var good = true;
good &= wz_validation();
good &= wz_radio_shipping();
good &= wz_val_select();
if (!good) e.preventDefault();
});

Javascript array indexOf returns undefined

When calling my function checkIss(), issFullArray.indexOf(issToCheck) always returns undefined. I've run a .length, output the contents of issFullArray, I can't figure out why it's not working- the array looks fine to me. As you can see below, I've tried explicitly setting issArray as an array and copying the array returned by my getIssList()
function updateIss() {
var issArray = [];
var currService = current.u_business_service;
var currIss = current.u_is_service;
issArray = getIssList(currService).slice(); //getIssList() returns an arry
if (checkIss(issArray, currIss) === false) {
//do stuff
}
}
function checkIss(issFullArray, issToCheck) {
if (issFullArray.indexOf(issToCheck) < 0) {
return false;
} else {
return true;
}
}
Easiest to just loop through the array and compare each value and return true if there is a match otherwise return false. Not much more code and works for all browsers.
function checkIss(issFullArray, issToCheck) {
for(i=0; i<issFullArray.length; i++) {
if(issFullArray[i]==issToCheck) {
return true;
}
}
return false;
}

Returning a boolean value in a JavaScript function

I am doing a client side form validation to check if passwords match. But the validation function always returns undefined.
function validatePassword(errorMessage)
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
if(password.value)
{
// Check if confirm_password matches
if(password.value != confirm_password.value)
{
return false;
}
}
else
{
// If password is empty but confirm password is not
if(confirm_password.value)
{
return false;
}
}
return true;
}
Please note that the validatePassword is called from a member function of the Form object.
function Form(validation_fn)
{
// Do other stuff
this.submit_btn = document.getElementById("submit");
this.validation_fn = validation_fn;
}
Form.prototype.submit = funciton()
{
var result;
if(this.validation_fn)
{
result = this.validation_fn();
}
//result is always undefined
if(result)
{
//do other stuff
}
}
You could simplify this a lot:
Check whether one is not empty
Check whether they are equal
This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:
function validatePassword()
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
return password.value !== "" && password.value === confirm_password.value;
// not empty and equal
}
You could wrap your return value in the Boolean function
Boolean([return value])
That'll ensure all falsey values are false and truthy statements are true.
An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. #pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:
function validatePassword() {
const password = document.getElementById("password");
const confirm_password = document.getElementById("password_confirm");
if (password.value.length === 0) {
return false;
}
if (password.value !== confirm_password.value) {
return false;
}
return true;
}
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean

Categories