How can my Javascript function log an expected value and still return undefined? [duplicate]

I have a recursive function that I put together for a challenge which calculates factorials by building an array and then reducing the values of the array in order to return the expected value.

When I run the function, I’m able to log my expected value but return ‘undefined’. Any explanation as to why this occurs would be greatly appreciated.

const sumOf = (thisArray) => thisArray.reduce((a,b)=> a + b)
let factorArray = [1, 1]

function factorial(endAtNumber) {
  if (endAtNumber === 1) return 1;
  if (endAtNumber === factorArray.length) {
    console.log(endAtNumber === factorArray.length)    // logs true
    console.log(sumOf(factorArray))                    // logs expected value (e.g factorial(5) = 120)
    return sumOf(factorArray)                          // returns undefined
  }
  else {
    let pushValue = sumOf(factorArray)
    let factorArrayLen = factorArray.length
    factorArray = []
    for (let i = 0; i <= factorArrayLen; i++) {
      factorArray.push(pushValue)
    }
  }
  factorial(endAtNumber)
}

console.log(factorial(5))
// expecting 120; returns undefined

How to send web app build files with API?

I am trying to create something similar to tawk.to or talkjs.com.
But I don’t know how to embed my app to user’s website and send data with their unique id.
For example tawk.to has user put the below code in their website:

For example tawk.to uses something like this:
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/UNIQUEUSERID/default';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->

And then sends this code via the URL above:

(function(global){
    global.$_Tawk_AccountKey='UNIQUEUSERID';
    global.$_Tawk_WidgetId='default';
    global.$_Tawk_Unstable=false;
    global.$_Tawk = global.$_Tawk || {};
    (function (w){
    function l() {
        if (window.$_Tawk.init !== undefined) {
            return;
        }

        window.$_Tawk.init = true;

        var files = [
            'https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-main.js',
            'https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-vendor.js',
            'https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-chunk-vendors.js',
            'https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-chunk-common.js',
            'https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-runtime.js',
            'https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-app.js'
        ];

        if (typeof Promise === 'undefined') {
            files.unshift('https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-promise-polyfill.js');
        }

        if (typeof Symbol === 'undefined' || typeof Symbol.iterator === 'undefined') {
            files.unshift('https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-iterator-polyfill.js');
        }

        if (typeof Object.entries === 'undefined') {
            files.unshift('https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-entries-polyfill.js');
        }

        if (!window.crypto) {
            window.crypto = window.msCrypto;
        }

        if (typeof Event !== 'function') {
            files.unshift('https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-event-polyfill.js');
        }

        if (!Object.values) {
            files.unshift('https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-object-values-polyfill.js');
        }

        if (typeof Array.prototype.find === 'undefined') {
            files.unshift('https://embed.tawk.to/_s/v4/app/62835fee0eb/js/twk-arr-find-polyfill.js');
        }

        var s0=document.getElementsByTagName('script')[0];

        for (var i = 0; i < files.length; i++) {
            var s1 = document.createElement('script');
            s1.src= files[i];
            s1.charset='UTF-8';
            s1.setAttribute('crossorigin','*');
            s0.parentNode.insertBefore(s1,s0);
        }
    }
    if (document.readyState === 'complete') {
        l();
    } else if (w.attachEvent) {
        w.attachEvent('onload', l);
    } else {
        w.addEventListener('load', l, false);
    }
})(window);

})(window);

Let’s say I have a index.js and index.css as build files of my app. And want to send custom data with user’s unique id to them. How can I set up a backend for this?

JavaScript innerHTML is undefined in console [duplicate]

I have this function that generates random characters when the page loads to essentially have a decoding animation. I call the decryptFunction from the setInterval:

var firstInterval = setInterval(function(){
decryptName();
clearInterval(interval);
 }, 200);

The code works fine but I keep getting the error:
functionality.js:15 Uncaught TypeError: Cannot read properties of undefined (reading ‘innerHTML’)
at decryptName (functionality.js:15:51)
at functionality.js:45:5

The code for the decrypt function is:

function decryptName(){
var name = document.getElementsByClassName("name")[0];
for (var i = 0, j = name.children.length; i <= j; i++) {
    if(name.getElementsByClassName("chars")[i].innerHTML != message[i]){
        var randomNum = Math.floor(Math.random() * message.length); 
        name.getElementsByClassName("chars")[i].innerHTML = message[randomNum];
        }
    else {
        document.getElementsByClassName("chars")[i].style.borderColor = "black";
        document.getElementsByClassName("chars")[i].style.backgroundColor = "black";
    }
}

}

Here’s the HTML code for the elements the functions are interacting with :

  <div class="firstSection">
            <div class="name">
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
                <br>
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
                <div class="chars"></div>
            </div>

Any help would be appreciated, been stuck on this error for a while. The code works fine, it’s just the error message I get in the console.

socket.io ‘on’ doesn’t get fired with Nodejs server

server.js

const express_l = require('express');
const path_l    = require('path');
const app_l     = express_l();
const http_l    = require('http');

const server_l   = http_l.createServer( app_l);

const socketio_l = require('socket.io');
const io_l = socketio_l( server_l);

app_l.use( express_l.static( path_l.join( __dirname, 'public')) );

io_l.on( "connection", argSocket => { console.log('New websocket connection!'); });

var PORT = 3000 || process.env.PORT;

server_l.listen( PORT, ()=>{ console.log(`from express server on port ${PORT}!`) });

main.js

const socket = io_l();

chat.html

...
...
  <script src = "/socket.io/socket.io.js"> </script>
  <script src = "js/main.js"> </script>
</body>
</html>

package.json

{
  "name": "chatcord",
  "version": "1.0.0",
  "description": "Realtime chat application built with Nodejs",
  "main": "server.js",
  "scripts": {
    "start": "node server",
    "dev": "nodemon server"  
  },
  "author": "xyz",
  "license": "MIT",
  "dependencies": {
    "express": "^4.18.1",
    "moment": "^2.29.3",
    "socket.io": "^4.5.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.16"
  }
}

Now, when I refresh http://localhost:3000/ in browser, I don’t see the console.log statement from the on function of socket.io.

Where am I going wrong? Please point out.

How do I map a specifik key in a json object? [duplicate]

I want to map a specifik key in a json object. I find tons of examples to do this will all keys, but what if you want the value of only one of them?

  • Object.keys(obj) – returns all the keys of object as array
  • Object.values(obj) – returns all the values of the object as array
  • Object.entries(obj) – returns an array of [key, value]

How do I get the result [“Doe”,”Smith”,”Jones”] with the example below?

jsonObj = [
  {"firstName":"John", "lastName":"Doe"},
  {"firstName":"Anna", "lastName":"Smith"},
  {"firstName":"Peter", "lastName":"Jones"}
]

Only list the values of lastName.

How would you map over an array with specific properties?

so using react I have a list of checkboxes and just hard-coded pretty much all the checkmarks (14 of them), I have been having a tough time doing this because i keep getting errors mainly because the I am trying to replace the numbers with index and also each one sets a new state for those specific values.. ill post the code and hopefully I can get some ideas of how it could be done, sorry I am new to programming

                <div className="stack pad">
                  <Checkbox
                    id="multi-filter-check-1"
                    label="CVP"
                    value="CVP"
                    onChange={(e) => {
                      setFilteredChannel(!checked[0] ? e.target.value : '');
                      handleCheck(e, 0);
                    }}
                    checked={checked[0]}
                    disabled={!!checked[1]}
                  />
                  <Checkbox
                    id="multi-filter-check-2"
                    label="SAC"
                    value="SAC"
                    onChange={(e) => {
                      setFilteredChannel(!checked[1] ? e.target.value : '');
                      handleCheck(e, 1);
                    }}
                    checked={checked[1]}
                    disabled={!!checked[0]}
                  />
                </div>
                <h3 className="heading-1 pad-lr">Business Unit</h3>
                <div className="stack pad">
                  <Checkbox
                    id="multi-filter-check-3"
                    label="CCSG"
                    value="CCSG"
                    onChange={(e) => {
                      setFilteredUnit(!checked[2] ? e.target.value : '');
                      handleCheck(e, 2);
                    }}
                    checked={checked[2]}
                    disabled={!!checked[3]}
                  />
                  <Checkbox
                    id="multi-filter-check-4"
                    label="SBS"
                    value="SBS"
                    onChange={(e) => {
                      setFilteredUnit(!checked[3] ? e.target.value : '');
                      handleCheck(e, 3);
                    }}
                    checked={checked[3]}
                    disabled={!!checked[2]}
                  />
                </div>
                <h3 className="heading-1 pad-lr">Enrollment Type</h3>
                <div className="stack pad">
                  <Checkbox
                    id="multi-filter-check-5"
                    label="INSTANT"
                    value="INSTANT"
                    onChange={(e) => {
                      setFilteredEtype(!checked[4] ? e.target.value : '');
                      handleCheck(e, 4);
                    }}
                    checked={checked[4]}
                    disabled={!!checked[5]}
                  />
                  <Checkbox
                    id="multi-filter-check-6"
                    label="DELAYED"
                    value="DELAYED"
                    onChange={(e) => {
                      setFilteredEtype(!checked[5] ? e.target.value : '');
                      handleCheck(e, 5);
                    }}
                    checked={checked[5]}
                    disabled={!!checked[4]}
                  />
                </div>
                <h3 className="heading-1 pad-lr">Offer Type</h3>
                <div className="stack pad">
                  <Checkbox
                    id="multi-filter-check-7"
                    label="consumer-upgrade"
                    value="consumer-upgrade"
                    onChange={(e) => {
                      setFilteredOffer(!checked[6] ? e.target.value : '');
                      handleCheck(e, 6);
                    }}
                    checked={checked[6]}
                    disabled={!!checked[7]}
                  />
                  <Checkbox
                    id="multi-filter-check-8"
                    label="SBS-UPGRADE"
                    value="SBS-UPGRADE"
                    onChange={(e) => {
                      setFilteredOffer(!checked[7] ? e.target.value : '');
                      handleCheck(e, 7);
                    }}
                    checked={checked[7]}
                    disabled={!!checked[6]}
                  />
                </div>
                <h3 className="heading-1 pad-lr">Stop Request Status</h3>
                <div className="stack pad">
                  <Checkbox
                    id="multi-filter-check-9"
                    label="SYSTEM"
                    value="SYSTEM"
                    onChange={(e) => {
                      setFilteredStopReq(!checked[8] ? e.target.value : '');
                      handleCheck(e, 8);
                    }}
                    checked={checked[8]}
                    disabled={!!checked[9] || !!checked[10]}
                  />
                  <Checkbox
                    id="multi-filter-check-10"
                    label="USER"
                    value="USER"
                    onChange={(e) => {
                      setFilteredStopReq(!checked[9] ? e.target.value : '');
                      handleCheck(e, 9);
                    }}
                    checked={checked[9]}
                    disabled={!!checked[8] || !!checked[10]}
                  />
                  <Checkbox
                    id="multi-filter-check-11"
                    label="NONE"
                    value="NONE"
                    onChange={(e) => {
                      setFilteredStopReq(!checked[10] ? e.target.value : '');
                      handleCheck(e, 10);
                    }}
                    checked={checked[10]}
                    disabled={!!checked[8] || !!checked[9]}
                  />
                </div>
                <h3 className="heading-1 pad-lr">Enrollment Status</h3>
                <div className="stack pad">
                  <Checkbox
                    id="multi-filter-check-12"
                    label="SUCCESS"
                    value="SUCCESS"
                    onChange={(e) => {
                      setFilteredEnrollStat(!checked[11] ? e.target.value : '');
                      handleCheck(e, 11);
                    }}
                    checked={checked[11]}
                    disabled={!!checked[12] || !!checked[13] || !!checked[14]}
                  />
                  <Checkbox
                    id="multi-filter-check-13"
                    label="PENDING"
                    value="PENDING"
                    onChange={(e) => {
                      setFilteredEnrollStat(!checked[12] ? e.target.value : '');
                      handleCheck(e, 12);
                    }}
                    checked={checked[12]}
                    disabled={!!checked[11] || !!checked[13] || !!checked[14]}
                  />
                  <Checkbox
                    id="multi-filter-check-14"
                    label="ABORTED"
                    value="ABORTED"
                    onChange={(e) => {
                      setFilteredEnrollStat(!checked[13] ? e.target.value : '');
                      handleCheck(e, 13);
                    }}
                    checked={checked[13]}
                    disabled={!!checked[11] || !!checked[12] || !!checked[14]}
                  />
                  <Checkbox
                    id="multi-filter-check-15"
                    label="FAILED"
                    value="FAILED"
                    onChange={(e) => {
                      setFilteredEnrollStat(!checked[14] ? e.target.value : '');
                      handleCheck(e, 14);
                    }}
                    checked={checked[14]}
                    disabled={!!checked[11] || !!checked[12] || !!checked[13]}
                  /> 
                </div>

Debugging game – array elements disappear when paused/breakpoint in developer tools

Game link and github repo

I am writing a space-shooter type game in vanilla js as a project for my first dev resume.

I am using html canvas to draw this game.

I have an ‘intro screen’ that is drawn for a few seconds before the game starts.

I have a click event listener that makes the main character shoot bullets.

There is a state class with an instance initialized once when the game starts. The state class has a characters property what holds an array with all the characters. The first character is the main character (called ‘Dilo’) and the next characters should be bullet class instances – added each time I on the canvas.

Issue:
When I click before the intro level ends, the bullets are added to the state.characters array, and are drawn on the canvas once the intro level ends.
HOWEVER
When I click after the intro level has ended (and game has started), the bullets are added to the state.characters array, but they are not drawn – it seems that their .update method is not call when it should be.

One of my major issues debugging is that I’ll see the unresponsive bullets in the state.update array, so I set breakpoints to see what goes wrong when their updte method SHOULD be called, BUT whenever the program pauses – the bullets disappear from the array. I can never debug with developer tools because they evaporate at every pause.

CSS attribute based conditional selector

I am working with a SVG element which is following

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
  <rect class="vBoxRect" width="1280" height="720" fill="green"></rect>
  <rect class="boundRect" x="70" y="70" width="1090" height="500" fill="green"></rect>
  <g class="bound" style="transform: translate(70px, 70px);">
    <g class="lines">
      <path class="ln1" d="M908.3333333333334,282.6600519725961L999.1666666666666,281.4207650273231" fill="none" stroke="white" opacity="0"></path>
      <path class="ln2" d="M45.416666666666664,458.72033023735816L136.25,458.72033023735816" fill="none" stroke="white" opacity="0"></path>
      <path class="ln3" d="M136.25,319.8198198198196L227.08333333333334,301.3071895424839" fill="none" stroke="white" opacity="1"></path>
      <path class="ln4" d="M45.416666666666664,294.2783670845388L136.25,289.9924997321333" fill="none" stroke="white" opacity="0"></path>
      <path class="ln5" d="M90.83333333333333,405.88235294117646L181.66666666666666,417.7735610373184" fill="none" stroke="white" opacity="1"></path>
    </g>
  </g>
</svg>

I want to write a selector in javascript that would return the first <path></path> which has opacity=1, which is

<path class="ln3" d="M136.25,319.8198198198196L227.08333333333334,301.3071895424839" fill="none" stroke="white" opacity="1"></path>

I am not sure how to do this. I tried document.querySelector(".lines>path[opacity=1]"); and it did not work.

I am looking for something in javascript that would be equivalent to the following SQL query

select TOP 1 * from DOM where opacity=1 and CAT='path'

example

Headings must have content and the content must be accessible by a screen reader React v.6

Created a random number generator application in React. According to the idea, you can choose different cubes and the value of the faces of the cubes is included in the value of the button. But it turns out that when the application is first loaded, an error occurs that the value of the button variable cannot be empty. What should I do in this situation?

import React from 'react'
import './Dice.css'

const diceButton = document.querySelector('.dice__button');
const btnD6 = document.getElementById("btn_d6");
const btnD20 = document.getElementById("btn_d20");
const btnD4 = document.getElementById("btn_d4");

//d20
function d20(min, max) {
    min = Math.ceil(1);
    max = Math.floor(20);
    var res = Math.floor(Math.random() * (max - min + 1)) + min;

   
    document.getElementById("demo").innerHTML ="&nbsp;" + res;
}

//d6
function d6(min, max) {
    min = Math.ceil(1);
    max = Math.floor(6);
    var res = Math.floor(Math.random() * (max - min + 1)) + min;

    document.getElementById("demo").innerHTML ="&nbsp;" + res;
}

//d4
function d4(min, max) {
    min = Math.ceil(1);
    max = Math.floor(4);
    var res = Math.floor(Math.random() * (max - min + 1)) + min;

    document.getElementById("demo").innerHTML ="&nbsp;" + res;
}


function dropD6() {
    diceButton.addEventListener('click', d6);
    document.getElementById("dice__button").innerHTML = "Кинуть d6:";
    document.getElementById("dice__type").innerHTML = "d6:";
}

function dropD20() {
    diceButton.addEventListener('click', d20);
    document.getElementById("dice__button").innerHTML = "Кинуть d20:";
    document.getElementById("dice__type").innerHTML = "d20:";
}

function dropD4() {
    diceButton.addEventListener('click', d4);
    document.getElementById("dice__button").innerHTML = "Кинуть d4:";
    document.getElementById("dice__type").innerHTML = "d4:";
}


diceButton.addEventListener('click', d20);
btnD6.addEventListener('click', dropD6);
btnD20.addEventListener('click', dropD20)
btnD4.addEventListener('click', dropD4)

const Dice = () => {
    
  return (
    <>
        <div class="main__div">
            <div class="dices__main">
                <div class="d20">
                    <div class="dice_tw">
                        <h1 class="dice_tw_screen" >Значение&nbsp;</h1>
                        <h1 class="dice_tw_screen" id="dice__type">d:</h1> 
                        <h1 class="dice_tw_screen" id="demo"></h1> 
                    </div>
                    <button class="dice__button" type="button" id="dice__button">Выбери дайс</button>
                </div>
    
                <div class="t">
                    <div class="wrapper">
                        <button class="dice__button_1" id="btn_d4">d4</button>
                    </div>
                    <div class="wrapper">
                        <button class="dice__button_1" id="btn_d6">d6</button>
                    </div>
                    <div class="wrapper">
                        <button class="dice__button_1" id="btn_d8">d8</button>
                    </div>
                    <div class="wrapper">
                        <button class="dice__button_1" id="btn_d10">d10</button>
                    </div>
                    <div class="wrapper">
                        <button class="dice__button_1" id="btn_d12">d12</button>
                    </div>
                    <div class="wrapper">
                        <button class="dice__button_1" id="btn_d20">d20</button>
                    </div>
                </div>
            </div>
        </div>
    </>
  )
}

export default Dice
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

setTimeout() inside a object and then don’t work

I’m building a interactive fiction game for a project of my school, but the setTimeout() function don’t work

const game = { 
   init: function () { 
     let intro1 = `– Ouçam irmãos, hoje essa escória tenta nos desafiar.  
   Aquele cujo os bárbaros chamam Aslog "O grande terror do leste",  
   ousa invadir o reino élfico e pôr em risco nossa sagrada capital.  
   Os bárbaros dizem que o exercício dele é imbatível, que não há  
   mortal, e até mesmo, deus que possa derrotá-lo em batalha,`; 
     let intro2 = `que ele devora tudo o que encontra, mas oq eu digo é que essas são  
   balelas de covardes que aceitaram a derrota e nem conseguiram se  
   defender. Nós somos Elfos, os favoritos dos deuses, aqueles a quem  
   foram confiados a magia, os garantidores da paz.`; 
     let intro3 = `Não há exército mortal ou demoníaco que não sucumba a nossa força. Hoje essa  
   monstruosidade perecerá pelas nossas flechas,lanças e magia,  
   hj esse "Terror" encontrará o seu fim na ponta de minha espada,  
   e mais um conquistador bárbaro sucumbirá na fronteira de nossa  
   sagrada capital.`; 
     let intro4 = `Arqueiros recepcione o invasor com o frio de  
   nosso aço, magos façam as estrelas caírem e o chão se abrir,  
   que os deuses lutem conosco. Glória aos deuses, Glória aos seus  
   favoritos, pela vitória! 
   – Arqueiros atirar! 
   – magos formação de batalha!`; 
     let intro = function () { 
       setTimeout(function (){console.log(intro1)}, 75); 
       setTimeout(function () { 
         console.log(intro2); 
       }, 1000); 
       setTimeout(function () { 
         console.log(intro3); 
       }, 2000); 
       setTimeout(function () { 
         console.log(intro4); 
       }, 3000); 
     }; 
     console.log(intro()); 
   }, 
  hist: function () { 
     this.init();}}
game.hist()

The original code has more stuff, but is to long to put here, but this doesn’t log nothing in the console. Someone know why?

Promise from AWS Typescript SDK S3 client never completes during Lambda execution

I just started learning Javascript and Typescript a week and a half ago. I’m writing a Lambda function in Typescript, however I cannot get the final S3 API call to complete and I am not sure what I’m doing wrong. My code (with some edits):

import {SQSHandler, SQSEvent, Context} from 'aws-lambda';

const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
import { Readable } from 'stream';

const s3 = new AWS.S3({region: "us-east-1"});

const bucket_name = "bucket";

export const handler: SQSHandler = async (event: SQSEvent, context: Context): Promise<void> => {
    console.log("EVENT: n" + serialize(event.Records));
    console.log(`Context: ${serialize(context)}`);
    // console.log('## ENVIRONMENT VARIABLES: ' + serialize(process.env));
    console.log(`AWS version: ${AWS.VERSION}`);

    await createS3Bucket(bucket_name);

    let uploads = [];
    let s3_key = "";

    for (const record of event.Records) {
        const body = JSON.parse(record.body);
        s3_key = 's3key';
        console.log(`Key name ${s3_key}`);

        const readableStream = new Readable();
        readableStream._read = () => {};
        readableStream.push(serialize(body));

        console.log(`Attempting upload to ${bucket_name}/${s3_key}..`);

        uploads.push(saveFileStreamToS3(s3_key, readableStream));
    }

    console.log(`Waiting for ${ uploads.length } uploads to finish...`);

    try {
        await Promise.all(uploads);
        console.log(`Uploads of ${ uploads.length } succeeded.`);
    } catch (error) {
        console.log(`Uploads of ${ uploads.length } failed.`);
    }
}

async function saveFileStreamToS3(key: string, fileStream: Readable) {
    try {
        console.log(`Attempting upload and returning promise..`);
        return s3
            .upload({
                Bucket: bucket_name,
                Key: key,
                Body: fileStream
            })
            .promise();
    } catch (exception) {
        throw new Error(exception);
    }
}

async function createS3Bucket(bucketName: string) {
    console.log(`Creating bucket ${bucketName}`);
    await s3.createBucket({
        Bucket: bucketName,
        ACL: 'private',
    }).promise();
}

let serialize = function (object) {
    return JSON.stringify(object, null, 2);
}

let clean = function (stringToClean) {
    return stringToClean.replace(""", "").replace(""", "").trim();
}

The first createbucket call completes, however the S3 uploads never do. I know the saveFileStreamToS3() method gets called with my handler function is invoked, however, neither of the log lines indicating all promises returned by s3.upload() complete or fail, ie. no exceptions, nothing. What am I missing here? Any help is greatly appreciated!

Counter App: Button function to trigger various if else messages

I’m building a passenger counter application for buses with vanilla javascript and I’m trying to wrap my head around how, when clicking a HTML DOM Object button, will alter the messages I want to output based on where the count is.

I have an increase and decrease button that increase or decrease the count by 1. Each bus has different passenger capacities, so I’ve placed each three busses in the navbar (dds, ddsb, mci). When clicking “dds” for example, I want specific messages to be called relative to where the count is. Likewise for other bus models.

let messageEl = document.getElementById("message-el")
let countEl = document.getElementById("count-el")
let ddsNavEl = document.getElementById("dds-nav-el")
let ddsbNavEl = document.getElementById("ddsb-nav-el")
let mciNavEl = document.getElementById("mci-nav-el")
let increaseEl = document.getElementById("increase-btn")
let decreaseEl = document.getElementById("decrease-btn")
let increaseFiveEl = document.getElementById("increaseFive-btn")
let decreaseFiveEl = document.getElementById("decreaseFive-btn")
var count = 0

/* BASIC COUNTER FUNCTIONALITY WITH NO SEATING LIMIT WARNINGS */
function increase() {
    count++
    countEl.textContent = count
}

function decrease() {
    count--
    countEl.textContent = count
}

function increaseFive() {
    count += 5
    countEl.textContent = count
}

function decreaseFive() {
    count -= 5
    countEl.textContent = count
}

function reset() {
    messageEl.textContent = "";
    countEl.textContent = 0
    count = 0
    ddsNavEl.style.fontWeight = "normal";
    ddsbNavEl.style.fontWeight = "normal";
    mciNavEl.style.fontWeight = "normal";
} 


/* COUNTER WITH SEATING AND STANDING LIMIT WARNINGS */

function ddsSelect() {

    if (count === 15) {
        message = "you are at full seating capacity"
    } else if (count > 16) {
        message = "you are over capacity"
    } else {
        message = ""
    }
    messageEl.textContent = message
    
    ddsNavEl.style.fontWeight = "bold";
    ddsbNavEl.style.fontWeight = "normal";
    mciNavEl.style.fontWeight = "normal";
}

function ddsbSelect() {

    if (count === 12) {
        message = "you are at full seating capacity"
    } else if (count > 13) {
        message = "you are over capacity"
    } else {
        message = ""
    }
    messageEl.textContent = message

    ddsbNavEl.style.fontWeight = "bold";
    ddsNavEl.style.fontWeight = "normal";
    mciNavEl.style.fontWeight = "normal";
}

function mciSelect() {
    
    if (count === 10) {
        message = "you are at full seating capacity"
    } else if (count > 11) {
        message = "you are over capacity"
    } else {
        message = ""
    }
    messageEl.textContent = message

    mciNavEl.style.fontWeight = "bold";
    ddsNavEl.style.fontWeight = "normal";
    ddsbNavEl.style.fontWeight = "normal";
}

Variable returns NaN when i try to subtract variable and function together

I’m probably stuck on the most obvious problem but i can’t really figure it out why is my promoPrice variable returning NaN. I suspect it’s because i’m trying to subtract a variable with a function but i can’t seem to find an alternative for what i’m trying to do here.

function program() {
  var productPrice;
  var promoPrice;

  function AskForPrice() {
    return (productPrice = parseFloat(prompt("Informe o preço do produto: ")));
  }

  function Discount(productPrice) {
    return productPrice * 0.05;
  }

  AskForPrice();
  promoPrice = parseFloat(productPrice - Discount());

  document.write(
    `Initial value: ${productPrice}<br>Value after discount: ${promoPrice}`
  );

  console.log(typeof promoPrice);
  console.log(typeof productPrice);
}

program();