Trying to mock a function return in node.js/express

I’m trying to test an application I’m writing in node.js/Express.

I want to mock the return of a mock-repository I’ve set up for development purposes.

Mock repo:

let dogs = [];

export const getDogs = () => {
  return dogs;
};

export const setDogs = (updatedDogs) => {
  dogs = updatedDogs;
};

I’m importing the function to mock a return value from in my test file;

import * as sut from "../dogs.js";
import * as dogsRepo from "../../repositories/dogs.js";
import { mockRequest, mockResponse } from "mock-req-res";
import { jest } from "@jest/globals";

describe("dogs controller", () => {
  describe("getDogById", () => {
    test("should return dog", () => {
      // Arrange
      const req = mockRequest({ id: 1 });
      const res = mockResponse();
      // dogsRepo.getDogs = jest.fn().mockReturnValue([]);
      // jest.spyOn(dogsRepo, "getDogs").mockReturnValue([]);
      jest.spyOn(dogsRepo, "getDogs").mockImplementation(() => []);

      //Act
      sut.getDogById(req, res);
    });
  });
});

I simply want my test to mock a return value of [] from the repository. I have done this many times in react projects but this is my first time doing so in node.js.

I have tried to mock the return of the function in three different ways and each one gives me the error;

“TypeError: Cannot assign to read only property ‘getDogs’ of object ‘[object Module]'”

What am I doing wrong?

How to Update State in map function in react

I have an object in a state, update all values under map Function

const [docUrls, setDocUrls] = useState({ imageUrl: "",  panUrl: "", statementUrl: "" })

data.map(item=>
 item.type==='image' ?
setDocUrls({ ...docUrls, imageUrl:item.url })

:item.type==='panUrl' ?
setDocUrls({ ...docUrls, panUrl:item.url  })

:item.type==='statement' ?
setDocUrls({ ...docUrls, statementUrl: item.url})

)

Regex: Capture All JavaScript Variable Declarations and Usages

I’m trying to write a regular expression for use with matchAll to match all const and let variable declarations and their usages.

Examples:

const foo = (x) => x
const bar = 'bar'; let baz = 123, qux = 456
                                   , quux = 1 / 2

foo(bar)
baz = qux

It should really work with any valid JavaScript. So far I’ve come up with the following:

str.matchAll(/b(?:const|let)bs+(w+)/g)

which produces what I want:

[
  ["const foo", "foo"],
  ["const bar", "bar"],
  ["let baz", "baz"]
]

except that it misses the comma-delimited declarations. I imagine they’d appear in the last array as ["let baz", "baz", "qux", "quux"], although the structure isn’t critical as long as everything is there. I’ve tried tacking something like (?:s*=.*,s*(w+))*? onto the end of the regex but no luck. Regular expressions aren’t my strong point. :/

The ultimate goal is to replace all of the matches with object property assignments, i.e. const foo = bar will become PREFIX.foo = PREFIX.bar.

I’m sure it’s possible to do this with an AST library as well, but this is for a small NPM package and I’d rather keep it small if possible.

Dynamically adding preview not working properly in Grapes js

I am using GrapesJs in React Js, When I have a preview page, I have to show the builder with the preview mode. Preview is executing, but that grapes Js sidebar component is not hiding and the builder is also editable.


  const {template, loading} = props; //getting grapes js data from props
  let editor = grapesjs.init({
    container: '#root',      
    height: '100%',
    fromElement: true,
    plugins: ['gjs-preset-webpage', 'gjs-blocks-flexbox'],
    assetManager: {
      storageType   : '',
      storeOnChange  : true,
      storeAfterUpload  : true,
      credentials: 'include',  
  },
  }); 
useEffect(()=>{
  if(loading){
    editor.setComponents('<div>loading....</div>');
  }else{
      editor.runCommand('preview');      
  }
},[template, loading])

  
return (<div></div>)
}

separate big table in html into small tables

I am creating a table but I have to separate it into separate tables. They must be separated by “table_title” and the content of the tables is “table_line” I would greatly appreciate your support

<thead>  
    <tr>
      <th>Product</th>
      <th></th>
    </tr>
  </thead>
 <tbody>
      <tr>
         <td colspan="2" class="titulo_tabla">Title 1</td>
      </tr>
      <tr>
         <td class="linea_tabla">Resolución de la pantalla</td>
         <td class="linea_tabla">1366 x 768 Pixeles</td>
      </tr>
      <tr>
         <td class="linea_tabla">Pantalla táctil</td>
         <td class="linea_tabla">No</td>
      </tr>
      <tr>
         <td class="linea_tabla">Tipo HD</td>
         <td class="linea_tabla">HD</td>
      </tr>
      <tr>
         <td class="linea_tabla">Retroiluminación LED</td>
         <td class="linea_tabla">Si</td>
      </tr>
      <tr>
         <td class="linea_tabla">Relación de aspecto nativa</td>
         <td class="linea_tabla">16:9</td>
      </tr>
      <tr>
         <td class="linea_tabla">Pantalla antirreflejante</td>
         <td class="linea_tabla">Si</td>
      </tr>
      <tr>
         <td class="linea_tabla">Brillo de pantalla</td>
         <td class="linea_tabla">220 cd / m²</td>
      </tr>
      <tr>
         <td class="linea_tabla">Densidad del pixel</td>
         <td class="linea_tabla">112 ppi</td>
      </tr>
      <tr>
         <td class="linea_tabla">Espacio de color RGB</td>
         <td class="linea_tabla">NTSC</td>
      </tr>
      <tr>
         <td class="linea_tabla">Gama de colores</td>
         <td class="linea_tabla">45%</td>
      </tr>
      <tr>
         <td class="linea_tabla">Máxima velocidad de actualización</td>
         <td class="linea_tabla">60 Hz</td>
      </tr>
      <tr>
         <td class="linea_tabla">Razón de contraste (típica)</td>
         <td class="linea_tabla">400:1</td>
      </tr>
      <tr>
         <td colspan="2" class="titulo_tabla">TItle 2</td>
      </tr>
      <tr>
         <td class="linea_tabla">Modelo del procesador</td>
         <td class="linea_tabla">i5-1135G7</td>
      </tr>
      <tr>
         <td class="linea_tabla">Frecuencia del procesador turbo</td>
         <td class="linea_tabla">4.2 GHz</td>
      </tr>
      <tr>
         <td class="linea_tabla">Familia de procesador</td>
         <td class="linea_tabla">Intel® Core™ i5 de 11ma Generación</td>
      </tr>
      <tr>
         <td class="linea_tabla">Núcleos del procesador</td>
         <td class="linea_tabla">4</td>
      </tr>
      <tr>
         <td class="linea_tabla">Caché del procesador</td>
         <td class="linea_tabla">8 MB</td>
      </tr>
      <tr>
         <td class="linea_tabla">Tipo de cache en procesador</td>
         <td class="linea_tabla">Smart Cache</td>
      </tr>
      <tr>
         <td class="linea_tabla">Frecuencia configurable TDP-up</td>
         <td class="linea_tabla">2.4 GHz</td>
      </tr>
      <tr>
         <td class="linea_tabla">TDP-up configurable</td>
         <td class="linea_tabla">28 W</td>
      </tr>
      <tr>
         <td class="linea_tabla">TDP-down configurable</td>
         <td class="linea_tabla">12 W</td>
      </tr>
      <tr>
         <td class="linea_tabla">Frecuencia configurable TDP-down</td>
         <td class="linea_tabla">0.9 GHz</td>
      </tr>
      <tr>
         <td colspan="2" class="titulo_tabla">Title 3</td>
      </tr>
      <tr>
         <td class="linea_tabla">Cantidad de puertos tipo A USB 3.2 Gen 1 (3.1 Gen 1)</td>
         <td class="linea_tabla">2</td>
      </tr>
      <tr>
         <td class="linea_tabla">Puertos Ethernet LAN (RJ-45)</td>
         <td class="linea_tabla">1</td>
      </tr>
      <tr>
         <td class="linea_tabla">Número de puertos HDMI</td>
         <td class="linea_tabla">1</td>
      </tr>
      <tr>
         <td class="linea_tabla">Versión HDMI</td>
         <td class="linea_tabla">1.4</td>
      </tr>
      <tr>
         <td class="linea_tabla">Combo de salida de auriculares / micrófono del puerto</td>
         <td class="linea_tabla">Si</td>
      </tr>
      <tr>
         <td class="linea_tabla">Tipo de puerto de carga</td>
         <td class="linea_tabla">Toma de entrada de CC</td>
      </tr>
   </tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
let types = [... new Set($('table.original tr .titulo_tabla').get().map(type => type.textContent))];

//create a container for the cloned tables
$('table.original').after(`<h4>After:</h4><div class="cloned-tables"></div>`)

//loop over types, clone tables, modify accordingly
$.each(types, function(index, type) {
  $(`<p class="type">${type}</p>${$('table.original')[0].outerHTML}`)
    .appendTo('.cloned-tables')
    .find('.titulo_tabla').each(function() {
      //if (this.textContent !== type) { this.parentElement.remove();  }        
      //this.remove();
  });
});
</script>

I would like to separate by table title, any help is welcome.
I would like to separate by table title, any help is welcome.
I would like to separate by table title, any help is welcome.
I would like to separate by table title, any help is welcome.
I would like to separate by table title, any help is welcome.
I would like to separate by table title, any help is welcome.
I would like to separate by table title, any help is welcome.
I would like to separate by table title, any help is welcome.
I would like to separate by table title, any help is welcome.
I would like to separate by table title, any help is welcome.

descripcion de código

How to make parent/child accordion navigation for D3

In using D3, if one wished to make an accordion where there were parent categories, and child nodes, how would you construct an accordion/disclosure triangle type interface, that when you click on child nodes, the target loads an individual chart?

Does anyone have info or perhaps can point to a place that shows how to build navigation/interactive structures/filters for D3. Trying to build a navigation type dashboard in D3

Sorting Characters Where The Characters are Valued Differently In My Project Context

I want to sort an array of characters consisting of letters F, S, T. There may be duplicates of each character.
Example Arrays:
['F', 'F', 'S', 'T', 'T'], ['F', 'S'], ['T', 'S', 'S', 'F']

In the context of my project, T = 0, F = 1, S = 2, So when an array is sorted, if T is in the array, it should be the first index. F should be the second index, and S should be the third index. Is there a way I can make this happen?

how to stop the first click loop after click next run

every click I do a loop in js, but when I click next the first loop is still running, finally there is a double loop on the same id, how do I stop the first loop and replace it with the next loop?

This is a program for creating chats, so when I click on person A, a chat with person A appears, but now what happens if I click on person A and B, the ID to display the chat alternately between Person A and Person B.

file.js

var base_url = window.location.origin + '/' + window.location.pathname.split('/')[1] + '/';

$(document).ready(function() {
    list()
})

function list() {
    setTimeout(function() {
        $.ajax({
            method: "GET",
            url: base_url + 'admin/pesan/get_list',
            dataType: "JSON",
            success: function(data) {
                $('#list_chat').empty()
                    // console.log(data[0].date_add)
                $.each(data, function(i, data) {
                    var temp = null
                    var nama = null
                    var id = null
                    if (data.nama_pengirim == 'Admin') {
                        nama = data.nama_penerima
                        id = data.id_penerima
                    } else {
                        nama = data.nama_pengirim
                        id = data.id_pengirim
                    }
                    // console.log(id)
                    if (temp != nama) {
                        $('#list_chat').append(
                            `<div class="d-flex flex-row mb-1 border-bottom pb-3 mb-3">
                                <a class="d-flex" href="#" id="klik_perusahaan" data-id="` + id + `">
                                    <img alt="Profile Picture" src="` + base_url + `assets/template/img/profile-pic-l.jpg" class="img-thumbnail border-0 rounded-circle mr-3 list-thumbnail align-self-center xsmall">
                                </a>
                                <div class="d-flex flex-grow-1 min-width-zero">
                                    <div class="pl-0 align-self-center d-flex flex-column flex-lg-row justify-content-between min-width-zero">
                                        <div class="min-width-zero">
                                            <a href="#" id="klik_perusahaan" data-id="` + id + `">
                                                <p class=" mb-0 truncate">` + data.badan_hukum + `. ` + nama + `</p>
                                            </a>
                                            <p class="mb-1 text-muted text-small">` + new Date(data.date_add).getHours() + ":" + new Date(data.date_add).getMinutes() + `</p>
                                        </div>
                                    </div>
                                </div>
                                </div>`
                        )
                    }
                });
            }
        });
        list();
    }, 1000);
}

$('#firstFull').on('click', '#klik_perusahaan', function() {
    var id = $(this).data('id')
    show_pesan(id)
})

function show_pesan(id) {
    setTimeout(function() {
        console.log(id)
        $.ajax({
            type: "post",
            dataType: "json",
            url: base_url + 'admin/pesan/get_pesan',
            data: { 'id': id },
            success: function(data) {
                var nama = null
                if (data[0].nama_pengirim == 'Admin') {
                    nama = data[0].nama_penerima
                } else {
                    nama = data[0].nama_pengirim
                }
                $('#show_chat').empty()
                $('#show_chat').append(
                    `<div class="d-flex flex-row justify-content-between mb-3 chat-heading-container">
                        <div class="d-flex flex-row chat-heading">
                            <a class="d-flex" href="#">
                                <img alt="Profile Picture" src="` + base_url + `assets/template/img/profile-pic-l.jpg" class="img-thumbnail border-0 rounded-circle ml-0 mr-4 list-thumbnail align-self-center small">
                            </a>
                            <div class=" d-flex min-width-zero">
                                <div class="card-body pl-0 align-self-center d-flex flex-column flex-lg-row justify-content-between min-width-zero">
                                    <div class="min-width-zero">
                                        <a href="#">
                                            <p class="list-item-heading mb-1 truncate ">` + data[0].badan_hukum + `. ` + nama + `</p>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="separator mb-5"></div>`
                )
                $.each(data, function(i, data) {
                    if (data.id_pengirim != 'Admin') {
                        $('#show_chat').append(
                            `<div class="card d-inline-block mb-3 float-left mr-2">
                                <div class="position-absolute pt-1 pr-2 r-0">
                                    <span class="text-extra-small text-muted white">09:30</span>
                                </div>
                                <div class="card-body" style="background-color:grey; border-radius:10px !important">
                                    <div class="d-flex flex-row pb-2">
                                        <a class="d-flex" href="#">
                                            <img alt="Profile Picture" src="` + base_url + `assets/template/img/profile-pic-l.jpg" class="img-thumbnail border-0 rounded-circle mr-3 list-thumbnail align-self-center xsmall">
                                        </a>
                                        <div class="d-flex flex-grow-1 min-width-zero">
                                            <div class="m-2 pl-0 align-self-center d-flex flex-column flex-lg-row justify-content-between min-width-zero">
                                                <div class="min-width-zero">
                                                    <p class="mb-0 truncate list-item-heading white">` + data.badan_hukum + `. ` + nama + `</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
    
                                    <div class="chat-text-left">
                                        <p class="mb-0 text-semi-muted white">` + data.pesan + `</p>
                                    </div>
                                </div>
                            </div>
                            <div class="clearfix"></div>`
                        )
                    } else {
                        $('#show_chat').append(
                            `<div class="card d-inline-block mb-3 float-right  mr-2">
                                <div class="position-absolute pt-1 pr-2 r-0">
                                    <span class="text-extra-small text-muted">09:41</span>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex flex-row pb-2">
                                        <a class="d-flex" href="#">
                                            <img alt="Profile Picture" src="` + base_url + `assets/template/img/profile-pic-l-4.jpg" class="img-thumbnail border-0 rounded-circle mr-3 list-thumbnail align-self-center xsmall">
                                        </a>
                                        <div class="d-flex flex-grow-1 min-width-zero">
                                            <div class="m-2 pl-0 align-self-center d-flex flex-column flex-lg-row justify-content-between min-width-zero">
                                                <div class="min-width-zero">
                                                    <p class="mb-0 list-item-heading truncate">Admin</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
    
                                    <div class="chat-text-left">
                                        <p class="mb-0 text-semi-muted">` + data.pesan + `</p>
                                    </div>
                                </div>
                            </div>
                            <div class="clearfix"></div>`
                        )
                    }
                    $('#show_chat').append(
                        `<div class="clearfix"></div>
                        </div>
                        </div>`
                    )
                });
            }
        })
        show_pesan(id)
    }, 1000)
}

view.html

<main>
    <div class="container-fluid">
        <div class="row app-row">
            <div class="col-12 chat-app" id="show_chat">

            </div>
        </div>
    </div>

    <div class="app-menu">
        <ul class="nav nav-tabs card-header-tabs ml-0 mr-0 mb-1" role="tablist">
            <li class="nav-item w-50 text-center">
                <a class="nav-link active" id="first-tab" data-toggle="tab" href="#firstFull" role="tab" aria-selected="true">Messages</a>
            </li>
            <li class="nav-item w-50 text-center">
                <a class="nav-link" id="second-tab" data-toggle="tab" href="#secondFull" role="tab" aria-selected="false">Contacts</a>
            </li>
        </ul>

        <div class="p-4 h-100">
            <div class="form-group">
                <input type="text" class="form-control rounded" placeholder="Search">
            </div>
            <div class="tab-content h-100">
                <div class="tab-pane fade show active  h-100" id="firstFull" role="tabpanel" aria-labelledby="first-tab">

                    <div class="scroll" id="list_chat"></div>

                </div>

                <div class="tab-pane fade  h-100" id="secondFull" role="tabpanel" aria-labelledby="second-tab">
                    <div class="scroll">

                        <?php foreach ($kontak as $data) : ?>
                            <div class="d-flex flex-row mb-3 border-bottom pb-3">
                                <a class="d-flex" href="#">
                                    <img alt="Profile Picture" src="<?= base_url() ?>assets/template/img/profile-pic-l.jpg" class="img-thumbnail border-0 rounded-circle mr-3 list-thumbnail align-self-center xsmall">
                                </a>
                                <div class="d-flex flex-grow-1 min-width-zero">
                                    <div class="m-2 pl-0 align-self-center d-flex flex-column flex-lg-row justify-content-between min-width-zero">
                                        <div class="min-width-zero">
                                            <a href="#">
                                                <p class="mb-0 truncate"><?= $data['badan_hukum'] . '. ' . $data['nama_perusahaan']; ?></p>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach ?>

                    </div>
                </div>
            </div>
        </div>

        <a class="app-menu-button d-inline-block d-xl-none" href="#">
            <i class="simple-icon-options"></i>
        </a>
    </div>

    <div class="chat-input-container d-flex justify-content-between align-items-center">
        <input class="form-control flex-grow-1" type="text" placeholder="Say something...">
        <div>
            <button type="button" class="btn btn-outline-primary icon-button large">
                <i class="simple-icon-paper-clip"></i>
            </button>
            <button type="button" class="btn btn-primary icon-button large">
                <i class="simple-icon-arrow-right"></i>
            </button>

        </div>
    </div>
</main>

<?php $this->load->view('template/footer') ?>

React application returning an empty div when deployed on github pages

I have been working on deploying the website I am working on to github pages but It seems to return an empty div when deployed. when served with npx serve build it displays all information fine, and is displays on local host normally but just returns a blank div when deployed on github pages.

steps I took to deploy:

  1. installed gh-pages
  2. added “homepage” to package.json
  3. npm run deploy

The package.json code is listed below incase there is an error in there

{
  "homepage": "https://jonlev03-hub.github.io/media-pilot/",
  "name": "media-pilot",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "gh-pages": "^4.0.0",
    "package.json": "^2.0.1",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "^5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "github-pages": "^0.1.0"
  }
}

and if you can’t find any issues in that block of code all the code for the site is located inside my repository at github.com/jonlev03-hub/media-pilot .

How to group items under specific parent item in React?

I have a groups API which has id and group_name field. There is another training API which gives me training_name and training_group_id.
Every training in training API is linked to a group.

Present Output on UI –
Group 1 –
Training 1 |
Group 2 –
Training 2 |
Group 2 –
Training 3 |
Group 2 –
Training 4

Is there a way I can show by grouping the trainings which has common group_name to appear under one group_name and not repeat as shown in above output?

Expected Output on UI –
Group 1 –
Training 1 |
Group 2 –
Training 2, Training 3, Training 4

Code –

function TileViewNew() {
  const { currentUserTrainings, trainingGroups } = useContext(MyContext);

  const renderTrainingGroupName = training => {
    const trainingGroupName = trainingGroups.find(group => {
      return group.id === training;
    });
    return trainingGroupName.group_name;
  };

  return (
    <Grid>
      {currentUserTrainings.map(({ training_name, training_group }) => (
        <>
          <Grid>
            <strong>{renderTrainingGroupName(training_group)}</strong>
          </Grid>
          {training_name}
        </>
      ))}
    </Grid>
  );
}

export default TileViewNew;

rails/webpacker module build fail issue from ./node_modules/mini-css-extract-plugin/dist/loader.js

I have upgraded @rails/webpacker from v4 to v5 (5.72.1, to be precise). While upgrading, I got following issue

ERROR in ./node_modules/croppie/croppie.css Module build failed (from
./node_modules/@rails/webpacker/node_modules/mini-css-extract-plugin/dist/loader.js):
TypeError: Cannot read property ‘tap’ of undefined

This is how I have setup my webpack config

const { environment } = require('@rails/webpacker');
const vue = require('./loaders/vue');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');

const customConfig = {
  resolve: {
    fallback: {
      dgram: false,
      fs: false,
      net: false,
      tls: false,
      child_process: false,
    },
  },
  entry: {
    vendor: ['babel-polyfill', 'vue', 'moment', 'axios'],
  },
};

environment.splitChunks((config) => {
  console.log('config', environment);
  return {
    ...config,
    ...{
      optimization: {
        splitChunks: { chunks: 'all', name: '~' },
        runtimeChunk: true,
      },
    },
  };
});


environment.config.delete('node.dgram');
environment.config.delete('node.fs');
environment.config.delete('node.net');
environment.config.delete('node.tls');
environment.config.delete('node.child_process');

environment.config.merge(customConfig);

environment.plugins.append('VueLoaderPlugin', new VueLoaderPlugin());
environment.loaders.append('vue', {
  test: /.vue$/,
  loader: 'vue-loader',
});

// Comment this if you need case-sensitive-paths-plugin in local development.
if (process.env.RAILS_ENV === 'development') {
  environment.plugins.delete('CaseSensitivePaths');

  // Only add en.js locale for local development.
  environment.plugins.append('moment', new webpack.ContextReplacementPlugin(/moment[/\]locale/, /(en).js/));
}

environment.plugins.prepend('Environment', new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(process.env))));
environment.plugins.prepend(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    jquery: 'jquery',
  })
);

const config = environment.toWebpackConfig();

config.resolve.alias = {
  jquery: 'jquery/src/jquery',
};

let sassLoader = environment.loaders.get('sass').use.find(item => item.loader === 'sass-loader')
sassLoader = {
  ...sassLoader,
  options: {
    ...sassLoader.options,
    sassOptions: {
      ...sassLoader.options.sassOptions,
      includePaths: ["./node_modules"],
    }
  }
}

let miniCssExtractPlugin = environment.plugins.get('MiniCssExtract')
console.log('miniCssExtractPlugin', miniCssExtractPlugin)

environment.loaders.append('vue', vue);

environment.config.merge({
  optimization: {
    minimize: false,
    minimizer: [
      new TerserPlugin({
        test: /.js(?.*)?$/i,
      }),
    ],
  },
  resolve: {
    alias: {
      app: path.resolve(__dirname, '../../app/'),
    },
  },
});

module.exports = environment

This is the logs

enter image description here

If I comment import 'croppie/croppie.css' in the js file where it is used, the error goes away.

Not sure if this issue is only while importing third party css file.

Order in Promise/Async/Await (Interview Question)

Question:

new Promise((resolve) => {
  console.log(1)
  resolve()
}).then(async () => {
  console.log(2)
}).then(async () => {
  console.log(3)
})

new Promise((resolve) => {
  console.log('a')
  resolve()
}).then(() => {
  console.log('b')
}).then(() => {
  console.log('c')
}).then(() => {
  console.log('d')
}).then(() => {
  console.log('e')
})

Answer:

1
a
2
b
c
d
3
e

But I think answer is…. 1 a 2 b 3 c d e

Please help to share how to think to get answer detailed. Thanks.

How to change width and height of graphic ‘rect’ programmatically in Echarts (by implementing onClick event or make it resizable by dragging)

I’m using latest echarts and trying to put a rectangle on the canvas using graphic option.
We can set width and height of 'type: rect' by using Shape.width and Shape.height according to this documentation.

What I want to do is that I want to change that width and height of rectangle

  1. by clicking on it (by implementing onClick event)
  2. by dragging like in css ‘resize’ property to a div. Is this possible in echarts?

Here is the sample option code that I’m currently trying to implement. You can use it by replacing it here. The setter function setWidth() can change the value of width variable but Shape.width will not call getWidth() function again. There will not be a new render happening.

let width = 100;

function getWidth() {
  return width;
}

function setWidth(value) {
  width = value;
}

option = {
  graphic: {
    elements: [
      {
        type: 'rect',
        draggable: true,
        shape: {
          x: 0,
          y: 0,
          width: getWidth(),
          height: 100
        },
        style: {
          fill: 'red'
        },
        onclick: function(e) {
          setWidth(400)
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  }
};

How do I organize an Array of objects according to the sum of its attributes?

I’m developing the backEnd part for a selling app in which I have 2 Array of Objects, one got the sellers’ name, and the other has the monthly sales.
I was told by my superiors to order the Array of names from the one that made the most sales to the one that made the least ( from highest to lowest ) using the data from the array which contains the sales, basically making a summation of the key => quantity.
I’m not sure how to do it, I tried to use a Reduce method with the sales of each seller but I can’t think how to compare them to reorganize the Array.
The code is:

const sellers= [{id:1,name: 'juan', age: 23},{id:2,name: 'adrian', age: 32},{id:3,name: 'apolo', age: 45}];

const sales= [{equipo: 'frances', sellerId: 2, quantity: 234},{equipo: 'italiano', sellerId: 3, quantity: 24},{equipo: 'polaco', sellerId: 1, quantity: 534},{equipo: 'frances', sellerId: 2, quantity: 1234},{equipo: 'frances', sellerId: 3, quantity: 2342}];

This is what I have already tried:

const bestSellers= () => {
  sales.reduce((sum, value) => ( value.sellerId == 1 ? sum + value.area : sum), 0); }

The final result should look like this:

const sellers= [{id:3,name: 'apolo', age: 45},{id:2,name: 'adrian', age: 32},{id:1,name: 'juan', age: 23}]

React app throws TypeError: Cannot read properties of undefined (reading ‘name’) when compiling

I keep running into an issue with my CRUD application when I go to edit a name from my list, it throws an error “TypeError: Cannot read properties of undefined (reading ‘name’)”.

It seems to stem from the “value={selectedUser.name}” in my input field, but when I remove it the app compiles but I cannot alter the field at all – nothing happens when you type. Any help is appreciated!

import React, { useState, useContext, useEffect } from 'react'
import { GlobalContext } from '../context/GlobalState'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { Form, FormGroup, Label, Input, Button } from 'reactstrap'

const EditUser = (props) => {
const [selectedUser, setSelectedUser] = useState({
  id: '',
  name: ''
});
const { users, editUser } = useContext(GlobalContext);
const navigate = useNavigate();
const currentUserId = useParams(props);

useEffect(() => {
  const userId = currentUserId;
  const selectedUser = users.find(user => user.id === userId)
  setSelectedUser(selectedUser)
}, [currentUserId, users])

const onSubmit = (e) => {
  e.preventDefault()
  editUser(selectedUser)
  navigate('/');
}

const onChange = (e) => {
  setSelectedUser({...selectedUser, [e.target.name]: e.target.value})
}

  return (
    <div>
        <Form onSubmit={onSubmit}>
            <FormGroup>
                <Label>Edit Name</Label>
                <Input type='text' name='name' value={selectedUser.name} onChange={onChange} placeholder='Enter Name'></Input>
            </FormGroup>
        <Button type='submit'>Edit Name</Button>
        <Link to='/' className='btn btn-danger m-2'>Back</Link>
        </Form>
    </div>
  )
}

export default EditUser