Best way to get a decent result from this Array check? - javascript

I am trying to get a decent result that I can do something with, but feel the way I am it at the moment in the 'check' function isn't actually returning other than an expression:
validate = () => {
const items = this.state.data;
const check = e => {
!e.error === undefined ? true : false;
};
const checkFields = items.some(check);
if (!checkFields) {
alert('form valid');
}
};
Is the 'check' function any good?

The check function does not return anything. Either:
Remove the braces so that it no longer is a code block, but an expression whose value is returned, or
Add a return before the expression.
Secondly:
The ! operator has precedence over ===, so !e.error === undefined is not doing what you think. You can use parentheses, like !(e.error === undefined), but why not just e.error !== undefined?
And it really is not necessary to apply the ternary operator on that. It is already a boolean expression, so just use it without that ? true : false.
In short:
const check = e => e.error !== undefined;
Concerning the overall function validate: Using alert is quite primitive, and not the most user-friendly thing to do. You should consider applying CSS styling to the input that does not pass validation.

Related

Best practice using null in a ternary operator in JavaScript

Hey first time poster/user, I have been working through some coding exercises. I wrote a piece of code that passed tests but I am unsure if this is best practice
In this sample I am iterating over an array using the filter function. I am using a call back function that will return words with length greater than 5.
sample code
const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];
const interestingWords = words.filter(word => {
return word ? word.length > 5 : null
})
In my head if the condition isn't met it shouldn't even try to return. What is happening when I return a null? or is this a case where I wouldn't use ternary at all.
The best I got was from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
The value null is written with a literal: null. null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.
So should I refrain from returning a null in this context?
All .filter's callback cares about is the truthy or falsey value returned inside it. Here, it'd be better to return that comparison directly, no conditional operator needed:
const interestingWords = words.filter(word => word.length > 5);
A construction like
return word ? word.length > 5 : null
could make sense if you needed to check a sub-property, but only if the array element existed first, eg:
const objects = [
null,
{ word: 'foo' },
{ word: 'barbar' },
null
];
const interestingObjects = objects.filter(
obj => obj ? obj.word.length > 5 : null
);
console.log(interestingObjects);
If elements of the array might be null or undefined, you can use the optional chaining operator.
const interestingWords = words.filter(word => {
return word?.length > 5
})

Can someone explain what this simple javascript (ES6) line does with arrow functions? [duplicate]

This question already has answers here:
What do multiple arrow functions mean in JavaScript?
(7 answers)
Closed 1 year ago.
I've been staring at this code for so long trying to understand what it's doing, but have no idea what's going on.
export const fieldDisabledIs = expectedValue => ({fieldDisabled}) =>
(expectedValue === false && isEmpty(fieldDisabled)) || fieldDisabled === expectedValue;
The caller makes a call like this:
fieldDisabledIs(true)
What is it doing? I think since there are two arrow functions, the return is a function itself. Something like:
function(expectedValue)
{
return function ({fieldDisabled})
{
(expectedValue === false && isEmpty(fieldDisabled)) || fieldDisabled === expectedValue;
}
}
Also this line here...
(expectedValue === false && isEmpty(fieldDisabled)) || fieldDisabled === expectedValue;
It seems redundant to have the first check if we can just compare fieldDisabled === expectedValue. Isn't it covered in the second condition?
The two arrow functions in the first line of the code is a technique called currying.
To quote wikipedia
"In mathematics and computer science, currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each takes a single argument."
Well okay.. that's pretty obvious, but why would you do that.
In the case of your example this might be used as below.
You could create a 'checker' for a specifc value, in this example we will use 'foo'.
const fieldDisabledIsFoo = fieldDisabledIs('foo');
Then you could use your checker whenever you want to check if the disabledField prop equals 'foo', without having to pass 'foo' again.
const myTestObj = { fieldDisabled: 'foo' };
fieldDisabledIsFoo(myTestObject) // === true;
And then you might define checkers for your expected values giving you a single checker function for each separate expected value and you dont have to pass these expected values in each time, or create a whole bunch of identical code. Pretty cool hey?
const fieldDisabledIsFalse = fieldDisabledIs(false);
const fieldDisabledIsBar = fieldDisabledIs('bar');
const fieldDisabledIsHello = fieldDisabledIs('hello');
To your second question. It seems as if they are not doing the same check.
I cant see what the isEmpty function does but I imagine it is something like
(str) => str.isEmpty()
If this is the case then the false checker will return true if the string is empty
const fieldDisabledIsFalse = fieldDisabledIs(false);
const myTestObj = { fieldDisabled: '' };
fieldDisabledIsFalse(myTestObject) // === true;
If the function did not have both checks the above check would return false, as an empty string '' does not strictly equal false.

Every function with Object.values not working

I have an object and I need to check if all the values are true.
{
condition1: true,
condition2: true,
condition3: false
}
Ive used Object.value to get an array of the true and false values. However I cant seem to get the every function to work, it always returns true.
const test = Object.values(equipmentSelection)
.every((element) => {
if (element = true) return true;
});
Just return the element without using conditional check, you can do like this
const test = Object.values(equipmentSelection)
.every(element => element)
});
You are using an assignment operator = instead of a logical == or === operator. So you are basically setting element to be equal to true and then use this same value (true) as the condition of if. So the if condition is always true and thus true is returned for each element in the array.
Since element is of type boolean, you don't need the if statement, just use its value:
.every(element => element);
You can do this.
const test = Object.values(equipmentSelection)
.every(element => element===true);
And like others have said,
.every( element => element);
Will return the elements value which is with true or false and that’s what you will get with the comparisons.

javascript hash values validation

I'm trying to give the same behaviour to 4 values in my hash array.
For example:
var array = {};
if (array[key].config.tmp == undefined) {
array[key].config.tmp = {}
}
if(array[key].config.tmp.tp1){
}
if(array[key].config.tmp.tp2){
}
if(array[key].config.tmp.tp3){
}
if(array[key].config.tmp.tp4){
}
Since tp1, tp2, tp3 and tp4 will have the same behaviour. I would like to simplify the validation.
Something like:
array[key].config.tmp.[tp1,tp2,tp3,tp4] is possible? Already tried. but it was
tp1,tp2,tp3 and tp4 may not exist(undefined). (tp1 and tp2 only sometimes).
Any advice so I won't duplicate code?
Thanks in advance
You could also use a filter on the array keys:
if ( ( array[key].config.tmp || {} ).keys().filter(
function(k) { return /^tp[1234]/.test( k ) }
).length ) )
use a short-circuit operator like ||. for instance, if you are checking for the existence of multiple properties, accessing a property which doesn't exist is falsy.
var c = a[key].config.tmp.a || a[key].config.tmp.b || .... || //default
In this example, c will hold the value of the first of these to evaluate to true. You could also include a "Default" value at the end if they all return false. Keep in mind that accessing a property of a property that doesn't exist is a type error however, so you must be sure that at least config.tmp exists. So you can replace your code with
if (a[key].config.tmp.a || a[key].config.tmp.b || ....) {
}

Changing match to allow null input in javascript

I have some inherited code which is causing problems in Safari.
The problem comes from a few lines in the code that do things like this:
if ( ... && $("#element1").val().match(/regex/) && ...)
The javascript itself is programmatically generated.
The problem is that sometimes that $("#element1").val() returns null and I can't easily put a typeof check before it, because it needs to treat null as empty string.
The easiest (and manageable) solution would be either to create a nullmatch function and call that instead or to override the .match function itself. The new function would then check for null first and (if it is null) pass empty string to match instead of null.
I am not sure how to do either, or which would be best.
It would be better to either replace, or add to it (e.g.
$("element1").val().nullmatch(/regex/) or
$("element1").val().nullToEmpty().match(/regex/)
That isn't really possible, because .nullmatch or .nullToEmpty would need to be a method on a possibly null value.
If you really want to write in this fashion, or it's easier for your backend to generate, then you could write a mini-plugin:
$.fn.valNullToEmpty = function() { return this.val() || ''; }
$("element1").valNullToEmpty().match(/regex/)
You can use the || operator:
if ( ... && ($("#element1").val() || "").match(/regex/) && ...)
Basically, foo || "" will return foo if it's truthy, or the empty string if foo is falsy (false, undefined, null, empty string, +0, -0 or NaN).
How about...
function nullString(str) {
if (str === null) {
return "";
else {
return str;
}
So your if statement could become
if ( ... && nullString($("#element1").val()).match(/regex/) && ...)
The jQuery docs for val() state that it returns null when the element is select and no options are selected.
So using valHooks may help
var originalSelectHook;
if ($.valHooks.select) {
originalSelectHook = $.valHooks.select.get;
}
$.valHooks.select = {
get: function(elem) {
var index = elem.selectedIndex;
if (index == -1 || elem.options[index].disabled) {
return "";
}
else {
return originalSelectHook(elem)
}
};
Code assumes that there is a existing hook for select

Categories

Resources