Begginer problems :( [closed]

Ok, so I’m taking some classes, and wanted to make a code that gave me a number for tips so I did this

I have the Javascript Debugger (Nightly) extension installed on the VsCode.
when I press F5 to run and debug and it asks me how do I want to do it I choose Node.js.

Here is the code:

function calcularPropina (totalCuenta, porcentajePropina){
    var totalCuenta = 140;
    var porcentajePropina = .20;
    var propina = totalCuenta * porcentajePropina;
    return propina; 
}

And clearly I am doing something wrong because the outcome on the Debug Console is just
“Note: Using the “preview” debug extension
D:NodeJsnode.exe .asdasdasd.js”

I just want to know if the problem is what I did, if it’s a debugging thing or if I just fucked up something in the way 🙁

I explained the problem with as much information as I could, I am sorry if I skipped something I still don’t know what is important and what is not.

How do you display an image with a source attached to an object? The object (question) is selected randomly and images should change with them

I have an array of objects which are questions. This is for a random question quiz. Basically, when one question is randomly selected, I thought all of the attributes would go with it (if “called” correctly). I am not sure how to display the image from the object when the question text (q) displays.

const questionBank = [
{
    q: "This is question 1's text",
    options:['1','2','3','4', '5'],
    answer:4,
    imgURL: 'http://drive.google.com/uc?export=view&id=googleDriveId',
},
{
    q: "question 2 will go here",
    options:['7','6','4'],
    answer:0,
    imgURL: 'http://drive.google.com/uc?export=view&id=differentDriveId',
}

function getNewQuestion(){
    const question = document.querySelector(".question");

    //set question text
    question.innerHTML = currentQuestion.q;

    //add image to question 
    //document.querySelector('.question').appendChild(img); (attempted, did not work)
    //var img = new Image(); (attempted, did not work)
    //img = document.createElement("img");  (attempted, did not work)
    //img.src = document.querySelector('.imgUrl'); (attempted, did not work)

I think that is all the relevant code.

I get an error running “node -v” in visual studio code

I’m brand new to coding and this is stumping me for some reason. The error that comes up when I type node -v in my visual studio code terminal is ‘node : The term ‘node’ is not recognized as the name of a cmdlet…” It works just fine when I run it in command prompt on my computer. I’ve read everywhere that you have to add it to your path which I’m not sure I did correctly now. I attached some pictures of what the path looks like for the user and system variable. I am hoping someone could give some feedback if this looks right or not. Thanks:)

JavaScript – forEach with set id in array [duplicate]

var tasks = [
  {
  id: "0",
  "title": "Programowanie",
  url: "https://data.1freewallpapers.com/download/code-symbols-programming-1920x1080.jpg",
},
{
  id: "1",
  "title": "Wirtualni",
  url: "https://www.zyjmocno.com/wp-content/uploads/753396-blackboard-wallpaper.jpg",
},
{
  id: "2",
  "title": "Zwierzęta",
  url: "https://www.tapeteos.pl/data/media/384/big/zwierzeta_1920x1080_065_kroliczek.jpg",
},
];


tasks.forEach((task) => {
        createTaskCard(task);
    });

How can I list all the tasks that have the value id = 0 in an array.
How do it in JavaScript. Need help. Thanks !!!

Moving scrollbars according to element position

I want my element center aligned until scrolling in div reached to the end, i did somecode but can’t handle this. letme share my code

clamp = (value, min, max) => {
  if (value < min) return min;
  else if (value > max) return max;
  return value;
};

const playground = document.getElementById('playground');
const viewarea = document.getElementById('viewarea');

const selfUser = document.getElementById('user1');

window.playgroundBounding = { minX: 0, maxX: playground.clientWidth, minY: 0, maxY: playground.clientHeight };

playground.onmouseup = function (e) {
  if (e.button === 0) mouseClicked(e);
};

function mouseClicked(event) {
  
  xposition = event.clientX + viewarea.scrollLeft - selfUser.offsetWidth / 2;
  yposition = event.clientY + viewarea.scrollTop - selfUser.offsetHeight / 2;


  xposition = clamp(xposition, window.playgroundBounding.minX, window.playgroundBounding.maxX - selfUser.offsetWidth);
  yposition = clamp(yposition, window.playgroundBounding.minY, window.playgroundBounding.maxY - selfUser.offsetHeight);
 
  $(selfUser).animate(
    {
      left: xposition + 'px',
      top: yposition + 'px',
    },
    500,
    'linear'
  );
 viewarea.scrollTo(xposition, yposition)
}
body {
  margin:0;
  padding:0;
}
#viewarea {
    width: 100vw;
    height: 100vh;
    overflow: auto;
    position: relative;
    scroll-behavior: smooth;
    transform-origin: left top;
    top:0px;
    left:0px;
    /*overflow: hidden;*/ 
}

#playground {
    width: 1920px;
    height: 1080px;
    background-image: url('https://www.tynker.com/projects/screenshot/60390c5cde3bf81ccf3101f6/erosion.png');
    background-position: top left;
    background-repeat: no-repeat;
    background-size: 1920px 1080px;
    position: relative;
    scroll-behavior: smooth;
    transform: translate(0px, 0px) scale(1, 1);
    left: 0px;
    top:0px;

}

.avatar {
    width: 50vw;
    height: 50vw;
    border-radius: 50%;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    color: blue;
    background-color: rgba(255, 255, 255, 0.5);
    border: 2px solid rgba(255, 255, 255, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: move;
    user-select: none;
    transition: transform 0.1s ease-in;
    position:absolute;
}

.avatar-image {
    width: 30vw;
    height: 30vw;
    background: url("https://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=200") top left / cover no-repeat;
    border-radius: 50%;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border: 3px solid white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="viewarea">
      <div id="playground">
        <div class="avatar " id="user1">
          <div class="avatar-image">
            <div class="user-name"></div>
          </div>
        </div>
      </div>
    </div>

Now on click avatar is moving on viewarea, i want scrollbars to scroll vertically and horizontally nicely according to player position, or maybe player remain in center until scrollbar scrolled completly and player can touch the border.

How do i type this payload object update?

so i’m working on a route and wanted to create a generic normalizer to use before saving my user into the database.

This is my normalizer function

import { INormalizer, IPayloadIndexer } from "../../interfaces/generics";

const normalizeRequestValues = <Type>(
  payload: IPayloadIndexer<Type>,
  normalizer: INormalizer
) => {
  const normalizerKeys = Object.keys(normalizer);

  const payloadEntries = Object.entries(payload);

  payloadEntries.forEach(([key, value]) => {
    if (normalizerKeys.includes(key)) {
      payload[key] = normalizer[key](value as string);
    }
  });
};

export default normalizeRequestValues;

And on the payload[key] = normalizer[key](value as string); part of the code i’m receiving this error:

(parameter) payload: IPayloadIndexer<Type>
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IPayloadIndexer<Type>'.
  No index signature with a parameter of type 'string' was found on type 'IPayloadIndexer<Type>'

INormalizer:

type INormalizer = {
  [key: string]: (str: string) => string;
};

export default INormalizer;

IPayloadIndexer:

type IPayloadIndexer<Type> = {
  [Property in keyof Type]: Type[Property];
};

export default IPayloadIndexer;

The function is being called first here:

import { IPayloadIndexer } from "../../interfaces/generics";
import { normalizeRequestValues } from "../generics";

import userNormalizer from "./userNormalizer.utils";

const normalizeUserRequestValues = <Type>(payload: IPayloadIndexer<Type>) => {
  normalizeRequestValues<Type>(payload, userNormalizer);
};

export default normalizeUserRequestValues;

Using this normalizer:

import { INormalizer } from "../../interfaces/generics";
import { capitalizeText } from "../generics";

const userNormalizer: INormalizer = {
  name: (name: string) => capitalizeText(name),
  email: (email: string) => email.toLowerCase(),
};

export default userNormalizer;

And then it is called in my route service, here:

import { hash } from "bcrypt";
import { Request } from "express";

import { IServiceReturnMessage } from "../interfaces/generics";
import { IUser, IUserCreate } from "../interfaces/users";
import { UserRepository } from "../repositories";
import { normalizeUserRequestValues, serializeUser } from "../utils/user";

class UserService {
  insertUser = async ({
    validated,
  }: Request): Promise<IServiceReturnMessage<IUser>> => {
    validated.password = await hash(validated.password, 10);

    normalizeUserRequestValues<IUserCreate>(validated as IUserCreate);

    const user = await UserRepository.save({ ...validated });

    const serializedUser = serializeUser(user);

    return { statusCode: 201, message: serializedUser };
  };
}

export default new UserService();

I could make it work by passing a //@ts-ignore above the line, but i really wanna learn how to do it, if any extra information is needeed i will gladly post in here.

Thanks in advance for any response!

How do u code a button to present a random group of selections in html and js

Okay so I’ve seen a few question similar but I’m still not clear. Just a little background, I’m coding the front end of a text based game basically using standard html, css, js. So here’s where I’m stuck

I’ve got a bunch of data eg;

Medicine; info1, info2, 3, 4, 5
Law; 1, 2, 3, 4, 5,
Engineering;
Teaching;

Something like this. Each set of data is duplicated in 5 places it’s the same id- medicine, law, Engineering, teaching but with different set of 5 subdatas.

There is a button named after each id

What I need is a way to ensure that if a user clicks say the button medicine 3 times they won’t see the same dataset but a new one each time.

If I can get a rough code it’ll be much appreciated. Note I’m new to coding 1 year so I’m still not very good with js so if you can give the least complicated approach. Thanks

TypeError: this.selectedNodes.value is not iterable

So I am working with v-network-graphs to create graphs in the front end using Vue.
I have defined my data as

data(){
    return{
      test: test_data,
      nodes:{},
      edges:{},
      nextNodeIndex: Number,
      selectedNodes: ref<string[]>([]),
      selectedEdges: ref<string[]>([]) 
    }
  }

and my methods are defined as

methods: {
    g(){  
      this.nodes = reactive(this.test.nodes)
      this.edges = reactive({ ...this.test.edges })
      console.log(this.nodes)
      console.log(this.edges)

      this.nextNodeIndex = ref(Object.keys(this.nodes).length + 1)     
    },
    addNode() {
      const nodeId = this.nextNodeIndex.value 
      this.nodes[nodeId] = {
        name: String(nodeId),
        size: 16,
        color: "blue",
        label: true
      } 
      this.nextNodeIndex.value++ 
      console.log(this.nextNodeIndex)
    },
    removeNode() {
      for (const nodeId of this.selectedNodes.value) {
        delete this.nodes[nodeId] //Delete the selected node, by their ID
      }
    },

Now when I try to remove a node I am getting the error this.selectedNodes.value is not iterable , how should I define selectedNodes then?

https://dash14.github.io/v-network-graph/examples/operation.html#add-remove-network-elements

The above link has an example on how to write remove edge function using the library. I am doing the same, but I want to write the function inside a method as I am working in a Vue project.
I am new to Javascript and Vue so any suggestions are greatly appreciated.

Is 1.5 MB too big of a bundle size for a react application?

I’m emitting a bundle.js from webpack that is this size. Does not seem terrible but I utilized a site called gtmetrix.com which gave me a D rating and said that this is too big ( “enormous” ).

It states to

Avoid enormous network payloads

Large network payloads cost users real money and are highly correlated
with long load times.

I am only using react, react-dom, and react-redux, and the app code is not that big.

Error: fractional component exceeds decimals in eithersJS

Why does the following return a fractional component error for exceeding decimals? It only seems to trigger on low balance.

If my balance is 0.1 ether or BNB I don’t see an error but if my balance is 0.0001 I would see this error

Error: fractional component exceeds decimals

var account = accounts[0]
var yourBalance = await provider.getBalance(account)
var fixedBalance= ethers.FixedNumber.fromValue(yourbalance , 18);
var stakedAmount = (fixedBalance * 0.50).toString();
var finalOutput = ethers.utils.parseUnits(stakedAmount , 18);  //this returns Error: fractional component exceeds decimals

Assert doesn’t catch errors

I have this function:

await sendTx(newProxyAddr, false, 'initialize', [0, nullAddr]);

…that produces this error:

Error: VM Exception while processing transaction: reverted with reason string 'Initializable: contract is already initialized'

But when I try to catch the error on a test using:

assert.throws(async () => {
   await sendTx(newProxyAddr, false, 'initialize', [0, nullAddr]);
}, Error, 'Thrown');

…, it tells me:

AssertionError: expected [Function] to throw an error

What am I doing wrong?

Thanks!

Check country exist and extract all the countries contain the word ‘land’ in countries array

const countries = [
 {
  name: 'Japan',
  capital: 'Tokyo',
  languages: ['Japanese'],
  population: 126960000,
  currency: 'Japanese yen'
 },
 {
  name: 'Latvia',
  capital: 'Riga',
  languages: ['Latvian'],
  population: 1961600,
  currency: 'Euro'
 },
 {
  name: 'Iceland',
  capital: 'Reykjavík',
  languages: ['Icelandic'],
  population: 334300,
  currency: 'Icelandic króna'
 },
 {
  name: 'Finland',
  capital: 'Helsinki',
  languages: ['Finnish', 'Swedish'],
  population: 5491817,
  currency: 'Euro'
 }
]

I have two questions to solve, help me:

  1. In countries array check if ‘Latvia’ exists in the array if it exists print ‘LATVIA’. If it does not exist add to the countries list.
  2. Extract all the countries contain the word ‘land’ from the countries array and print it as array

SVG to DXF using javascript

I am trying to find a tool / npm package for converting svg to dxf file using javascript. I have found inkscape GUI which works quite well but I dont know how can I use it for my web app?

My SVG is quite complex and conversion to DXf only works with inkscape GUI so far.

If there is any other tool which can deployed with web app would be helpful I am looking for suggestions.