Find the minimum number of items that covers all the words [closed]

Consider the data object like (note its just an example, actual data is quite large)

data = [
    { id: 1, d: ['a', 'b', 'c', 'd', 'e'] },
    { id: 2, d: ['f', 'g', 'h', 'i', 'j', 'a', 'b'] },
    { id: 3, d: ['e', 'a', 'b', 'c', 'd', 'a', 'i'] },
    { id: 4, d: ['e', 'f', 'g', 'h', 'i'] },
    { id: 5, d: ['f', 'g', 'a', 'b', 'c'] },
]

I need to find the min. best items from data, so it covers all the unique d items.
This data set is from a-j, so in the above case the results is items having id: 1,4.

React OnClick Event behavior is unexpected

Product Card

function ProductCard ({image, name, stats, id}){

    let dispatch =  useDispatch()
    let quantity = 1

    return (
        <>
        <div className="product-card">
                <div className="product-image-wrapper">
                    <img src={image} alt="" />
                </div>
                <div className="image-metadata">
                    <div className="data-wrapper">
                        <div className="product-details">
                            <div className="product-category">{stats.category}</div>
                            <div className="product-name">{name}</div>
                        </div>
                        <div className="action-btn-wrapper">
                            <div className="add-to-cart" onClick={()=>{
                                    dispatch(addToCart({name,image,stats,id,quantity}))
                                }
                            }>
                                <img src={addToCartIcon} alt="" />
                            </div>
                        </div>
                    </div>
                </div>
                
            </div>
        </>
    )
}

CART Component

import React, { useEffect } from "react";
import Header from "../components/header";

import Footer from "../components/footer";
import Checkout from "../components/checkout";

import { useSelector } from "react-redux";


function Cart (){
    let cartCount = useSelector(state => state.cart.cart)
    
    useEffect(()=>{
        document.title  = `TRAX- Cart(${cartCount.length} Items)`
    },[cartCount])
    return (
        <>
            <Header/>
            <Checkout/>
            <Footer/>
        </>
    )
}

export default Cart;

Checkout Component

import React from "react";
import cartImage from '../assets/website-icons/9026048_shopping_cart_simple_icon.svg'
import productImage from '../assets/featured/chair-model.jpg'
import arabicImage from '../assets/featured/arabic-model.jpg'

import { useSelector } from "react-redux";
import CartItem from "../widgets/cartItem";


function Checkout(){
    let cartCount = useSelector(state => state.cart.cart)
    return (
        <div className="cart-wrapper">
                <div className="cart-page-icon">
                    <div className="icon-container">
                        <img src= {cartImage} alt="Shopping Cart Icon" />
                        {/* CART */}
                    </div>
                </div>
                <div className="mini-slogan-wrapper">
                    Shop for upto $200 to enjoy<span>FREE SHIPPING</span>.
                </div>

                <div className="cart-table-content">
                    <div className="cart-table">
                        <div className="table-cell header-cell">
                            <div className="table-col-1">Product</div>
                            <div className="table-col-2">Quantity</div>
                            <div className="table-col-3">Price</div>
                            <div className="table-col-4">Subtotal</div>
                        </div>
                        {
                            cartCount.map(({name,image,stats,id,quantity}) => {
                                return <CartItem id={id} productImage={image}  quantity={quantity} productStats={{category : stats.category, color : stats.color}} productName={name}/>
                            })
                        }
                        {/* <div className="table-cell">
                            <div className="table-col-1">
                                <div className="product-entry">
                                    <div className="product-image">
                                        <img src={productImage} alt="" />
                                    </div>
                                    <div className="product-description">
                                        <div className="product-name">Sunny T-Shirt Merch By Zomato</div>
                                        <div className="product-extras">Color: Red, Size : XL, Fabric : Cotton</div>
                                        <div className="product-remove-btn">Remove</div>
                                    </div>
                                </div>
                            </div>
                            <div className="table-col-2">
                                <div className="quantity-adjuster">
                                    <div className="decrementor">
                                        <img src={decrementor} alt="" />
                                    </div>
                                    <div className="quantity-value">1</div>
                                    <div className="incrementor">
                                        <img src={incrementor} alt="" />
                                    </div>
                                </div>
                            </div>
                            <div className="table-col-3">$300</div>
                            <div className="table-col-4">$300</div>
                        </div>
                        <div className="table-cell">
                            <div className="table-col-1">
                                <div className="product-entry">
                                    <div className="product-image">
                                        <img src={arabicImage} alt="" />
                                    </div>
                                    <div className="product-description">
                                        <div className="product-name">Arabic Scarf - Embroidery Print</div>
                                        <div className="product-extras">Color: Mehroon, Size : Standard, Fabric : Linen</div>
                                        <div className="product-remove-btn">Remove</div>
                                    </div>
                                </div>
                            </div>
                            <div className="table-col-2">
                                <div className="quantity-adjuster">
                                    <div className="decrementor">
                                        <img src={decrementor} alt="" />
                                    </div>
                                    <div className="quantity-value">1</div>
                                    <div className="incrementor">
                                        <img src={incrementor} alt="" />
                                    </div>
                                </div>
                            </div>
                            <div className="table-col-3">$120</div>
                            <div className="table-col-4">$120</div>
                        </div> */}
                    </div>
                    <div className="checkout-container">
                        <div className="checkout-heading">
                            Cart Summary
                        </div>
                        <div className="selection-group">
                            <div className="selection-option">
                                <div className="selection-indicator-wrapper">
                                    <div className="selection-ball"></div>
                                </div>
                                <div className="selection-value">Regular Shipping</div>
                                <div className="selection-cost">$12.00</div>
                            </div>
                            <div className="selection-option">
                                <div className="selection-indicator-wrapper">
                                    <div className="selection-balls"></div>
                                </div>
                                <div className="selection-value">Express Shipping</div>
                                <div className="selection-cost">20.00</div>
                            </div>
                        </div>
                        <div className="checkout-secondary-row" id="checkout-subtotal">
                            <div className="heading-secondary-row">Subtotal</div>
                            <div className="cost-secondary-row">$420</div>
                        </div>
                        <div className="checkout-secondary-row" id="checkout-tax">
                            <div className="heading-secondary-row">Tax</div>
                            <div className="cost-secondary-row">$10</div>
                        </div>
                        <div className="checkout-total" id="checkout-total" >
                            <div className="heading-total">Total</div>
                            <div className="cost-total">$430</div>
                        </div>

                        <div className="checkout-btn">Checkout</div>
                    </div>
                </div>
        </div>
    )
}

export default Checkout;

Cart Item Component

import React from "react";
import decrementor from '../assets/website-icons/decrementor.svg'
import incrementor from '../assets/website-icons/incrementor.svg'
import { useDispatch } from "react-redux";
import { removeFromCart,incrementQty,decrementQty } from "../state-manager/Slices/cartSlice";


function CartItem ({productImage,productName, productStats,id,quantity}){
    let dispatch = useDispatch()
    return (
        <div className="table-cell">
            <div className="table-col-1">
                <div className="product-entry">
                    <div className="product-image">
                        <img src={productImage} alt="" />
                    </div>
                    <div className="product-description">
                        <div className="product-name">Sunny T-Shirt Merch By Zomato</div>
                        <div className="product-extras">Color:{productStats.color}, Size : XL, Fabric : Cotton</div>
                        <div className="product-remove-btn" onClick={()=>{
                            dispatch(removeFromCart({productImage,productName,productStats,id}))
                        }}>Remove</div>
                    </div>
                </div>
            </div>
            <div className="table-col-2">
                <div className="quantity-adjuster">
                    <div className="decrementor" onClick={()=>{
                        dispatch(decrementQty({id}))
                    }}>
                        <img src={decrementor} alt="" />
                    </div>
                    <div className="quantity-value">{quantity}</div>
                    <div className="incrementor" onClick={()=>{
                        dispatch(incrementQty({id}))
                    }}>
                        <img src={incrementor} alt="" />
                    </div>
                </div>
            </div>
            <div className="table-col-3">${300}</div>
            <div className="table-col-4">${quantity * 300}</div>
        </div>
    )
}

export default CartItem;

CardSlice

import { createSlice } from "@reduxjs/toolkit"

let CartSlice = createSlice({
    name : 'Cart',
    initialState : {
        cart : [],
        checkoutTotal : 0
    },
    reducers : {
        addToCart : (state,action)=>{
            
            if(state.cart.length < 1){
                state.cart = [...state.cart, action.payload]    
            }else {
                state.cart.map(item => {
                    if(item.id == action.payload.id){
                        item.quantity++;
                    }else {
                        state.cart = [...state.cart, action.payload]

                    }
                })
            }
        },
        removeFromCart : (state,action)=>{
            state.cart.map((item, index, cartItemArray) =>{
                if(item.id == action.payload.id){
                    let rar = cartItemArray.splice(index,1)
                    console.log(rar)
                }       
            })
            
        },
        incrementQty : (state,action)=>{
            state.cart.map(item =>{
                console.log(action.payload)
                if(item.id == action.payload.id){
                    item.quantity = item.quantity + 1
                }
            })
        }, 
        decrementQty : (state,action)=>{
            state.cart.map(item =>{
                
                if(item.id == action.payload.id){
                    if(item.quantity > 0){
                        item.quantity = item.quantity - 1
                    }else {
                        console.log('its already nulled out')
                    }
                }
            })
        }
    }
})

export default CartSlice.reducer
export const {addToCart,removeFromCart, incrementQty,decrementQty}  = CartSlice.actions

I’m using redux for state management, whenever I add to cart, upon the third click the cart count starts doubling up like from 2 to 4 and from 4 to 6 and so on, I have tried a lot and I can’t wrap my head around it. Please Let me know what am I doing wrong?

The issue where the drawable window cannot reach the far right of the screen when you reduce/increase the screen size

<html>
<style>
#bar {
  position: fixed; /* Fixed position to stay in place on scroll */
  top: 0;
  bottom: 0;
  left: 0;
  width: 3px; /* Initial width of the bar */
  background-color: #f1f1f1; /* Background of the bar */
  border-right: 1px solid #d3d3d3; /* Border of the bar */
  z-index: 9;
}

#handle {
  width: 100px; /* Diameter of the handle circle */
  height: 100px; /* Height of the handle circle */
  background-color: #2196F3;
  border-radius: 50%; /* Make it round */
  position: absolute; /* Absolute position within the bar div */
  top: 50%; /* Center it vertically */
  right: -3.125em; /* Align to the right of the bar */
  transform: translateY(-50%); /* Adjust vertical position */
  cursor: pointer; /* Change cursor to indicate it's draggable */
  z-index: 10;
  clip-path: inset(0 0 0 50%); /* Clip left half of the circle */
  background-image: url('https://i.gifer.com/2P5x.gif');
  background-repeat: no-repeat;
  background-size: 90% 100%; /* Width and height values */
  background-position: calc(100% +  0.625em) center; /* Move the image to the right by 10 pixels from the edge */
}

#handle.blue-bg {
    background-image: url('https://virtualisedreality.files.wordpress.com/2012/07/the-best-top-desktop-blue-wallpapers-blue-wallpaper-blue-background-hd-33.jpg');
    background-position-x: right;
}

</style>
<body>


<div id="bar">
  <!-- This is the draggable handle -->
  <div id="handle"></div>
</div>

<script>
// Make the handle draggable
dragElement(document.getElementById("handle"));

function dragElement(elmnt) {
  var startPosX = 0, currentPosX = 0;
  var maxBarWidth = window.innerWidth - (elmnt.offsetWidth / 16); // Tarayıcı penceresinin genişliğini kullanma , Set the maximum width for the bar.

  elmnt.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    startPosX = e.clientX;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
  e = e || window.event;
  e.preventDefault();
  currentPosX = e.clientX - startPosX;
  startPosX = e.clientX;
  var bar = document.getElementById("bar");
  var newWidth = bar.clientWidth + currentPosX;
  //console.log(`newWidth = ${bar.clientWidth} + ${currentPosX} = ${newWidth}`)
  
  // Define the minimum width to keep the handle from entering the bar area
  var minBarWidth = 3; // This is the initial width of the bar

  // Restrict the width within the minimum and maximum bounds
  newWidth = Math.max(minBarWidth, Math.min(newWidth, maxBarWidth));

  // Set the new width
  bar.style.width = newWidth + "px";

  var handle = document.getElementById("handle");

   // Adding or removing the 'blue-bg' class based on the handle's position
    if (newWidth >= maxBarWidth) {
        handle.classList.add('blue-bg');
    } else {
        handle.classList.remove('blue-bg');
    }

}

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
</script>

</body>
</html>

Greetings, when I reduce the size of the screen (such as 90 percent, 100 percent), the draggable window to the right cannot reach the right corner of the screen. It can reach an area such as the middle point of the screen.
In short, how can I ensure that the drawable window can reach the far right of the screen under all circumstances, whether the screen is zoomed in or out? What is the solution to this problem?

The problem:

enter image description here

Even if zoomed in or out, the view that is desired to appear under all circumstances when you pull the Handle to the far right:

enter image description here

Firebase Firestore Listener Not Unsubscribing

I have a Firebase Firestore listener function in my .api file below;

export function getRedemptionsListener(user_id, venue_id, callback) {
  const redemptions = [];
  firestore()
    .collection(`users/${user_id}/redemptions`)
    .where("venue.venue_id", "==", venue_id)
    .where("used", "==", true)
    .onSnapshot((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        redemptions.push({ id: doc.id, ...doc.data() });
      });
      callback(redemptions);
    });
}

I am calling it in my screen here;

  function getData() {
    Promise.all([getProfile(user.uid), getVenue(id), getOffers(id)])
      .then(([profile, venue, offers]) => {
        const isFavourite = profile?.favourites?.includes(id);
        setIsFavourite(isFavourite);
        setVenue(venue);
        const updatedOffers = matchOffers(offers, []);
        setOffers(updatedOffers);
        const subscriber = getRedemptionsListener(user.uid, id, (redemptions) => {
          setRedemptions(redemptions);
          const updatedOffersWithRedemptions = matchOffers(offers, redemptions);
          setOffers(updatedOffersWithRedemptions);
        });
        subscriber();
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        setLoading(false);
      });
  }

When I log out of my app function below;

return (
  <NavigationContainer theme={colorScheme === "light" ? DefaultTheme : DarkTheme}>
    {user ? <SignedInLayout /> : <AuthLayout />}
  </NavigationContainer>
);

I get the error;

Cannot read property forEach of null

from querySnapshot.forEach((doc) => {

I’m assuming this is because the listener is not being removed.

I have tried the below in my .api file but the listener doesn’t work in this case.

export function getRedemptionsListener(user_id, venue_id, callback) {
  const redemptions = [];
  const subscriber = firestore()
    .collection(`users/${user_id}/redemptions`)
    .where("venue.venue_id", "==", venue_id)
    .where("used", "==", true)
    .onSnapshot((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        redemptions.push({ id: doc.id, ...doc.data() });
      });
      callback(redemptions);
    });
    return subscriber();
}

Why isn’t the conditional class binding applied after state update in Next.js?

I am working on a mega menu in React (Next.js). I fetch the menu items from an API endpoint with AJAX call, the menu items are displayed. The first step would be that if I click on one of the menu items, the other menu items disappear, and the sub-menu items of the clicked menu item appear instead. For now, I’m stuck on the fact that I can’t remove the other menu items. I created a function that updates the state of “selectedItem” onClick event. So far it’s fine, the state update is happening. However, the conditional class binding does not work, the “renderMenuItems” function does not receive the updated state and therefore the element does not receive the “selected” class. How do I remove the other menu items afterwards is another question.

'use client';

import { css, cx } from '@/styled-system/css';
import Image from 'next/image';
import MainMenuActions from './mainMenuActions';
import MainMenuSearch from './mainMenuSearch';
import { useState, useEffect } from 'react';
import Hamburger from 'hamburger-react';
import IconSearchRegular from '@/components/icon/iconSearchRegular';
import IconChevronDownLight from '@/components/icon/iconChevronDownLight';
import { token } from '@/styled-system/tokens';

interface Props extends React.ComponentProps<'div'> {
  className?: string;
  topMenuIsOut: boolean;
}

interface MenuItem {
  title: string;
  href: string;
  newPage: boolean;
  childrens: MenuItem | MenuItem[];
}

export default function MainMenuBottom(props: Props) {
  const { className, topMenuIsOut } = props;

  const [searchIsOpen, setSearchIsOpen] = useState(false);
  const [hamburgerIsOpen, setHamburgerIsOpen] = useState(false);
  const [menuItems, setMenuItems] = useState<JSX.Element[]>([]); // Specify the type explicitly
  const [selectedItem, setSelectedItem] = useState<MenuItem | null>(null);

  const handleMenuItemClick = (clickedItem: MenuItem) => {
    setSelectedItem(clickedItem);
  };

  const renderMenuItems = (items: MenuItem[], selectedItem: MenuItem | null) => {
    return items.map((item) => (
      <li
        onClick={() => handleMenuItemClick(item)}
        className={`d-flex align-items-center ${selectedItem === item ? '' : 'test-class'}`}
        key={item.href}
      >
        {item.title}
        <IconChevronDownLight size={8} color={token('colors.metuYellow')} className={styles.bottomNavIcon} />
      </li>
    ));
  };

  useEffect(() => {
    fetch('https://www.myapiurl.com')
      .then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then((data: { 'main-menu': MenuItem[] }) => {
        const mainMenuItems = data['main-menu'];

        // Render main menu items
        setMenuItems(renderMenuItems(mainMenuItems, null));
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div className={cx(styles.mainMenuBottom, className, 'container')}>
      {searchIsOpen && (
        <div className={styles.bottomSearch}>
          <MainMenuSearch width="100%" placeholder="Kezdj el gépelni..." onClose={() => setSearchIsOpen(!searchIsOpen)} />
        </div>
      )}
      <div className={cx(styles.bottomNavWrapper, !topMenuIsOut ? styles.bottomNavWrapperFloating : undefined)}>
        <div className={cx(styles.bottomNavLogo, !topMenuIsOut && !searchIsOpen ? styles.bottomNavLogoFloating : undefined)}>
        </div>

        <ul className={cx(styles.bottomNav, !topMenuIsOut ? styles.bottomNavFloating : undefined)}>
          {menuItems.length > 0 && menuItems} {/* Render the dynamic menu items only when menuItems is not empty */}
        </ul>
      </div>
      <div className={styles.bottomIcons}>
        <MainMenuActions />
        <div className={styles.bottomIconSearch} onClick={() => setSearchIsOpen(!searchIsOpen)}>
          <IconSearchRegular size={16} />
        </div>
        <div className={styles.bottomIconHamburger}>
          <Hamburger size={26} toggled={hamburgerIsOpen} toggle={setHamburgerIsOpen} />
        </div>
      </div>
    </div>
  );
}

I would be really grateful for any help. Thank you in advance.

Arrow function VS Anonymous function with $(this) in jQuery [duplicate]

i have found this bug (or feature) during my coding:

if u use arrow function as handler for jQuery event then construction $(this) is not working inside this function.

I understand arrow and anonymous functions are different and in some cases they are not interchangeable, but how to explain this exact case?

here is code example https://codepen.io/wd3/pen/abxjyQG where u can see two similar blocks with arrow and anonymous functions

$(document).ready(()=>{
  // input1 - anonymous
  $('.input1').on('click', function(){
    $(this).removeClass('wrong')
    $('.input1').val(parseInt($('.input1').val()) + 1)
  })
  
  // input2 - arrow
  $('.input2').on('click', ()=>{
    $(this).removeClass('wrong')
    $('.input2').val(parseInt($('.input2').val()) + 1)
  })
  
  // input3 - arrow with currentTarget
  $('.input3').on('click', (e)=>{
    $(e.currentTarget).removeClass('wrong')
    $('.input3').val(parseInt($('.input3').val()) + 1)
  })
  
})

Coding challenge question regarding JavaScript

I am doing a coding course on codecademy and am currently stuck at a certain question within a coding challenge. I have received 3 JS files, two of which I should not modify in any way, as I was told that they are helper functions I should use and a file with an array of books. Question 2 is leaving me completely baffled. I have sat on it for a solid 2 hours now and although it works locally on vscode it gives me the same error message over and over. I would greatly appreciate any help because I am really frustrated. I will first send the introduction of the challenge and the first question for some added content:

Intro:
In the code editor, we have provided you with the starting code for a Book Finder website. Once the application is complete, you will be able to input a genre, title, or author into the search bar, and get back a list of books that match that criteria. You can see the list of books that your application will search in bookList.js.

Your task is to finish building the application by completing the function definitions for the captureSearchValue(), filterBooks(), structureBooksAsHtml(), and searchBtnClickHandler() functions. You should only make edits to these four function definitions within script.js. We’ve defined helper functions in helper.js that you will need to use as you build out your program.

Question 1:
The captureSearchValue function captures the search bar input value and returns it.

My code for the first question is correct according to them.

Question 2:
The filterBooks() function takes in a search string and a list of books as parameters and returns all of the books that contain an exact match of the search input as an array of objects. Objects in this array should be formatted as books with title, author, and tags properties, similar to the original books array. It should use the flattenObjectValuesIntoArray() function to search all fields within a book object easily.

The helper code:

// Flatten object keys into an array so that we search the entire object by the input value
const flattenObjectValuesIntoArray = (arrOfObjs) => {
  let flattenedObj;
  const flattenedObjsArr = [];
  for (let obj = 0; obj < arrOfObjs.length; obj++) {
    const objValues = Object.values(arrOfObjs[obj]);
    flattenedObj = [...objValues.flat()]
    flattenedObjsArr.push(flattenedObj)
  }
  return flattenedObjsArr;
};

// Structure filtered books as HTML and return
const structureBookAsHtml = (book) => {
  const bookDiv = document.createElement("div");
  bookDiv.setAttribute('class', 'bookDiv');
  
  const bookTitle = document.createElement("h2");
  bookTitle.innerHTML = book.title;
  bookTitle.setAttribute('class', 'bookTitle');

  const bookAuthor = document.createElement("h3");
  bookAuthor.innerHTML = book.author;

  const bookTags = document.createElement("p");
  bookTags.innerHTML = book.tags.join(", ");

  bookDiv.append(bookTitle, bookAuthor, bookTags);
  
  return bookDiv;
};

const renderBooksToDom = (elements) => {
  const bookListContainer = document.querySelector("#bookList");
  bookListContainer.innerHTML = "";

  bookListContainer.append(...elements);
};

The array file:

const books = [
  {
    title: "The City We Became",
    author: "N. K. Jemisin",
    tags: ["fantasy", "fiction", "afrofutursim", "science fiction", "sci-fi"]
  },
  {
    title: "The Catcher in the Rye",
    author: "J. D. Salinger",
    tags: ["fiction", "young adult", "YA", "realism", "coming of age", "classic"]
  },
  {
    title: "The Hundred Thousand Kingdoms",
    author: "N. K. Jemisin",
    tags: ["fantasy", "fiction", "adventure", "series"]
  },
  {
    title: "Sapiens: A Brief History of Humankind",
    author: "Yuval Noah Harari",
    tags: ["nonfiction", "history", "anthropology", "science", "sociology"]
  },
  {
    title: "Behave: The Biology of Humans at Our Best and Worst",
    author: "Robert M. Sapolsky",
    tags: ["nonfiction", "anthropology", "science", "sociology", "biology"]
  },
  {
    title: "The Parable of the Talents",
    author: "Octavia Butler", 
    tags: ["fiction", "dystopian", "science fiction"]
  },
  {
    title: "1984",
    author: "George Orwell", 
    tags: ["fiction", "dystopian", "science fiction", "classics", "adult"]
  },
  {
    title: "Remarkably Bright Creatures",
    author: "Shelby Van Pelt",
    tags: ["fiction", "mystery", "magical realism"]
  },
  {
    title: "Crying in H Mart",
    author: "Michelle Zauner",
    tags: ["memoir", "nonfiction", "autobiography"]
  },
  {
    title: "Wild: From Lost to Found on the Pacific Crest Trail",
    author: "Cheryl Strayed",
    tags: ["nonfiction", "memoir", "adventure", "travel"]
  }
]

The index.html:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="styles.css">
    <script src="bookList.js"></script>
    <script src="bookList.test.js"></script>
    <script src="helper.js"></script>
    <script src="script.js" defer></script>
  </head>
  <body>
    <h1>Book Finder</h1>
    <input id="search-bar" type="text" placeholder="Search for books by tags">
    <button class="btn" id="search-btn">Search</button>
    <div id="bookList">
      <!-- List of books will be rendered here -->
    </div>
  </body>
</html>

my code:

// Click handler for search button
let cap = document.getElementById('search-bar')
let capValue = cap.value;
const captureSearchValue = () => {
return cap.value
};

const filterBooks = () => {
  let flattenedArr =flattenObjectValuesIntoArray(books);
  let match = [];
  for (let i = 0; i < flattenedArr.length; i++) {
    for (let j = 0; j < flattenedArr[i].length; j++) {
      if (flattenedArr[i][j] === capValue){
        match.push(books[i])
      }
    }
  }; return match
  };

// Empty the book list container, iterate over list of filtered books, return list of books formatted as HTML using the function in `helper.js`
const structureBooksAsHtml = () => {};

// Handler triggered when a user clickers the "Search" button. Chains previously defined functions together to filter books based on the search value, formats the books as HTML and renders them to the DOM
const searchBtnClickHandler = () => {};

// Grab search button from the DOM

// Attach an event listener to the search button
searchBtn.addEventListener("click", () => {
  searchBtnClickHandler(books);
});

I am only at the filterBooks function, I have not reached the other functions yet so dont mind them.

This is the message i am getting for question 2 when i submit my answer:

Given the filter fantasy, your filterBooks function returned an array with 0 elements. We expected it to return 2.

I would greatly appreciate any help on this problem. It does not seem to make any sense to me

I think that the issue is related to the capvalue but I am honestly clueless

Are identifiers (ee.g. variables) stored in memory between route visits in a Next.js application?

This question builds on the following, where no clear and correct answer has been given at the time of writing: Do modules run multiple times upon import in a Next.js app?

Relevant Knowledge


  • How the JS runtime works: Understanding the JavaScript runtime environment
  • If a module is imported multiple times, but with the same specifier (i.e. path), the JavaScript specification guarantees that you’ll receive the same module instance (i.e. the body of a module is only executed once, upon the first import): What Happens When a Module Is Imported Twice?
  • An identifier is only kept in the JS heap (memory) for as long as it is directly, or indirectly via the environment record chain, attached to the global object. Simplified, identifiers are removed from memory when there is no code in the current script execution, or WebAPIs that it started, that can reach the identifier (it is out of all “scopes”): The Lifecycle of Memory in JavaScript
  • In a Next.js application, server components and client components run server-side when the application is built (next build), creating an HTML file and a React Server Component Payload (RSC Payload). These, alongside any client components, are sent to the browser: How are Server Components rendered? (it is not clear from the Next.js docs if the client components are sent separately, or if they are part of the RSC payload.)

Assumptions


  • The Next.js app in question is hosted on Vercel

Questions


  1. If a server component creates an identifier and assigns an object to
    it, is that object only available build-time? I am guessing the
    answer is yes if the route is static, as the server components
    only run build-time.

  2. If we now assume the route is dynamic, does the server component run every time the route is visited by a browser?

  3. If yes, are the variables somehow kept in memory (on the Vercel
    server), between each route visit?

Note


This question is general in nature, but stems from a desire to control database communication (for instance with the Prisma ORM). I would like to understand whether we create a new PrismaClient object, for instance, on each route visit.

Is it possible to access a privet s3 bucket using temporary AWS credentials from react native application

I have react native expo app. I need to access an image from privet s3 bucket without using pre-signed url.
Iam able to get temporary credentials for AWS with the help of AWS cognito identity pool.

1.Is it possible to access the image using these credentils with or without the help of cognito and without using pre-signed URI.
2.Can I can access the image with a static URI (permanent URI of a perticular image in s3).
3.Is there a better approach using AWS amplify

Iam able to get the image by initializing s3 and fetch it using getObject method. But it is slower than expected

How can a parent frame “interrupt” the `window.prompt` of a cross-origin isolated child frame?

(Please put aside the utility/inadvisability of window.prompt usage – that’s not what this question is about. I’m using this case to debug a broader issue of frame-frame interference.)


The cross-origin isolated child frame’s window.prompt is being “interrupted” (i.e. abruptly closed without user interaction) by some unknown code in a parent (or perhaps sibling) frame.

Things I know:

  • A frame can interrupt another cross-origin isolated frame’s prompt/alert/etc. by calling prompt/alert/etc. itself (regardless of parent/child relationship). The other frame’s prompt closes, and the new one appears in its place.
  • A parent frame can interrupt a cross-origin isolated child frame’s prompt/alert/etc. by navigating (i.e. window.location.reload(), window.location.href=...)
  • window.focus() does not interrupt another frame’s prompt/alert/etc.

This applies to Chrome Linux, Version 123.0.6312.105, at least. I’m not sure about other browsers. Unfortunately I’m not able to consistently reproduce instances of the “interruption” since I think the root cause is third-party ad code that is running in the parent frame, and it has only happened a couple of times over the course of a month.

I know that parent navigation and parent/sibling frame calls to prompt/alert/etc. are not the cause. The interruption happens without navigation or other prompts/alerts/popups/etc appearing. It just closes the iframe’s prompt, and that’s it.

An ideal answer to this question would simply give a list of tested/viable ways in which a cross-origin isolated parent or sibling frame could “interrupt” a frame’s prompt/alert/etc. – without causing a navigation or another prompt/popup/etc. to appear. There could be many causes, so the more possibilities listed, the better.

I suspect there could be behavioral differences between browsers on this issue, so answers that are only tested in Chrome are okay.

Thanks!

Xpath of element based only in text content?

I’m trying to get the xpath of the second button “buy” for this HMTL code, but without using class, id nor other attribute nor full Xpath, only the text content relative to it like in this examples . The code has 2 “ul” elements within a “div”. Each “ul” has 3 or 4 “li”. I want like this since the internal attributes chang, but the structure and text content remains.

My goal is have the Xpath of the second “Buy”, this is, the one related with the “li” that contains the text “Home”.

My attempts in Chrome console so far are like below, but is not working:

$x("//*[text()='Home']")
$x("//ul[text()='Home']")
$x("//*[text()='Home']/following-sibling::li")

In the image below I show it.

enter image description here

div {
    background-color:#eeeeee;
    display:inline;      
}

#ul li {
  display: grid;
    column-count: 4;
    column-gap: 20px;
    display: inline;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<div>
<ul>
    <li data-dqa-li="" data-components="xyzq-li" id="daw48" class="daw-view"><div data-components="xyzq-li-row" id="daw49" class="xyzq-list-item section-title daw-view"><div class="xyzq-list-column flex-width ">
                <div class="xyzq-list-item">
                    <div class="xyzq-list-column flex-width ">
                        <div class="xyzq-list-item inner-list-item " style="">
                            <div class="xyzq-list-column flex-width column-unshrink ">
                                <div class="xyzq-list-item">
                                    <div class="xyzq-list-column main-text section-title-text" dir="ltr" data-dqa-message="">
                                                Electronics
                                    </div>
                                </div>
                                <!----><!----><!----><!----></div>
                        </div>
                    </div>
                    <!----><!----></div>
            </div>
        </div></li>
    <li data-dqa-li="" data-components="xyzq-li" id="daw50" class="daw-view"><div data-components="xyzq-li-row" id="daw51" class="xyzq-list-item daw-view"><div class="xyzq-list-column flex-width fixed-width">
                <div class="xyzq-list-item">
                    <div class="xyzq-list-column flex-width ">
                        <div class="xyzq-list-item inner-list-item " style="">
                            <div class="xyzq-list-column flex-width column-unshrink ">
                                <div class="xyzq-list-item">
                                    <div class="xyzq-list-column main-text description-regular" dir="ltr" data-dqa-message="">
                                                Cameras
                                    </div>
                                </div>
                                <!----><!----><!----><!----></div>
                        </div>
                    </div>
                    <!----></div>
            </div>
            <div class="xyzq-list-column flex-width ">
                <div class="xyzq-list-item">
                    <div class="xyzq-list-column flex-width ">
                        <div class="xyzq-list-item inner-list-item " style="">
                            <div class="xyzq-list-column flex-width column-unshrink ">
                                <div class="xyzq-list-item">
                                    <div class="xyzq-list-column main-text bold-text description-regular" dir="ltr" data-dqa-message="">
                                                4K Front
                                    </div>
                                </div>
                                <!----><!----><!----><!----></div>
                        </div>
                    </div>
                    <!----><div class="xyzq-list-column column-unshrink button-column ">
                        <div data-components="xyzq-button" id="daw52" class="list-cam-narrow-button expand-taparea button daw-view"><button tabindex="0" class="secondary-button row-button text-button disabled-loading-caption" data-dqa-button="secondary" type="button"><span dir="ltr" class="caption">Buy</span></button>
                        </div>
                    </div>
                </div>
            </div>
        </div></li>

</ul>

<ul>
    <li data-dqa-li="" data-components="xyzq-li" id="daw48" class="daw-view"><div data-components="xyzq-li-row" id="daw49" class="xyzq-list-item section-title daw-view"><div class="xyzq-list-column flex-width ">
                <div class="xyzq-list-item">
                    <div class="xyzq-list-column flex-width ">
                        <div class="xyzq-list-item inner-list-item " style="">
                            <div class="xyzq-list-column flex-width column-unshrink ">
                                <div class="xyzq-list-item">
                                    <div class="xyzq-list-column main-text section-title-text" dir="ltr" data-dqa-message="">
                                                Home
                                    </div>
                                </div>
                                <!----><!----><!----><!----></div>
                        </div>
                    </div>
                    <!----><!----></div>
            </div>
        </div></li>
    <li data-dqa-li="" data-components="xyzq-li" id="daw50" class="daw-view"><div data-components="xyzq-li-row" id="daw51" class="xyzq-list-item daw-view"><div class="xyzq-list-column flex-width fixed-width">
                <div class="xyzq-list-item">
                    <div class="xyzq-list-column flex-width ">
                        <div class="xyzq-list-item inner-list-item " style="">
                            <div class="xyzq-list-column flex-width column-unshrink ">
                                <div class="xyzq-list-item">
                                    <div class="xyzq-list-column main-text description-regular" dir="ltr" data-dqa-message="">
                                                Appliances
                                    </div>
                                </div>
                                <!----><!----><!----><!----></div>
                        </div>
                    </div>
                    <!----></div>
            </div>
            <div class="xyzq-list-column flex-width ">
                <div class="xyzq-list-item">
                    <div class="xyzq-list-column flex-width ">
                        <div class="xyzq-list-item inner-list-item " style="">
                            <div class="xyzq-list-column flex-width column-unshrink ">
                                <div class="xyzq-list-item">
                                    <div class="xyzq-list-column main-text bold-text description-regular" dir="ltr" data-dqa-message="">
                                                Fans
                                    </div>
                                </div>
                                <!----><!----><!----><!----></div>
                        </div>
                    </div>
                    <!----><div class="xyzq-list-column column-unshrink button-column ">
                        <div data-components="xyzq-button" id="daw52" class="list-cam-narrow-button expand-taparea button daw-view"><button tabindex="0" class="secondary-button row-button text-button disabled-loading-caption" data-dqa-button="secondary" type="button"><span dir="ltr" class="caption">Buy</span></button>
                        </div>
                    </div>
                </div>
            </div>
        </div></li>
    <li data-dqa-li="" data-components="xyzq-li" id="daw53" class="daw-view"><button data-dqa-button="list" tabindex="0" data-components="xyzq-li-button-row" id="daw54" class="daw-view"><div class="xyzq-list-item ">
                <div class="xyzq-list-column flex-width ">
                    <div class="xyzq-list-item">
                        <div class="xyzq-list-column flex-width ">
                            <div class="xyzq-list-item inner-list-item " style="">
                                <div class="xyzq-list-column flex-width column-unshrink ">
                                    <div class="xyzq-list-item">
                                        <div class="xyzq-list-column main-text description-regular" dir="ltr" data-dqa-message="">
                                                Discount Code
                                        </div>
                                    </div>
                                    <!----><!----><!----><!----></div>
                            </div>
                        </div>
                        <div class="xyzq-list-column column-unshrink icon-drilldown " title="Select" data-dqa-img="drilldown"/>
                        <!----></div>
                </div>

            </div>
        </button></li>
</ul>



</div>
</body>
</html>

why is my higher order function returning true and false?

I have to create my own higher order filter() function to filter an array of 10 words that only returns word that have 6 or more letters but my function is only returning true and false and not omitting words that are not 6 or more letters instead of actually returning the words in a new array. Do add additional code to execute the function?

Also I am not allowed to use the built-in filter function.

const wordArray = ["mine", "script", "function", "array", "javascript", "python", "coding", "html", "css", "bye"];
//myFilterFunction(HOF) takes an array (arr) and hypothetical function (fn) as arguments//
let myFilterFunction = (arr) => (fn) => {
    const newArray = [];
    for (let i = 0; i < arr.length; i++) {
        newArray.push(fn(arr[i]));
    }
    return newArray; //return a array
};
//myFilterFunction is used with an anonymous function to return whether each word is 6 or more   letters//
const printArray = myFilterFunction(wordArray)((word) => word.length >= 6);
//Output the result to the console//
console.log("this array only contains words that are 6 letters or more: " + printArray);

Collision detection side

    // ball starting position
    ball.x = app.screen.width/2;
    ball.y = 400;

    // ball.x = app.screen.width/2;
    // ball.y = 400;

    // moving platfrom basic settings (position and anchor)
    smallPlatform.x = app.screen.width/2;
    smallPlatform.y = 770;
    smallPlatform.anchor.set(0.5);
    

    blueBlock.x = app.screen.width/2;
    blueBlock.y = 200;
    blueBlock.width = 60;
    blueBlock.anchor.set(0.5);

    
    // adding objects to the stage
    app.stage.addChild(background);
    app.stage.addChild(ball);
    app.stage.addChild(smallPlatform);
    app.stage.addChild(blueBlock);

    // collision detection func for ball and other objects
    const rectCircleCollide = function (target, ball) {    

        const distX = Math.abs(ball.x - target.x);
        const distY = Math.abs(ball.y - target.y);
        if (distX > target.width / 2 + ball.radius ||
            distY > target.height / 2 + ball.radius    ) {
            return false;    }
        if (distX <= target.width / 2 || distY <= target.height / 2) {
            return true;    }
        const dx = distX - target.width / 2;
        const dy = distY - target.height / 2;
        return dx * dx + dy * dy <= ball.radius * ball.radius;
    
    };


        if (rectCircleCollide(blueBlock, ball)) {

            if (ball.y-ball.radius <= blueBlock.y+blueBlock.height/2 || ball.y+ball.radius >= blueBlock.y-blueBlock.height/2) {
                ball.ySpeed = -ball.ySpeed;
            }if (ball.x+ball.radius >= blueBlock.x-blueBlock.width/2 || ball.x-ball.radius <= blueBlock.x-blueBlock.width/2) {
                ball.xSpeed = -ball.xSpeed;
            }
        }
        
        // Collision detection for left, right walls and top.
        if (ball.x+ball.radius >= app.screen.width-25 || ball.x-ball.radius <= 25) { 
            ball.xSpeed = -ball.xSpeed;
        }else if (ball.y-ball.radius <= 25) {
            ball.ySpeed = -ball.ySpeed;
        }else if (ball.y+ball.radius > app.screen.height) {
            ticker.stop();
            // ball.ySpeed = -ball.ySpeed;
        }

Making Arkanoid game using pixijs lib. I need to find the side from which the ball collided with the blueBlock and change the ball‘s direction accordingly. in my code, for some reason, the direction changes incorrectly. Please help me find the sollutin.

Issue with selecting specific dates in React Native

Iam using react-native-calendar-picker I want to enable users to select dates from a specific range of dates or a specific dates

I’ve been following the documentation, but I’m encountering some unexpected behavior.

     const [selectedDate, setSelectedDate] = useState(null); 
    const handleDateChange = (date) => {
        setSelectedDate(date);
    };

    return (
        <CalendarPicker
            //some styling args...
            onDateChange={handleDateChange}
            selectedStartDate={selectedDate}
        />
    );

enter image description here

here i want the users to select only the marked dates

Any guidance on how to achieve this specific date selection behavior would be greatly appreciated.