How to do recursion by hand?

I am having a brain lapse in recursion and trying to get the math right. The function gives me what I want but my brain does not.

let recurseSum = (x, n) => {
    if(n === 1){ return x}

    return x + recurseSum(x, n-1)
}

log = console.log
log(recurseSum(3, 2))

How is this broken down again, the answer and what I write is not right.

3 + recurse(3, (2-1) = 3 + 1 = 4
3 + resurse(3, (1-1) = 3....ggrrrrrrr

How do I write this out properly.

Axios is not returning status

I am using Axios to make a request to a server. When the server responds with a code of anything other than a 200, I get an error that the request failed and the status code is undefined.

I would like to know the status code so I can decide how to respond to it.

Example response:

{
    message: 'Request failed with status code 500',
    stack: 'AxiosError: Request failed with status code 500n  …/./node_modules/axios/lib/adapters/xhr.js:125:66)',
    code: 'ERR_BAD_RESPONSE',
    status: undefined,
    method: 'get',
    …
}

code: "ERR_BAD_RESPONSE"
message: "Request failed with status code 500"
method : "get"
stack: "AxiosError: Request failed with status code 500n    at settle (webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)n    at XMLHttpRequest.onloadend (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:125:66)"
status: undefined

Example request:

  return axios
    .get(url, {
      params: flattenedParams
    })
    .then((response: AxiosResponse) => {
      if (response.status == 500) {
        throw new Error("server side error");
      }
      return response;
    });

Pre-run animation on page load

The first time I run my animation it runs at about 5fps and looks really janky. Is there a way to run it whilst the page loads or instantly after loading?

Also I have tried preloading the images with a preload in the header of my html. No luck with that.

My animation has three images that start with no width or height or opacity, but grow and become visible once the corresponding text-option is clicked. This creates the effect of the image growing from either the left or right of the container.

When loading the page, the first image (the one with active class) appears and is clearly loaded. When you then click a different text option, then the image expands but at a very slow rate. Once this image is loaded, then it never has this problem until the next refresh. So I would have assumed it would be a matter of preloading the image, but when I tried to preload the image with this <link rel="preload" href="img.png" as="image"> nothing had changed.

HTML:

<section class="section-2">
        <div class="image-container">
          <img src="img.png" alt="" class="selectable-image active">
          <img src="img.png" alt="" class="selectable-image">
          <img src="img.png" alt="" class="selectable-image">
        </div>
        <div class="text-selection-container">
          <div class="text-option active">
            <p class="title">Title</p>
            <p class="description">Description</p>
          </div>
          <div class="text-option">
            <p class="title">Title</p>
            <p class="description">Description</p>
          </div>
          <div class="text-option">
            <p class="title">Title</p>
            <p class="description">Description</p>
          </div>
        </div>
      </section>

SCSS:

.section-2 {
  display: flex;
  background-color: var(--second-background);
  padding: min(100px, 3svw);
  box-sizing: border-box;
  height: 60vh;

  .image-container {
    width: 50svw;
    height: 100%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    img {
      width: 0%;
      opacity: 0;
      transition: all 0.5s ease;
    }
    .selectable-image.active {
      opacity: 1;
      width: 100%;
    }
  }
  .text-selection-container {
    width: 50%;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    padding: min(50px, 2svw);
    padding-left: 0;
    .text-option {
      margin: 1svw;
      padding-left: min(50px, 2svw);
      .title {
        font-size: 2svw;
        margin-bottom: 0.5svw;
        font-weight: 700;
      }
      .description {
        font-size: 1svw;
        font-weight: 400;
      }
    }

    .text-option.active {
      border-left: 4px solid var(--primary);
      padding-left: calc(min(50px, 2svw) - 4px)
    }
  }
}

JS:

document.addEventListener("DOMContentLoaded", function () {
  const textOption = document.querySelectorAll(".text-option");
  const selectableImage = document.querySelectorAll(".selectable-image");
  function clickedTextOption(clickedOption) {
    textOption.forEach((option,index) => {
        const active = option.classList.toggle("active", option === clickedOption);
      selectableImage[index].classList.toggle('active', active);
    });    
  }

  textOption.forEach(option => {
    option.addEventListener("click", () => {
      clickedTextOption(option);
    });
  });

});

P.S. img.png is just a placeholder

How would be the best way to prevent this lag on load?

Thanks in advance!

Shopify liquid, cart drawer, quantity buttons/remove items not working with upsell item in cart-drawer functionality. There’s a problem with the AJAX

I’ve been troubleshooting for a while since I’m not truly a developer. I have some minor experience with programming. So if you can imagine a basic cart drawer, with an upsell item, an add to cart button, etc, but the quantity buttons and the trash icon (remove item) buttons in cart are not updating properly, the carts estimated total is actually handling fine. I don’t know how to get the event listeners to properly update the new cart information. I’ve been relying heavily on chatGPT. But it’s not quite where it needs to be to help troubleshoot an issue even when provided the exact code. I can provide code in a comment.

Jest toThrow() method doesn’t work properly

It fails even though the error thrown by my JS code seems to be correct. Relevant Jest code block:

 describe('operate', () => {
    test("works with addition", () => {
        expect(evaluate_expression("3+5")).toEqual(8);
    });
    test("works with substraction", () => {
        expect(evaluate_expression("128-29")).toEqual(99);
    });
    test("works with multiplication", () => {
        expect(evaluate_expression("25*5")).toEqual(125);
    });
    test("works with division", () => {
        expect(evaluate_expression("990/99")).toEqual(10);
    });
    test("division 0 is handled", () => {
        expect(evaluate_expression("5/0")).toThrow('Division by zero');
    });
});

JavaScript code:

function append_to_display(value) {
    if (start == false)
        document.getElementById('display').value += value;
    else {
        document.getElementById('display').value = value;
    };
};

function calculate() {
    try {
        const expression = document.getElementById('display').value;
        console.log(expression);
        const result = evaluate_expression(expression);
        document.getElementById('display').value = result;
        document.getElementById('current_value').textContent = result;
    } catch (error) {
        document.getElementById('display').value = 'Error';
    }
};

function evaluate_expression(expression) {
    const output_queue = [];
    const operator_stack = [];
    const operators = { '+': 1, '-': 1, '*': 2, '/': 2 };

    const tokens = expression.match(/([0-9]+|+|-|*|/)/g);

    tokens.forEach(token => {
        if (!isNaN(token)) {
            output_queue.push(parseFloat(token));
        } else if (token in operators) {
            while (
                operator_stack.length > 0 &&
                operators[token] <= operators[operator_stack[operator_stack.length - 1]]
            ) {
                output_queue.push(operator_stack.pop());
            }
            operator_stack.push(token);
        } else {
            throw new Error('Invalid expression');
        }
    });

    while (operator_stack.length > 0) {
        output_queue.push(operator_stack.pop());
    }

    const result_stack = [];
    output_queue.forEach(token => {
        if (!isNaN(token)) {
            result_stack.push(token);
        } else {
            const b = result_stack.pop();
            const a = result_stack.pop();
            switch (token) {
                case '+':
                    result_stack.push(a + b);
                    break;
                case '-':
                    result_stack.push(a - b);
                    break;
                case '*':
                    result_stack.push(a * b);
                    break;
                case '/':
                    if (b === 0) {
                        throw new Error('Division by zero'); // HERE IS THE PROBLEM
                    }
                    result_stack.push(a / b);
                    break;
                default:
                    throw new Error('Invalid operator');
            }
        }
    });

    if (result_stack.length !== 1) {
        throw new Error('Invalid expression');
    }
  • The evaluate_expression() is called via the calculate() on clicking the “=” button on the calculator.

The exact line in the JavaScript code is this:

    if (b === 0) {
         throw new Error('Division by zero'); // HERE IS THE PROBLEM
    }

I have tried to append rejects to expect here, but this doesn’t work.

How can I straighten the lines making up the arrows of this full screen button (and also reduce the excessive variable use)?

Here’s my code so far:

function toggleState(target) {
  target.classList.toggle("animate");
}
:root {
    --btn-size: 15vmin;
    --btn-anim-len: 0.5s;
    --btn-anim-len-half: calc(0.5*var(--btn-anim-len));
    --btn-anim-len-quar: calc(0.25*var(--btn-anim-len));
    --btn-anim-func: cubic-bezier(0.55,-0.15,0.45,1.15);
    --btn-color: #929292;
    
    /*Variables to trim:*/
    --fs-btn-pos1: calc((3/15)*var(--btn-size));
    --fs-btn-pos2: calc((4/15)*var(--btn-size));
    --fs-btn-pos3: calc((5/15)*var(--btn-size));
    --fs-btn-pos4: calc((6/15)*var(--btn-size));

    --fs-btn-neg1: calc(-1*var(--fs-btn-pos1));
    --fs-btn-neg2: calc(-1*var(--fs-btn-pos2));
    --fs-btn-neg3: calc(-1*var(--fs-btn-pos3));
    --fs-btn-neg4: calc(-1*var(--fs-btn-pos4));
}
#fs-btn {
    height: var(--btn-size);
    aspect-ratio: 1/1;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: var(--btn-color);
    transition: rotate var(--btn-anim-len) var(--btn-anim-func);
}
#fs-btn::before, #fs-btn::after {
    position: absolute;
    display: block;
    box-sizing: border-box;
    content: "";
    color: var(--btn-color);
    transition:
        height var(--btn-anim-len-half) ease-in-out var(--btn-anim-len-quar),
        width var(--btn-anim-len-half) ease-in-out var(--btn-anim-len-quar),
        box-shadow var(--btn-anim-len) ease-in-out,
        filter calc(0.1*var(--btn-anim-len)) var(--btn-anim-func);
}
#fs-btn::before {
    height: var(--fs-btn-pos3);
    width: var(--fs-btn-pos1);
    box-shadow:
        var(--fs-btn-pos4) var(--fs-btn-pos3),
        var(--fs-btn-neg4) var(--fs-btn-pos3),
        var(--fs-btn-pos4) var(--fs-btn-neg3),
        var(--fs-btn-neg4) var(--fs-btn-neg3);
}
#fs-btn::after {
    height: var(--fs-btn-pos1);
    width: var(--fs-btn-pos3);
    box-shadow:
        var(--fs-btn-pos3) var(--fs-btn-pos4),
        var(--fs-btn-pos3) var(--fs-btn-neg4),
        var(--fs-btn-neg3) var(--fs-btn-pos4),
        var(--fs-btn-neg3) var(--fs-btn-neg4);
}
#fs-btn:hover:active {
    filter: brightness(0.9);
}
#fs-btn.animate {
    rotate: 180deg;
}
#fs-btn.animate::before {
    height: var(--fs-btn-pos1);
    width: var(--fs-btn-pos3);
    box-shadow:
        var(--fs-btn-pos3) var(--fs-btn-pos2),
        var(--fs-btn-neg3) var(--fs-btn-pos2),
        var(--fs-btn-pos3) var(--fs-btn-neg2),
        var(--fs-btn-neg3) var(--fs-btn-neg2);
}
#fs-btn.animate::after {
    height: var(--fs-btn-pos3);
    width: var(--fs-btn-pos1);
    box-shadow:
        var(--fs-btn-pos2) var(--fs-btn-pos3),
        var(--fs-btn-pos2) var(--fs-btn-neg3),
        var(--fs-btn-neg2) var(--fs-btn-pos3),
        var(--fs-btn-neg2) var(--fs-btn-neg3);
}
<div id="fs-btn" onclick="toggleState(this)"></div>

As you can see, the lines look fine here, but when run on Google the lines look off which makes the button look a little sloppy. According to the math ‘n’ stuff, they should be straight, but when the program runs on Google they aren’t.
I also want to reduce the number of variables used to make the button, but I can’t think of a more efficient method that I can change the size of easily without having to modify the values of every single box-shadow to the new size.

Constant stack size in Chrome Web Worker despite varying –js-flags stack size arguments

I am using the following code to estimate the size of the stack inside a Web Worker in Google Chrome running on Linux (x86_64):

var i = 0;
function recurse () {
    i++;
    recurse();
}
try {
    recurse();
} catch (ex) {
    alert('maxStackSize = ' + i + 'nerror: ' + ex);
}

I am finding however that regardless of what I set the stack size argument to I always get the same value: 6969 with the devtools closed or 6968 with the devtools open. I always close all other instances of Chrome before beginning my test and I run Chrome from the terminal as follows:

/opt/google/chrome/chrome --incognito
/opt/google/chrome/chrome --incognito --js-flags="--stack-size 2048"
/opt/google/chrome/chrome --incognito --js-flags="--stack-size 128"

Chrome seems to be accepting the arguments (checked via intentionally misspelling them/putting in invalid values), so I do think --js-flags is being parsed but it does not seem to have any effect on the depth of the stack. Why is this the case?

Website fade in animation IntersectionObserver

So basically I have a section called creations where I am displaying three videos that play when the user hovers over them, and they are placed next to eachother, I want it so that when the user scrolls down and the section is in the viewport it smoothly fades in from the left. I try it by adding classlist ‘hidden’ and ‘faded-in’. But I have a problem where if the user scrolls down the website and the section comes into the viewport it keeps on being hidden and doesnt get the classlist ‘faded-in’. It only gets the classlist of ‘faded-in’ if i reload the website and am already looking at the section.

This is my html code:

<section class="creations">
        <h1>ONZE<span class="auto-projecten"></span></h1>
        <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Deleniti, iure?</p>
        <!-- TODO: Scroll animation, do typing animation when text is inside viewport-->
        

        <div class="row">
            <div class="creations-col">
                <video id="enzolucavideo" src="images/enzoluca.mp4" preload="auto" poster="images/enzoluca.png"></video>
                <div class="layer">
                    <h3>Enzo Luca</h3>
                </div>
            </div>
            <div class="creations-col">
                <video id="expertvideo" src="images/expert.mp4" preload="auto" poster="images/expert.png"></video>
                <div class="layer">
                    <h3>Expert</h3>
                </div>
            </div>
            <div class="creations-col">
                <video id="keukenmaxxvideo" src="images/keukenmaxx.mp4" preload="auto"></video>
                <div class="layer">
                    <h3>Keukenmaxx</h3>
                </div>
            </div>
        </div>
        
        
    </section>

and this is my app.js:

document.addEventListener('DOMContentLoaded', function () {
    // Function to start or reset typing animation
    function startOrResetTypingAnimation() {
        var typed = new Typed(".auto-projecten", {
            strings: [".PROJECTEN"],
            typeSpeed: 160
        });
    }

    // Function to handle the intersection of the target element
    function handleIntersection(entries, observer) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                // Target element is inside the viewport
                startOrResetTypingAnimation();
                observer.unobserve(entry.target); // Stop observing once animation is triggered
                // Remove the 'hidden' class when it's intersecting
                entry.target.classList.remove('hidden');
                entry.target.classList.add('faded-in');

                
            } else {
                // Add the 'hidden' class when it's not intersecting
                entry.target.classList.remove('faded-in');
                entry.target.classList.add('hidden');
            }
        });
    }

    // Using Intersection Observer to trigger typing animation and fade-in effect
    var observer = new IntersectionObserver(handleIntersection, { threshold: 0.5 });
    var creationsSection = document.querySelector(".creations");
    if (creationsSection) {
        observer.observe(creationsSection);
    }
});

and this is my style.css:

.hidden{
    opacity: 0;
    filter: blur(5px);
    transform: translateX(-100%);
    transition: all 1s;
}
.faded-in{
    opacity: 1;
    transform: translateX(0%);
    transition: all 1s;
}

.creations-col:nth-child(2){
    transition-delay: 200ms;
}
.creations-col:nth-child(3){
    transition-delay: 400ms;
}
.creations-col:nth-child(4){
    transition-delay: 600ms;
}

How to make static blocks in muuri grid?

I have a grid with more than 5 items and all items are inside grid class. Now i want to make 2 of these block static / non draggable. How can i achieve this ?

I have tried the following code but its not working for me.

var staticBlock = document.querySelector('.static-block');
var staticItem = grid.getItems([staticBlock])[0];

// Override the drag handle to prevent dragging
staticItem.getElement().addEventListener('mousedown', function(event) {
  event.stopPropagation(); // Prevent dragging when clicked
});

Understanding the existing Javascript code [closed]

I am new to Javascript programming. I am going through the old codes and finding it difficult to understand the logic. What are different ways to understand the logic used in the code in a quicker way? Note that I am using Visual Studio Code.

I am going through a long Javascript file and trying to understand the purpose of the code and logic used.

How can I execute my JavaScript Code in Tricentis Tosca

I am currently working on some tests regarding the dataLayer of a webshop. My goal is to use Tosca to check the dataLayer at specific points in the webshop to verify that the correct data for tracking is pushed to the dataLayer.

The Tosca Manual shows 2 modules for this “Execute JavaScript” and “Verify JavaScript”.
I can get the dataLayer or specific values by adding the following into the line for JavaScript: “return dataLayer[0].event.charAt(0)”
This is just for getting to know the module, but it shows that I can correctly read some things from the dataLayer. But I am struggling to move on from this point. Cause I would really like to search/filter for specific values or do some checks directly via JavaScript.
But I cant manage to let Tosca execute anything more then a simple read from the dataLayer even though it works fine when I execute the code in the browser console.
Example: “var result = dataLayer.filter(obj => {
return obj.event === “PageView”})”
simple piece of code to search through the dataLayer for a specific type of event and save that to a variable, but Tosca wont execute this code. I added an extra pair of ” so it looks like this: “var result = dataLayer.filter(obj => {
return obj.event === “””PageView”””})”
But no matter if I add a return before or not – Tosca always says “Expression provided in test step item “JavaScript”could not be parsed due to the following reason: Token is not valid in this context: ” ”
Seems like he has a problem with the quotation marks, but I added an extra pair for each of them to skip them – just like the manual says. And if I use a number instead of a string (which of course doesnt make sense, but just for trying it): “return var result = dataLayer.filter(obj => {
return obj.event === 1})” I get the error No suitable value found for command ‘
return obj.event === 1’

Therefor I am clueless about what syntax I need to follow to execute my JavaScript code. I would be thankful for any help. Maybe I am even missing an easier way to check the DataLayer?

Why my responsive chart option settings doesn’t work?

I am trying to make my charts responsive, using echarts.js. I found here that I can use the property media and query.

The problem is that I do not see any change when I change the width.

let myChart = echarts.init(document.getElementById('barchart'));
 
        let option = {
            baseOption: { // baseOption
                tooltip: {
                    formatter: 'Hashtag {b} <br /> Tweets: {c}'
                },
                toolbox: {
                    feature: {
                        dataView: {},
                        restore: {},
                        saveAsImage: {},                           
                    },
                    left: '1%',
                    top:'top',
                    right:'auto',
                    bottom:'auto'
                },
                grid: {
                    left: '2%',
                    top: '17%',
                    right: 'auto',
                    bottom: '10%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true,
                        interval: 0
                      },
                      axisLabel: {
                        interval: 0,
                        rotate: 45,
                        width: 78,
                        overflow: 'truncate'
                      },
                      axisPointer: {
                        show: true,
                        type: 'shadow'
                      },
                    data: hashtags
                
                    
                },
                yAxis: { 
                    type: 'value'
                },
                series: [
                    {
                        name: 'Tweet count',
                        type: 'bar',
                        data: countOfEachHashTag,
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        label: {
                            show: true,
                            position: 'top'
                        },
                        itemStyle: {
                            color: 'rgb(8,72,103)'
                        }
                    }
                ]
            },
            media: [
                {
                    query: {
                        maxWidth: 576
                    },
                    option: {
                        grid: {
                            left: 'auto',
                            top: 'auto',
                            right: 'auto',
                            bottom: 'auto',
                            width: '406',
                            height: '600',
                            containLabel: true
                        }
                    }
                }
            ]
        };
    myChart.setOption(option);

My code seems correct, as per the example, but I do not see any change in the container’s width and height when I resize my window and the container size descreases too.

My html code for this chart is this:

<div id="barChartCollapse" class="collapse show">
     <div id="barchart" style="width: auto;height:600px;">

     </div>
</div>

Is something missing?

minWidth, as per the example, works, but maxWidth doesn’t. The example link that I provided specifically points that width, height, aspectRatio (height / width), each of which can add min or max as prefix. That’s very strange.

How to get information from Google sheet using API

I’m trying to send data from google sheet using POST.

Actually it works, if I write data in code. But I wand to get it from google sheet

My code

function sendDataToRoistatAPI() {
  var url = "https:XXX";
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName("Users"); 

  var data = sheet.getDataRange().getValues();

  for (var i = 0; i < data.length; i++) {
    var rowData = data[i];
    var payload = {
      manual_custom_metric_id: rowData[1], 
      source: rowData[2], 
      value: rowData[3], 
      period: rowData[4], 
    };

    var options = {
      method: "post",
      contentType: "application/json",
      payload: JSON.stringify(data),
    };

    var response = UrlFetchApp.fetch(url, options);
    Logger.log(response.getContentText()); 
  }
}

The mistake is
{“status”:”error”,”error”:”incorrect_request”,”description”:”Argument value is not a positive valuenRequired argument period is missingnArgument manual_custom_metric_id is not a positive integer number”}

In google sheet named Users I have colums: manual_custom_metric_id,source,value,period

The background image ends at some point React.js

First of all, sorry for my bad English. On the site I have made, when I press the send button by taking information such as name and surname from the user with the form, it is added to the table you see in the picture, but after a point, the background image does not continue, a white field appears. how can I fix it? (I’m using react)

My css codes:

.bolum1{
    background-image: url(Assets/bg1.png);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 50% 0;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
.katman{
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6 );
    position: absolute;
    top: 0;
    left: 0;

}

pic

bolum1: editing the background image.
katman: giving the background a dark color (briefly layer)