Could you explain me this freecodecamp recursion function, please?

Here’s the code

function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : rangeOfNumbers(startNum, endNum - 1).concat(endNum);
}

I understand that until startNum equals endNum it will recall itself, but the thing that I don’t understand is where the value is stored?

Say for example it’s rangeOfNumbers(3,6)
So it’s gonna be like this:

6-1
5-1
4-1

Right? And each time the numbers are added to the array and we get [3,4,5,6], but I don’t understand how and where it stores this array.

If I’m not mistaken, concat merges two or more arrays, but there are no arrays.

I just want to have a full understanding of it. Otherwise, I won’t remember it and won’t be able to use it.

Appearing/disappearing element using ‘style.display’ not working

So I thought it would be pretty simple to implement an if statement to have an element appear or disappear at the click of a button.
After a couple of hours now, I have not gotten further than getting the element to disappear. It registers the second click(tested with a console.log), but the display property does not change back to ‘flex’.

I’ve also already tried different variations of ‘getElementById’ and ‘querySelector’ during my sentence.

const edit = document.getElementById('edit-btn');
const fill = document.querySelector('#filler');

edit.addEventListener('click', popInOut(fill))

function popInOut(e){
    if(e.style.display=='flex'){
        e.style.display='none'
    }else if(e.style.display=='none'){
        e.style.display='flex'
    }
}

The ‘filler’ element is a bootstrap column with this styling.

#filler{
    display:flex;
    flex-direction: column;
    background-color: #1c1f22;
    position:absolute;
    top:40%;
    height:50%;
}

How to secure a no-authentication game leaderboard?

I making a online quiz game (SPA web application) and I want to implement a leaderboard with the player’s score. I’m sending a request with the player’s initials and score to my back-end (REST API). Problem is that anybody could see the request to the REST API, in the network tab, and send a similar request from Postman. How do you secure such a leaderboard? There is no authentication – you just type in 3 symbols (your initials) just like in arcade games.

I’m using ExpressJS with MongoDB for the API.

“GET http://localhost:8801/main.js net::ERR_ABORTED 404 (Not Found)” error

Google thinks that I am trying to read data from localhost:8801, but I am trying to read that data from another file called “main.js.” The error is “GET http://localhost:8801/main.js net::ERR_ABORTED 404 (Not Found)” How can I reference the command from main.js without google thinking that it is a subdirectory. Here is my code in index.html:

https://sourceb.in/iuMyon5XI7

Thank you in advance.

405 Method Not Allowed – Axios

I am trying to get a user’s email and save it to a database without refreshing the page using Axios but, I keep getting a 405 error. Also, I am trying to connect to my localhost using post from postman api and I am getting a 405 error as well.

Html:

<form id="emaildata" action="" method="POST" role="form">
              <input type="email" name="email" id="joinme" placeholder="Email:">
              <input type="submit" value="Subscribe">
</form>

JS/Axios:

 (function() {
      "use strict";
      document.getElementById("emaildata").addEventListener("submit", function(e) {
        e.preventDefault();
        let email = document.getElementById("joinme").value;
    
        const emailData = new FormData();
        emailData.append('email', email);
        emailData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    
        axios.post('http://127.0.0.1:8000', emailData) // 4
          .then(res => alert("Form Submitted")) // 5
          .catch(errors => console.log(errors)) // 6
      });
    })()

Postman:405 Error

Google apps script function work in backend but called by javascript responds undefined

Ok, this is my function.

.gs
function createIfNotExistSheet( name = 'Controller Settings' ) {
  var resp = "";
  try {
    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var newSheet = activeSpreadsheet.getSheetByName(name);

    if (newSheet == null) {
      newSheet = activeSpreadsheet.insertSheet();
      newSheet.setName(name);
    }
    resp = "Sheet "+ name +" are ready, at id = "+ newSheet.getSheetId();
  }
  catch (e) {
    resp = e;
  }
  finally{
    Logger.log(resp);
    return resp;
  }
}

I call it from js with:

js.
settingsFile = google.script.run.createIfNotExistSheet(cC.settingsFile['name']);

Whether I call it with or without the argument the result does not change, settingsFile returns undefined.

export css file to be available through a url

I have the following scenario.

Two independent node projects need to have the same css colouring. My idea is that I have a custom.css in my public folder of my node project, and another node project would be able to consum this file over a link. For example, if my node project runs on localhost:3000, my idea is that the css file would be available by localhost:3000/custom.css.

Does anybody has an idea how to do that?

I am looking for a way to implement such a link to export the css.

Thanks in advance

JavaScript Image Collision Detection

Ok. So, I’m trying to find out when 2 images collide in a game I made, but I’ve been receiving conflicting advice and I’m not exactly sure how to get any of the solutions to work (as all of them result in errors, and the collision results as null)

here are the two options I’ve been trying to solve (any solution works really, I’m just stumped and can’t seem to get it to work regardless of what I try).

  // first option
  function trackXY(){
        for(let i=0; i<2; i++){
          let playerrr = document.getElementById('moveAva');
          let pikaTest = document.getElementById('pikaLocation' + i);
          
          let playHeight = window.getComputedStyle(playerrr).getPropertyValue('height');
          let playWidth = window.getComputedStyle(playerrr).getPropertyValue('width');
          let playLeft = window.getComputedStyle(playerrr).getPropertyValue('left');
          let playTop = window.getComputedStyle(playerrr).getPropertyValue('top');

          let pokeHeight = window.getComputedStyle(pikaTest).getPropertyValue('height');
          let pokeWidth = window.getComputedStyle(pikaTest).getPropertyValue('width');
          let pokeLeft = window.getComputedStyle(pikaTest).getPropertyValue('left');
          let pokeTop = window.getComputedStyle(pikaTest).getPropertyValue('top');
          let xPlayer = parseInt(playLeft + .5*playWidth);
          let yPlayer = parseInt(playTop + .5*playHeight);
          let xEnemy = parseInt(pokeLeft + .5*pokeWidth);
          let yEnemy = parseInt(pokeTop + .5*pokeHeight);
          let rPlayer = .5*parseInt(playHeight);
          let rEnemy = .5*parseInt(pokeHeight);
          let dX = xEnemy - xPlayer;
          let dY = yEnemy - yPlayer;
          let distance = Math.sqrt((dX*dX)+(dY*dY))
          if(distance <= (rEnemy+rPlayer)){
              alert("collison!");
              playHeight = parseInt(playHeight) + .5*parseInt(pokeHeight);
              document.getElementById('pikaInvent').style.display = "block";
              document.getElementById('pikaWon').style.display = "block";
          }
        }
      }
     //second option
     function trackXY(){
        for(let i=0; i<1; i++){
            let playerrr = document.getElementById('moveAva');
            let pikaTest = document.getElementById('pikaLocation' + i);


        let xPlayer = parseInt(playerrr.style.left + .5*playerrr.style.width);
        let yPlayer = parseInt(playerrr.style.top + .5*playerrr.style.height);
        let xEnemy = parseInt(pikaTest.style.left + .5*pikaTest.style.width);
        let yEnemy = parseInt(pikaTest.style.top + .5*pikaTest.style.height);
        let rPlayer = .5*parseInt(playerrr.style.height);
        let rEnemy = .5*parseInt(pikaTest.style.height);
        let dX = xEnemy - xPlayer;
        let dY = yEnemy - yPlayer;
        let distance = Math.sqrt((dX*dX)+(dY*dY))
        if(distance <= (rEnemy+rPlayer)){
            alert("collison!" + enemy.id);
        }
      }
    }
trackXY();

if anyone could help, I could really appreciate it. Or, if you have another solution for collision detection with 2 rectangular images. Thanks!

Binance API {“code”:-1022,”msg”:”Signature for this request is not valid.”}. Not sure what I am doing incorrectly

I’m not sure what is wrong with this code. I think I might be missing something somewhere but I can’t figure it out. I keep getting the error

const ts = Date.now()

var crypto = require('crypto')
                  , text = 'recvWindow=59999&timestamp=ts' 
                  , key = 'BqDjQf3F5VNOvSaX1rncMsZqmSOpGTBPz5UgOohto0P3bQlfHvjUlVrkbYc6pwc3'
                  , hash;

var hash = crypto.createHmac('sha256', key).update(text).digest('hex');


[hash, key, ts.toString()];

Clear completed task button To-do list

I have tried to create a code that clear all completed task (completed task which is the items with a line-through on them) when the clear completed button is clicked. I will leave the function open as I’m open to new ideas and you should run code snippet to better understand the question.thanks

var addButton = document.getElementById("add_button");
var ul = document.querySelector("ul");
var input = document.getElementById("entry_box");
var clearBtn = document.getElementById("clear");
var saveBtn = document.getElementById("save");
var emptyBtn = document.getElementById("empty");


function newToDoItem() {
  var li = document.createElement("li");
  li.appendChild(document.createTextNode(input.value));
  ul.appendChild(li);
  input.value = "";
}

function inputLength() {
  return input.value.length;
}

function addToDoItem() {
  if (inputLength() > 0) {
    newToDoItem();
  }
}

function keyPressEvent(event) {
  if (inputLength() > 0 && event.keyCode === 13) {
    newToDoItem();
  }
}

function toggleToDoItemState(event) {
  if (event.target.tagName === "LI") {
    event.target.classList.toggle("done");
  }
}


addButton.addEventListener("click", addToDoItem);
//clearBtn.addEventListener("click", clearCompletedToDoItems);
ul.addEventListener("dblclick", toggleToDoItemState);
input.addEventListener("keypress", keyPressEvent);
*{
    
    padding: px0;
    margin: px0;
}
body{
    width:100%;
    display:-webkit-box;
    -webkit-box-pack:center;
    
    
}

#big_wrapper{
    text-align: center;
    max-width:1000px;
    margin:20px 0px;
    display:-webkit-box;
    background: rgb(201, 207, 214);
    -webkit-box-orient: vertical;
    -webkit-box-flex:1;
    border-radius: 20px;

}
#big_wrapper{
      width:1000px;
    
}
#position{
    padding: 20px;

}
ul {
    cursor: pointer;
}

.done {
    text-decoration: line-through;
}
<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="utf-8" />
    <title>erand boy</title>
    <link rel="stylesheet" href="todo.css" />
  </head>
  <body>
    <div id="big_wrapper">
      <div id="position">
        <header>
          <h1>My to-do list</h1>
          <p>wirte the list of things you need to do here.</p>
        </header>
        <div>
          <input type="text" id="entry_box" />
          <button id="add_button">Add</button>
          <p><strong>Double click an item to mark it complete.</strong></p>
          <ul id="toDolist" style="text-align: left"></ul>
        </div>
        <div id="button_wrapper">
          <button id="save">Save list</button>
          <button id="clear">Clear completed</button>
          <button id="empty">Empty list</button>
        </div>
      </div>
    </div>
    <script src="to-do.js"></script>
  </body>
</html>

Thrheybsh

Implementing TLV in javascript

I am trying to implement TLV for e-invoice in Javascript. I am able to convert the values to hex and from hex to base64. When I add the base64 value to the QRcode and try to test it, I get an error telling me there is something wrong with my data. Below is my implementation

const  __toString = (tag, value) => {
    const tagToHex = "0"+(tag).toString(16)
    const valueLengthToHex = value.length <= 15 ? "0" + (value.length).toString(16) :(value.length).toString(16)
    const valueToHex = this.toHex(value)

    return `${tagToHex}${valueLengthToHex}${valueToHex}`;
}

const toHex = (str) => {
    let result = '';
    for (let i=0; i<str.length; i++) {
      result += str.charCodeAt(i).toString(16);
    }
    return result;
}

Entry point

const generateString = [
    __toString(1, 'Bobs Records'),
    __toString(2, '310122393500003'),
    __toString(3, '2022-04-25T15:30:00Z'),
    __toString(4, '1000.00'),
    __toString(5, '150.00'),
];

return btoa(generateString.join(''))

MDEwYzQyNmY2MjczMjA1MjY1NjM2ZjcyNjQ3MzAyMGYzMzMxMzAzMTMyMzIzMzM5MzMzNTMwMzAzMDMwMzMwMzE0MzIzMDMyMzIyZDMwMzQyZDMyMzU1NDMxMzUzYTMzMzAzYTMwMzA1YTA0MDczMTMwMzAzMDJlMzAzMDA1MDYzMTM1MzAyZTMwMzA=

I get the base64 string above. When I set it as the value of the qrcode and try to scan it, I get errors and I do not know where I am missing it.

Can I use async/await in Jest, when the tested function is not using async/await?

I have a simple controller for adding new users. After the successful resolution (user added), the controller sends a 202 response. As you can see, the function is promise based and is not using async/await.

const addUserController = function (req, res, next) {
    Users.addOne(req.userid, req.body.email)
    .then(() => {
      res.status(202).send();
    })
    .catch((err) => {
      console.log(err);
      res.status(500).json({ message: "Internal server error." });
    });
};

When I am testing this function in Jest with the, the function executes immediately, without going to the then() part, resulting in a mistaken 200 code, instead of 202, so the following test fails:

it("Should add a user", () => {
    let req, res, next, pool;
    pool = new Pool();
    req = httpsMocks.createRequest();
    res = httpsMocks.createResponse();
    res.next = null;
    req.userid = 1;
    req.body = {
      id: 2
    }
    pool.query.mockResolvedValue({rows:[], rowCount: 1});
    apiController.addUserController(req, res, next);
    expect(res.statusCode).toBe(202);
    expect(pool.query).toBeCalledTimes(1);
});

However, when I make it like that:

it("Should add a user", async () => {
    let req, res, next, pool;
    pool = new Pool();
    req = httpsMocks.createRequest();
    res = httpsMocks.createResponse();
    res.next = null;
    req.userid = 1;
    req.body = {
      id: 2
    }
    pool.query.mockResolvedValue({rows:[], rowCount: 1});
    await apiController.addUserController(req, res, next);
    expect(res.statusCode).toBe(202);
    expect(pool.query).toBeCalledTimes(1);
});

that is I add async/await, it works alright – the response status code is 202, meaning the function was awaited and the test passes.
But why? When I hover over the newly added ‘await’ VS code is suggesting that

‘await’ has no effect on the type of this expression.

Well it makes sense – it should have no effect, as the tested function is not async, so it shouldn’t work, but well, it works – only when I add the async/await to the Jest function it works fine.

Could someone explain this to me?

Regex match dash optional flag

I’m trying to interpret user commands as dash optional flag.

{run -o -f -a file1 file2}

Something like this:

/{run (-o|-f) (w+) (.+?)}/g;

Is very limiting with only 1 choice of flag, how do I let them flag any amount, spit out the flags into groups, and not worry about a set amount of whitespace in between.

string = "{run    -a  file1 file2}"
string = "{run    -a -o -f  file1 file2}"
string = "{run -f-a-o  file1 file2}"

string.match(regex) should output each flag and each file name.