Higher Order Functions and Callbacks – Using “return”

function eitherCallback(callback1, callback2) {
  return (element, i, array) => {return callback1(element, i, array) || callback2(element, i, array)}
}

function filterArray(array, callback) {
 const newArray = [];
 for (let i = 0; i < array.length; i += 1) {
   if (callback(array[i], i, array)) newArray.push(array[i]);
 }
 return newArray;
}
const arrOfNums = [10, 35, 105, 9];

const integerSquareRoot = n => Math.sqrt(n) % 1 === 0; // condition 1 as a function
const over100 = n => n > 100; // condition 2 as a function

const intSqRtOrOver100 = eitherCallback(integerSquareRoot, over100); // function to combine functions

console.log(filterArray(arrOfNums, intSqRtOrOver100)); // should log: [105, 9]

Above is a piece of code that I’ve written for my coding bootcamp prep. However, I am confused on the purpose of the second “return” in the eitherCallback function. I have read the syntax on arrow functions in ES6 and I read that the return is not needed if the function is a single line. However, when I remove that second “return” the output of console.log(filterArray(arrOfNums, intSqRtOrOver100)); returns an empty array.

The eitherCallback function takes two arguments: callback1 and callback2, which are going to be functions integerSquareRoot and over100. When I look at those functions, the return of those two functions are booleans which leads me to my confusion. Since callback1 and callback2 already return booleans, why do I get an empty array if I omit the second “return” in the eitherCallback function?

Thank you.

Parse float not working as expected in JS

I trying to alert sum of 2 numbers from inputs but problem is that i cannot convert it into number type. Instead of this i getting NaN.
Snippet:

        var ipt1 = document.getElementById("w1").value
        var ipt2 = document.getElementById("w2").value

        function add(){
        let l1 = parseInt(ipt1)
        let l2 = parseInt(ipt2)

        alert(l1+l2)
        }
<body>
    <input type="" id="w1"><br>
    <input type="" id="w2"><br>

    <input type="submit" value="dodaj" onclick="add()">
</body>

How to update one field according to another in react?

I have two input fields for an exchange interface. The goal is to update the other according to input (based on exchange rate). User can input in either one.

The problem: if users input 5 and get 500 in the other, then they remove two 0 from 500, it won’t be able to get the state update and return 0.05 in the other.

To make it easier to visualize, i have it in codesandbox. Below is the code.

import "./styles.css";
import React from "react";

export default function App() {
  const rate = 100;
  const [token, setToken] = React.useState();
  const [eth, setEth] = React.useState();

  console.log("token", token);
  console.log("eth", eth);

  return (
    <div className="App">
      <h1>1 eth = 100 token</h1>
      <h2>goal: change one input, the other updates automatically</h2>
      <input
        placeholder="eth"
        value={eth}
        onChange={(e) => {
          let eth_input = e.target.value;
          console.log(eth_input);
          setToken(eth_input * rate);
        }}
      />
      <input
        placeholder="token"
        value={token}
        onChange={(e) => {
          let token_input = e.target.value;
          console.log(token_input);
          setEth(token_input / rate);
        }}
      />
    </div>
  );
}

JS import in Vue Single File Component Leads to Error

Here is a sample template I have constructed:


<template>
</template>

<script>
const Vue = require("vue")

</script>

This compiles cleanly and causes no issues. However if I do:


<template>
</template>

<script>
import Vue from "vue"

</script>

I get this error:

process-update.js:32 
        
       TypeError: Cannot set properties of undefined (setting 'render')
    at normalizeComponent (componentNormalizer.js:24:1)
    at Module../components/test.vue (test.vue:8:27)
    at __webpack_require__ (bootstrap:853:1)
    at hotApplyInternal (bootstrap:749:1)
    at Object.hotApply [as apply] (bootstrap:411:1)
    at cb (process-update.js:76:1)
    at process-update.js:91:1

Does anyone know what may be going on?
Thanks in advance!

Where to learn Javascript framework/library authoring?

Any search I try to make on this subject only yields results for learning existing JS frameworks. But I want to know what these guys know to write such frameworks themselves. When I checked out @headlessui/react for example, thinking it had simple enough components from which I can understand some basics of library development, I find they’re still quite complex—the code structure, modular architecture, component organization and data flow… All that could be overwhelming. Very much different from what I would write if I were to create a simple, reusable component the best way I could think of!

I think it’s more than just JavaScript design patterns I need to know. I’d like to write code and build things that people would use, but I find out there’s still much I need to know. Can someone help me as to what resources/books can launch me in that direction? I’ve tried many times but never found what I was looking for. I already know and understand JavaScript so it makes me wonder where these guys are learning from.

how to sum each specific rendered row horizontally on jquery datatable

I get data for datasrc from sql query and I display for each column using

"data": "attribute", "name": "name",
                    "render": function (data, type, full, meta) {}

I can’t get calculate value from sql query, I have to get each rendred value of specific row to sum and put the result in each column horizontally
exemple bellow of eachrow : row 1 col1 + row 1 col2 + row 1 col3 and put te result in row 1 col4

and the same for all horizontal ligne.

Rows                  Col1        Col2      Col3    Col4  col5      col6      col7 
1                      12         1         23       36    string    string   string
2                       1         0          5       6     string    
3                       6         2          9       16    string    

for this jquery datatable serverside Showing 1-10:

"autoWidth": true,
            "processing": true,
            "serverSide": true,
            "ajax": {
                'type': 'POST',
                'url': 
                'dataSrc':function (json) {
                   

                    return json.data;
                },
                'complete': function (response) {
                   
                }
            },
            "columns": [
                {"data": "id"},
               {"data": "attribute", "name": "name",
                    "render": function (data, type, full, meta) {}
}
                    ---
                  ---

Getting the best possible time from a list of trajectories

I have a problem I am working on as homework and I am having trouble figuring out how to solve it and if the approach I am taking can be optimized.

The problem is the following:

As an input I received this :

const inputFull = `08:20;Paris;Berlin
5
09:20;Paris;Amsterdam;03:20
08:30;Paris;Bruxelles;01:20
10:00;Bruxelles;Amsterdam;02:10
12:30;Amsterdam;Berlin;06:10
11:30;Bruxelles;Berlin;09:20`;

The first line is: start_date, start_city, finish_city
The second line is: Number of lines that will follow
The third line is: a list of all trajectories in this format: start_date, start_city, finish_city, duration (HH: mm)

My expected output: the best you can reach the finish_city ( in this case 18:40 )
and the trajectory will be ( line 2 -> line 3 -> line 4 )

This is what I implemented so far, I hit a dead-end I know I am supposed to use recursion but not sure how?

const bestTime = (
  startTime,
  startCity,
  finishCity,
  listTravelSize,
  listTravel
) => {
  var startTimeIter;
  var startCityIter;
  const markTime = [];
  const listTravelSecondIter = [];
  // check only cities that start with the same start city
  const listTravelFiltered = checkCities(listTravel, startCity, startTime);
  // recursion part
  listTravelFiltered.map((item) => {
    // item is of ListTravel type
    startTimeIter = sumTime(item.startTime, item.duration);
    startCityIter = item.finishCity;
    // check if the finish city is the same as the finish city
    if (startCityIter === finishCity) {
      markTime.push(startTimeIter); // first duration + 
    }
    const travel = {
      startTime: startTimeIter,
      startCity: startCityIter,
      finishCity: finishCity,
      duration: item.duration,
    };
    listTravelSecondIter.push(travel);
  });
  bestTime(
    startTimeIter,
    startCityIter,
    finishCity,
    listTravelSecondIter.length,
    listTravelSecondIter
  );
};

React.js – Styled components – center image in direct div parent with other objects

I understand that question looks pretty easy, but I haven’t found anything helping me.

I have an image inside a div, and I want that image to be centered in that div even if I add, for example, a text.

Here is some code and images to better understand that problem :

If I only have my image in my div (with solid border), all is well :

<div>
    <img height = '75px' width = '75px' src={USDCoin}/> 
</div>      

enter image description here

But adding a text, I can’t figure out how to keep the image in the center of the div (well aligned with the grey lines) and the text below that :

<div>
    <img height = '75px' width = '75px' src={USDCoin}/> 
    test
</div>  

enter image description here

Thank you in advance for your precious help !

Discord.js || Can bot track ban list?

There are a lot of to ban a user in a server, you can do it manually or with another bot. I want my bot to scan a banlist, and if someone will get banned, it will send a message “user (id) has been banned

I started writing smt but now, I had no idea what can I do to check it.

client.on('guildBanAdd', messsage =>{

  try {
  const banList = await message.guild.fetchBans();
  if (bannedUser) await message.channel.send(`${bannedUser.tag} is banned.`);
  
})

Unable to center element horizontally and vertically

I’m making my personal website (available at https://wnetmc.github.io/ and all my code is on https://github.com/wnetMC/wnetmc.github.io) and I think i broke something because the text “wnet” and the links are not centered anymore. Yet I am using

<div class="content d-flex align-items-center">

and

<div class="container text-center">

I know this question will get downvoted to hell but if someone could answer, id really appreciate it. Thank you.

edit: entire website seems to be broken on github pages, but works fine when i download it… I don’t know what’s happening.

.env setup to hide key

I’m fairly new to javascript and wanted to hide my API key. Can’t seem to get dotenv to work. I’ve followed the steps on the dotemv documentation but no luck. First i ran “npm install dotenv –save” which added the following files/folders into my project

  • Node_modules folder
  • package-lock.json
  • package.json

app.js

import "dotenv/config"; 
import express from "express";
require("dotenv").config();

console.log(process.env.API_KEY);
const API = API_KEY;

.env

API_KEY = "123"

Uncaught TypeError: Failed to resolve module specifier “dotenv/config”. Relative references must start with either “/”, “./”, or “../”.

I tried adding the “/” and “./” but the same error. it’s in the same location.

object Object Keeps Persisting on my Static S3 Website [duplicate]

I have tried the JSON.stringify method and the Console.Log method and neither have worked for me. I am hosting a static S3 website with APIGateway, Lambda, and DynamoDB.

const countEl = document.getElementById('count');


updateVisitCount();
//Testinglllll
function updateVisitCount() {
 fetch('https://8zsb3och04.execute-api.us-east- 
 2.amazonaws.com/Prod')
  .then(response => {
   return response.json()
    })
     .then(data => {

    let countEl = data;
     console.log(data)
      document.getElementById('count').innerHTML = data;
        })
}[Dynamo Table][1]

ref prop is not passed, TypeError: null is not an object (evaluating ‘inputRef.current.focus’)

I am making a custom input component


const CustomInput = (props) => {
  console.log(props);
  return (
    <TextInput
      {...props}
      ref={props.ref}
      placeholder={props.placeholder}
      style={{ ...styles.text, ...props.style }}
    />
  );
};

in the file I want to use it I have

const ForgottenPasswordScreen = (props) => {
...
const inputRef = React.createRef();

  useEffect(() => {
    inputRef.current.focus();
  }, []);
...

<CustomInput
          placeholder={"E-mail..."}
          value={email.value}
          ref={inputRef}
          onChangeText={(text) => setEmail({ value: text, error: "" })}
        />
...

If I am using normal TextInput there is no problem, but when I try to use my CustomInput,
i get the error

TypeError: null is not an object (evaluating ‘inputRef.current.focus’)

I don’t get why ref={props.ref} is not doing the job. I thought that ref will be passed to my component too. How to pass ref properly ?