Trying to make a calculator that does multiple operations in JS, but the ‘operator’ gets stuck if I do not press ‘=’

Sorry for the long winded title. Basically I am writing a calculator in JS and have got onto a point where I want it to do multiple operations in a row; I believe the problem lies in the storeVariable(); when I try to do a third calculation (e.g. 2 x 3 – 2) the calculator gets stuck on the multiplication operator and so does 2 x 3 x 2. Any help with this would be appreciated.

(tried pasting my code but couldn’t figure it out so the github link is here https://github.com/KingClouderton6/calculator)

Why do curly braces break this arrow function? [duplicate]

In Chrome Dev Tools, the following logs NaN rather than the desired 526.

const nums = [7,2,11,4,9,0,1,7,14,3];
const sumSquares = nums.map((element)=>{Math.pow(element, 2)}).reduce((a, b)=>a + b, 0);
console.log(sumSquares);
// console logs `NaN`

The issue appears to lie with the formatting of .map‘s arrow function. Here I have used parenthesis and curly braces, when neither was necessary. However, I wouldn’t expect this to break my function. When removing the parenthesis and curly braces, the console logs 526, as desired:

const nums = [7,2,11,4,9,0,1,7,14,3];
const sumSquares = nums.map((element)=>Math.pow(element, 2)).reduce((a, b)=>a + b, 0);
console.log(sumSquares);
// console logs `526`

Why do curly braces change the output here?

How can i make my Metafans theme functional again after mistakenly uninstalling my tophive plugin

Hello wonderful developers! MY website has been so non-functional after I finished creating my website and I decided to uninstall plugins that I considered redundant and I mistakenly deleted tophive core wordpress functionality plugin on my metafans theme website and reinstalled it back but not remembering how I configured it again, my sign in and sign up button are no longer working, my menu icon is no longer popping up my menu items on mobile screen. I checked my console log this was the error I saw:

    at Tophive.setupMobileItemAnimations (theme.min.js?ver=2.2.0:496)
    at Tophive.init (theme.min.js?ver=2.2.0:813)
    at new Tophive (theme.min.js?ver=2.2.0:136)
    at theme.min.js?ver=2.2.0:886
    at theme.min.js?ver=2.2.0:911```.

Additional Variation Images Gallery update images on color selection

I’m in desperate need of some help to extend the plugin of the title to suit my needs in a way that I’ll explain below:

So I have two variation filters (color and size) and I would like to make the plugin swap variation images once just the color filter changes (which makes sense anyway, since variation images usually show the same product in different colors, whereas size doesn’t usually differentiate a product’s appearance; a T-shirt in size M looks identical to the same T-shirt in size L)… I know that’s how WooCommerce works, and it’s been criticized in the past for this behavior but nothing has changed yet…

So I’ve come up with the piece of code below that for any selected color, it extracts a variation of that color and a random size (it’s not random actually; it’s the last size in the array of variations) and assigns it to a variable named variation. So all that’s needed is a way to call the function showVariationImage(variation) in frontend.js of the plugin to do the images swap… But the function, as well as all other functions in the file, are declared anonymously, so I can’t call them from within my hook (unless I’m missing something, as JS isn’t exactly my cup of tea)… Can someone please advise me on how to achieve what I need – if that’s even possible?

So this is my code:

add_action('woocommerce_after_single_product', 'swap_variation_images_after_color_selection');
function swap_variation_images_after_color_selection()
{
?>
<script type="text/javascript">
(function($) {
    $(window).load(function() {
        $("a.filter-item").click(function() {
            var attribute = $(this).attr('data-value');

            console.log("Attribute: ---> " + attribute);

            var variations = $('form.variations_form').data('product_variations');

            console.log("Variations: ---> " + Object.values(variations));

            var variation_id = '';
            var variation;

            for (var i = 0; i < variations.length; i++) {
                if (variations[i].attributes.attribute_pa_color == attribute) {
                    variation_id = variations[i].variation_id;
                    variation = variations[i];
                }
            }

            if (variation_id != '') {
                console.log("Images: ---> " + Object.values(variation.variation_gallery_images));
               
                // ALL OF THE LINES BELOW ARE MY ATTEMPTS TO CALL THE APPROPRIATE FUNCTION... ALL FAILED MISERABLY...
                $.fn['WooVariationGallery'].variation = variation;
                $.fn['WooVariationGallery'].images = variation.variation_gallery_images;
              
                $('.woo-variation-gallery-wrapper').WooVariationGallery['galleryInit'];
             //   $('.woo-variation-gallery-wrapper').WooVariationGallery['showVariationImage'];//(variation.variation_gallery_images);
                //$('.woo-variation-gallery-wrapper').trigger('woo_variation_gallery_variation_images', variation.variation_gallery_images);
                //$('.woo-variation-gallery-wrapper').trigger('before_woo_variation_gallery_init', variation.variation_gallery_images);
                //$('.woo-variation-gallery-wrapper').trigger('woo_variation_gallery_init', variation.variation_gallery_images);
                // UP TO HERE...
            }
        });
    })
})(jQuery);
</script>
<?php
}

And this is the content of file frontend.js of the plugin, that does all the images preloading/swapping, etc…

Hope someone can help me. TIA.

Uncaught Error: Cannot find module ‘./imgShop/X React

i have a issue with setting the src of an Card.Img element, this element is being generated via a .map() which maps the props of an object from an array, let me show you:

const items = [
{name:"Banana",price:4,img : './imgShop/pexels-any-lane-5945848.jpg',id:1},
{name:"Apple",price:2,img : './imgShop/pexels-bruno-scramgnon-575610.jpg',id:2},
{name:"Orange",price:4,img : './imgShop/pexels-dominika-roseclay-2090902.jpg',id:3},
{name:"Lemon",price:3,img : './imgShop/pexels-lukas-1414110.jpg',id:4},
{name:"Pumpkin",price:10,img : './imgShop/pexels-miguel-á-padriñán-673073.jpg',id:5},
{name:"Kiwi",price:5,img : './imgShop/pexels-pixabay-51312.jpg',id:6},
{name:"Green apple",price:3,img : './imgShop/pexels-pixabay-533343.jpg',id:7},
{name:"Cherry",price:1,img : './imgShop/pexels-lisa-109274.jpg',id:8},
{name:"Guacamole",price:7,img : './imgShop/pexels-dominika-roseclay-2095924.jpg',id:9},
{name:"Melon",price:12,img : './imgShop/pexels-brian-van-den-heuvel-1313267.jpg',id:10},
{name:"Pomegranate",price:9,img : './imgShop/pexels-karolina-grabowska-4226732.jpg',id:11},
{name:"Pear",price:2,img : './imgShop/pexels-mali-maeder-568471.jpg',id:12},]

And

const Shop = () => {
let firstArray = items.slice(0,4)
let secondArray = items.slice(4,8)
let thirdArray = items.slice(8)

return(
    <div id="shop-container" className="container d-flex">
        <div className="col">
        {firstArray.map(item => {
           return(
            <Card style={{ width: '18rem' }} key={item.id}>
        <Card.Img variant="top" src={require(item.img)} />
        <Card.Body>
            <Card.Title>{item.name}</Card.Title>
            <Card.Text>
            Some quick example text to build on the card title and make up the bulk of
            the card's content.
            </Card.Text>
        </Card.Body>
        </Card>
           )
       
       })}
               
           
        </div>
        <div className="col">
       
        </div>
        <div className="col">
            
        </div>
    </div>
)

}

I already try putting only the path of one image and works, but when i put item.img throws me that error, and i have to use the require function because if not webpack doesn’t process the img

How to get the id of previous ul

I have a div with 4 seperate lists, I need to know the id of the list before the one i click on.

So lets say i click on ul2 i need an alert of ul1 id.

currently im getting the clicked id with:

  var clicked_id = this.id;

and ive tried the following to get the above ul

  var div_id2 = $(this).parents(".divtest").next(".ultest").attr("id");
  var div_id = $(this).closest('ul').find('.ultest').attr('id');
  var x = $(this).prev().attr('id');

simplification of layout:

  <div id="doesnt matter" class="divtest">
    <ul id="ul1" class="ultest">
      <li id="doesnt matter"></li>
      <li></li>
      <li></li>
    </ul>
    <ul id="ul2" class="ultest">
      <li></li>
      <li></li>
      <li></li>
    </ul>
    <ul id="ul3" class="ultest">
      <li></li>
      <li></li>
      <li></li>
    </ul>
    <ul id="ul4" class="ultest">
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>

Get object keys using another object

I would like to receive every user id that got the object {"cool": true}. So in this case these would be 681980629554137898 and 953522081637941260.

My JSON file:

{"681980629554137898": [{"id": "681980629554137898"}, {"cool": true}],
"790606386957778984": [{"id": "790606386957778984"}, {"cool": false}],
"953522081637941260": [{"id": "953522081637941260"}, {"cool": true}]
}

Svelte / Vanilla JS – do I need to use .then() on awaiting an async function?

This is probably best explained with code:

in my utils file I have created the following async function:

export async function post(fetch, url, body) {
    const res = await fetch(url, {
        method: 'POST',
        body,
        headers
    });
    return await res.json();
}

I’ve stripped down the function to avoid posting too much code.

Now in my .svelte component file, the function above is called as followed:

async function handleLogin() {
    const result = await post(fetch, 'https://accountingserver.dev/auth/login', {
        email: email,
        password: password
    });
    console.log(result);
}

In the above example, the result is output correctly as expected. But I have found I can also do the following and get the same outcome:

post(fetch, 'https://accountingserver.dev/auth/login', {
    email: email,
    password: password
}).then((result) => {
    console.log(result);
});

So my question, is any of the two methods more valid and if so .. why?

How can I call a function with a parameter inside fetch method?

I am working on a function with one parameter, and it should be called with an argument in an Html file, my problem is that this function should loop through fetched data from a local JSON File, the parameter takes a part in the code inside the fetch method, so I cant call the main function, any solutions?!! hope my code shows it clearly

HTML code:

 <div class="on-off-btns">
              <span onclick="showSlide(counter=1)">moon</span>
              <span onclick="showSlide(counter=2)">mars</span>
              <span onclick="showSlide(counter=3)">europa</span>
              <span onclick="showSlide(counter=4)">titan</span>
            </div>

javascript code:

let links = document.querySelectorAll(".on-off-btns span");
let counter = 1;

let myFile = "./data.json";
const showSlide = (s) => {
  fetch(myFile)
    .then((res) => res.json())
    .then((data) => {
      for (let i = 0; i < data.destinations.length; i++) {
        for (let j = 0; j < links.length; j++) {
          if (s > data.destinations.length) {
            counter = 1;
          } else if (s < 1) {
            counter = data.destinations.length;
          }
        }
        images.src = data.destinations[counter - 1].images["png"];
        titles.textContent = data.destinations[counter - 1].name;
        descriptions.textContent = data.destinations[counter - 1].description;
      }
    });
};

Nightwatch: Unable to get the updated array value in the assertion

Using Nightwatch with JS. Below is the Page object which I am using. Under commands, I initialized an empty array, “deletedPlans”. Then further in the code, I’m pushing values to it. In the end, in the assertion, I am trying to print the updated array value in the message, but it prints nothing, taking the array value as empty. Whereas, inside the function where I’ve commented, it prints the array value perfectly. What wrong I am doing?

module.exports = {
url:'/xyz',

elements: {     
    deleteAction:{
        selector: '//span[text()="Delete"]',
        locateStrategy: 'xpath'
    },
    PlanTitleVerify:{
        //some selector
    }
},

commands:[{

    deletePlan: async function (browser){

            var myPage = this
            var deletedPlans =[]
            
            browser 
                .elements('xpath', '//div[@class="ant-card-head-title"]//span', function (elements) {
      
                    elements.value.forEach(element => {
                        let key = Object.keys(element)[0];
                        let ElementIDvalue = element[key];
      
                        browser.elementIdText(ElementIDvalue, function (result) {    
                        let planName = result.value
                        deletedPlans.push(planName) //Adding value to the Array
                
                        console.log("Plan to be deleted:" + deletedPlans) //Here value gets printed      
                    
                        myPage
                          .pause(2000)
                          .click('@deleteAction')
                        })         
                    })           
                })

            myPage.assert.not.elementPresent('@PlanTitleVerify', 'Deleted plans are:' + deletedPlans) //Here value is blank
    },
  }]
};

Listing all values of an object’s property from JSON file

I’m trying to list all ‘languages’ from a JSON file into a <li> using the rest countries API (https://restcountries.com/v3.1/all) that looks like this (example country Malta)

languages: {
eng: "English",
mlt: "Maltese"
},

My code

filteredCountries.map(country =>
          <div key={country.cca2}>
            <h1>{country.name.common}</h1>
            <>Capital: {country.capital}</><br/>
            <>Population: {country.population.toLocaleString()}</>
            <h3>Languages</h3>
            <ul>
              {Object.keys(country.languages).map(lang => { 
              <li key={lang.name}>{lang.name}</li>
            }
              )}
            </ul>
            <img src={country.flags.png} alt='Country Flag'/>
          </div>

I am able to pull the country name, capital, population and flag but unable to list the languages in an efficient manner since every country has a varied number of languages. Using Object.keys doesn’t provide errors but it doesn’t display what I want. I tried using country.languages.map but I get the error of TypeError: country.languages.map is not a function I was able to get the country name and capital using country.name.cca2 and country.capital respectively

Transform javascript string with `import` statement into a function in the browser

I will like my vue application to transform the following string:

const test = 'import { pi } from "MathPie"; function test() { console.log(pi); } export default test;'

into a function that I could call.

import { pi } from "MathPie";

function test() {
  console.log(pi);
}

export default test;

I already tried using eval (even if it’s evil), but it doens’t work because import statement aren’t supported by it.

eval(test)()
> Cannot use import statement outside a module
> Should log '3.14159'

The snippet is for presentation only, I’m aware of Math.PI

My question is how I can evaluate a string with import statement?

Vuejs show keys of unknown nested array

I hava a sample and dynamic array like this:

 nodes: [
        {
          n1: "Foods",
        },
        {
          n4: "Drinks",
          b7: [
            {
              a2: "Beers",
              a4: [
                {
                  a5: "Budweiser",
                  a6: "deneme",
                },
                {
                  a7: "Heineken",
                },
                {
                        a8: "1",
                        a9: "2",
                        
                    },
                    
              ],
            },
            {
              z1: "Wines",
            },
            {
              z2: "Whiskey",
            },
          ],
        },
      ]

This array always changes dynimacally. I want to show this array keys in a tree table. So we should see relationship between parens and child. For example:

n1
n4
  b7
     a2
     a4
        a5
        a6

How do i get real time messages with Axios in Node JS?

import axios from 'axios'

axios.get('http://MYIP/MYURL',{
  auth: {
    username: 'admin',
    password:'888888ov#'
  }
})
      .then(function (res) {
          console.log(res);
         /*  console.log(auth);
          console.log(user); */

          // ... do something with the response
      })
      .catch(function (error) {
          console.log(error);
      })
      .then(function () {
        console.log('teste')
      });

This is my code. Im connecting with this URL. The thing is, it returns me messages constantly,and i would like to get their return with axios in real time. Connect once and listen to the return from the URL in real time until i close the connection. How can i do that?

Debugging a “cannot read properties of undefined” error [closed]

quire often I find myself coming accross this error:

   main.96977df238dbd452662b.js:1 ERROR TypeError: Cannot read properties of undefined (reading 'label')

what will be the best approach to track who’s the problematic key.
In my expreince this usually happens when I have an object in which i “assume” object has property for example: item.label will cause the error above.

  • just a though: wouldn’t it make lots of sense for javascript to present the name of the key that caused the fail?