JavaScript. Задача с сравнением каждого элемента двух массивов [closed]

Дано 2 массива с 10 случайными числами. Нужно сравнить каждый элемент первого массива со вторым. Если такой элемент обнаружен, требуется вывести “1” в третий логовый массив и пропустить этот элемент первого массива, сразу перейдя ко второму. В ином случае, проверив оба массива и не обнаружив нужных элементов, требуется вывести “0” в логовый массив и перейти к следующему элементу первого массива. Всего в логе должно оказаться 10 элементов.

Скелет

HTML

        <b>A = </b><input type="text" id="inputF" class="inputFirstNum" size=50 value="">
        <button class="randArr1" onclick="randArr1()">Random</button>
        <b>B = </b><input type="text" id="inputS" class="inputSecondNum" size=50 value="">
        <button class="randArr2" onclick="randArr2()">Random</button>
        <button class="equal"onclick="equal()">Check</button>

JavaScript

function randArr(){
    let arr = [];
    for (let i = 0; i < 9; i++ ) {
        let a = Math.round( Math.random() * 100 );
        arr = arr +  a + ",";
        } 
    let b = Math.round( Math.random() * 100 );
    let res = arr + b;
    return res;
}

function randArr1(){
    inputF.value = randArr();
}

function randArr2(){
    inputS.value = randArr();
}

filter nested array of objects depending on children conditions

there is a tree of categories. its an array of objects (in this case 1 ob
ject with children property. children property is an array containing
or not containing other categories objects and so on ). Each object also has a property “disabled”.
It can be either true or false. The starting point is that some bottommost children “disabled”
are set to true. In this case all of them are set to true. The task is to find parents ids
which disabled have to be set to true if all of its children disabled are set to true. In
this particular case all parents ids have to be found because all bottommost children disabled
are set to true. My function returns only lowest level of parents. What am I doing wrong?

let parentIdsToDisable = [];
    function findParentIdsToDisable(tree) {
      tree.forEach((category) => {
        if (category.children.length > 0) {
          if (category.children.every((child) => child.disabled === true)) {
            category.disabled = true;
            parentIdsToDisable.push(category.id);
          }
        }
        findParentIdsToDisable(category.children);
      });
  }

const categories = [
  {
    id: 69,
    name: 'Прикраси',
    key: 'prykrasy',
    description: 'Прикраси',
    disabled: false,
    mpath: '69.',
    children: [
       {
        id: 70,
        name: 'Аксесуари',
        key: 'aksesyary-dlya-prykras',
        description: 'Аксесуари для прикрас',
        disabled: true,
        mpath: '69.70.',
        children: []
      },
       {
        id: 72,
        name: 'Ювелірні вироби',
        key: 'uvelirni-vyroby',
        description: 'Ювелірні вироби',
        disabled: false,
        mpath: '69.72.',
        children: [
          {
            id: 73,
            name: 'Срібло',
            key: 'vyroby-iz-sribla',
            description: 'Ювелірні вироби із срібла',
            disabled: true,
            mpath: '69.72.73.',
            children: []
          }
        ]
      },
       {
        id: 71,
        name: 'Біжутерія',
        key: 'bizhuteriya',
        description: 'Біжутерія',
        disabled: true,
        mpath: '69.71.',
        children: []
      }
    ]
  }
]

Can you stop a nested child node from executing its constructor until a parent node has constructed?

Imagine a scenario where I have the following DOM tree

<body>
  <parent-component>
    <div>
      <child-component></child-component>
    </div>
  </parent-component>
</body>

The child component has a seekParent function that fires off a CustomEvent that should be caught by the <parent-component>, which then uses a callback to tell the child this is the parent component node.

Consider when the child component is is defined via customElements.define() first. The child’s constructor fires off the CustomEvent as soon as <child-component> is defined, since parent nodes do not need to be valid and at this stage be HTMLUnknownElement.

The event bubbles through the <parent-component> without being caught because that component has not yet called its constructor, to attach an event listener.

Is it at all possible to not parse child nodes within a DOM tree until a parent becomes defined / valid Element? Otherwise, is there any way around this issue besides using a setTimeout()?

Thanks

download the pdf of component in react

I have a page that consist of a component that has a chart.js component. I use html2canvas and then jspdf for create a pdf of component but there is problem with chart.js on responsive mode .i want to chart in pdf be same as desktop chart but when screen resize the chart resize to based on width is there a way to fix this issue?

Why is this value updating on each array inside my 2d array?

I have a 2d array:

let arr = [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]

When I try to update the 1st sub array in the 2nd position with:

arr[0][1] = 4

The output is:

[ [ 0, 4, 0, 0 ], [ 0, 4, 0, 0 ], [ 0, 4, 0, 0 ], [ 0, 4, 0, 0 ] ]

Why are all of the sub arrays updating?

The full code is:

let arr = [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
arr[0][1] = 4
console.log(arr)

How can I use refresh token in react

I have a get refresh token url like this client.com/api//auth/refresh-token. but I have a hard time using this. I think it should save a refresh token in the local storage after the login. but how can I use it?

login.tsx

export const useLogin = () => {

    const LoginAuth = async (data: AuthenticationProps) => {
        await axios.post(baseURL + `client/auth/login`,
        {
            email: data.email,
            password: data.password,
        },
        {
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            }
        }
        )
        .then((res) => {
            if(res.status === 200) {
                console.log("success")
            }
        }, (err) => {
            console.log(err);
        })
        
    }
    return {
        LoginAuth,
    }
}

Using Proxy To Get Item From Array by Item Key Value- Bad Idea? Better Way?

Title says it all. I’m building out some complex functionality right now, and previously I was returning an array. I don’t want to change the return type since there’s a lot of code written against this already, but users are asking for a way to get items from the array based on the name property of the item without having to filter the returned array themselves.

I’m also shying away from converting it into a key/value object using the name property because the most common use case is to loop over the array.

Below is a code snippet of what I am doing. Essentially instead of returning array I return arrayProxy so they can use the syntax array["name=Name Of Something"] to get the item with that name, with a fallback for default behavior of course.

Is this a bad use of Proxy, or is there a better/different way I should be doing this? Something feels janky about it, but I can’t find anything wrong with it per se.

Looking for input from someone with more experience in this area than I have just to get kind of a “lgtm” or “gtfo” on this idea.

const itemArray = [
    {
        name: "Bob",
        value: 99
    },
    {
        name: "Fu",
        value: 101
    },
    {
        name: "Bar",
        value: 404
    }
]

const itemArrayProxy = new Proxy( itemArray, {
    get: ( target, prop, receiver ) => {

        // If we are getting an item by name instead of index
        if ( String(prop).match(/name=/) ){

            // Get just the name to match
            const name = String(prop).split("=")[1];

            // Filter out all items that don't match the name
            const results = receiver.filter( item => item.name === name );

            // Return the results, or undefined
            return results.length && results.length === 1
                ? results[0]
                : results.length 
                    ? results
                    : undefined
        }

        // Default get functionality fallback
        return Reflect.get( target, prop, receiver );
    }
})

console.log( itemArrayProxy["name=Fu"] ) // Gets the object with name = "Fu"

Error in styling when using function to determine flex React Native

Im trying to create 2 dropdown menus where depending on which are clicked would reduce a third view’s flex number to accommodate the other 2 expanded views. Im using two useState variables to keep track of the 2 different dropdown menus, and calculate the flex as shown:

const [isFirstExpanded, setIsFirstExpanded] = useState(false)
const [isSecondExpanded, setIsSecondExpanded] = useState(false)

const calculateFlex = () => {
    if (isFirstExpanded && isSecondExpanded) {
        return 0; // This means both dropdowns are expanded, and should hide the third view
    } else if (isFirstExpanded || isSecondExpanded) {
        return 2; // Only one of the dropdowns are open, so half the size of the third view
    } else {
        return 4; // None of the dropdowns are open, so show the full view
    }
}
<View style={{flex: 1}}>
    <View style={{flex: calculateFlex, backgroundColor: "red"}}/> // View to be grown or shrunk depending on below views

    <TouchableOpacity style={{flex: 1}} onPress={setIsFirstExpanded(!isFirstExpanded)}/>
    <View style={isFirstExpanded ? styles.expandView : styles.hideView}/> // The dropdown that is hidden by default

    <TouchableOpacity style={{flex: 1}} onPress={setIsSecondExpanded(!isSecondExpanded)}/>
    <View style={isSecondExpanded ? styles.expandView : styles.hideView}/> // The dropdown that is hidden by default
</View>

This code leaves out some innocuous things, if needed I can copy/paste them. My problem occurs when the first view to be grown or shrunk doesn’t seem to follow the calculate flex function. Not sure why, or if there is a better way to calculate this.

Can’t run react-native app on iOS 5 error: duplicate symbols for architecture x86_64

Log output:

duplicate symbol ‘_bridgeRef’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtil.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlob.o)
duplicate symbol ‘_fsQueue’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtil.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlob.o)
duplicate symbol ‘_commonTaskQueue’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtil.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlob.o)
duplicate symbol ‘_fileStreams’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtilFS.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlobFS.o)
duplicate symbol ‘_expirationTable’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtilNetwork.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlobNetwork.o)
ld: 5 duplicate symbols for architecture x86_64

Can someone help me write a simple script for my google sheet based on a monthly time basis or teach me how to?

https://docs.google.com/spreadsheets/d/10wT1xopLKYn8kptHByDGav-fDBkhehq2HcRwkLhaJr0/edit?usp=sharing

I need a simple script to be written where the January Row will be locked at the 1st of Febuary and so on till December where it will lock the next year January the 1st.

I did this cause not every month has a 31st but every month has a 1st.

Its a rather simple and intuitive script but, I don’t have the knowledge to write the script. If someone can write it or teach me the abc’s to writing it so that I can understand the script, I would appreciate it.

I shared a doc link to my google sheet so you have an idea of what I am looking for and envisioning.

  • I want cells B12:F12 to lock on the first of Febuary. (Yellow cells) The greyed out cells are locked no matter what so that does not have to be changed.
  • The comment section or (cells in white) can be unlocked indefinetely and doesn’t need to be changed.

Summary: In my google sheet I need the (yellow cells) locked on a monthly basis based on the first of every month. January’s cells B12:F12 locked on Febuary 1st, Febuary’s cells B13:F13 locked on March 1st and so on till December where it locks on January 1st of next year.

Thank You for reading this and your time.

Vue – Advanced Cropper (Uncaught TypeError: this.$refs.cropper.getResult is not a function)

I have a crop function for Vue Advanced Cropper like this:

            crop() {
            const { canvas } = this.$refs.cropper.getResult();
            if (canvas) {
                const form = new FormData();
                canvas.toBlob(blob => {
                    form.append('files[]', blob);
                    // Perhaps you should add the setting appropriate file format here
                }, 'image/jpeg');

                this.formData = form;

            }

        },

My HTML:

    <div v-if="cropView">
    <h1>Step 2: Crop images</h1>
    <div class="upload-example__cropper-wrapper">
        <div v-for="image in this.images" :key="image">
            <cropper ref="cropper" class="upload-example__cropper"
                     check-orientation :src="image.src"/>
            <button v-if="image.src" class="upload-example__button" @click="crop">Crop</button>
            <!--<div class="upload-example__reset-button" title="Reset Image" @click="reset()"></div>-->
            <div class="upload-example__file-type" v-if="image.type">
                {{ image.type }}
            </div>
        </div>
    </div>
</div>

I have included the import for Cropper:

    import {Cropper} from 'vue-advanced-cropper'

Version from package.json:

"vue-advanced-cropper": "^2.8.1"

Everything works until I get to the crop function where it says the following:
Uncaught TypeError: this.$refs.cropper.getResult is not a function

My first thought was, that it may have something to due with looping through multiple images, however it does not work with juse one either. I have tried combining the part from disc and upload to server from here:
https://norserium.github.io/vue-advanced-cropper/guides/recipes.html#upload-image-to-a-server

NVDA / focus / accessibility Issues

We are building custom dropdown components with a hierarchical selection of checkboxes. Each hierarchy is shown/hidden using standard bootstrap 3 accordion code which handles screen readers very well (this is a Drupal site so bootstrap 3 is the version supported).

We have code controlling the up/down/home/end keys which completely fails to trigger when NVDA is running. Clicking the down arrow is supposed to take you to the next visible checkbox. The home key takes you to the first. The end key takes you to the last.

All this works fine when NVDA is not running. When running, the home/end keys do nothing. The up/down arrow act like tab/shift-tab so they don’t go to the next checkbox; they go to the next tabable element.

This is happening in all browsers.

Does anyone know how to fix this?

Fiddle:
https://jsfiddle.net/1pya0bm3/1/

    $(document).ready(function(){
        $('.region_of_delivery_checkbox').keyup(function(e){
            var code = (e.keyCode ? e.keyCode : e.which);
            var tabables = $(".region_of_delivery_checkbox:visible");
            var index = tabables.index(this);
            console.log(`checkbox and tabables.length = ${tabables.length} and tabables.index(this) is: ${tabables.index(this)}`);
            if(code == 40) {
                console.log("40");
                tabables.eq(index + 1).focus();
                console.log(`tabables.eq(index + 1) is: ${index}`);
            } else if(code == 38) {
                console.log("38");
                tabables.eq(index - 1).focus();
            } else if(code == 35) {
                console.log("35");
                tabables.eq(tabables.length - 1).focus();
            } else if(code == 36) {
                console.log("36");
                tabables.eq(0).focus();
            }
        });
    });

What is an “Object” in a JavaScript NodeJS code?

I saw the following code:

const User = require('../model/User');
const jwt = require('jsonwebtoken');

const handleRefreshToken = async (req, res) => {
    const cookies = req.cookies;
    if (!cookies?.jwt) return res.sendStatus(401);
    const refreshToken = cookies.jwt;

    const foundUser = await User.findOne({ refreshToken }).exec();
    if (!foundUser) return res.sendStatus(403); //Forbidden 
    // evaluate jwt 
    jwt.verify(
        refreshToken,
        process.env.REFRESH_TOKEN_SECRET,
        (err, decoded) => {
            if (err || foundUser.username !== decoded.username) return res.sendStatus(403);
            const roles = Object.values(foundUser.roles);
            const accessToken = jwt.sign(
                {
                    "UserInfo": {
                        "username": decoded.username,
                        "roles": roles
                    }
                },
                process.env.ACCESS_TOKEN_SECRET,
                { expiresIn: '10s' }
            );
            res.json({ roles, accessToken })
        }
    );
}

module.exports = { handleRefreshToken }

And I can not understand what is the Object in this line of code:

const roles = Object.values(foundUser.roles);

I mean is it instance of a class? What class? Where did it instantiated?

Istanbul scripts are not running

No coverage information was collected, exit without writing coverage information
D:JobProjectsToDoListToDosListnode_modules.bintape.CMD:1
@ECHO off
^

SyntaxError: Invalid or unexpected token
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1032:15)
at Module._compile (node:internal/modules/cjs/loader:1067:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Object.Module._extensions. [as .js] (D:JobProjectsToDoListToDosListnode_modulesistanbullibhook.js:109:37)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at runFn (D:JobProjectsToDoListToDosListnode_modulesistanbullibcommandcommonrun-with-cover.js:122:16)
at D:JobProjectsToDoListToDosListnode_modulesistanbullibcommandcommonrun-with-cover.js:251:17

@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0

IF EXIST “%dp0%node.exe” (
SET “_prog=%dp0%node.exe”
) ELSE (
SET “_prog=node”
SET PATHEXT=%PATHEXT:;.JS;=;%
)

endLocal & goto #undefined# 2>NUL || title %COMSPEC% & “%_prog%” “%dp0%..tapebintape” %*

could not render component in react

When I use history.push () method, from signup to log in, goes to a particular API/URLenter code here but does not render the login component.

import React, { useState } from "react";
import "./UserRegister.css";
import { Link } from "react-router-dom";
import ing from "../assets/ing.png";
import { message } from "antd";
import { createBrowserHistory } from "history";
const UserRegister = () => {
  const history = createBrowserHistory();
  const [role, setRole] = useState("");
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [mobile, setMobile] = useState("");
  const [password, setPassword] = useState("");
  const [confirmpassword, setConfrimpassword] = useState("");

  console.log({
    role,
    username,
    email,
    mobile,
    password,
    confirmpassword,
  });
  const fetchRegister = () => {
    fetch("/api/user/userregister", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        role,
        username,
        email,
        mobile,
        password,
        confirmpassword,
      }),
    })
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        if (data.error) {
          message.error(data.error);
        } else {
          history.push("/login");
        }
      });
  };

  return (
    <div className="body_body">
      <div className="signup-container">
        <div className="welcome-img">
          <img src={ing} alt="welcome image" height="350px" width="450px" />
        </div>

        <div class="form-container">
          <h2>Create your Account Today ! </h2>

          <p class="title">Sign Up</p>

          <div class="signup-form">
            <div class="form-item selector">
              <span class="item-indicator"></span>
              <label className="select_label" for="role">
                Choose your role
              </label>
              <select
                id="role"
                className="role_select"
                value={role}
                onChange={(e) => setRole(e.target.value)}
              >
                <option value="Student">Student</option>
                <option value="Company">Company</option>
                <option value="Mentor">Mentor</option>
              </select>
            </div>
            <div class="form-item fullname">
              <input
                type="text"
                placeholder="Please enter your username "
                value={username}
                onChange={(e) => setUsername(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>
            <div class="form-item email">
              <input
                type="text"
                placeholder="Enter your email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>

            <div class="form-item confirm-password">
              <input
                type="text"
                placeholder=" Enter Mobile No"
                name="mobile"
                value={mobile}
                onChange={(e) => setMobile(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>
            <div class="form-item password">
              <input
                type="password"
                placeholder="Enter Password"
                name="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>

            <div class="form-item confirm-password">
              <input
                type="password"
                name="Confirmpassword"
                placeholder="Enter Confirm Password"
                value={confirmpassword}
                onChange={(e) => setConfrimpassword(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>

            <p class="login">
              Already have an account?
              <Link to="login">Login</Link>
            </p>
            <div class="actions">
              <button type="submit" onClick={() => fetchRegister()}>
                Sign Up
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default UserRegister;

enter code here