Node js. How to understand s1 = s2 === s3 and s1 && s2?

Viewed 162

I am trying to fix code, but I stopped at two rows of code that are so weird I can't understand them. All rows:

//Extraction of urls
let f = !this.last_product_url
for(const productLink of productLinks) {
    const url = await productLink.getAttribute('href')

    if(!f) {
        f = url === this.last_product_url
        f && productUrls.push(url)
    }
    else {
        productUrls.push(url)
    }
}

What are these two rows do:

f = url === this.last_product_url
f && productUrls.push(url)
6 Answers

f = url === this.last_product_url will assign the result of url === this.last_product_url to f.

f && productUrls.push(url) is same as below:

if(f) productUrls.push(url)

The two lines are doing

f = (url === this.last_product_url);
if (f) {
  productUrls.push(url);
}

The loop body could be clarified by writing

let f = !this.last_product_url;
for (const productLink of productLinks) {
    const url = await productLink.getAttribute('href')

    if (!f) {
        f = (url === this.last_product_url);
    }
    if (f) {
        productUrls.push(url);
    }
}

But what this weird f flag really does is to take all urls from productLinks after the one where url === this.last_product_url. So the whole thing should probably be written as

const allProductUrls = await Promise.all(productLinks.map(productLink =>
    productlink.getAttribute('href');
));
const lastIndex = this.last_product_url 
  ? allProductUrls.indexOf(this.last_product_url)
  : 0;
if (lastIndex > -1) {
    productUrls.push(...allProductUrls.slice(lastIndex));
}

Syntactically, this is what happens:

f = url === this.last_product_url:

Check for strict equality between variables url and this.last_product_url and assign to f.


f && productUrls.push(url):

If f is true, push url to productUrls.

This works as follows. The statement A && B is evaluated, but B is only checked if A is true, since if A is false, A && B is never true. Thus, if A is true, then B is checked: the url is pushed.

f = url === this.last_product_url
f && productUrls.push(url)

These two lines of code are compact way of representing below logic:

if(url === this.last_product_url){
      productUrls.push(url);
}

f = url === this.last_product_url is equivalent to

if (url === this.last_product_url) {
 f = true;
} else {
 f = false;
}

And

f && productUrls.push(url) is equivalent to

if (f) {
 productUrls.push(url)
}

f = url === this.last_product_url -> f = (url === this.last_product_url) -> returns boolean value based on url and this.last_product_url comparison

f && productUrls.push(url) -> push function will be called only when f is true -> if(f) { productUrls.push(url) }

Related