My code works but I don’t think it is good. How to improve it?

Is there a way to beautify my code? It works but there repeated blocks and I am not sure that I’m using some functions in the right way.
I’m not new to javascript but I want to improve it and get rid of Bad Coding Habits.

Below is my code snippet that I’m using on the server to upload product images to cloud storage using multer and sharp.

const EasyYandexS3 = require('easy-yandex-s3')
const multer = require('multer')
const sharp = require('sharp')
const slug = require('slug')

const s3 = new EasyYandexS3({
  auth: {
    accessKeyId: process.env.KEY_ID,
    secretAccessKey: process.env.SECRET_KEY,
  },
  Bucket: process.env.BACKET, // Название бакета
  debug: false, // Дебаг в консоли
})

const storage = multer.memoryStorage()
const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === 'image/jpeg' ||
    file.mimetype === 'image/jpg' ||
    file.mimetype === 'image/png'
  ) {
    cb(null, true)
  } else {
    cb(null, false)
  }
}

const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: 1024 * 1024 * 5, // ограничение до 5 мб
  },
})

const uploadFields = upload.fields([
  { name: 'cover', maxCount: 1 },
  { name: 'media', maxCount: 4 },
])

const uploadImages = (req, res, next) => {
  uploadFields(req, res, (err) => {
    if (err instanceof multer.MulterError) {
      if (err.code === 'LIMIT_UNEXPECTED_FILE') {
        return res.send('Превышено количество файлов.')
      }
    } else if (err) {
      return res.send(err)
    }
    next()
  })
}
const resizeImages = async (req, res, next) => {
  // Функция загрузки фотографий в бакет
  async function transform(size, file, filename, type) {
    const folder = slug(req.body.title)
    const resizedImgFilename = `${filename}-${size}`
    const resizedImgBuffer = await sharp(file.buffer)
      .resize(size)
      .toFormat('jpeg')
      .jpeg({ quality: 90 })
      .toBuffer()
    const upload = await s3.Upload(
      {
        buffer: resizedImgBuffer,
        name: resizedImgFilename,
      },
      `/products/${folder}/`
    )
    if (size === 800) {
      type.push(upload.Location.slice(0, -4))
    }
  }

  // Проверяем какие файл загружены
  if (req.files.media === undefined && req.files.cover === undefined) {
    return next()
  } else if (req.files.media === undefined) {
    await Promise.all(
      req.files.cover.map(async (file) => {
        const filename = Date.now() + Math.round(Math.random() * 1e2) + 'c'
        const type = req.body.cover
        await transform(800, file, filename, type)
        await transform(400, file, filename, type)
        await transform(250, file, filename, type)
      })
    )
  } else if (req.files.cover === undefined) {
    await Promise.all(
      req.files.media.map(async (file) => {
        const filename = Date.now() + Math.round(Math.random() * 1e2) + 'm'
        const type = req.body.media
        await transform(800, file, filename, type)
        await transform(400, file, filename, type)
        await transform(250, file, filename, type)
      })
    )
  } else {
    await Promise.all(
      req.files.media.map(async (file) => {
        const filename = Date.now() + Math.round(Math.random() * 1e2) + 'm'
        const type = req.body.media
        await transform(800, file, filename, type)
        await transform(400, file, filename, type)
        await transform(250, file, filename, type)
      })
    )
    await Promise.all(
      req.files.cover.map(async (file) => {
        const filename = Date.now() + Math.round(Math.random() * 1e2) + 'c'
        const type = req.body.cover
        await transform(800, file, filename, type)
        await transform(400, file, filename, type)
        await transform(250, file, filename, type)
      })
    )
  }
  next()
}

module.exports = {
  uploadImages,
  resizeImages,
}

Do all error objects in Javascript have the same structure?

I’m implementing error outputting modal in React web app and therefore instead of just using .catch((e) => console.log(e) I’m planning to pass the error details into a separate component and display 3 parts of this error object: name, message, stack, in separate fields of this component.

I know that standard Error type object has all of those properties, however, I was wondering whether there are some exceptions and some error could be returned without all of these fields?

How to store JSON in variable from fetch API

I can’t disclose the URL and what API I’m using because it breaches my work’s policy but hopefully I can provide enough information for assistance. I have a javascript function that runs on a on-click (I’m eventually building up a form that will make use of this fetch).

function getdata() {
let customer_po = document.getElementById("customer").value;
let access_token;
let data = {
    'grant_type': 'REDACTED'
}
let state = {
    "state": "REDACTED"
}
fetch(prod_auth, {
    method: "POST",
    headers: login_header,
    body: new URLSearchParams(data),
})
    .then(response => response.json())
    .then(result => console.log(result))

}

This works and I can access the JSON dictionary in the console. However, when I try to use my access_token variable declared earlier in such a way:

.then(response => response.json())
.then(result => {access_token = result["access_token"];})

and console.log(access_token) gives undefined. I need to access this variable in my getdata() function so it can be used as a parameter in another fetch call. Any help would be appreciated. Thank you!

Creating like button for multiple items

I am new to React and trying to learn more by creating projects. I made an API call to display some images to the page and I would like to create a like button/icon for each image that changes to red when clicked. However, when I click one button all of the icons change to red. I believe this may be related to the way I have set up my state, but can’t seem to figure out how to target each item individually. Any insight would be much appreciated.

`
 //store api data
 const [eventsData, setEventsData] = useState([]);

 //state for like button
 const [isLiked, setIsLiked] = useState(false);

useEffect(() => {
 axios({
  url: "https://app.ticketmaster.com/discovery/v2/events",
  params: {
    city: userInput,
    countryCode: "ca",
  },
  })
  .then((response) => {
    setEventsData(response.data._embedded.events);
  })
  .catch((error) => {
    console.log(error)
  });
});

//here i've tried to filter and target each item and when i 
console.log(event) it does render the clicked item, however all the icons 
change to red at the same time
  const handleLikeEvent = (id) => {
   eventsData.filter((event) => {
     if (event.id === id) {
       setIsLiked(!isLiked);
     }
    });
  };

return (
   {eventsData.map((event) => {
        return (
          <div key={event.id}>
              <img src={event.images[0].url} alt={event.name}></img>
              <FontAwesomeIcon
                 icon={faHeart}
                 className={isLiked ? "redIcon" : "regularIcon"}
                 onClick={() => handleLikeEvent(event.id)}
               />
          </div>
)

  `

 

Is it possible to tell if an async function is currently running at the top of the stack?

I’m trying to do something that involves a global context that knows about what function is running at the moment.

This is easy with single-threaded synchronous functions, they start off running and finish running when they return.

But async functions can pop to the bottom of the stack and climb back up multiple times before completing.

let currentlyRunningStack: string[] = [];
function run(id: string, cb: () => any) {
  currentlyRunningStack.push(id);
  cb()
  currentlyRunningStack.shift();
}

// works with synchronous stuff
run("foo", () => {
  run("bar", () => console.log("bar should be running"));
  console.log("now foo is running");
});

// can it work with asynchronous
run("qux", async () => {
  // async functions never run immediately...
  await somePromise();
  // and they start and stop a lot
});

Is it possible to keep track of whether or not an asynchronous function is currently running or currently waiting on something?

Jquery cannot find newly added elements [duplicate]

The Context

To make the explanation of my issue easier, I have created a small example:

Let’s say we have this simple website (index.html):

<!DOCTYPE html>
<html lang="en">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <body>
        <script id="navigation" src="nav.js"></script>
        <p>Amazing website content</p>
        <script src="something.js"></script>
    </body>
</html>

Let’s say the nav.js script imports our navigation bar from a nav.html into our index.html, so the script would look something like this:

fetch('nav.html')
    .then(res => res.text())
    .then(text => {
        let oldE = document.querySelector("script#navigation");
        let newE = document.createElement("div");
        newE.innerHTML = text;
        oldE.parentNode.replaceChild(newE,oldE);
    })

and for simplicity sake our “navigation bar” (nav.html) looks like this:

<ul class="class-nav">
  <li><a href="#">Home</a></li>
  <li><a href="#">News</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">About</a></li>
</ul>

Finally, we have something.js which is a javascript that uses jQuery to do some stuff, for now, we just want to be able to print out elements with the class name class-nav:

jQuery(document).ready(function($) {
    "use strict";
    var magic = function() {
        $('.class-nav').each(function() {
            console.log(this);
        });
    };
    magic();
});

The Issue

If I hardcoded my navigation bar (nav.html) to the webpage (index.html), the magic() function in something.js (that uses jQuery) works and is able to print out the navigation bar class-nav.

However, if we have it in the current setup, where we have our navigation bar added to the webpage from a separate nav.html file, the magic() function isn’t able to find class-nav.

Why? And how can I modify something.js to be able to retrieve class-nav using jQuery?

How to make these fixed cols’ width on a Bootstrap 4.0 table-responsive?

I’ve been trying to get this one to work based on similar questions/answers, but no success.

This is my attempt to fix the col width by explicitly setting each column’s width, but nothing changes!

<thead style="white-space: nowrap">
                <tr>
                  <th style="width: 1%" class="text-center">ClientID</th>
                  <th style="width: 2%" class="text-center">Task Nº</th>
                  <th style="width: 25%" class="text-center">Task</th>
                  <th style="width: 4%" class="text-center">Date Assigned</th>
                  <th style="width: 4%" class="text-center">Link To File</th>
                  <th style="width: 22%" class="text-center">Notes</th>
                  <th style="width: 14%" class="text-center">Approval</th>
                  <th style="width: 26%" class="text-center">Comments</th>
                </tr>
              </thead>

Here’s the Fiddle if you feel like giving a hand. Thank you!

Here’s

How to change the font in Algolia’s autocomplete?

I’m using Algolia’s autocomplete feature, which is working fine, but how can I change the font of the text shown in the autocomplete results? I’m using Javascript / JQuery

I would like to use a custom font (Cera) that I use in the rest of my website (which I’m loading via @font-face)

$('.algolia').autocomplete(
            var1,
            var2,
            var3,
            var4,
        )

TypeError: Cannot read properties of undefined (reading ‘create’). Happens when running npm run build:ssr

Getting an error when running npm run build:ssr to try to deploy my angular application
See the code below that the error is pointing to.
I’ve been trying to figure out why is giving me that error for weeks now.

const webpack = require('webpack');
const WebpackConfigFactory = require('@nestjs/ng-universal')
  .WebpackConfigFactory;

module.exports = WebpackConfigFactory.create(webpack, {
  // Nest server for SSR
  server: './server/main.ts'
});

Sort array in alphabetic order without using Array.sort in Java

I want to sort values of an array in alphabetic order, using merge sort. I have this code so far, but I when I run it, the output is jumbled and not in correct order. (Charlottetown, Fredericton, Montreal, Toronto, Vancouver, …)

If anyone has any advice/solutions, I would appreciate your help 🙂

Here is my current code.

    class Main {
  public static void main(String[] args) {
    String [] words = {"Montreal", "Halifax", "Toronto", "Vancouver",
              "Whitehorse", "Winnipeg", "Calgary", "Edmonton", 
              "Hamilton", "Regina", "Saskatoon", "Sault Ste. Marie", "Moncton", "Gander", "Fredericton", "Charlottetown"};
   for(int i = 0; i < words.length; i++)
{
    int smallest = i;
    for(int j = i + 1; j < words.length; j++) 
    {
        if(words[j].compareTo(words[i]) < 0)
            smallest = j;
    }
    
    String aux = words[i];
    words[i] = words[smallest];
    words[smallest] = aux;
}
for(int i = 0; i < words.length; i++)
{
    System.out.println(words[i]);
}
  }
}

Render a razor component in a new browser tab and pass a list of objects to it

I’m trying to create a control that opens a razor component and displays the objects sent to the page after a user clicks a Print button. Using the IJSRuntime.InvokeAsync() the blank page opens to a blank component page but the objects are not being captured.
Here is the button onclick event-

    public async Task PrintViewableOrderPackingSlips()
    {
        OrdersToPrint = OrdersToPack.Where(o => o.IsOrderVisible).ToList();        

        await IJS.InvokeAsync<object[]>("open", "/PrintPackingSlip", "_blank", new object[]{ OrdersToPrint });   


    }

That invokes this razor component page

@layout Blazing_Fruit.Pages.BlankLayout

@page "/PrintPackingSlip"


<body onload="window.print()">

    <Div>print page</Div>  
          

</body>


@code{


    [Parameter]
    public JsonContent orders { get; set; }

    [Parameter]
    public List<UnshippedOrder> value { get; set; }

    
}

Obviously I’m not capturing the object passed over because I get this error in the originating page

Uncaught (in promise) TypeError: cyclic object value

and this error in the new component window

Uncaught (in promise) Error: Found malformed component comment at Blazor:{“sequence”:0,”type”:”server”,”prerenderId”:”aa8c4268d131416eb85784e2fcf8549f”,”descriptor”:

How can I pass my list of objects to the new component?

Skip starting blank rows in Excel with XLSX in JavaScript Sheet-JS

I have the following code that works great when the header row is row 1

  readerData(rawFile) {         
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = e => {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: "array" });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const header = this.getHeaderRow(worksheet);
          const results = XLSX.utils.sheet_to_json(worksheet,{ header: 0, range: 0, defval: ""});
          this.generateData({ header, results });
          this.loading = false;
          resolve();
        };
        reader.readAsArrayBuffer(rawFile);
      });
    },
    generateData({ header, results }) {
      this.excelData.header = header;
      this.excelData.results = results;
      this.excelData.original_results = [...results];
      this.onSuccess && this.onSuccess(this.excelData);

         var grid = this.$refs.membersGrid.ej2Instances;                         
        grid.dataSource = this.excelData.results;
          grid.refresh(); 
    },
      getHeaderRow(sheet) {
      const headers = [];
      const range = XLSX.utils.decode_range(sheet["!ref"]);
      let C;
      const R = range.s.r;
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
        /* find the cell in the first row */
        let hdr = "UNKNOWN " + C; // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
        headers.push(hdr);
      }
      return headers;
    },

It works great and put all of the Header values into the excelData.header and it put all of the named array data into the excelData.results. My problem is it all goes to a mess when the first row or first two rows are blank or I need to skip them. I’ve tried

  https://github.com/SheetJS/sheetjs/issues/463

but I’m using “xlsx”: “^0.17.1” . When I used

    range.s.r = 1;

I was able to change my range to A2 but I could not get my named array of data. Any help is appreciated .

I’m trying to access to my get method with the route api/products and it throws me this error, what could be the cause?

THIS IS THE ERROR

[Error: ENOENT: no such file or directory, open ‘C:UsersUsuarioDesktopproductos.txt’] {
errno: -4058,
code: ‘ENOENT’,
syscall: ‘open’,
path: ‘C:UsersUsuarioDesktopproductos.txt’
}

[on screen it only shows me an empty obj or nothing directly]

[INDEX.JS]

const express = require("express");
const app = express();
const http = require("http").Server(app);
const fs = require("fs").promises;
const path = require("path")
const routes = require("./routes");
const io = require("socket.io")(http);
const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);

app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
app.set("views", "./views");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/", (req, res) => {
  fs.readFile("productos.txt", "utf-8");
  res.render("form");
});

app.post("/productos", async (req, res) => {
  fs.readFile("productos.txt", "utf-8")
    .then((data) => {
      const type = JSON.parse(data);
      const newProduct = {
        id: nanoid(),
        ...req.body,
      };
      type.push(newProduct);
      fs.writeFile("productos.txt", JSON.stringify(type));
      res.render("productos", {
        type,
      });
    })
    .catch((err) => {
      if (!req.body.title && !req.body.price && !req.body.thumbnail) {
        res.status(400).json({
          error: "Bad Request",
          message: "Title, price and thumbnail are required",
        });
      }
      console.log(err);
    });
});

app.get("/productos", (req, res) => {
  fs.readFile("productos.txt", "utf-8").then((data) => {
    res.render("productos", {
      type: JSON.parse(data),
    });
  });
});

routes(app);

const port = 8080;
app
  .listen(port, () => {
    console.log(`App listening on port ${port}!`);
  })
  .on("error", (err) => {
    console.log(err);
    throw err;
  });

[API.JS]

const fs = require("fs").promises;
const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);

class Productos {
  constructor(txtNameFile) {
    this.txtNameFile = txtNameFile;
    this.productos = [];
  }

  async fileInJSON() {
    let fileTxt = await fs.readFile(this.txtNameFile, "utf-8");
    let type = JSON.parse(fileTxt);
    return type;
  }

  async fileSaving(item) {
    let type = JSON.stringify(item);
    await fs.writeFile(this.txtNameFile, type);
  }

  async obtenerProductos() {
    try {
      const productos = await this.fileInJSON();
      return productos;
    } catch (error) {
      console.log(error);
    }
  }

  async obtenerProducto(id) {
    try {
      const productos = await this.fileInJSON();
      const producto = productos.find((producto) => producto.id === id);
      return producto;
    } catch (error) {
      console.log(error);
    }
  }

  async create(data) {
    try {
      // create and adding product using fs module system
      const newProduct = {
        id: nanoid(),
        ...data,
      };
      this.productos.push(newProduct);
      await this.fileSaving(this.productos);
      return newProduct;
    } catch (error) {
      console.log(error);
    }
  }

  async eliminarProducto(id) {
    try {
      const productos = await this.fileInJSON();
      const producto = productos.find((producto) => producto.id === id);
      const index = productos.indexOf(producto);
      productos.splice(index, 1);
      await this.fileSaving(productos);
    } catch (error) {
      console.log(error);
    }
  }

  async actualizarProducto(id, data) {
    try {
      const productos = await this.fileInJSON();
      const producto = productos.find((producto) => producto.id === id);
      const index = productos.indexOf(producto);
      productos[index] = {
        ...producto,
        ...data,
      };
      await this.fileSaving(productos);
      return productos[index];
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = Productos;

[ROUTES/PRODUCTOSROUTER.JS]

const express = require("express");
const Productos = require("../api");
const router = express.Router();
const itemService = new Productos("../productos.txt");

router.get("/", async (req, res) => {
  res.json(await itemService.obtenerProductos());
});

router.post("/", async (req, res) => {
  if (!req.body.title && !req.body.price && !req.body.thumbnail) {
    res.status(400).json({
      error: "Bad Request",
      message: "Title, price and thumbnail are required",
    });
  }
  const producto = itemService.create(req.body);
  res.json(await producto);
});

router.get("/:id", async (req, res) => {
  const producto = itemService.obtenerProducto(req.params.id);
  if (producto) {
    res.json(await producto);
  } else {
    res.status(404).json({ error: "Producto no encontrado" });
  }
});

router.put("/:id", async (req, res) => {
  const id = req.params.id;
  const producto = itemService.actualizarProducto(id, req.body);
  res.json(await producto);
});

router.delete("/:id", async (req, res) => {
  const id = req.params.id;
  itemService.eliminarProducto(id);
  res.json({ message: "Producto eliminado" });
});

module.exports = router;

[ROUTES/INDEX.JS]

const productosRouter = require("./productosRouter");

function routes(app) {
  app.use("/api/productos", productosRouter);
}

module.exports = routes;