find a cookie exists in the cookie string - javascript - 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")

Related

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.

Dynamically handle string and array in code

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;

How can I group similar URLs (with subdomain) in an array using JavaScript (or any of its libraries)

I have to convert this
['https://150sec.com/story-of-enigma'
,'https://www.google.co.in/search?q=hiccups'
,'http://10.1.4.128:3000/#/campaigns/new'
,'http://localhost:3000/'
,'https://www.youtube.com/watch?v=yydZbVoCbn0&t=170s'
,'https://150sec.com/how-to-play-a-paino/'
,'https://www.worldfree4u.lol/mahabharat-1988'
,'https://www.google.co.in/search?q=hello+world'
,'http://nthloop.github.io/bowerbird/'
,'https://pages.github.com/'
,'https://github.com/'
,'https://www.youtube.com/watch?v=vbydZb23432t=170s'
,'http://localhost:2000/']
into
[
['https://150sec.com/story-of-enigma',
'https://150sec.com/how-to-play-a-paino/'],
['https://www.google.co.in/search?q=hiccups',
'https://www.google.co.in/search?q=hello+world'],
['http://10.1.4.128:3000/#/campaigns/new'],
['http://localhost:3000/'],
['https://www.youtube.com/watch?v=yydZbVoCbn0&t=170s',
'https://www.youtube.com/watch?v=vbydZb23432t=170s'],
['https://www.worldfree4u.lol/mahabharat-1988'],
['http://nthloop.github.io/bowerbird/',
'https://pages.github.com/',
'https://github.com/']
]
I know, it awkward to directly ask for a solution, but I have tried a lot of things like this.
As you want to group them only by the hostname (incl. port) without the domain, you need to extract it first. Rest of it it pretty straightforward.
const inputs = ['https://150sec.com/story-of-enigma', 'https://www.google.co.in/search?q=hiccups', 'http://10.1.4.128:3000/#/campaigns/new', 'http://localhost:3000/', 'https://www.youtube.com/watch?v=yydZbVoCbn0&t=170s', 'https://150sec.com/how-to-play-a-paino/', 'https://www.worldfree4u.lol/mahabharat-1988', 'https://www.google.co.in/search?q=hello+world', 'http://nthloop.github.io/bowerbird/', 'https://pages.github.com/', 'https://github.com/', 'https://www.youtube.com/watch?v=vbydZb23432t=170s', 'http://localhost:2000/'];
const results = inputs.reduce((a, x) => {
const hostparts = new URL(x).host.split('.');
let host;
if (hostparts.length < 3) {
host= hostparts.shift();
} else {
host= hostparts.slice(1, hostparts.length - 1);
}
if (a[host]) {
a[host].push(x);
} else {
a[host] = [x];
}
return a;
}, {});
console.log(Object.values(results));
Keep in mind that this solution is for modern browsers only.
This should put you on the right track, it uses
array.prototype.reduce
array.prototype.find
array.prototype.findIndex
string.prototype.includes
URL
const data = ['https://150sec.com/story-of-enigma','https://www.google.co.in/search?q=hiccups','http://10.1.4.128:3000/#/campaigns/new','http://localhost:3000/','https://www.youtube.com/watch?v=yydZbVoCbn0&t=170s','https://150sec.com/how-to-play-a-paino/','https://www.worldfree4u.lol/mahabharat-1988','https://www.google.co.in/search?q=hello+world','http://nthloop.github.io/bowerbird/','https://pages.github.com/','https://github.com/','https://www.youtube.com/watch?v=vbydZb23432t=170s','http://localhost:2000/'];
let result = data.reduce((group, current) => {
if (group.length === 0) {
group.push([current])
return group;
}
let url = new URL(current);
let index = group.findIndex(val => {
let test = val.find(local => (local.includes(url.host)));
if (test === undefined) { return false }
return true;
});
if (index < 0) { return [ ...group, [current] ] }
group[index].push(current);
return group;
}, []);
console.log(result);
You can use .map(), .filter(), URL() and RegExp to check the .origin of the current URL
let res = urls.map(url =>
urls.filter(curr =>
new RegExp(newURL(url).origin.split(/http:|https:|\/|\.\w+$/)
.filter(Boolean).join("|"))
.test(new URL(curr).origin))
);

Searching for items in a JSON array Using Node (preferably without iteration)

Currently I get back a JSON response like this...
{items:[
{itemId:1,isRight:0},
{itemId:2,isRight:1},
{itemId:3,isRight:0}
]}
I want to perform something like this (pseudo code)
var arrayFound = obj.items.Find({isRight:1})
This would then return
[{itemId:2,isRight:1}]
I know I can do this with a for each loop, however, I am trying to avoid this. This is currently server side on a Node.JS app.
var arrayFound = obj.items.filter(function(item) {
return item.isRight == 1;
});
Of course you could also write a function to find items by an object literal as a condition:
Array.prototype.myFind = function(obj) {
return this.filter(function(item) {
for (var prop in obj)
if (!(prop in item) || obj[prop] !== item[prop])
return false;
return true;
});
};
// then use:
var arrayFound = obj.items.myFind({isRight:1});
Both functions make use of the native .filter() method on Arrays.
Since Node implements the EcmaScript 5 specification, you can use Array#filter on obj.items.
Have a look at http://underscorejs.org
This is an awesome library.
http://underscorejs.org/#filter
edited to use native method
var arrayFound = obj.items.filter(function() {
return this.isRight == 1;
});
You could try find the expected result is using the find function, you can see the result in the following script:
var jsonItems = {items:[
{itemId:1,isRight:0},
{itemId:2,isRight:1},
{itemId:3,isRight:0}
]}
var rta = jsonItems.items.find(
(it) => {
return it.isRight === 1;
}
);
console.log("RTA: " + JSON.stringify(rta));
// RTA: {"itemId":2,"isRight":1}
Actually I found an even easier way if you are using mongoDB to persist you documents...
findDocumentsByJSON = function(json, db,docType,callback) {
this.getCollection(db,docType,function(error, collection) {
if( error ) callback(error)
else {
collection.find(json).toArray(function(error, results) {
if( error ) callback(error)
else
callback(null, results)
});
}
});
}
You can then pass {isRight:1} to the method and return an array ONLY of the objects, allowing me to push the heavy lifting off to the capable mongo.

Dynamic arrays in Javascript/JQuery

Why does my array length always come out to 0 even though var email is equal to a string. (I've alerted out var email and the data is there).
var emails = new Array();
//get all the emails
$('.emailBox input').each(function (i)
{
var email = $(this).val();
if(email != '')
{
emails[email] = email;
alert(emails.length);
}
});
Because you're adding a property to the array.
var a = [];
a.foo = 42;
a.length === 0; // true
Instead try
emails.push(email);
This is the same as emails[emails.length] = email
As an aside:
var emails = new Array();
Is bad. You should be using [] instead of new Array() mainly because it's more terse and readable.
if (email != '') {
The above can be replace with if (email) { in case jQuery ever returns undefined or null
To make the entire code more elegant you should use
var emails = $('.emailBox input').map(function() {
return this.value;
}).filter(function (k, v) { return v; }).get();
Or without jQuery
var emails = [].map.call(document.querySelectorAll(".emailBox input"), function (v) {
return v.value;
}).filter(function (v) { return v; });
Although you'll need a QSA shim and a ES5 shim for legacy platform support.
Edit:
If you want the array to be unique then reduce it.
var arr = arr.reduce(function (memo, val, key, arr) {
// if the first index of the value is the index then add it.
// if the first index is different then we already have it.
if (arr.indexOf(val) === key) {
memo.push(val);
}
return memo;
}, []);
You could do all of that using a few jQuery methods.
var emails = $('.emailBox input')
.map(function() { return $(this).val() || null; })
.get();
jsFiddle.
emails[email] = email isn't doing what you want it to do. Try
emails.push(email);

Categories

Resources