Stuck in Simple Maths Recursive Issue Javascript

I’m working on this Math recursive question.
What is needed to do is when I put in 0 to the console, it should display the answer then take that answer put into the equation and display the next answer, it should continuing doing this till the value indicate on the loop.

At the moment this is my code:

const pw= (x) =>{
    sum = []
    for(let i=0; i<5; i++){
    let a = (x*x*x)
    sum+= ((4-a)/10)
        
    }
    return sum
    
}

So if I put in 0 the answer is 0.4, then it should take that answer (0.4) automatically put it through the code and return the next answer which is 0.3 and so on.

At the moment that’s where i’m stuck i dont know how to automatically put the next vaule in.
Any guidance will be appreachiated.

console.log(pw(0))
(0.4)
(0.3)
(0.3973)
(0.3937287271683)

Express.js: req.body is empty when using form-data

I’m encountering an issue where req.body is empty when I send data using form-data in my Express.js application. However, when I send data using raw JSON, I receive the expected object in req.body. Here’s my setup:

This is my index.js

require("dotenv").config();
const express = require("express");
const server = express();
const cors = require("cors");
const port = process.env.PORT || 3000; 
const bodyParser = require("body-parser");
//database
require("./db/conn");

//middlewares
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
server.use(cors());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());

//routes
const userRouter = require("./routes/UserRoutes");
const authRouter = require("./routes/AuthRouter");

server.use("/user", userRouter);
server.use("/auth", authRouter);

server.listen(port, () => {
  console.log(`server started at http://localhost:${port}`);
});

This is route

const express = require("express");
const router = express.Router();
const { Auth } = require("../middlewares/auth");

const {
  Login,
  UpdateUser,
  Dashboard,
  Register,
  Posts,
} = require("../controllers/UserController");

router.post("/register", Register);
router.post("/login", Login);
router.put("/update/:id", Auth, UpdateUser);
router.get("/dashboard", Auth, Dashboard);
router.get("/getposts", Auth, Posts);

module.exports = router;

This is controller

const UserModel = require("../model/userModel");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");

const Register = async (req, res) => {
  console.log(req.body);
  res.send(req.body);
  const { name, email, password } = req.body;
  // if (!name || !email || !password) {
  //   return res.status(400).json({ error: "All fields are required" });
  // }
  // try {
  //   const user = await UserModel.findOne({ email });
  //   if (user) {
  //     return res.status(400).json({ error: "User already exists" });
  //   }

  //   const hashedPassword = await bcrypt.hash(password, 10);

  //   const newUser = new UserModel({
  //     name,
  //     email,
  //     password: hashedPassword,
  //   });
  //   const saveUser = await newUser.save();
  //   res
  //     .status(201)
  //     .json({ message: "User registered successfully", user: saveUser });
  // } catch (error) {
  //   res.status(500).json({ error: "Something went wrong at the server" });
  // }
};

const Login = async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    return res.status(400).json({ error: "All fields are required" });
  }

  try {
    const user = await UserModel.findOne({ email });
    if (!user) {
      return res.status(404).json({ error: "Invalid login details" });
    }
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      return res.status(401).json({ error: "Invalid login credentials" });
    }
    const payload = {
      id: user.id,
      email: user.email,
    };
    const accessToken = jwt.sign(payload, process.env.SECRET_KEY, {
      expiresIn: "1m",
    });
    const refreshToken = jwt.sign(payload, process.env.SECRET_KEY, {
      expiresIn: "10d",
    });

    res.status(200).json({
      message: "login sucessfull",
      isLogged: "true",
      data: payload,
      accesstoken: accessToken,
      refreshtoken: refreshToken,
    });
  } catch (error) {
    res.status(500).json({ error: "Something went wrong at the server" });
  }
};

const UpdateUser = async (req, res) => {
  const userId = req.params.id;

  req.body.password = await bcrypt.hash(req.body.password, 10);

  try {
    const user = await UserModel.findOne({ _id: userId });
    if (!user)
      return res.status(500).json({ message: "no user found with this id" });

    const updatedUser = await UserModel.findOneAndUpdate(
      { _id: userId },
      req.body,
      {
        new: true,
      }
    );

    if (updatedUser) {
      return res
        .status(200)
        .json({ message: "user updated  sucessfully", data: updatedUser });
    }
  } catch (e) {
    return res
      .status(500)
      .json({ message: "something went bad at server " + e });
  }
};

const Dashboard = async (req, res) => {
  res.status(200).json({ message: "Welcome to the dashboard" });
};

const Posts = async (req, res) => {
  res.status(200).json({ message: "post request" });
};

const getAllData = async (req, res) => {
  res.status(200).json({ message: "get data" });
};
module.exports = { Login, UpdateUser, Dashboard, Posts, Register };

I’ve already tried adjusting the middleware order, but the issue persists. Any insights into what might be causing this problem would be greatly appreciated.

Resuming a conversation in Bot Framework throws TypeError: Cannot perform ‘set’ on a proxy that has been revoked

I’m playing with the Microsoft Teams Bot Framework samples, specifically bot-conversation (source)

I want to post user messages to a back-end via a websocket, then post a message to chat when I get a response.

I’m currently wiring the bot up as follows

class TeamsConversationBot extends TeamsActivityHandler {
    ws = null;

    constructor(adapter) {
        super();
        this.adapter = adapter;

        this.onMessage(async (context, next) => {
            //Outbound messages from user to back-end. Works fine.
            TurnContext.removeRecipientMention(context.activity);
            await context.sendActivity({ type: 'typing' });
            const text = context.activity.text.trim();

            await this.handleUserPrompt(context, text);
            await next();
        });


        this.ws = new WebSocket('wss://.../dev');
        this.ws.on('message', async (data) => {
            // Inbound message from back-end to user
            console.log('nKhydra->Teams: ', data.toString('utf8'));
            const messageData = JSON.parse(data);
            await this.handleKhydraFragment(messageData);
        });
    }

And this is how I’m attempting to rehydrate the conversation when I get a text block to display.

    async handleKhydraFragment(messageData) {
        const fragment = messageData.fragment;
        if ('textBlock' in fragment) {
            const claimsIdentity = await this.adapter.createClaimsIdentity(process.env.MicrosoftAppId);
            await this.adapter.continueConversationAsync(claimsIdentity, messageData.conversationReference, async (context) => {
                context.sendActivity(fragment.textBlock);
            });
        } else {
            console.log(fragment);
        }
    }

Interestingly, the correct text is posted to the chat when a fragment with a textBlock arrives, however, immediately after that I get

E:SourceMicrosoft-Teams-Samplessamplesbot-conversationnodejsnode_modulesbotbuilder-corelibturnContext.js:392
                    this.responded = true;
                                   ^

TypeError: Cannot perform 'set' on a proxy that has been revoked
    at Proxy.<anonymous> (E:RoboraSourceMicrosoft-Teams-Samplessamplesbot-conversationnodejsnode_modulesbotbuilder-corelibturnContext.js:392:36)
    at Generator.next (<anonymous>)
    at fulfilled (E:RoboraSourceMicrosoft-Teams-Samplessamplesbot-conversationnodejsnode_modulesbotbuilder-corelibturnContext.js:9:58)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v18.15.0

What am I missing?

Tic Tac Toe in Javascript with minimax not returning score to original call, any clue how to fix this?

const minimax = (newBoard,currentPlayer)=>{
            
            let availSpots = emptyIndexes(newBoard)
            newBoard = Array.from(newBoard)
            if(CheckForWin(newBoard) && currentPlayer === players[0]){
                return {score:-10}
            }
         else if(CheckForWin(newBoard) && currentPlayer ===players[1]{
                return {score:10}
            }
            else if (availSpots.length === 0){
                return {score:0}
            }
            
            let Moves = []
            for(let k = 0;k<availSpots.length;k++){
                let move = {}
                move.index = availSpots[k]
                newBoard[availSpots[k]] = currentPlayer
                if(currentPlayer === players[1] ){
                    let result = minimax(newBoard,players[0]).score
                    move.score = result
                }
                else{
                    let result = minimax(newBoard,players[1]).score
                    move.score = result
                }
                newBoard[availSpots[k]] = move.index
                Moves.push(move)
                console.log(Moves)
                
            }
            let BestMove;
                if(currentPlayer === players[1]){    
                    let bestscore1 = -Infinity
                        for(let j = 0;j < Moves.length;j++){
                            if(Moves[j].score > bestscore1){
                                bestscore1 = Moves[j].score
                                BestMove = j
                            }    
                        }
                }
                else if(currentPlayer === players[0]){
                    let bestscore = Infinity
                        for(let i = 0;i < Moves.length;i++){
                            if(Moves[i].score < bestscore){
                                bestscore = Moves[i].score
                                BestMove = i 
                            }
                        }
                }
                return Moves[BestMove]
    }                               
function emptyIndexes(array){
        let indexArray = []
        for(i = 0;i<array.length;i++){
            if(array[i] == ''){
                indexArray.push(i)
            }
        }
        return indexArray
    }
      

I think the problem may lie in my call for emptyIndexes.
The return IndexArray always returns 0.
The Moves array does not return score to original 8 open indexes.
how do I get the score to return to the original minimax call function. I’ve tried debugging but couldnt find where im going wrong. Anything helps.

Moduarizing a shiny app with R and JS code

Goal

I have a working shiny app that lets users write handwritten notes in a canvas which are then converted to text input. My goal is now to modularity this functionality so that I can create as my canvases as I want.

Details

This became possible due to the Google Input Tools.

Following is the working code in 4 files:

app.R:

library(shiny)
 
 ui <- fluidPage(
   tags$head(
     tags$script(src = "handwriting.js"),
     tags$script(src = "handwriting.canvas.js"),
     tags$script(src = "handwriting_for_shiny.js"),
     tags$style(HTML("
       #handwritingCanvas {
         border: 1px solid #000;
         margin-top: 10px;
         margin-bottom: 10px;
       }
     "))
   ),
   titlePanel("Handwriting Recognition"),
   sidebarLayout(
     sidebarPanel(
       actionButton("clear_canvas", "Clear Canvas"),
       actionButton("undo", "Undo"),
       actionButton("redo", "Redo"),
       actionButton("send", "Send"),
       textAreaInput("manual_text", "Enter Text", value = "")
     ),
     mainPanel(
       textOutput("recognized_text"),
       br(),
       tags$canvas(id = "handwritingCanvas", width = "400px", height = "200px")
     )
   )
 )
 
 server <- function(input, output, session) {
   observeEvent(input$clear_canvas, {
     session$sendCustomMessage("eraseCanvas", message = NULL)
   })
 
   observeEvent(input$undo, {
     session$sendCustomMessage("undoCanvas", message = NULL)
   })
 
   observeEvent(input$redo, {
     session$sendCustomMessage("redoCanvas", message = NULL)
   })
 
   observeEvent(input$send, {
     session$sendCustomMessage("sendCanvas", message = NULL)
 
   })
 
   observe({
     session$onSessionEnded(stopApp)
   })
 
   observe({
     session$sendCustomMessage("initCanvas", message = NULL)
   })
 
   observeEvent(input$recognized_text, {
     print(input$recognized_text)
     if (!is.null(input$recognized_text)) {
       updateTextAreaInput(session, "manual_text", value = input$recognized_text)
     }
   })
 
 }
 
 shinyApp(ui, server)

Following three files are in the www directory:
(From github) handwriting.js: https://github.com/ChenYuHo/handwriting.js/blob/master/handwriting.js
(From github) handwriting.canvas.js: https://github.com/ChenYuHo/handwriting.js/blob/master/handwriting.canvas.js

handwriting_for_shiny.js

$(document).ready(function() {
         var handwritingCanvas;


     var canvas = document.getElementById('handwritingCanvas');
     handwritingCanvas = new handwriting.Canvas(canvas, 3);

     $('#clear_canvas').click(function() {
       handwritingCanvas.erase();
     });

     $('#undo').click(function() {
       handwritingCanvas.undo();
     });

     $('#redo').click(function() {
       handwritingCanvas.redo();
     });

     $('#send').click(function() {
       var trace = handwritingCanvas.trace;
       var options = {
         language: 'en',
         numOfReturn: 1
       };
       var callback = function(result, err) {
         if (err) {
           console.error(err);
         } else {
           Shiny.setInputValue('recognized_text', result[0]);
         }
       };
       handwriting.recognize(trace, options, callback);
     });

     // Enable undo and redo
     handwritingCanvas.set_Undo_Redo(true, true);

     $('#handwritingCanvas').on('mouseup', function() {
       // Removed the automatic recognition on mouseup
     });
   });

This works. How do I convert this into a module. I understand what I can do in the app.R code but what about the handwriting_for_shiny.js? The critical part there seems to be Shiny.setInputValue(‘recognized_text’, result[0]); The recognized_text thing should somehow be in a namespace., i.e., wrapped in ns in the javascript code. How to do that?

Convert image jpeg external api to webp format [closed]

I would like to inquire about the process of converting PNG images to the WebP format. Could you provide a guide or necessary steps for carrying out this conversion? I am interested in understanding the process in detail, including recommended software or tools, and the potential benefits of using the WebP format compared to PNG in the context of web development. Your insights and guidance in this matter would be immensely valuable to me as I seek to expand my expertise in image manipulation and optimization techniques. I eagerly anticipate your assistance in unraveling the intricacies of PNG to WebP conversion and its implications for web development

I never tried to fix this problem

Using Socket.io in different parts of the project

everybody.
Here’s the thing: how can I process several events in different parts of a file? (react)

Example:

//File1.tsx
     useEffect(()=> {
        socket.on('message', (data: {message: IMessage}) => {
            console.log(data);
        });
        return () => {
            socket.off('message');
        }
    }, []);

and it’s work fine, but:

//File2.tsx
     useEffect(()=> {
        socket.on('message', (data: {message: IMessage}) => {
            console.log(data);
        });
        return () => {
            socket.off('message');
        }
    }, []);

and it’s don’t work

Events are coming in, but everything falls into the first. And when I just change the name of the event (on the server too), everything works fine.

Q: Is it possible to organize processing of several events with the same name?

Can’t add new ‘object in array’ using firestore

I’m having problemas at understanding firestore.

I understand Collection as Array, and Document as value (object).

soy, I want to push a new object inside and array of array, so:

Collection 1, includes Collection A, B, C… etc.

I want to be able to push a new object, in Collection A, inside Collection 1. Is that possible?

import { useState } from 'react';
import { addDoc, collection } from 'firebase/firestore';
import { db } from './firebase';

const useAppointmentDataBase = () => {
    const [success, setSuccess] = useState(false);

    const addNewAppointment = async (dateString, newAppointment) => {
        try {
            const appointmentCollectionRef = collection(
                db,
                'appointmentsDataBase',
                '1-2-3456'
            );

            await addDoc(appointmentCollectionRef, { test: 1, test: 2 });

            setSuccess(true);
        } catch (error) {
            console.error('Error adding document: ', error);
        }
    };

    return { success, addNewAppointment };
};

export default useAppointmentDataBase;

And this is my firestore structure.

enter image description here

I tried to understand the documentation, but still being confused for me….

I want to make an automate clicks on an android game on multiple accs and keep it running 24/7. Any idea how to do this? ;-;

I wanted to automate clicks on an android game on multiple accs and keep it running 24/7 like hosting the automation on some hosting server if it’s possible or keep it running on a PC/phone. I currently have no knowledge on coding, please guide me through what I’d have to learn/do to do the above thing.

I don’t know where to start or anything or any lang or anything like that can help me to begin with.

Why is key name undefined when trying to display key value in html?

I’m trying to display database data in html using Javascript fetch api. I have looked at plenty of content for this problem but nothing seems to work right. However, I can display all the data in json format no problem. The problem occurs when I reference my model field names (key names) in javascript. sun_from_hour returns undefined. Is it a notation problem? I have tried several solutions.

class SundayTime(models.Model):
    sun_teacher_id_time = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True,
                                            default='',
                                            related_name='sun_teacher_time_available_id')
    sun_from_hour = models.TimeField(null=True, blank=False)
    sun_to_hour = models.TimeField(null=True, blank=False)


class SunJsonListView(View):
    def get(self, *args, **kwargs):
        times = list(SundayTime.objects.values('sun_from_hour', 'sun_to_hour'))
        return JsonResponse({'times': times}, safe=False)

const sunButton = document.getElementById('sun_availability_show');
const sunContainer = document.getElementById('sun_availability_div');
const sunUrl = '/daily_appointment_availability-sun_json/'
sunButton.addEventListener('click', reqSunData);


function reqSunData() {
    fetch(sunUrl, {
        method: "GET",
    })
        .then((response) => {
            return response.json();
        })
        .then(times => sunAdder(times))
        .catch((error) => {
            console.error(error);
        })
}

function sunAdder(times) {
    console.log(times);
    const ul = document.createElement('ul');
    sunContainer.append(ul);
    
    Object.keys(times).forEach(timeData => {
        console.log(Object.values(times));
        const li = document.createElement('li');
        li.insertAdjacentHTML('beforeend', `<li>[${times.sun_from_hour}]</li>`);
        // here sun_from_hour is undefined
        li.textContent = JSON.stringify(times);

        ul.append(li);
    })
}

// the json data that is displayed in html 
// {"times":[{"sun_from_hour":"00:00:00","sun_to_hour":"00:45:00"}, 
// {"sun_from_hour":"01:30:00","sun_to_hour":"01:45:00"}]}

Escape Keyboard event not firing while dragging

I’m trying to make a drag event stop when the mouse enters a specific zone. I could not make it work with trying to simulate a mouseup event so I thought I can simulate pressing the escape key to stop the drag event. The simEscape function is starting but it’s not simulating the key stroke.
Any idea why ?

<html>
   <head>
      <style type="text/css">
         #boxA, #boxB {
            float:left;padding:10px;margin:10px;-moz-user-select:none;
         }
         #boxA { background-color: #6633FF; width:75px; height:75px;  }
         #boxB { background-color: #FF6699; width:150px; height:150px; }
      </style>
       
       </head>
   <body>
      <center>
        <div id = "main">
         <h2>cancel drag test</h2>
         <div id="boxA" draggable="true" ondragstart="return dragStart(event)">
            <p>Drag Me</p>
         </div>
         <div id="boxB" ondragenter="return dragEnter(event)" ondrop="return dragDrop(event)" >Stop Dragging here</div>
        </div>   
      </center>
   </body>
   <script>
    function dragStart(ev) {
    ev.dataTransfer.effectAllowed='move';
    ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
    ev.dataTransfer.setDragImage(ev.target,0,0);
    return true;
  }
 function dragEnter(ev) {
    ev.preventDefault();
    simEscape();
    return true;
 }
 function dragOver(ev) {
    simEscape();
    return false;
 }
 function dragDrop(ev) {
    var src = ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(src));
    ev.stopPropagation();
    return false;
 }

function simEscape(){
 console.log("SimEscapedStarted"); // confirm the function starts
   
 const event = new KeyboardEvent('keydown', {
    isTrusted: true,
    charCode: 0,
    key: "Escape",
    code: "Escape",
    which: 27,
    keyCode: 27,
  });
  
  document.getElementById('boxA').dispatchEvent(event);
}
</script>
</html>

Why does my Leetcode Reverse Integer solution does an infinite loop?

For this easy question, I eventually got to this code :

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(b) {
    let x = b;
    let result = 0;
    while(x !== 0) {
        console.log(`tomato: ${x}`)
        let digit = x % 10;
        console.log({digit});
        result = result * 10 + digit;
        console.log({result});
        x = Math.floor(x / 10)
        console.log(`potato ${x}`);
    }
    return result;
};

and it’s running an infinite loop:

tomato: 123
{ digit: 3 }
{ result: 3 }
potato 12
tomato: 12
{ digit: 2 }
{ result: 32 }
potato 1
tomato: 1
{ digit: 1 }
{ result: 321 }
potato 0
tomato: -123

I know the answer is uncomplete, not considering negative numbers, etc, and I got it right eventually, but in this sceneario I don’t understand why potato eventually prints 0 and tomato -123 if there’s no code between them and loop never ends.

Socket IO – event listeners not working on Microsoft edge

In my react app, I connect to my socket IO server like so:

io("http://localhost:5006", {
    query: { username: userData?.username, token },
})

Here is the code for the server side:

    // Configure socket io server

    const io = new Server(server, {
        cors: {
            origin: "*",
        },
    })

    server.listen(5006, () => console.log("Socket conncetd on 3001"))

On the server, I handle the connection event, add the user to the users object, and then add event listeners:

socket.on("send_message", (data) => {
    let otherSocketId = users[data["otherUsername"]]
    console.log("BAKCNE DOK")
    socket.to(otherSocketId).emit("testevent", "WHATTTTTT")
    // socket
    //     .to(otherSocketId)
    //     .emit("receive_message", { message: data.message, chatId: data.chatId })
})

socket.on("disconnect", (reason) => {
    console.log(reason)
    console.log("Disconnected")
})

I emit send_message when a user sends a message to a particular chat/user, and then emit a receive message event. Everything works as expected when tested with Chrome and Firefox, however issues arise when trying with microsoft edge.

When using Microsoft edge, the user successfully connects to the server and can emit the send_message event. The other user receives the receive_message event as expected.

However, the user on Microsoft Edge is unable to listen to the receive_message event, and does not receive any data. They can still emit events successfully. Note that this is not on issue on other browsers. Could this be because of the settings I have in the server? Again, the socket is still connected (socket.connected === true) and the server logs the connection.

Receieve message listener:

socket.on("receive_message", (data) => {
    // nothing logged when using Microsoft edge
    console.log(data)
})

What could be causing this behaviour? I also searched settings that could cause issues with Microsoft edge and websockets, however none of these issues were apparent.

Making text change colour dynamically depending on the colour underneath it

I am trying to have the menu change between black & white depending on the colour underneath it. I have tried mix-blend-mode but it creates certain scenarios where the text just becomes illegible.

I have managed to get it to analyse the background and output a colour but it seems to just read itself when making the decision. I’ve tried to get around it (run the analysis on a :before that sits away from the text but I don’t think it’s working either…

The issue is:
It recognises the background but it won’t change the text colour to contrast against the background. Dark background = white text., light background = black text I’ve tried a few different ways but they would either flicker the colour or just not change the colour at all..

function getContrastRatio(color1, color2) {
  // Convert hex colors to RGB if necessary
  color1 = (color1.charAt(0) === '#') ? color1.substr(1) : color1;
  color2 = (color2.charAt(0) === '#') ? color2.substr(1) : color2;

  // Extract RGB values
  var r1 = parseInt(color1.substr(0, 2), 16);
  var g1 = parseInt(color1.substr(2, 2), 16);
  var b1 = parseInt(color1.substr(4, 2), 16);
  var r2 = parseInt(color2.substr(0, 2), 16);
  var g2 = parseInt(color2.substr(2, 2), 16);
  var b2 = parseInt(color2.substr(4, 2), 16);

  // Calculate relative luminance
  var lum1 = (Math.max(r1, g1, b1) + Math.min(r1, g1, b1)) / 2;
  var lum2 = (Math.max(r2, g2, b2) + Math.min(r2, g2, b2)) / 2;

  // Calculate contrast ratio
  var contrastRatio = (lum1 + 0.05) / (lum2 + 0.05);

  return contrastRatio;
}

function readBackgroundColor() {
  var menu = document.querySelector('.sticky-menu');
  var contentTop = menu.offsetTop + menu.offsetHeight;
  
  // Use the body as the default content element
  var content = document.body;

  // Iterate over all elements with class "colour" to find the one under the menu
  var colours = document.querySelectorAll('.colour');
  for (var i = 0; i < colours.length; i++) {
    var rect = colours[i].getBoundingClientRect();
    if (rect.top >= contentTop && colours[i] !== menu) { // Exclude the menu from consideration
      break;
    }
    content = colours[i];
  }

  // Check if the content element is a child of the menu
  if (!menu.contains(content)) {
    var computedStyle = window.getComputedStyle(content);
    var backgroundColor = computedStyle.backgroundColor;

    // Calculate contrast ratio for black and white text
    var blackContrast = getContrastRatio(backgroundColor, 'black');
    var whiteContrast = getContrastRatio(backgroundColor, 'white');

    // Choose the color with better contrast
    var textColor = blackContrast > whiteContrast ? 'black' : 'white';

    menu.style.color = textColor;

    console.log("Background:", backgroundColor, "Text:", textColor);
  }
}

// Event listener for scroll
window.addEventListener('scroll', readBackgroundColor);

// Initial call to read background color
readBackgroundColor();
body, html {padding:0;margin:0;}
.colour {height:250px;width:100vw;}

.black {background:black;}
.blue  {background:blue;}
.red   {background:red;}
  
.sticky-menu {
  position: fixed;
  top: 0;
  padding: 10px;
  line-height:0;
  font-size:50px;
}
<div class="sticky-menu">home</div>

<div class="colour black"></div>
<div class="colour white"></div>
<div class="colour blue"></div>
<div class="colour red"></div>
<div class="colour white"></div>