JS Code working fine in Chrome but not working in Mozilla firefox

I am removing items from Cart with updating the cart when minus buton in quantity selector is clicked.
Below is the code:


document.addEventListener('DOMContentLoaded', function() {
  console.log('Script is running');

  var plusButtons = document.querySelectorAll('.plus');
  var minusButtons = document.querySelectorAll('.minus');
  
  plusButtons.forEach(function(button) {
    button.addEventListener('click', function(event) {
      event.preventDefault();
      alert("button clicked");
      var quantityDiv = button.closest('.quantity');
      var input = quantityDiv.querySelector('.quantity-input');
      var currentQuantity = parseInt(input.value);
      var inventoryQuantity = parseInt(quantityDiv.getAttribute('data-inventory-quantity'));
      
      if (currentQuantity + 1 > inventoryQuantity) {
        alert('You cannot add more than the available stock.');
      } else {
        updateCartQuantity(button.getAttribute('data-line'), currentQuantity + 1, input);
      }
    });
  });

  minusButtons.forEach(function(button) {
    button.addEventListener('click', function(event) {
     
      event.preventDefault();
      
      var quantityDiv = button.closest('.quantity');
      var input = quantityDiv.querySelector('.quantity-input');
      var currentQuantity = parseInt(input.value);
      
      if (currentQuantity > 0) {
        updateCartQuantity(button.getAttribute('data-line'), currentQuantity - 1, input);
      }  
    });
  });

This code is working fine in Chrome browser . But in mozilla firefox the function is not executed . This is a shopify website.

CORS Error between Google App Script and JavaScript Fetch

I am 16, so please understand this is probably not gonna be the greatest code you’ve seen. Anyways, I am writing a system for Google Sheets where users in my organization can update table data, but the data isn’t pushed to the main spreadsheet until it is approved by an administrator. However, when trying to send data from my backend to my spreadsheet, I receive a CORS error. I am using a Web App deployment, but I may have misconfigured something. The code is hosted on a webserver.

I have tried this code

function doPost(e) {
  return ContentService.createTextOutput(JSON.stringify({status: "success", "data": "my-data"})).setMimeType(ContentService.MimeType.JSON);
}

which I found at this StackOverflow post. That worked for a moment, but now it is not working anymore. What are the next steps?

Google App Script:

function doPost(e) {
  return ContentService.createTextOutput(JSON.stringify({status: "success", "data": "my-data"})).setMimeType(ContentService.MimeType.JSON);
}

function doPost(e) {
  // Set CORS headers
  var headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type'
  };
  
  var response = {};
  try {
    // Parse the POST data
    var data = JSON.parse(e.postData.contents);

    if (data.buttonPressed === 'true') {
      // Process your data here
      response.status = 'Success';
      response.message = 'Data push request received';
    } else {
      response.status = 'Error';
      response.message = 'Invalid request data';
    }
  } catch (error) {
    response.status = 'Error';
    response.message = 'Failed to process request: ' + error.message;
  }
  
  // Return the response with CORS headers
  return ContentService.createTextOutput(JSON.stringify(response))
    .setMimeType(ContentService.MimeType.JSON)
    .setHeaders(headers);
}


function doOptions() {
  // Handle preflight OPTIONS requests
  return ContentService.createTextOutput('')
    .setMimeType(ContentService.MimeType.TEXT)
    .setHeaders({
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type'
    });
}

function pushChanges() {
  // Your existing pushChanges function here
  const admins = ["[email protected]"];
  const userEmail = Session.getEffectiveUser().getEmail();

  if (admins.includes(userEmail)) {
    Logger.log('User is an admin. No email sent.');
    return;
  }

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheets = ss.getSheets();
  let allData = {};
  sheets.forEach(sheet => {
    const data = sheet.getDataRange().getValues();
    const sheetName = sheet.getName();
    allData[sheetName] = data.map(row => 
      row.map(cell => encodeURIComponent(cell.toString().replace(/"/g, '""'))).join(',')).join('%0A');
  });

  const formattedData = Object.keys(allData)
    .map(sheet => `sheet=${encodeURIComponent(sheet)}&data=${allData[sheet]}`)
    .join('&');

  const baseUrl = 'https://landenbarker.com/PushData?';
  const fullUrl = baseUrl + formattedData + `&editormail=${encodeURIComponent(userEmail)}`;

  const subject = 'Spreadsheet Data Updated';
  const body = 'The data in the spreadsheet has been updated. You can view the data at the following link:nn' + fullUrl;

  admins.forEach(admin => {
    MailApp.sendEmail(admin, subject, body);
  });

  Logger.log('Email sent to admins with data link.');
}

HTML Backend:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSV Data and Push Changes</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        #buttonContainer {
            margin: 20px 0;
            text-align: center;
        }
        .button {
            border: none;
            padding: 10px 20px;
            margin: 0 10px;
            font-size: 16px;
            cursor: pointer;
            color: white;
            border-radius: 5px;
            display: inline-flex;
            align-items: center;
        }
        .button.checkmark {
            background-color: #4CAF50; /* Green */
        }
        .button.xmark {
            background-color: #f44336; /* Red */
        }
        .button img {
            margin-right: 8px;
        }
    </style>
</head>
<body>
    <h1>CSV Data and Push Changes</h1>
    <div id="contactInfo">Loading...</div>
    <div id="csvTable">Loading...</div>

    <div id="buttonContainer">
        <button class="button checkmark" onclick="pushData()">
            <img src="https://img.icons8.com/material-outlined/24/checked.png" alt="Checkmark Icon"> Push Data
        </button>
        <button class="button xmark" onclick="discardData()">
            <img src="https://img.icons8.com/material-outlined/24/delete-forever.png" alt="X Icon"> Discard Data
        </button>
    </div>

    <script>
        function getDataFromCurrentUrl() {
            const url = window.location.href;
            const urlParams = new URLSearchParams(new URL(url).search);
            const dataParam = urlParams.get('data');
            const editorMail = urlParams.get('editormail');

            const contactInfoDiv = document.getElementById('contactInfo');
            if (editorMail) {
                contactInfoDiv.innerHTML = `<p>Email: ${decodeURIComponent(editorMail)}</p>`;
            } else {
                contactInfoDiv.innerHTML = 'No email parameter found in URL.';
            }

            const csvTableDiv = document.getElementById('csvTable');
            if (dataParam) {
                try {
                    const decodedData = decodeURIComponent(dataParam);
                    const csvLines = decodedData.split('n');
                    const headers = csvLines[0].split(',');
                    const rows = csvLines.slice(1).map(line => line.split(','));

                    let tableHtml = '<table><thead><tr>';
                    headers.forEach(header => {
                        tableHtml += `<th>${header}</th>`;
                    });
                    tableHtml += '</tr></thead><tbody>';
                    
                    rows.forEach(row => {
                        tableHtml += '<tr>';
                        row.forEach(cell => {
                            tableHtml += `<td>${cell}</td>`;
                        });
                        tableHtml += '</tr>';
                    });
                    tableHtml += '</tbody></table>';

                    csvTableDiv.innerHTML = tableHtml;
                } catch (e) {
                    csvTableDiv.innerHTML = 'Error processing CSV: ' + e.message;
                }
            } else {
                csvTableDiv.innerHTML = 'No data parameter found in URL.';
            }
        }

        function pushData() {
            const scriptUrl = 'https://script.google.com/a/macros/student.nisdtx.org/s/AKfycbwcXp9ovTej4Yn4_IqdZTrvBsBFcqVT-bEHoZbNmV1pU3CAk0CNjucxDyLwuaYyLlrX6A/exec';

            fetch(scriptUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ buttonPressed: 'true' })
            })
            .then(response => response.json())
            .then(result => {
                console.log('Success:', result);
                alert('Data push request sent successfully.');
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Failed to send data push request. Check the console for details.');
            });
        }

        function discardData() {
            alert('Discard Data button clicked');
            // Add your discard data logic here
        }

        // Run the function to display data on page load
        getDataFromCurrentUrl();
    </script>
</body>
</html>

I have been looking for a StackOverflow solution for quite a bit and have yet to find one.

Failed to resolve import when importing virtual module

I am trying to write type declarations for a javascript module in typescript. I want to define interfaces using a virtual module (not sure if its the right term for it). I defined base module types without a problem, but when I want to import interfaces from declared virtual module I get an following error because there is no file for it:

[vite] Internal server error: Failed to resolve import
“vuex-shared-mutations/types” from “src/stores/AuthStore.ts”. Does the
file exist?

I am using Vuejs with vite. Here are my type definitions for module:

// src/types/vuex-shared-mutations.d.ts
interface BaseStrategyOptions {
    key: string
}

interface BroadcastChannelStrategyOptions implements BaseStrategyOptions {

}

interface LocalStorageStrategyOptions implements BaseStrategyOptions {
    maxMessageLength: number
}

interface CreateMutationsSharerParams {
    predicate: Array<string> | Function;
    strategy?: BroadcastChannelStrategy | LocalStorageStrategy
}

declare module "vuex-shared-mutations" {
    function createMutationsSharer(params: CreateMutationsSharerParams);
    export = createMutationsSharer
}

// I get error when I try to import this module
declare module "vuex-shared-mutations/types" {
    declare class BaseMutationSharingStrategy {
        addEventListener(fn: function)
        share(data: any)
    }

    declare class LocalStorageStrategy extends BaseMutationSharingStrategy {
        constructor(options: LocalStorageStrategyOptions)
    }

    declare class BroadcastChannelStrategy extends BaseMutationSharingStrategy {
        constructor(options: BroadcastChannelStrategyOptions);
    }

    export {
        BroadcastChannelStrategyOptions,
        LocalStorageStrategyOptions,
        CreateMutationsSharerParams,

        LocalStorageStrategy,
        BroadcastChannelStrategy,
    };
}

And this is how I am trying to import said module:

// src/stores/AuthStore.ts
import Vuex from 'vuex';
import type { AccessToken } from '@/model/auth';
import createMutationsSharer from "vuex-shared-mutations"; // this line does not cause any issues
import { BroadcastChannelStrategy } from 'vuex-shared-mutations/types'; // this line throws said error

interface AuthStoreData {
  accessToken?: AccessToken,
}

const AuthStore = Vuex.createStore({
  state(): AuthStoreData {
    return {
      accessToken: undefined,
    }
  },
  mutations: {
    set(state: AuthStoreData, item: AccessToken) {
      state.accessToken = item;
      return state;
    },
    reset(state: AuthStoreData) {
      state.accessToken = undefined;
      return state;
    },
  },
  plugins: [
    createMutationsSharer({
      predicate: ["set", "reset"],
      strategy: new BroadcastChannelStrategy({ key: "auth-store-channel" })
    })
  ]
})

export default AuthStore;

For context, I am trying to define types for vuex-shared-mutations npm package. How can I solve this issue ? Or should I try a different solution for defining these parameter types ?

How did youtube stop the click func for ads?

Main Question: How to close the ad in Javascript?

I used to use a userscript on YouTube that I made that would click the skip ad button after the 5-second required time so I don’t violate YouTube’s terms.
Here is the Code:

// ==UserScript==
// @name         By Mohtady
// @namespace    http://tampermonkey.net/
// @version      2024-07-20
// @description  By Mohtady!
// @author       You
// @match        https://www.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    function getRandomInterval(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }

    setInterval(function() {
        let skipButton = document.getElementsByClassName("ytp-skip-ad-button");

        if (skipButton != undefined && skipButton.length > 0) {
            setTimeout(() => {
                skipButton[0].click();
                // after 5 sec
            }, 5000);
            // ad found!
        }

        console.log("Running");
    }, getRandomInterval(1000, 3000));

})();

And when I tried to run document.getElementsByClassName("button")[0].click() in the console it found the button (document.getElementsByClassName("button")[0]) but when it tried to click it, it did nothing.
Literally Nothing, no errors and it did nothing I could see on the webpage and the ad was still running.
I expected it to be an easy matter but it seems not!

Did YouTube change the way it reads button clicks?
Is anyone facing the same problem?

Content script – Function returning “Null” value after accessing DOM when page load has completed

Goal – I am building a Chrome extension. I need to access DOM elements from a specific web page once the page and all DOM elements have loaded.

Index.html – Page I am accessing

 <div class="db">some text</div>

Current behaviour – My function returns

Null

Expected behaviour – I expected to see the below within my console once the page completed loading

<div class="db">some text</div>

Contentscript.js – Below is script that runs once page has loaded

window.addEventListener('load', getWorkspaceDetails);

function getWorkspaceDetails() {
    let workspaceName = document.querySelector('.db');
    console.log(workspaceName);
};

Below is the only situation where the console logs expected DOM element

setTimeout(() => {
    let workspaceName = document.querySelector('.db');
    console.log(workspaceName);
  };
}, 5000);

It feels the query did not respect the page load and thus the query failed. I prefer not to use setTimeout. How can I ensure window.addEventListener() works as expected?

dynamically insert values in popover table

i have created a table in popover (bootstrap5). which display after user click on map feature. i am trying to insert value in popover table but iam getting error Cannot read properties of undefined (reading ‘nodeType’)

`

<thead>

   <tr>
    
    <th>Information</th>
  </tr>
</thead>
<tbody>
<tr>
    <td>Name</td>
    <td><label id="c_nme"></td>
  </tr>
  
    <td>Area</td>
    <td><label   id="ar"></td>
  </tr>
  <tr>
    <td>Year</td>
    <td><label   id="yr"></td>
  </tr>
   
    <td><button class="btn" id = "closetable"><i class="fa fa-close" ></i> Close</button></td>
    
  </tr>
  
</tbody>

`

var popup = new ol.Overlay({
  element: document.getElementById('popup'),
});
map.addOverlay(popup);
    
<!------------------------------------------------------------------------------->
element = popup.getElement();
map.on('click', function (evt) {

 var pixel = map.getEventPixel(evt.originalEvent);
  map.forEachFeatureAtPixel(pixel, function(feature) {
   var coodinate = feature.getGeometry().getCoordinates();
 
  popup.setPosition(coodinate);
  var name = feature.get('Name');
   var time = feature.get('area');
  let popover = bootstrap.Popover.getInstance(element);
  if (popover) {
    popover.dispose();
  }
  popover = new bootstrap.Popover(element, {
    animation: false,
    container: element,
    content: function () {
           return $('.s_nme').html(feature.get('Name'));
        },
    html: true,
    placement: 'top',
    title: ' Details',
  });
  popover.show();
});
});

i have added my code it works perfect when i am using this

popover = new bootstrap.Popover(element, {
    animation: false,
    container: element,
    content: '<p>The location you clicked was:</p><code>' + name + '</code>',
    html: true,
    placement: 'top',
    title: ' Details',
  });
  popover.show();

but when i am trying to add table it doesnot work

Indefinite Currying in JavaScript

I am trying to make a function such that if I call either,
curriedSum(10, 12)(21); curriedSum(13)(21)(12, 12); curriedSum(12)(12, 30); should return correct answer.
I am trying to make it dynamic i.e. there can be more than 3 calls, can be any number of calls.

This is the code that I am trying

if(!Array.prototype.sum){
    Array.prototype.sum = function(){
        return this.reduce((acc, item) => acc + item, 0)
    }
}

let curriedSum = (...args) => {
    if(args.length === 0) {
        return 0;
    }else {
        let currSum = args.sum();
        
        return (...innerArgs) => {
            if(innerArgs.length == 0){
                return currSum;
            }
            
            return curriedSum(currSum, ...innerArgs);
        }
    }   
}

console.log(curriedSum(2)(23)(12, 29));

It consoles [Function (anonymous)] but if I call curriedSum(2)(23)(12, 29)() then it returns the correct value, so I want to make such that I don’t need to call that extra () and it should be dynamic too.

Typescript unable to pass value as a param – error ‘refers to a type, but is being used as a value here’?

I am working typescript, trying to pass a value to a new object but I am unclear on the type that it expects and how to properly format the value.

The object is of type MeshData and the value I am trying to pass the baseObj parameter, which appears to accept types IBaseObject<ObjectBaseProps>, IBaseObject<ObjectWithAnimationProps>, and null:

export type MeshData = {
    initialized: boolean
    uuid: string,
    baseObj: 
        IBaseObject<ObjectBaseProps> | 
        IBaseObject<ObjectWithAnimationProps> | 
        null,
}

.

export interface ObjectBaseProps extends CompoundProps {
    position: {
        x: number;
        y: number;
        z: number;
    },
    rotation: {
        x: number;
        y: number;
        z: number;
    },
    scale: {
        x: number;
        y: number;
        z: number;
    },
}

When I attempt to pass a value of type IBaseObject<ObjectBaseProps> however, I get the following error:

‘IBaseObject’ only refers to a type, but is being used as a value
here.

            initialized:false,
            uuid: uuidv4(),
            baseObj: IBaseObject<ObjectBaseProps>({
                    position: { x: 0, y: 0, z: 0 },
                    rotation: { x: 0, y: 0, z: 0 },
                    scale: { x: 0, y: 0, z: 0 },
                }),

How can I correctly pass this value? What is wrong here?

Why does my `for` loop not make it so the first fetch reliably returns first?

To start, I realize that I can use async/await or promise chains to accomplish this. I’m trying to understand why the following specifically doesn’t work.

My understanding of this code is that it should make the p1 fetch, which in turn sends the HTTP request to the event queue and immediately starts making the request async, run the for loop (blocking, code below won’t run until the for completes), then make the p2 fetch (by this time I would expect that the p1 fetch would be complete), then we get to the p1.then and the p2.then. Since I gave the p1 a huge head start in the form of the for loop, I would expect that we almost always would print 0. But that is not the case. It seems completely indeterministic. I understand that there are network conditions, but I would think that the head start given by the for loop would be enough to deterministically return 0.

This makes me feel like I have a gap in my understanding. I’m wondering why this works this way?

let x = 1;
let url = "https://www.google.com";

let p1 = fetch(url);

for (let i = 0; i < 1000000000; i++) {}

// Is it possible to ensure that the promise `p1` gets resolved earlier than `p2`? (By blocking the code here) Not working with the `for` loop.

let p2 = fetch(url);

p1.then(() => {
  x = 0;
});

p2.then(() => {
  x = x * 1;
  // Because of the race condition between `p1` and `p2`, the value of `x` is indeterministic.
  console.log(x);
});

I tried increasing the iterations of the for loop and still got an indeterministic result.

Size and border are not suitable in SVG screenshots when screenshoting a div element

I want to make the custom element doesn’t require a div element inside, make the image’s size like the div’s size, and make the div’s bottom border appear. Also, the style element should be in the div to work, and it’s better to solve. This code works perfectly except those stuff. Simply, html2canvas is missing some elements so I remade it but with SVG.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        class CaptureElement extends HTMLElement {
            capture() {
                const div = this.querySelector("div");
                const br = document.createElement("br");
                div.appendChild(br);
                const canvas = document.createElement("canvas");
                const context = canvas.getContext("2d");
                const data = new XMLSerializer().serializeToString(div);
                const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${div.scrollWidth}" height="${div.scrollHeight}">
                                <foreignObject width="100%" height="100%">
                                    ${data}
                                </foreignObject>
                             </svg>`;
                const img = new Image();
                img.onload = () => {
                    canvas.width = div.scrollWidth;
                    canvas.height = div.scrollHeight;
                    context.drawImage(img, 0, 0);
                    const base64 = canvas.toDataURL("image/png");
                    console.log(base64);
                    div.removeChild(br);
                    if (this.hasAttribute("download")) {
                        var filename;
                        const download = this.getAttribute("download");
                        if (!download.endsWith(".png")) {
                            filename = download + ".png";
                        }
                        else {
                            filename = download;
                        }
                        const a = document.createElement('a');
                        a.href = base64;
                        a.download = filename;
                        a.click();
                    }
                };
                img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
            }
        }

        customElements.define("capture-element", CaptureElement);
        document.addEventListener("DOMContentLoaded", () => {
            document.querySelector("button").addEventListener("click", () => {
                document.querySelector("capture-element").capture();
            })
        });
    </script>
    <style>
        button {
            color: white;
            background-color: gray;
            border-radius: 5px;
        }

        div.button {
            text-align: center;
        }
    </style>
    <title>Custom element</title>
</head>

<body>
    <div class="button">
        <button>Download</button>
    </div>
    <br>
    <br>
    <capture-element download="Certification.png">
        <div id="certification">
            <style>
                * {
                    border: 0px;
                    background-color: white;
                    font-family: "Arial";
                }

                h1 {
                    background: linear-gradient(to right bottom, rgba(255, 188, 13, 1) 23%, rgba(0, 212, 255, 1));
                    font-weight: lighter;
                    color: transparent;
                    background-clip: text;
                    text-align: center;
                }

                p {
                    margin-left: 5px;
                }

                div#certification {
                    border-top: 1px solid black;
                    border-right: 1px solid black;
                    border-left: 1px solid black;
                    border-bottom: 2px solid black;
                    border-radius: 0px;
                    width: 50%;
                    min-width: 500px;
                    max-width: 1000px;
                    margin: auto;
                }

                .uname {
                    color: transparent;
                    font-weight: bolder;
                    font-size: xx-large;
                    text-align: center;
                    margin-top: 0px;
                    background: linear-gradient(to right bottom, rgb(132, 160, 68) 23%, rgb(66, 171, 192));
                    background-clip: text;
                }

                .fname {
                    font-weight: bold;
                    font-size: x-large;
                    text-align: center;
                    margin-right: 150px;
                    margin-top: 0px;
                }

                div:not(#certification) {
                    text-align: center;
                }
            </style>
            <h1>Digital certification</h1>
            <p>This certification is made for developers, from developers. This one is specially made for:</p>
            <p class="uname">Username</p>
            <p>From:</p>
            <p class="fname">HTML, CSS, JavaScript</p>
            <div>
                <ruby><meter style="font-size: xx-large;" min="0" max="100" low="33" high="66" optimum="80"></meter>
                    <rt style="font-size: larger;">0%</rt>
                </ruby>
            </div>
        </div>
    </capture-element>
</body>

</html>

calculating camera position with different altitudes (Mapbox, Javascript)

I’ve been implementing the concept from this mapbox blog to animate 3d routes from GPS activities into my fitness app – Trackster.

Everything works great for GPS activities that are at ~sealevel. When the altitude increases, it gets increasingly skewed.

Here is an example activity at sea level

Here is an example of the ugly version in Quito, Ecuador (9.9k feet in altitude)

Feels like I’m just not understanding why the altitude is throwing off the newly calculated coordinates by so much?? Here is the algorithm used to get the camera position.

computeCameraPosition(
  pitch,
  bearing,
  targetPosition,
  altitude,
  previousCameraPosition = null,
  smooth = false
) {

  function lerp(start, end, amt) {
    return (1 - amt) * start + amt * end
  }


  var bearingInRadian = bearing / 57.29;
  var pitchInRadian = (90 - pitch) / 57.29;
  var altFac = (altitude / Math.tan(pitchInRadian))


  var d = Math.cos( targetPosition.lat * (Math.PI/180) ) * (40075000 / 360)
  var latDiff = (altFac * Math.cos(-bearingInRadian)) / this.latRadFac // 111320 m/degree latitude
  var lngDiff = ( altFac * Math.sin(-bearingInRadian)) / d;

  var correctedLng = targetPosition.lng + (lngDiff);
  var correctedLat = targetPosition.lat - (latDiff);

  const newCameraPosition = {
    lng: correctedLng,
    lat: correctedLat
  };

  if (smooth) {
    if (previousCameraPosition) {
      const SMOOTH_FACTOR = 0.9
      newCameraPosition.lng = lerp(newCameraPosition.lng, previousCameraPosition.lng, SMOOTH_FACTOR);
      newCameraPosition.lat = lerp(newCameraPosition.lat, previousCameraPosition.lat, SMOOTH_FACTOR);
    }
  }

  return newCameraPosition

},

Strange error when initializing firebase cli

I followed every step to set it up, but when i install dependencies it says

npm ERR! code 1
npm ERR! path C:Projectsmercuryfunctionsnode_modulesprotobufjs
npm ERR! command failed
npm ERR! command C:Usersjulian.cachefirebaseruntime/shell.bat -c -- node scripts/postinstall
npm ERR! '--' is not recognized as an internal or external command,
npm ERR! operable program or batch file.

when i try to deploy after i get

Error: Error parsing triggers: Cannot find module 'firebase-functions/v2/https'
Require stack:
- C:Projectsmercuryfunctionsindex.js
- C:Usersjulian.cachefirebasetoolslibnode_modulesfirebase-toolslibdeployfunctionsruntimesnodetriggerParser.js
1) If you want to compile the package/file into executable, please pay attention to compilation warnings and specify a literal in 'require' call. 2) If you don't want to compile the package/file into executable and want to 'require' it from filesystem (likely plugin), specify an absolute path in 'require' call using process.cwd() or process.execPath.

i tried:

npm cache clean --force
npm uninstall firebase-tools -g
npm install -g firebase-tools
firebase init

but i still get the error. does anyone know how to fix this??

how can i define a variable wrong?

i’m doing an assignment where i need to build a function-based console log generator. i need to declare two variables and for some reason the way i’m doing is wrong:

var message;
var style;
function consoleStyler(color, background, fontSize, txt) {
    message = "%c" + txt;
    style = `color: ${color};`;
    style += `background: ${background}`;
    style += `font-size: ${fontSize};`;
    console.log(consoleStyler(message, style));
}

(i declared them outside the function because the assignment needs them later within other function)
The output says there’s a range error and also points specifically the message variable as being wrong.

  • I tried defining the variables inside the function but the full assignment needs them to be global.
  • Also tried leaving the parentheses of “consoleStyler” within the console.log blank, but the assignment especifies that it needs the parameters there.
  • Defining everything inside style also doesn’t work, it needs to be in separate lines of code.
  • I just really don’t get what is wrong at the message variable, the backticks must be included so i’m clueless, if anyone can figure it out something that could help me, i’ll be very thankfull!