Dynamically handle string and array in code - javascript

Datatype of stack id either can be an array or a string.
In the below code stack[0].id is Array and stack[1].id is string.
Issue is stackConfig is undefined when id is returned as array.
How do i handle this dynamically?
let stack = [{id:['stack1','stack2']},{id:'stack2'}]
let stackConfig = this.stackConfigs.find(c => c.id === selectionId);

You could try something like this:
let stack = [{id:['stack1','stack3']},{id:'stack2'},{id:'stack4'}]
let selectionId = 'stack2';
let stackConfig = stack.find(c => {
if(Array.isArray(c.id)) { if (c.id.indexOf(selectionId) != -1) return true;}
else { return c.id === selectionId }
return false;
});
console.log(stackConfig);

The first thing you should do is check whether c.id === selectionId is true at any point. This might never be true, hence why it is undefined.
You could try to handle having the selectionId also undefined as follows:
if (c.id.indexOf(selectionId) != -1) return true;

Related

Check all values in && comparison?

JavaScript is known to only check the first variable in a && comparison in case the first variable returns false. Is there a way to 'ask' JavaScript to check both variables i.e. when they are methods?
For example: Suppose you have 2 methods that validate 2 separate user inputs:
const validateEmail = value => {
if(value.contains('#')){
setShowEmailError(false);
return true;
}
setShowEmailError(true);
return false;
};
const validatePswd = value => {
if(value !== ''){
setShowPswdError(false);
return true;
}
setShowPswdError(true);
return false;
};
Then check both conditions:
if(validateEmail(email) && validatePswd(pswd)){
//validate entire form and render errors
}
However, the above will not execute the validatePswd method if the first method validateEmail returns false.
Is there a way to check if both values are true and run both methods? Having JavaScript run both methods would be a breeze in some cases.
You can execute them in an array and then accumulate the result with && by reduce function.
const validateEmail = value => {
if(value.includes('#')){
//setShowEmailError(false);
return true;
}
//setShowEmailError(true);
console.log('wrong email')
return false;
};
const validatePswd = value => {
if(value !== ''){
//setShowPswdError(false);
return true;
}
// setShowPswdError(true);
console.log('wrong password');
return false;
};
// you can execute any number of validations within the array.
const result = [validateEmail('something'), validatePswd('')].reduce((acc, f) => acc && f, true);
console.log(result)
UPDATE
Or as #lux suggested using every method.
const validateEmail = value => {
if(value.includes('#')){
//setShowEmailError(false);
return true;
}
//setShowEmailError(true);
console.log('wrong email')
return false;
};
const validatePswd = value => {
if(value !== ''){
//setShowPswdError(false);
return true;
}
// setShowPswdError(true);
console.log('wrong password');
return false;
};
// you can execute any number of validations within the array.
const result = [validateEmail('something'), validatePswd('')].every(r => r);
console.log(result)
I don't know if you are looking for something like this:
const valEmail = validateEmail(email);
const valPsw = validatePswd(pswd);
if(valEmail && valPsw ){
//validate entire form and render errors
}

Checking existing array have given value or not

In following code i have define empty array houseTotal, now I would like to push value inside array which is unique and not exist previously. I have use some, unique, sort filter but its pushing all the value it gets. Here is my code:
let houseTotal = [];
await rel.map((each, index) => {
if (
!isEmpty(each.house_detail) ||
!houseTotal.some(el => el === each.house_detail._id)
) {
houseTotal.push(each.house_detail._id);
}
});
return houseTotal.length;
What I have done mistake here ? Thank you.
If houseTotal is to have UNIQUE values and no duplicates.. I'm going to assume "duplicates" can be == each other and I'll use the Array.includes function
let houseTotal = [];
await rel.map((each, index) => {
if (
!isEmpty(each.house_detail) ||
!houseTotal.some(el => el === each.house_detail._id)
) {
let detail=each.house_detail._id
if(!houseTotal.includes(detail)){houseTotal.push(detail);}
}
});
return houseTotal.length;
And I got the solution, it was small mistake I have made on above code, I forgot to change object id returning from mongo to string so just added toString().
let houseTotal = [];
await rel.map((each, index) => {
if (
!isEmpty(each.house_detail) ||
!houseTotal.some(el => el === each.house_detail._id.toString())
) {
houseTotal.push(each.house_detail._id.toString());
}
});
return houseTotal.length;

find a cookie exists in the cookie string - javascript

i need to find a cookie name is available or not in the cookie string , i have achieved this, we can use cookie-parser but i don't want to use the package so i have written the below code ,can i reduce the code in a better way more optimised ?
function checkCookie(cookie, cookieToBeSearched){
if(cookie === "" || cookie === undefined){
return false
}
let res = cookie.split(";").some(cookie => {
let eachCookie = cookie.split("=");
return eachCookie[0].trim() === cookieToBeSearched
});
return res;
}
let cookie = "_ga=GA1.2.2091695351.1539084164; __qca=P0-338702612-1539084164095; __gads=ID=770d92bcdac8de40:T=1539084164:S=ALNI_MbsRKpoSJdn8tsdShMHMZUAR17uZA; _gid=GA1.2.798724103.1539582973";
console.log("Cookie is available - ", checkCookie(cookie, "_gid"))
console.log("Cookie is available - ", checkCookie(cookie, "_giddd"))
The regular expression is a nice solution.
function getCookie(name) {
var exp = new RegExp('[; ]'+name+'=([^\\s;]*)');
var matchs = (' '+document.cookie).match(exp);
if (matchs) return matchs[1];
return false;
}
Why don't you use
if (document.cookie.indexOf('cookie_name') > -1 ) {
//alert("cookie exists");
return true
}
Its simple!
You can avoid explicitly checking cookie value for "" and undefined. You can also splitting the string on =.
function checkCookie(cookie, cookieToBeSearched){
if(!cookie){
return false
}
let res = cookie.split(";").some(cookie => {
let cookieReg = new RegExp('^'+cookieToBeSearched+'=')
return cookie.trim().match(cookieReg)
});
return Boolean(res);
}
let cookie = "_ga=GA1.2.2091695351.1539084164; __qca=P0-338702612-1539084164095; __gads=ID=770d92bcdac8de40:T=1539084164:S=ALNI_MbsRKpoSJdn8tsdShMHMZUAR17uZA; _gid=GA1.2.798724103.1539582973";
console.log("Cookie is available - ", checkCookie(cookie, "_gid"))
console.log("Cookie is available - ", checkCookie(cookie, "_giddd"))
By converting the string as an object, we can use an Object/Hashmap to quickly find the corresponding value of key, rather than iterate over the array when we need to find the value of the key.
Therefore, we can leverage O(1) for finding in hashmap rather than O(N) by iterating over the array.
const cookies = (key, cookie = document.cookie) => {
if (!cookie) return;
return cookie.split(";").reduce((acc, item) => {
item ? acc[item.split('=')[0].trim()] = item.split('=')[1] : null;
return acc;
}, {})
}
cookies("key")

boolean check is not working in NodeJS

I am developing the node js API and I a querying data by the URL
get_posts_default?pageId=ge4JqBn9F0srzHnVFHmh&asking_post=false&asking_responce=false&maxSort=-1&minSort=-1&limit=20
This is the function who is responsible for handling this request
public async get_poset_list(userDeta: hs_I_fb_en_user_auth_paylode,pageId:string,asking_post:boolean,asking_responce:boolean,maxSort:number,minSort:number,limit:number):Promise<hs_I_fb_en_post_return[]>{
try {
hs_d_w("Is asking post: - "+asking_post);
hs_d_w("Limit: - "+limit);
if(asking_post===true){
hs_d_w("Asking post true");
if(minSort<=-1 && maxSort<=-1){
hs_d_w("Asking post Defolt");
return this._postQueryes.get_only_poses(pageId,limit);
}else{
if(minSort>-1){
hs_d_w("Asking post MIn");
return this._postQueryes.get_only_poses_min(pageId,minSort,limit);
}
if(maxSort>-1){
hs_d_w("Asking post Max");
return this._postQueryes.get_only_poses_max(pageId,maxSort,limit);
}
hs_d_w("Asking post None");
return [];
}
}else{
if(minSort<=-1 && maxSort<=-1){
hs_d_w("Asking talk Defolt");
return this._postQueryes.get_only_talkes(pageId,limit);
}else{
if(minSort>-1){
hs_d_w("Asking talk min");
return this._postQueryes.get_only_talkes_min(pageId,minSort,limit);
}
if(maxSort>-1){
hs_d_w("Asking talk max");
return this._postQueryes.get_only_talkes_max(pageId,maxSort,limit);
}
hs_d_w("Asking talk none");
return [];
}
}
} catch (e) {
hs_d_w("get_poset_list : " + e);
return Promise.reject(e)
}
}
Now if I call set asking_post=false or asking_post=true it allways call the main else area of this function
return this._postQueryes.get_only_talkes(pageId,limit);
This one.
I don't understand why it's happening? Can anyone please help me on this?
When you get something from the req.query it will always return a String. So, make sure to convert it to boolean using
const variable = (variable == 'true')
// or
const variable = (variable === 'true')
On a side note, when a variable is boolean you don't have to check explicitly with ===. This will also work
if(foo) {
} else {
}
EDIT: as #Kamalakannan said Boolean('string') will not work. My apologies.
Query params are considered as strings. So if you check with ===, it will be falsy.
Do string comparison, like if ("true" === asking_post) or if ("false" === asking_post)
Boolean(asking_post) will always return true for string values
const t = Boolean("true");
const f = Boolean("false");
console.log("Value of 'true':", t);
console.log("Value of 'false':", f);
So don't use Boolean(asking_post).
You can simply convert it with JSON.parse.
const x = JSON.parse('true');
const y = JSON.parse('false');
It will return boolean values for both.
When you get any values from request you always get String type.
So you need to convert it into Boolean first. Or just check with String.
You can do this: (I personally preferred)
var isTrue = (asking_post == 'true');
But please be caution to use following method:
var isTrue = Boolean("false"); // return true
var isTrue = !!"false"; // return true
Any string which is not empty will give you true by using the above methods.

How do I ensure an array has no null values?

I would like test my Array (input value) before submit my form.
My array with value :
const fields = [
this.state.workshopSelected,
this.state.countrySelected,
this.state.productionTypeSelected,
this.state.numEmployeesSelected,
this.state.startAt
];
I've try this :
_.forEach(fields, (field) => {
if (field === null) {
return false;
}
});
alert('Can submit !');
...
I think my problem is because i don't use Promise. I've try to test with Promise.all(fields).then(());, but i'm always in then.
Anyone have idea ?
Thank you :)
The problem is that even though you're terminating the lodash _.forEach loop early, you don't do anything else with the information that you had a null entry.
Instead of lodash's _.forEach, I'd use the built-in Array#includes (fairly new) or Array#indexOf to find out if any of the entries is null:
if (fields.includes(null)) { // or if (fields.indexOf(null) != -1)
// At least one was null
} else {
// All were non-null
alert('Can submit !');
}
For more complex tests, you can use Array#some which lets you provide a callback for the test.
Live example with indexOf:
const state = {
workshopSelected: [],
countrySelected: [],
productionTypeSelected: [],
numEmployeesSelected: [],
startAt: []
};
const fields = [
state.workshopSelected,
state.countrySelected,
state.productionTypeSelected,
state.numEmployeesSelected,
state.startAt
];
if (fields.indexOf(null) != -1) {
console.log("Before: At least one was null");
} else {
console.log("Before: None were null");
}
fields[2] = null;
if (fields.indexOf(null) != -1) {
console.log("After: At least one was null");
} else {
console.log("After: None were null");
}
You do not need to use promises unless there is an asynchronous operation (for example if you are getting that array from your server).
If you already have that array you can do something like:
// Using lodash/underscore
var isValid = _.every(fields, (field) => (field!==null)}
// OR using the Array.every method
var isValid = fields.every((field)=>(field!==null))
// Or using vanilla JS only
function checkArray(array){
for(var i = 0; i < array.length ; i ++){
if(array[i]===null){
return false;
}
}
return true;
}
var isValid = checkArray(fields);
// After you get that value, you can execute your alert based on it
if(!isValid){
alert('Something went wrong..');
}
Try this simple snippet
var isAllowedToSubmit = true;
_.forEach(fields, (field) => {
if (!field) {
isAllowedToSubmit = false;
}
});
if(isAllowedToSubmit)
alert('Can submit !');
You can do that without library:
if (fields.some(field => field === null)) {
alert('Cannot submit');
} else {
alert('Can submit');
}
You don't need to use lodash, you can do this in simple vanilla javascript. Simply iterate over each field and if an error occurs set your errors bool to true
let errors = false;
fields.forEach(field) => {
if(field === null || field === '') {
errors = true;
}
});
if (!errors) {
alert('Yay no errors, now you can submit');
}
For an es6 you can use.
const hasNoError = fields.every((field, index, selfArray) => field !== null);
if (!hasNoError) {
alert('yay It works');
};
Have a look at Array.every documentation Array every MDN documentation

Categories

Resources