AG Grid filtering without an active AG Grid instance?

I’ve got my hands on a persisted ag-grid filter-model object, I have a set of rows that conform to it’s expectation. But I don’t actually have an ag-grid component anywhere on the page. Is there a way to filter my data headless? I do have the libraries available, I just don’t need a table at the moment.

data + filter-model => ???? => filtered data

Table filtering in HTML and JavaScipt

I have a table that I want to be able to filter in JavaScript (see below). I would like the filter to be as the ones in an Excel spreadsheet, where I can filter multiple columns at once. I have the functions for the search, select all, and the cancel button I do not have the function to put the content for filtering or the filtering function for the table.

Do not want any items to be hard coded!

Part of the table:

Type    Unit From   Unit To Formula
Length  µm  mm  i ÷ 1000
Length  µm  in  i × 0.00003937
Length  mm  cm  i ÷ 10
Length  mm  m   i ÷ 1000
Length  mm  km  i ÷ 1000000
Length  mm  in  i × 0.03937
Length  mm  ft  i ÷ 304.8
Length  mm  yd  i × 0.0010936132983377078
Length  mm  mi  i × 0.00000062137
Length  mm  µm  i × 1000
Length  cm  mm  i × 10
Length  cm  m   i ÷ 100
Length  cm  km  i ÷ 100000
Length  cm  in  i × 0.3937
Length  cm  ft  i ÷ 30.48
Length  cm  yd  (i ÷ 30.48) ÷ 3
Length  cm  mi  i × 0.0000062137
Length  cm  µm  i × 10000
Length  m   mm  i × 1000
Length  m   cm  i × 100
Length  m   km  i ÷ 1000
Length  m   in  i × 39.37
Length  m   ft  i ÷ 0.304
Length  m   yd  i × 1.0936
Length  m   mi  i × 0.00062137
Length  m   rod i ÷ 5.0292
Length  m   µm  i × 1000000
Length  km  mm  i × 1000000
Length  km  cm  i × 100000
Length  km  m   i × 1000
Length  km  in  (i × 3280.8) ÷ 12
Length  km  ft  i × 3280.8
Length  km  yd  i × 1093.6
Length  km  mi  i × 0.62137
Length  km  µm  (i × 1000000) × 1000
Length  in  mm  (i ÷ 0.39370) × 10
Length  in  cm  i ÷ 0.39370
Length  in  m   i ÷ 39.37
Length  in  km  i ÷ 39370
Length  in  ft  i ÷ 12
Length  in  yd  i ÷ 36
Length  in  mi  i × 0.000015783
Length  in  µm  i ÷ 0.00003937
Length  ft  mm  i ÷ 0.32808
Length  ft  cm  i ÷ 0.032808
Length  ft  m   i × 0.304
Length  ft  km  i ÷ 3280.8
Length  ft  in  i × 12
Length  ft  yd  i ÷ 3
Length  ft  mi  i ÷ 5280
Length  ft  rod i ÷ 16.5
Length  yd  mm  (i ÷ 0.010936) × 10
Length  yd  cm  i ÷ 0.010936
Length  yd  m   i ÷ 1.0936
Length  yd  km  (i ÷ 1.0936) ÷ 1000
Length  yd  in  (i × 3) × 12
Length  yd  ft  i × 3
Length  yd  mi  i ÷ 1760
Length  yd  rod i ÷ 5.5
Length  mi  mm  i ÷ 0.000062137
Length  mi  cm  i ÷ 0.0000062137
Length  mi  m   i ÷ 0.00062137
Length  mi  km  i ÷ 0.62137
Length  mi  in  i × 63360
Length  mi  ft  i × 5280
Length  mi  yd  i × 1760
Length  rod mm  i × 5029.200000000001
Length  rod cm  i × 502.92
Length  rod m   i × 5.0292
Length  rod km  i × 0.0050292
Length  rod in  i × 1.375
Length  rod ft  i × 16.5
Length  rod yd  i × 5.5
Length  rod mi  i ÷ 9680
Length  rod furlong i ÷ 40
Length  furlong mi  i ÷ 8
Length  furlong rod i × 40
Weight  gr  g   i ÷ 15.43234
Weight  gr  kg  i ÷ 15432.34
Weight  gr  mt  (i ÷ 15432.34) ÷ 1000
Weight  gr  oz  (i ÷ 15.43234) ÷ 28.349
Weight  gr  lb  ((i ÷ 15.43234) ÷ 28.349) ÷ 16
Weight  gr  mg  i × 64.8
Weight  g   gr  i × 15.43234
Weight  g   kg  i ÷ 1000
Weight  g   oz  i ÷ 28.349
Weight  g   lb  i ÷ 454
Weight  g   mg  (i × 15.43234) × 64.8
Weight  kg  gr  i × 15432.34
Weight  kg  g   i × 1000
Weight  kg  mt  i ÷ 1000
Weight  kg  lb  i × 2.2046226
Weight  kg  short ton   (i × 2.2046226) ÷ 2000
Weight  mt  gr  ((i × 1000) × 1000) × 15.43234
Weight  mt  g   (i × 1000) × 1000
Weight  mt  kg  i × 1000
Weight  mt  oz  (i × 2204.6) × 16
Weight  mt  lb  i × 2204.6
Weight  mt  short ton   i × 1.1
Weight  oz  gr  (i × 28.349) × 15.43234
Weight  oz  g   i × 28.349
Weight  oz  kg  (i × 28.349) × 1000
Weight  oz  lb  i ÷ 16
Weight  oz  mg  ((i × 28.349) × 15.43234) × 64.8
Weight  lb  g   i × 454
Weight  lb  kg  i × 0.454
Weight  lb  mt  i ÷ 2204.6
Weight  lb  oz  i × 16
Weight  lb  short ton   i ÷ 2000
Weight  lb  mg  ((i × 454) × 15.43234) × 64.8
Weight  short ton   g   (i × 907.2) × 1000
Weight  short ton   kg  i × 907.2
Weight  short ton   mt  i × .9072
Weight  short ton   oz  (i × 2000) × 16
Weight  short ton   lb  i × 2000
Weight  st  g   (i × 6.36) × 1000
Weight  st  kg  i × 6.36
Weight  st  mt  (i × 6.36) ÷ 1000
Weight  st  oz  (i × 14) × 16
Weight  st  lb  i × 14
Temperature °F  °C  (i-32) × (5 ÷ 9)
Temperature °F  K   i+161.15
Temperature °C  K   i+273.15
Temperature °C  °F  i × (9 ÷ 5)+32
Temperature K   °C  i-273.15
Temperature K   °F  i-161.15
Capacity    mL  cL  i ÷ 10
Capacity    mL  dL  i ÷ 100
Capacity    mL  L   i ÷ 1000
Capacity    mL  tsp i ÷ 4.9
Capacity    mL  fl oz   i ÷ 29.57
Capacity    mL  pt  (i ÷ 29.57) ÷ 16
Capacity    dL  cL  i × 10
Capacity    dL  L   i ÷ 10
Capacity    dL  mL  i × 100
Capacity    L   mL  i × 1000
Capacity    L   cm³ i × 1000
Capacity    L   in³ i × 61.022
Capacity    tsp fl oz   i ÷ 6
Capacity    tsp mL  i × 4.9
Capacity    tsp tbsp    i ÷ 3
Capacity    tbsp    tsp i × 3
Capacity    fl oz   pt  i ÷ 16
Capacity    fl oz   mL  i × 29.57
Capacity    fl oz   qt  i ÷ 32
Capacity    c   fl oz   i × 8
Capacity    gill    dL  i × 1.183
Capacity    gill    pt  i ÷ 4
Capacity    pt  fl oz   i × 16
Capacity    pt  qt  i ÷ 2
Capacity    pt  c   i × 2
Capacity    pt  gill    i × 4
Capacity    pt  gal i ÷ 4
Capacity    qt  L   i × .95
Capacity    qt  fl oz   i × 32
Capacity    qt  pt  i × 2
Capacity    qt  in³ i × 57.75
Capacity    qt  c   i × 4
Capacity    qt  gal i ÷ 4
Capacity    qt  English fl oz   i × 40
Capacity    Wine qt fl oz   i × 32
Capacity    US dry qt   in³ i × 67.20
Capacity    gal L   i × 3.78
Capacity    gal pt  i × 8
Capacity    gal mL  (i × 3.78) × 1000
Capacity    gal qt  i × 4
Capacity    in³ qt  i ÷ 57.75
Area    ha  acre    i × 2.471
Area    ha  yd² (i × 2.471) × 4840
Area    ha  m²  i × 10000
Area    acre    yd² i × 4840
Area    acre    m²  i × 4046.86
Area    acre    ha  i ÷ 2.471
Area    m²  acre    i ÷ 4046.86
Area    m²  yd² (i ÷ 4046.86) × 4840
Area    m²  ha  i ÷ 10000
Area    yd² acre    i ÷ 4840
Area    yd² m²  (i ÷ 4840) × 4046.86
Area    yd² ha  (i ÷ 4840) ÷ 2.471
Time    ms  s   i ÷ 1000
Time    ms  min i ÷ 60000
Time    ms  h   i ÷ 3600000
Time    ms  d   i ÷ 86400000
Time    ms  w   i ÷ 604800000
Time    ms  m   i ÷ 2628000000
Time    ms  y   i ÷ 31536000000
Time    s   min i ÷ 60
Time    s   h   i ÷ 3600
Time    s   d   i ÷ 86400
Time    s   w   i ÷ 604800
Time    s   m   i ÷ 2628000
Time    s   y   i ÷ 31536000
Time    s   ms  i × 1000
Time    min s   i × 60
Time    min h   i ÷ 60
Time    min d   i ÷ 1440
Time    min w   i ÷ 10080
Time    min m   i ÷ 43800
Time    min y   i ÷ 525600
Time    min ms  i × 60000
Time    h   s   i × 3600
Time    h   min i × 60
Time    h   d   i ÷ 24
Time    h   w   i ÷ 168
Time    h   m   i ÷ 730
Time    h   y   i ÷ 8760
Time    h   ms  i × 3600000
Time    d   s   i × 86400
Time    d   min i × 1440
Time    d   h   i × 24
Time    d   w   i ÷ 7
Time    d   m   i ÷ 30.4166666667
Time    d   y   i ÷ 365
Time    d   ms  i × 86400000
Time    w   s   i × 604800
Time    w   min i × 10080
Time    w   h   i × 168
Time    w   d   i × 7
Time    w   y   i ÷ 52.1428571429
Time    w   ms  i × 604800000
Time    y   s   i × 31536000
Time    y   min i × 525600
Time    y   h   i × 8760
Time    y   d   i × 365
Time    y   w   i × 52.1428571429
Time    y   m   i × 12
Time    y   ms  i × 31536000000
Digital byte    KB  i ÷ 1024
Digital byte    MB  i ÷ 1000000
Digital KB  MB  i ÷ 1000
Digital KB  byte    i × 1024

Rendered table

Excel Filter

HTML filter

I want to be able to filter this table as in excel.
Programming would be in JavaScript

console log results adding to each other, rather than printing separately

I have a function that works, and it gives me the correct return when I only use one consol.log statement. But as soon as I add 2 or more console.log statements when calling my function, it will add the printed return values together rather than print them individually. I do not want this.

Ran the function

let sum = 0;
const scores = [];

function getAverage(scores) {
  for (let i = 0; i < scores.length; i++) {
    sum += scores[i];
  }
  return (sum / scores.length)
}

console.log(getAverage([92, 88, 12, 77, 57, 100, 67, 38, 97, 89]));
console.log(getAverage([45, 87, 98, 100, 86, 94, 67, 88, 94, 95]));

Which correctly prints the first log statement as 71.7, but instead of printing 85.4 below as my second console.log should, it adds the two together into 157.1. When I comment out the first console.log, then the second log statement works just fine. I am just unsure of what is adding the two return values together when both values are printed at the same time.

.Net export to CSV file using javascript, and replacing character

I’m using .NET 8.0.

I am exporting a grid to CSV file using javascript…

One column of the grid has this value

AAA;BBB;CCC 

When I export to CSV I need that the cell that contains this value appear one under the other in the same cell ,like this

Column1   Name       Value

1         apple         AAA
                        BBB
                        CCC
2         orange        DDD  

I have this function in JS

function GenerateCSV(table_id, name) {
    // Select rows from table_id
    var rows = document.querySelectorAll('table#' + table_id + ' tr');
    // Construct csv
    var csv = [];
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll('td, th');
        for (var j = 0; j < cols.length; j++) {
            // Clean innertext to remove multiple spaces and jumpline (break csv)
            var data = cols[j].innerText.replace(/(ss)/gm, ' ').replace(";", "rn")
              row.push('"' + data + '"');
         }
        csv.push(row.join(','));
    }
    var csv_string = csv.join('n');

    var filename = name + '.csv';
    var link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('target', '_blank');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

In this line

var data = cols[j].innerText.replace(/(ss)/gm, ' ').replace(";", "rn")

I am replacing “;” for “rn”

it half works.. It just replace the first character ";" instead of replacing all ";"
It shows

 Column1   Name       Value
    
    1      apple         AAA
                         BBB;CCC

How can make the replacement on the entire line?

Thanks

Storing tokens using Cache API in a service worker

I have a project where I need to attach a bearer token onto HTTP requests going to an API. The straightforward way to persist the token is to store it in localStorage and then manually attach it to every fetch call. However, to prevent/partially mitigate XSS risks, I was wondering if the following was a better alternative:

  • All HTTP communication to the API is handled in a separate service worker. The “rendering process code” (i.e. the one with access to the DOM) communicates with the service worker via postMessage etc to access the api
  • The token is stored in a global variable in the service worker and persisted by the Cache API
  • To prevent the main page form accessing the Cache API, I set caches.match, caches.open etc all to null in a script element at the very very top of every page
  • A very strict CSP directive for workers is set so that no untrusted code can run on any worker

The cache API was chosen instead of indexeddb etc mainly because I didn’t think I would need it at all so disabling it in the page process had limited side effects.

Wondering what potential flaws this solution might have.

Why is unshift so much faster than shift?

I am trying to build a fast queue and seeing my two options,

shift <- [1][2][3][4] <- push
unshift -> [4][3][2][1] -> pop

, I was pretty stunned to find that there is such huge difference between them.

I understand why push and pop are faster than unshift and shift, because all elements in the array need to be adjusted, but why is there such huge difference between unshift and shift?

Times in milliseconds.

push 2.600000023841858
unshift 989.2999999523163

pop 4.100000023841858
shift 14029.299999952316

push/shift 14032.600000023842
unshift/pop 993.7999999523163

function test(repeats, array, method, arg) {
  const start = performance.now()
  for (let i=0; i < repeats; i++) array[method](arg)
  return performance.now() - start
}

let arr, start
let length = 100000

start = performance.now()
arr = []
console.log("push", test(length, arr, "push", 1))
assert(arr.length === length, "Not expected length")
  
console.log("shift", test(length, arr, "shift"))
assert(arr.length === 0, "Not expected length")

console.log("push/shift", performance.now() - start)

start = performance.now()
arr = []
console.log("unshift", test(length, arr, "unshift", 1))
assert(arr.length === length, "Not expected length")
  
console.log("pop", test(length, arr, "pop"))
assert(arr.length === 0, "Not expected length")

console.log("unshift/pop", performance.now() - start)

function assert(condition, message) { if (!condition) throw message }

Fadeout in a scroll animation

So i have found this code, and i want to add some small fadeout to this animation. So on one scroll it goes through some frames, and i wanna add two things that i need some help with. So first of all, how to make it go through more frames on one scroll, and second of all, how to add a fadeout effect to one scroll? Yeah, im pretty stupid in JS for now.

const html = document.documentElement;
const canvas = document.getElementById("hero-lightpass");
const context = canvas.getContext("2d");

const frameCount = 148;
const currentFrame = index => (
  `https://www.apple.com/105/media/us/airpods-pro/2019/1299e2f5_9206_4470_b28e_08307a42f19b/anim/sequence/large/01-hero-lightpass/${index.toString().padStart(4, '0')}.jpg`
)

const preloadImages = () => {
  for (let i = 1; i < frameCount; i++) {
    const img = new Image();
    img.src = currentFrame(i);
  }
};

const img = new Image()
img.src = currentFrame(1);
canvas.width=1158;
canvas.height=770;
img.onload=function(){
  context.drawImage(img, 0, 0);
}

const updateImage = index => {
  img.src = currentFrame(index);
  context.drawImage(img, 0, 0);
}

window.addEventListener('scroll', () => {  
  const scrollTop = html.scrollTop;
  const maxScrollTop = html.scrollHeight - window.innerHeight;
  const scrollFraction = scrollTop / maxScrollTop;
  const frameIndex = Math.min(
    frameCount - 1,
    Math.ceil(scrollFraction * frameCount)
  );
  
  requestAnimationFrame(() => updateImage(frameIndex + 1))
});

preloadImages()

I did try several times to do it by myself, but i think i just didnt understand the code.

From a web frontend, is it possible to call an third party API that requires a secret key, while keeping the secret key secret?

Let’s say there is an API that does something useful that people pay monthly to consume. Let’s say an endpoint for this API is the following:

https://www.example.com/api/GetMeaningOfLife

When POSTing to the API, the client must provide a secret key that identifies they are a paying customer to the API. If no secret key is provided, the API fails.

When in the context of a web application, to ensure the secret key remains secret, one can just consume the API on the server side, and pass along the result of the API call to the resulting web page. This way there is no way for users to snoop around in the browser’s developer console to find the secret key, since the API consumption is done on the server.

However, what if the API is meant to be called from the frontend (i.e. JavaScript)? How do you call a service like this from JavaScript with a secret key, but also ensure others cannot just copy/paste the secret key from your site and start impersonating you on their own site to access an API you are paying for? What options do I have?

Node js install in webstrom/visual studio

Hi please support me on this issue i dont know what I getting error on webstrom software and visual studio.
I just install Node js
Node ver: v22.11.0

and im trying to run the command:
npx create-react-app my-app

and I got errors
please see my terminal :

Loss of info on refresh , javascript. Refetching not working

let globalPlayers = [];
let currentList = []; // This will store the current players


// DOMContentLoaded event listener to execute the functions
document.addEventListener('DOMContentLoaded', function () {
    // Fetch current players first, then fetch all players
    fetchCurrentPlayers();
});

// Function to fetch current players and add to currentList
function fetchCurrentPlayers() {
    fetch('helpers/fetch_pairings.php')
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch current players');
            }
            return response.json();
        })
        .then(currentPlayersData => {
            console.log('Fetched current players data:', currentPlayersData);  // Log the response to inspect its structure
            
            // Ensure that the 'data' is an array before calling map
            if (Array.isArray(currentPlayersData.data)) {
                const currentListTemp = currentPlayersData.data.map(playerData => {
                    return new Player(
                        playerData.PlayerID,
                        playerData.playerName,
                        playerData.playerPhoto,
                        playerData.playerRole,
                        parseFloat(playerData.value) || 0,
                        playerData.ClubID,
                        playerData.clubName,
                        `gallery/clubs/${playerData.ClubID}.png`, // Use ClubID for image path
                        playerData.pointsThisRound || 0,
                        false, // isCaptain default value
                        playerData.priceHistory || [], // Optional field
                        playerData.statistics || null // Optional field
                    );
                });

                console.log(currentList); // Log the processed current list
                currentList = currentListTemp;
                // Once current players are fetched, fetch all players and filter out paired ones
                fetchAllPlayers();
            } else {
                console.error('Expected an array for "data", but got:', currentPlayersData.data);
                // Handle the case where "data" is not an array or is missing
            }
        })
        .catch(error => {
            console.error('Error fetching current players:', error);
        });
}



// Function to fetch and display all players
function fetchAllPlayers() {
    fetch('helpers/fetch_all_players.php')
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch players');
            }
            return response.json();
        })
        .then(playersData => {
            // Extract unique club names and roles
            const uniqueClubs = new Set();
            const uniqueRoles = new Set();

            const players = playersData.map(playerData => {
                // Add clubName and playerRole to respective sets
                if (playerData.clubName) uniqueClubs.add(playerData.clubName);
                if (playerData.playerRole) uniqueRoles.add(playerData.playerRole);

                // Create and return a Player object
                return new Player(
                    playerData.PlayerID,
                    playerData.playerName,
                    playerData.playerPhoto,
                    playerData.playerRole,
                    parseFloat(playerData.value) || 0,
                    playerData.ClubID,
                    playerData.clubName,
                    `gallery/clubs/${playerData.ClubID}.png`,
                    playerData.pointsThisRound || 0,
                    false, // isCaptain default value
                    playerData.priceHistory || [],
                    playerData.statistics || null
                );
            });

            // Filter out players that are already in currentList (paired players)
           // Create a Set from currentList for fast lookups
            const currentPlayerIDs = new Set(currentList.map(player => player.playerID));
            
            // Filter out players that are in currentList
            const unpairedPlayers = players.filter(player => !currentPlayerIDs.has(player.playerID));
            
            


            // Assign the unpaired players to globalPlayers
            globalPlayers = unpairedPlayers;

            // Populate filters with unique clubs and roles
            populateFilters('clubFilter', Array.from(uniqueClubs));
            populateFilters('roleFilter', Array.from(uniqueRoles));

            // Add listeners for filters and search box
            setupFilterListeners();
            setupSearchListener();
            setupSortListeners();

            console.log(globalPlayers);
            console.log(currentList);

            displayPlayers(globalPlayers);
        })
        .catch(error => {
            console.error('Error fetching players:', error);
        });
}

So , the fetching itself works , i logged it and i saw it . the thing is when refresh the page. the currentPlayers comes as Empty but the globalPlayers refetches the info again. Why is it happening?
The spinners update fine aswell , so that makes me thing that fetchAllPlayers is running but fetchCurrentPlayers isn’t which would be very strange because fetchAllPlayers is called only inside fetchCurrentPlayers()

Thanks in advance!

axios behind a domain

I have a problem with my frontend which is built and mounted to my FastApi application.

The frontend uses a custom axios client, which dynamically loads the baseURL from a config.js file.

No matter what I do, the frontend redirects all API calls to http://ip:port/api/path instead of https://sub.domain.tld/api/path.

Here some snippets of my custom axios client:

export const useApiStore = defineStore('api', () => {
  const baseURL = ref(window.config.baseURL || '');
  console.log('Initial baseURL:', baseURL.value);

  const client = computed(() => {
    console.log('Creating axios client with baseURL:', baseURL.value);
    return axios.create({
      baseURL: baseURL.value, 
    });
  });

  const setBaseURL = (url) => {
    console.log('Setting new baseURL:', url); 
    baseURL.value = url;
  };

  return { baseURL, client, setBaseURL };
});

Load the api.js into main.js:

const app = createApp(App);
const pinia = createPinia();
app.use(pinia);

const apiStore = useApiStore();
apiStore.setBaseURL(window.config.baseURL); 

From the vue component make an api_call:

const apiStore = useApiStore();
const response = await apiStore.client.post('/api/v1/start', payload);

This code, at least in my opinion, should work.

I’ve been trying to solve this bug for weeks, but just can’t seem to get it fixed.

The reverse proxy cannot really be at fault here, as NginxProxyManager works with like everything, without any custom config.

Why is Split() not being read properly?

I’m working on a challenge called Compare the Triplets in Hacker Rank where the function takes in two arrays as parameters and you are meant to compare the indexes and award a point to the group with a higher number and return the score for each array.

my code is as follows:

let aTemp = readLine().split(' ');
    let a0 = parseInt(aTemp[0]);
    let a1 = parseInt(aTemp[1]);
    let a2 = parseInt(aTemp[2]);
    let bTemp = readLine().split(' ');
    let b0 = parseInt(bTemp[0]);
    let b1 = parseInt(bTemp[1]);
    let b2 = parseInt(bTemp[2]);
    
    let aScore = 0;
    let bScore = 0;
    
    if(a0 > b0){
        a++;
    };
    if (a0 < b0){
        b++;
    };
    if(a1 > b1){
        a++;
    };
    if (a1 < b1){
        b++;
    };
    if(a2 > b2){
        a++;
    };
    if (a2 < b2){
        b++;
    };
    console.log(aScore + ' ' + bScore);

I am getting the error:

TypeError: Cannot read properties of undefined (reading ‘split’)

I have tried searching this error to get more information but do not seem to see anything relevant to my issue.

why am I getting NaN? Javascript function w/ for loop

I am trying to use a function to add up the numbers in an array and take the average of them. When I try to call my function I get NaN, rather than the average of my array values. the code is below

let sum = 0
const scores = [];
function getAverage(scores) { for(let i=0; i< scores.length; i++) {sum +=      getAverage(i);} console.log(sum/scores.length)}

getAverage([90, 24, 34, 44, 76, 67, 88]);

Expecting the average of my array values. However it just prints NaN.

Deploying My Multi-Page Application to Vercel and GitHub Pages

I’m having a frustrating time trying to deploy my multi-page web application to both Vercel and GitHub Pages. The application is simple, with three pages: an index page, a contact page, and an about me page. It also includes various assets like images, screenshots, and JavaScript files, along with dependencies like Bootstrap and FontAwesome (installed via Node modules).
Check the GitHub repo here.
Check the hosted one for GitHub live demo and the one for Vercel live demo

Problems Encountered on Vercel:

  1. Image Issues: When I deploy the application, the images don’t load on the live site.
  2. Routing Issues: Other pages like the contact page and about me page are sometimes not accessible, often returning a “Page Not Found” error.
  3. Styling and Script Issues: Inconsistent rendering — sometimes CSS partially works, but JavaScript files don’t load at all. At other times, everything looks completely broken.

Problems Encountered on GitHub Pages:

  1. Deployment fails entirely — when I check GitHub Pages, my site doesn’t appear to host properly.
  2. There’s no error log visible for troubleshooting, so I’m stuck figuring out why the site won’t load.

My Folder Structure:

Gallery
├─ .git
├─ .gitignore
├─ about.html
├─ contact.html
├─ index.html
├─ LICENSE
├─ package-lock.json
├─ package.json
├─ README.md
├─ src
│  ├─ assets
│  │  └─ images
│  │     ├─ screenshots
│  │     │  ├─ about.png
│  │     │  ├─ contact.png
│  │     │  └─ index.png
│  │     └─ static
│  │        ├─ Images I used in the HTML files are here
│  ├─ scripts
│  │  ├─ all.js
│  │  └─ classes
│  │     └─ builder.js
│  └─ styles
│     ├─ about.css
│     ├─ all.css
│     └─ color.css
├─ vercel.json
├─ vite.config.json
└─ vite.config.mjs

What I’ve Tried:

  1. I verified the folder structure, ensuring all assets are properly linked.
  2. I’ve checked and updated my package.json and build scripts to align with the hosting requirements.
  3. On GitHub Pages, I ensured the gh-pages branch exists and the correct source is selected in settings.
  4. On Vercel, I used both default settings and manual configurations but still faced the same issues.

File snippets
Here are some on the files incase you need them.

  1. package.json
{
  "name": "gallery",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "devDependencies": {
    "vite": "^6.0.1",
    "vite-plugin-static-copy": "^2.2.0"
  },
  "dependencies": {
    "@fortawesome/fontawesome-free": "^6.7.1",
    "@popperjs/core": "^2.11.8",
    "bootstrap": "^5.3.3"
  }
}

  1. vercel.json:
{
  "builds": [{ "src": "package.json", "use": "@vercel/static-build" }],
  "routes": [{ "src": "/(.*)", "dest": "/index.html" }]
}
  1. vite.config.mjs:
import { defineConfig } from 'vite';

export default defineConfig({
    build: {
        outDir: 'dist'
    }
});

An image of the output after I run build (not what I am expecting at all)

I’m trying to make a slow loading effect but I’ve run into a problem

document.addEventListener('DOMContentLoaded', () => {
    let img = document.querySelector('.logosection-logo');
    let timer = 0;
    let inset = 0

    for (let i = 0; i <= 10; i++) {
        setTimeout(() => {
            img.style.clipPath = 'inset(0 0 ' + inset + '% 0)';
        }, timer);
        inset = 100 - i*10
        timer += 100;
        console.log(timer, i*10, inset)
    }
});

it doesnt working at all somebody know how to fix it?

as i understand the error is related to async, i am new to js