How to inspect and display JS and React info from console ? (compared to Python)

I would like to know why this question (How to view Javascript documentation from console?) was closed. In fact, it’s what I’m looking for. Since I don’t find any explanation but the answers given to the question I suppose that is a matter of words.

I would like to know which functions (or properties) has JS and React to display info about themself (like JS modules, built-ins, etc, or in the case of React, for instance, a hook definition).

Let me explain better with a few examples:

  • Recently I found the console.dir() method that belongs to JS and let you displays an interactive list of the properties of the specified JavaScript object
  • Python has: built-in functions like dir() and help() or modules like inspect, dis or pkgutil.
  • Finally, I upload an image with an example that VS gives me when I hover on a hook but when I go to the docs I didn’t find that hook definition. I tried googling it but I only found this that is useful but it’s not the same.

enter image description here

What’s the criteria for output determinism in Javascript

const x = [1,2,3]
x.splice(0,1)//[1]
x.splice(0,1)//[2]
x.splice(0,1)//[3]

I know that pure functions should not mutate things and should be deterministic.

And I know that .splice is impure because of (at least) the mutation that it does. But how about determinism, is splice considered indeterministic (same for push, unshift…)? If we thought about the params as only 0 and 1 then it’s indeterministic, but if we thought of x as input too, then it’s deterministic, no?

Because I’m thinking of this Array.prototype.splice.call(x, 0, 1) which will make it deterministic.

In other words, what is the criteria for output determinism are in a function which sits on the prototype and does something with this, like splice.

More specifically what constitutes the input (is this included as an input?)?

“Invalid validator function: unique” shows up even though I register as a new user

This is my code

User.init({
    email: {
      type: DataTypes.STRING,
      validate: {
        isEmail: {
          args: true,
          msg: "Invalid email format"
        },
        notEmpty: {
          args: true,  
          msg: 'Cannot be blank'
        },
        unique: {
          args: true,
          msg: "Email must be unique"
        }
      },
    }

I check using Postman. I register as a new user but the “Invalid validator function: unique” shows up instead of being registered.

Returning value from stream to parent function

I have a stream for writing some text to a cloud storage bucket.
On finish I want a message to be returned to the parent function.

I tried returning the bufferstream but this gives me the whole bufferstream object. I just want the message to be returned.

e.g. if I have another function calling toBucket I want the message that the file has been uploaded being returned so I can show it in the browser.

How can I fix this?

const toBucket = (message, filename) => {
  const storage = new Storage();
  // Initiate the source
  const bufferStream = new stream.PassThrough();
  // Write your buffer
  bufferStream.end(Buffer.from(message));

  const myBucket = storage.bucket(process.env.BUCKET);
  const file = myBucket.file(filename);
  // Pipe the 'bufferStream' into a 'file.createWriteStream' method.
  bufferStream
    .pipe(
      file.createWriteStream({
        validation: 'md5',
      })
    )
    .on('error', (err) => {
      // eslint-disable-next-line no-console
      console.error(err);
    })
    .on('finish', () => {
      // The file upload is complete.
      const message = `${filename} is uploaded!`;
      // eslint-disable-next-line no-console
      console.log(message);
      return message;
    });
};

for use in

() => async {
await things happening...

const saved = toBucket(message,filename);

sendToBrowser(saved);

}

How to generate a PDF with javascript

I have my javascript code that generates the rows of my table as follows:

    var row = table.insertRow();                        
    row.innerHTML = "<tr><td>"+ms+"</td><td id='cuota' name ='cuota' class='col-xs-7'>"+cuota+"</td><td id='interes' name='interes'>"+interes+"</td><td id='amorti' name='amorti'>"+amortizacion+
    "</td><td id='capital' name='capital'>"+capital+"</td><td id='segurodesgrav' name='segurodesgrav'>"+segurodesgrav+"</td><td  id='seguroinmobil' name='seguroinmobil'>"+seguroinmobil+"</td><td id='gastosadm' name='gastosadm'>"+gastosadm+"</td><td id='cuotafinal' name='cuotafinal'>"+cuotafinal+"</td></tr>";

In my html I use this script to generate my pdf, but it generates it wrong, how can I fix it, or in another simpler way I can create the pdf, without losing the css, I don’t want to use canvas, because the previous programmer used it, but it has problems when generating the pdf on screens such as cell phones and it comes out cut off at the mid (width), the height is correct.

<script>  
  function demoFromHTML() {
        var pdf = new jsPDF('p', 'pt', 'letter'); 
        source = $('#visibletabla')[0];

        specialElementHandlers = { 
            '#bypassme': function (element, renderer) { 
                return true
            }
        };
        margins = {
            top: 80,
            bottom: 60,
            left: 20,
            width: 8000,
            border:0 
        }; 
        pdf.fromHTML(
            source, // HTML string or DOM elem ref.
            margins.left, // x coord
            margins.top, { // y coord
                'width': margins.width, // max width of content on PDF
                'elementHandlers': specialElementHandlers
            },

            function (dispose) { 
                pdf.save('silmulador_planahorrocasa.pdf');
            }, margins
        );
  }
</script>

How do I generate the pdf (wrong)

How do I have the table in the html

How to switch to dark mode on click event in Javascript

I’m building a web page and I am trying to toggle the prefers-color-scheme on a click event. That is, when the button is clicked I wish that the windows detect the media query @media (prefers-color-scheme:dark)

theme.addEventListener("click", () => {
   // event to switch theme
}

Is this possible?

How to properly extract payload from nestjs/jwt token?

I ran into a problem with decrypting a token in a project, I want to extract data from the incoming token, compare it with the data from the database, and then perform certain actions.
The problem is that when I get the payload from “jwtService.decode()”, I can’t access the “decodedJwt.email” field, nest complains that “decodedJwt” is not an object. But if you return typeof “decodedJwt” then the answer is a string. However, I cannot access the “email” field in the code itself. If I return “decodedJwt” in this function, then in postman I will get the very necessary object with the necessary fields, including the same “email” field. What’s my mistake?

Reply from nest:
Property ’email’ does not exist on type ‘string | { [key: string]: any; }’.
Property “email” does not exist on type “string”.ts(2339)

async refreshTokenByOldToken(authHeader: string) {
  const decodedJwt = this.jwtService.decode(authHeader.split(' ')[1])
  return decodedJwt.email
}

Change image and title js

I am new to javascript and jquery. How can I make the main image change when clicking on the image below, and also change the title for each image?

Is it really necessary to use js or is there another way to do it?

.custom-slider {
  text-align: center;
}
.main-image > img {
  margin-top: 5px;
  width: 50px;
  border-radius: 100px;
  box-shadow: 0 0 0 3px pink, 0 0 13px #333;
}
.img-to-select > .img-to-select__item > img {
  width: 30px;
  border-radius: 100px;
  height: 100%;
}
.img-to-select {
  overflow: hidden;
  display: flex;
  justify-content: space-around;
}
.img-to-select > .img-to-select__item {
   display: flex;
   justify-content: space-around;
}
<div class="custom-slider-section">
  <div class="custom-container">
    <div class="custom-slider">
      <div class="custom-slider__title">
        <span>Title
        </span>
      </div>
      <div class="main-image">
        <img src="https://i.picsum.photos/id/973/200/300.jpg?hmac=gFjS6R63ZUmM9pkLFyPxuEmsxvZ_e8VJxB3mcXpvTUQ">
      </div>
      <div class="img-to-select">
        <div class="img-to-select__item selected">
          <img src="https://i.picsum.photos/id/973/200/300.jpg?hmac=gFjS6R63ZUmM9pkLFyPxuEmsxvZ_e8VJxB3mcXpvTUQ">
        </div>
        <div class="img-to-select__item">
          <img src="https://i.picsum.photos/id/732/200/300.jpg?hmac=mBueuWVJ8LlL-R7Yt9w1ONAFVayQPH5DzVSO-lPyI9w">
        </div>
        <div class="img-to-select__item">
          <img src="https://i.picsum.photos/id/230/200/300.jpg?hmac=pyhlpgJN2oBeEzhJbnJYrCsLoJM6MKd_NUQGIQhVx5k">
        </div>
        <div class="img-to-select__item">
          <img src="https://i.picsum.photos/id/377/200/300.jpg?hmac=veEWg3ApI7rkKqMF6MuaWBmxPgnEe-Ar9eDdMG3q-kk">
        </div>
      </div>
    </div>
  </div>
</div>

iterate throug array with removed elements by splice vs filter

Can somebody explain to me why the output is different?
I remove one element in both cases so why does the for loop make a difference between splice and reasigning the value?

filter:
1 2 3 4 5

splice:
1 2 3 5

let arr = [];
let arr2 = [];

class test {
  constructor(s) {
    this.s = s;
  }

  destroy() {
    arr = arr.filter((e) => e !== this);
  }

  destroy2() {
    var index = arr2.indexOf(this);
    if (index !== -1) {
      arr2.splice(index, 1);
    }
  }
}

arr.push(new test("1"));
arr.push(new test("2"));
arr.push(new test("3"));
arr.push(new test("4"));
arr.push(new test("5"));

arr2.push(new test("1"));
arr2.push(new test("2"));
arr2.push(new test("3"));
arr2.push(new test("4"));
arr2.push(new test("5"));

console.log("filter: ");

for (let t of arr) {
  if (t.s === "3") {
    t.destroy();
  }
  console.log(t.s);
}

console.log("nsplice: ");

for (let t of arr2) {
  if (t.s === "3") {
    t.destroy2();
  }
  console.log(t.s);
}

How to optimize select option in ReactJS

I’m creating a project where I need to render almost 2100+ select option. But whenever I render with default bootstrap select option than I render too slow. That’s why I do use react-select & react-window. I follow many way to solve it but can’t.

How can I solve it?

Dependencies

  • react-select
  • react-window
  • react-bootstrap

Information

  • I’m getting 2100+ data with useSelector from redux store.
  • Wherever I look for solve this issue, I found this example everywhere. Here they use loop to render 2500 or more. But my data are coming from redux store.
  • My data is look like
data = [{"title": "A", "key": "a", "code": "512"},
        {"title": "B", "key": "b", "code": "513"}
        .....
       ]
  • I’m using functional component to use useSelector that’s why I can’t get data outside component.
  • I can’t create a code sandbox cause of there the data will be missing.
  • I have follow many ways to solve this but can’t. Here I’m providing current situation of my code.

Code

import React from 'react'
import { useSelector } from 'react-redux'
import Select, { createFilter } from 'react-select';
import { FixedSizeList as List } from 'react-window'


const Board = () => {

    const icons = useSelector(state => state.icons.iconsData)
    

    return (
        <>
            <div className="container py-5">
                <div className="d-flex flex-row">
                    <div>
                        <p>Select Option</p>
                        <Select options={icons}/>
                    </div>
                </div>
            </div>
        </>
    )
}

export default Board

Sorting an array based on a inner array

I want to sort an array based on a inner array value sorted alphabetically. example.

i want this array to be sorted by the prefix “old” so old A, old B etc

const array = [
  { personName: "Vans", personTags: ["young",  "old A"] },
  { personName: "Lia", personTags: ["young",  "ok"] },
  { personName: "Rein", personTags: ["old B", "hairless", "ok"] },
  { personName: "Cris", personTags: ["old A",  "old B", "acrounimouslyness"] },
  { personName: "Mercy", personTags: ["young", "hairless", "ok"] },
  { personName: "Cbum", personTags: ["old C", "hairless", "young"] },
];

becomes

const array = [
  { personName: "Vans", personTags: ["young",  "old A"] },
  { personName: "Cris", personTags: ["old A",  "old B", "acrounimouslyness"] },
  { personName: "Rein", personTags: ["old B", "hairless", "ok"] },
  { personName: "Cbum", personTags: ["old C", "hairless", "young"] },
];

//would be removed

{ personName: “Lia”, personTags: [“young”, “ok”] },
{ personName: “Mercy”, personTags: [“young”, “hairless”, “ok”] },