Find if cookie name exists in the cookie string I need to determine whether a cookie name is available or not in the cookie string. I have achieved this. We could use the cookie-parser package but I don't want to use that package so I have written the below code. Can I reduce the code in a better way that is more optimised?


    function checkCookie(cookie, cookieToBeSearched){
                if(cookie === "" || cookie === undefined){
                    return false
                }
                let res = cookie.split(";").some(cookie =&gt; {
                    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"))
Option 1: Same functionality, smaller size


  Can I reduce the code in a better way more optimised?


If you want to optimize for size, then here's a suggestion for a more compact version:

function checkCookie(cookies, name) {
    return (cookies || '')
        .split(/;\s*/)
        .some(cookie =&gt; cookie.split('=', 1)[0] === name)
}    



(cookies || '') produces the same function result as the original if(…) return false
split uses a regular expression that matches the space after the semicolon, saving the trim in the lines below
the assignments for eachCookie and res can be removed, leading to a single line some call


Benefits: short &amp; concise

Limitations: only checks for existence of a cookie, not its value

Option 2: More versatility, similar size

There is an opportunity for a different design that allows for more generic use cases: you can first parse the cookie string into a plain object and then check for the existence of the cookie in question.

function parseCookie(cookie) {
    return (cookie || '')
        .split(/;\s*/)
        .reduce((result, entry) =&gt; {
            const [key, value] = entry.split('=', 2)
            result[key] = value
            return result
        }, {})
}

function checkCookie(cookies, name) {
    return Boolean(parseCookie(cookie)[name])
}


Granted, this a solution may be a bit "slower" than the original implementation. This shouldn't be an actual issue unless you intend to parse millions of cookie strings and time is a constraint.

What you gain in return though is a lean, readable, reusable function that lets you check for the existence of a cookie and in addition can also return the cookie’s value.

Benefits: check for cookie existence and get values; faster than original solution when checking multiple cookies

Limitations: no savings in size

Option 3: Universal key-value parser, a bit larger

The above solution is based on code that I use to parse URL query strings. Both cookie- and query strings are key-value pairs, except cookies use a semicolon ; as a separator, while query strings use an ampersand &amp;. If we adapt our function to accept the separator and equals sign as (optional) parameters, we can parse query strings and cookies with the same function:

function parseValues(cookie, sep, eq) {
    sep = sep || /;\s*/
    eq = eq || '='

    return (cookie || '')
        .split(sep)
        .reduce((result, entry) =&gt; {
            const [key, value] = entry.split(eq, 2)
            result[key] = decodeURIComponent(value)
            return result
        }, {})
}

function parseCookies(cookies) {
    return parseValues(cookies)
}

function parseQuery(query) {
    return parseValues(query, '&amp;')
}

function checkCookie(cookies, name) {
    return Boolean(parseCookie(cookie)[name])
}


Option 4: Consider using libraries

I understand that you wanted to write your own function as opposed to introducing cookie-parser, which does a lot more than what you actually need - especially signing &amp; signature verification - and is thus larger in size than what you aim for.

Other options would be cookie or lightcookie, which are smaller in size and might be a good choice over writing your own function. 

const lightcookie = require('lightcookie')

function checkCookie(cookies, name) {
    return Boolean(lightcookie.parse(cookies)[name])
}


Benefits: save time; avoid mistakes; benfit from tested &amp; verified code

Limitations: can be larger than what you are willing or able to include