Apply an openlayers filter and have it persist when I save the map as an image

I have made an openlayers map with various polylines on it. I am using the default openstreetmap layer, but would like to darken it to make my polylines stand out. I’ve discovered that I can do this as follows:

map.getLayers().getArray()[0].on('postcompose', function (evt) {
   evt.context.canvas.style.filter="invert(99%)";
});

However, I’d also like to give my users the ability to download this map as a PNG. For that, I am using the following code, triggered from a button click:

map.once('postcompose', function(event) {
   var canvas = event.context.canvas;
   if (navigator.msSaveBlob) {
      navigator.msSaveBlob(canvas.msToBlob(), 'mymap.png');
   } else {
      canvas.toBlob(function(blob) {
         saveAs(blob, 'mymap.png')
      });
   }
});
map.renderSync();

Unfortunately, this does not preserve the amendment I made to adjust the canvas.

Please can someone help me? Thank you for reading.

How to check if component function have been called using Vue3, Vitest, and Vue Test Utils?

I have a component written in Vue 3 and script setup. Now I am trying to write a unit test for it, where I am instantiating a spy to check whether a function has been called.

I read somewhere that functions in components are closed by default, so I have to add them to the defineExpose function. I did that.

Now when I run my test, for some it’s still not seen that the function is called. Does anyone know how this works?

Below is my component:

<script setup lang="ts">
import Modal from '../modal/Modal.vue'
import Button from '../button/Button.vue';
import Select from '../select/Select.vue';
import {ref} from '@vue/reactivity';
import {useI18n} from 'vue-i18n';
import DocumentDiscardModalTypes from './DocumentDiscardModal.types';
import {SelectOption} from '../../../types/utility.types';

const {t} = useI18n();

const emit = defineEmits(['model-closed', 'confirmed']);

const props = defineProps<DocumentDiscardModalTypes>();

const isDiscardDisabled = ref(true);
const selectedOption = ref({
  id: '0',
  label: t('select_an_option'),
});

function resetSelectedOption() {
  selectedOption.value = {
    id: '0',
    label: t('select_an_option'),
  };
  emit('model-closed');
}

function closeConfirmationModal() {
  emit('model-closed');
}

function handleDiscard() {
  emit('confirmed', selectedOption.value.label);
  emit('model-closed');
}

function handleChange(e: SelectOption) {
  selectedOption.value = e;
  isDiscardDisabled.value = false;
}

function getOptions() {
  return [
    {
      id: '0',
      label: t('select_an_option'),
      disabled: true,
    },
    {
      label: t('wrong_document'),
      id: '1',
    },
    {
      label: t('quality_issue'),
      id: '2',
    },
    {
      label: t('other'),
      id: '3',
    },
  ];
}

defineExpose({resetSelectedOption, handleDiscard, getOptions, closeConfirmationModal})
</script>

<template>
  <Modal
      class="discard-aab-modal"
      modal-size="medium"
      :id="id"
      @modal-close="resetSelectedOption"
      :isOpen="isOpen"
      :no-scrolling="true"
  >
    <span slot="modal-title">{{ t('discard_document') }}</span>
    <span slot="modal-content">
        <p class="modal-text">
          {{ t('discard_document_argument') }}
        </p>
        <Select
            id="status-select"
            :options="getOptions()"
            @selected="handleChange"
            :value="selectedOption"/>
      </span>
    <span slot="modal-footer" class="modal-footer">
        <Button
            id="cancel-button"
            @clicked="closeConfirmationModal"
            style-type="secondary"
            :label="t('cancel')"
            :disabled="false"/>
        <Button
            id="discard-button"
            @clicked="handleDiscard"
            style-type="primary"
            :label="t('discard')"
            :disabled="isDiscardDisabled"/>
      </span>
  </Modal>
</template>

<style lang="scss" scoped>
@import 'DocumentDiscardModal.styles';
</style>

And this is my unit test:

describe('DocumentDiscardModal.vue', () => {
    const documentDiscardedModelWrapper = mount(DocumentDiscardModel, {
        propsData: {
            id: 'document-discard-modal',
            isOpen: true,
        },
    });

    const getOptionsSpy = vi.spyOn(documentDiscardedModelWrapper.vm, 'getOptions');

    test('getOptions should have been called', () => {
        expect(getOptionsSpy).toHaveBeenCalled();
    });
}

stripe react native subscription creation-Error- This customer has no attached payment source or default payment method

I am trying to create a subscription paymentsheet in react native, below is my code for backend. When I uncomment trial_period_days: 3, even if payment methods are not declared. But if I comment this line, then I am getting error – “StripeInvalidRequestError: This customer has no attached payment source or default payment method. Please consider adding a default payment method.” I tried below code to declare payment methods, but it did not work. I want new customers to also be able to use all the available payment methods that their country and OS platform supports.

const stripe = require('stripe')(stripeSecretKey);
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
app.get('/', (req, res) => {
  res.send('Test');
});
app.post('/payment-sheet-subscription', async (req, res) => {
  const {email = `test${Math.floor(Math.random() * 9999) + 1}@domain.com`} =
    req.body;

  const customer = await stripe.customers.create({email});

  const ephemeralKey = await stripe.ephemeralKeys.create(
    {customer: customer.id},
    {apiVersion: '2020-08-27'},
  );
  const PRICE_ID = 'price_1NQ4EnSBro6pGrG8ZYfdBX5x';
  const subscription = await stripe.subscriptions.create({
    customer: customer.id,
    items: [{price: PRICE_ID}],
    // trial_period_days: 3,
  });
  const updatedSubscription = await stripe.subscriptions.update(
    subscription.id,
    {
      payment_settings: {
        payment_method_types: ['card'],
      },
    },
  );
  if (typeof updatedSubscription.pending_setup_intent === 'string') {
    const setupIntent = await stripe.setupIntents.retrieve(
      updatedSubscription.pending_setup_intent,
    );

    // if (typeof subscription.pending_setup_intent === 'string') {
    //   const setupIntent = await stripe.setupIntents.retrieve(
    //     subscription.pending_setup_intent,
    //   );

    return res.json({
      setupIntent: setupIntent.client_secret,
      ephemeralKey: ephemeralKey.secret,
      customer: customer.id,
    });
  } else {
    throw new Error(
      'Expected response type string, but received: ' +
        typeof subscription.pending_setup_intent,
    );
  }
});

How do I correctly wrap a for loop around an async operation in TypeScript/Javascript (NodeJS)?

I have the following code that exports SVG icons from Iconify JSON files:

import { promises as fs } from 'fs';
import { IconSet, exportToDirectory } from '@iconify/tools';
import { validateIconSet } from '@iconify/utils';

let iconsetName = "dashicons";

(async () => {
    // Read data, parse JSON

    const rawData = JSON.parse(
        await fs.readFile('JSON/' + iconsetName + '.json', 'utf8')
    );

    // Validate icon set (optional step)
    const validatedData = validateIconSet(rawData);

    // Create new IconSet instance
    const iconSet = new IconSet(validatedData);

    // Done. Do something with icon set...
    // For example, export as SVG files
    await exportToDirectory(iconSet, {
        target: iconsetName
    })
})();

I have about 90-100 icon sets to process, so I figured I could store all names in an array and then wrap the async logic at the bottom in a for loop, allowing the script to process every icon set I have.

This is the code I tried:

import { promises as fs } from "fs";
import { IconSet, exportToDirectory } from "@iconify/tools";
import { validateIconSet } from "@iconify/utils";

let iconSets: string[] = [
   "devicon-line",
   "devicon-original",
   "devicon-plain",
   "devicon",
   "ei",
   "el",
   "emblemicons",
   "emojione-monotone",
   "emojione-v1",
   "emojione",
   "entypo-social",
   "entypo",
   "eos-icons",
   "ep",
   "et",
   "eva",
   "fa-brands",
   "fa-regular",
   "fa-solid",
   "fa",
   "fa6-brands",
   "fa6-regular",
   "fa6-solid",
   "fad",
   "fe",
   "feather",
   "file-icons",
   "flag",
   "flagpack",
   "flat-color-icons",
   "flat-ui",
   "fluent-emoji-flat",
   "fluent-emoji-high-contrast",
   "fluent-emoji",
   "fluent-mdl2",
   "fluent",
   "fontelico",
   "fontisto",
   "formkit",
   "foundation",
   "fxemoji",
   "gala",
   "game-icons",
   "geo",
   "gg",
   "gis",
   "gridicons",
   "grommet-icons",
   "guidance",
   "healthicons",
   "heroicons-outline",
   "heroicons-solid",
   "heroicons",
   "humbleicons",
   "ic",
   "icomoon-free",
   "icon-park-outline",
   "icon-park-solid",
   "icon-park-twotone",
   "icon-park",
   "iconamoon",
   "iconoir",
   "icons8",
   "il",
   "ion",
   "iwwa",
   "jam",
   "la",
   "line-md",
   "logos",
   "ls",
   "lucide",
   "majesticons",
   "maki",
   "map",
   "material-symbols",
   "mdi-light",
   "mdi",
   "medical-icon",
   "memory",
   "mi",
   "mingcute",
   "mono-icons",
   "nimbus",
   "nonicons",
   "noto-v1",
   "noto",
   "octicon",
   "oi",
   "ooui",
   "openmoji",
   "pajamas",
   "pepicons-pencil",
   "pepicons-pop",
   "pepicons-print",
   "pepicons",
   "ph",
   "pixelarticons",
   "prime",
   "ps",
   "quill",
   "radix-icons",
   "raphael",
   "ri",
   "si-glyph",
   "simple-icons",
   "simple-line-icons",
   "skill-icons",
   "solar",
   "streamline-emojis",
   "streamline",
   "subway",
   "svg-spinners",
   "system-uicons",
   "tabler",
   "teenyicons",
   "topcoat",
   "twemoji",
   "typcn",
   "uil",
   "uim",
   "uis",
   "uit",
   "uiw",
   "vaadin",
   "vs",
   "vscode-icons",
   "websymbol",
   "whh",
   "wi",
   "wpf",
   "zmdi",
   "zondicons"
];

const forLoop = async (_: any) => {

   console.log("Start");

   for (let index = 0; index < iconSets.length; index++) {

    const setName = iconSets[index];

      (async () => {
         // Read data, parse JSON

         const rawData = JSON.parse(
            await fs.readFile("JSON/" + setName + ".json", "utf8")
         );

         // Validate icon set (optional step)
         const validatedData = validateIconSet(rawData);

         // Create new IconSet instance
         const iconSet = new IconSet(validatedData);

         // Done. Do something with icon set...
         // For example, export as SVG files
         await exportToDirectory(iconSet, {
            target: setName
         });
      })();
   }

   console.log("End");
};

But I’m positive I’m doing something horribly wrong (I’m new to TS and JS). And the script doesn’t work.

How do I get this script to process my JSON files sequentially and save everything out at once?

NgRx selectors and currying

I have been using NgRx for a while and trying to understand the language feature or design pattern being used to create selectors as described on this NgRx documentation page. Coming from a Object Oriented Programming background, seeing numerous functions instead of a simple call which takes a bunch of attributes has confused me.

javascript window.close() is unexpectedly closing 2 tabs

I have a web page, which consists of html inside an iframe. This page calls

window.open(url,'_blank').focus();

to open a new tab, which allows the user to perform some oauth authentication, and then redirects back to my site, whereupon I want to close that tab, and navigate back in the originating tab to the same place, as though I had never opened a tab in the first place.

To manage this I have the following code, which is basically saying “if I am in a tab that was opened, send a message to the opening window with navigation information, and then close

  if (window.parent.opener)
                {
                  let data = {"for":"mywindow", "operation":"navigate","code":this.code, "state":this.state};
                  //handle this message in the message handler component, and redirect here on the original window
                  window.parent.opener.postMessage(data);
                  window.parent.close();
                }

Now, in most environments this works perfectly well. However in some environments it is closing not just the opened tab, but also the original tab.

Does anyone know how I can prevent the originating tab from closing?

Note that the code calls window.parent because of the complication that all the code is executing inside an i-frame.

how to create array of objects from 2 different array?

I have 2 arrays with different length and the number of items in each array is dynamic. I want to build the finalArray. How can I do that?

 const array1 = [7665,7666]
 const array2 = [
{
    "id": 1,
    "name": "user-1",
},
{
    "id": 2,
    "name": "user-2", 
},
{
    "id": 3,
    "name": "user-3",
},
  ]

 const finalArray = [
    {
      7665: [],
      7666: [],
      users: 'user-1',
    },
    {
      7665: [],
      7666: [],
      users: 'user-2',
    },
    {
      7665: [],
      7666: [],
      users: 'user-3',
    }
  ]

How to highlight nested elements inside SVG and change their color or highlight them in react native

enter image description here

This is a map of a mall which is an image(SVG, or PNG), I’m asked to do the following:

there is an input above the Map where user can look for a store by name, when a store is chosen it should be selected in the Map like highlighted or something to show his position in the mall, the second task is :

the user can press on any store to select it we should highlight the store and open a bottomsheet.

my question is:

which solution could be used to accomplish this behavior, if an SVG is used i know that there are difficulties using TouchableOpacities inside and SVG, how can we highlight the selected store inside the card ? which data should i receive from backend ? i’m thinking of using an array where the first element in the array would be the first right top store in the map in our case the array should be somthing like this :

[A-FITNESS , DECATLON, DNS , KARI ]

i’m thinking of using an array where the first element in the array would be the first right top store in the map in our case the array should be somthing like this :

[A-FITNESS , DECATLON, DNS , KARI ]

but i don’t know how to click nested elements inside an SVG and how to change the color or highlight a part of the SVG

How can I show my data with a parent child relationship with javascript?

const data = [
    { id: 1, text: 'hello', parent: null },
    { id: 2, text: 'hello2', parent: 1 },
    { id: 3, text: 'hello3', parent: 2 },
    { id: 4, text: 'where are u?', parent: null },
  ];
  function convertToTree(data: any) {
    const tree: any = {};
    data.forEach((item: any) => {
      const parentId = item.parent;
      if (!parentId) {
        tree[item.id] = { ...item, children: [] };
      } else {
        if (!tree[parentId]) {
          tree[parentId] = { children: [] };
        }
        tree[parentId].children.push({ ...item, children: [] });
      }
    });
    return tree;
  }

  function TreeNode({ data }: any) {
    const [isVisible, setIsVisible] = useState(false);

    const handleClick = () => {
      setIsVisible(!isVisible);
    };

    return (
      <div>
        <p onClick={handleClick}>{data.text}</p>
        {isVisible && data.children && data.children.length > 0 && (
          <ul>
            {data.children.map((child: any) => (
              <li key={child.id}>
                <TreeNode data={child} />
              </li>
            ))}
          </ul>
        )}
      </div>
    );
  }

I want to show this data as perent-child depending on the parent data in the data using javascript-react.
rule1- when I click on the parent data I want to see the child data.
rule2- since every child can also be a parent, if a child has child data, I want to access its own child data when I click on the child.

But in the code I wrote, only when I click on the parent data, only the children come. As it appears in the data, the child data also has childi, but I cannot see them.

thank you for your help

How can i get specific notes for a user in the database and display it with my html css design?

I created a note-taking app with php, css, and javascript. I connected my note taking app to mySQL database to store the users and their notes and I want that the user can view his saved notes with the design that I have in my .php file together with .css file. When I try to save the note, it stores in the database however, I am getting only plain text in my web app. Here is a sample of what I get after saving the inputs

{"success":true,"noteData":{"title":"test1000","description":"this is a test","date":"2023-07-04"}}

I have the following codes for javascript and php for reference.

here is my script file

const addBox = document.querySelector(".add-box"),
    popupBox = document.querySelector(".popup-box"),
    popupTitle = popupBox.querySelector("header p"),
    closeIcon = popupBox.querySelector("header i"),
    titleTag = popupBox.querySelector("input"),
    descTag = popupBox.querySelector("textarea"),
    addBtn = popupBox.querySelector("button");

const months = ["January", "February", "March", "April", "May", "June", "July",
    "August", "September", "October", "November", "December"];
let notes = [];

// Fetch notes from the server
//fetchNotes();

addBox.addEventListener("click", () => {
    popupTitle.innerText = "Add a new Note";
    addBtn.innerText = "Add Note";
    popupBox.classList.add("show");
    document.querySelector("body").style.overflow = "hidden";
    if (window.innerWidth > 660) titleTag.focus();
});

closeIcon.addEventListener("click", () => {
    titleTag.value = descTag.value = "";
    popupBox.classList.remove("show");
    document.querySelector("body").style.overflow = "auto";
});

function showNotes() {
    if (!notes) return;
    document.querySelectorAll(".note").forEach(li => li.remove());
    notes.forEach((note, id) => {
        let filterDesc = note.description.replaceAll("n", '<br>');
        let liTag = `<li class="note">
                        <div class="details">
                            <p>${note.title}</p>
                            <span>${filterDesc}</span>
                        </div>
                        <div class="bottom-content">
                            <span>${note.date}</span>
                            <div class="settings">
                                <i onclick="showMenu(this)" class="uil uil-ellipsis-h"></i>
                                <ul class="menu">
                                    <li onclick="updateNote(${id}, '${note.title}', '${filterDesc}')"><i class="uil uil-pen"></i>Edit</li>
                                    <li onclick="deleteNote(${id})"><i class="uil uil-trash"></i>Delete</li>
                                </ul>
                            </div>
                        </div>
                    </li>`;
        addBox.insertAdjacentHTML("afterend", liTag);
    });
}

function fetchNotes() {
    // Fetch notes from the server for the logged-in user
    fetch('fetch_notes.php')
        .then(response => response.json())
        .then(data => {
            notes = data;
            showNotes();
        })
//        .catch(error => console.error('Error:', error));
}

function showMenu(elem) {
    elem.parentElement.classList.add("show");
    document.addEventListener("click", e => {
        if (e.target.tagName != "I" || e.target != elem) {
            elem.parentElement.classList.remove("show");
        }
    });
}

function deleteNote(noteId) {
    let confirmDel = confirm("Are you sure you want to delete this note?");
    if (!confirmDel) return;

    // Create a form dynamically
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = 'delete_note.php';

    // Create an input field for the note ID
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'noteId';
    input.value = noteId;

    // Append the input field to the form
    form.appendChild(input);

    // Append the form to the document and submit it
    document.body.appendChild(form);
    form.submit();
}

function addLeadingZero(number) {
    return number < 10 ? `0${number}` : number;
}

function formatDate(date) {
    const year = date.getFullYear();
    const month = addLeadingZero(date.getMonth() + 1);
    const day = addLeadingZero(date.getDate());
    return `${year}-${month}-${day}`;
}

function updateNoteData(noteData) {
    titleTag.value = noteData.title;
    descTag.value = noteData.description;
}

function updateNote(noteId, title, filterDesc) {
    let description = filterDesc.replaceAll('<br>', 'rn');
    addBox.click();
    titleTag.value = title;
    descTag.value = description;
    popupTitle.innerText = "Update a Note";
    addBtn.innerText = "Update Note";

    // Store the note ID and set the update flag
    addBtn.dataset.noteId = noteId;
    addBtn.dataset.isUpdate = true;
}

addBtn.addEventListener("click", e => {
    e.preventDefault();
    let title = titleTag.value.trim(),
        description = descTag.value.trim();

    if (title || description) {
        let currentDate = new Date();
        let noteInfo = {
            title,
            description,
            date: formatDate(currentDate)
        };
        let isUpdate = addBtn.dataset.isUpdate === "true";
        let noteId = addBtn.dataset.noteId;

        // Create a form dynamically
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'save_note.php';

        // Create an input field for the note ID
        const inputId = document.createElement('input');
        inputId.type = 'hidden';
        inputId.name = 'noteId';
        inputId.value = noteId;

        // Create an input field for the note information
        const inputInfo = document.createElement('input');
        inputInfo.type = 'hidden';
        inputInfo.name = 'noteInfo';
        inputInfo.value = JSON.stringify(noteInfo);

        // Create an input field for the update flag
        const inputUpdate = document.createElement('input');
        inputUpdate.type = 'hidden';
        inputUpdate.name = 'isUpdate';
        inputUpdate.value = isUpdate ? 'true' : 'false';

        // Append the input fields to the form
        form.appendChild(inputId);
        form.appendChild(inputInfo);
        form.appendChild(inputUpdate);

        // Append the form to the document and submit it
        document.body.appendChild(form);
        form.submit();
    }
});

and here is my php file:

<?php
include 'connect.php';

session_start();
if (!isset($_SESSION['username'])) {
    header('location: login.php');
}
$username = $_SESSION['username'];
?>

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">  
    <title>InkWave | My Notes</title>
    <h1> <img src="images/notes.png">InkWave</h1>
    <link rel="stylesheet" href="notes_style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
  </head>

  <body>
    <div class="popup-box">
      <div class="popup">
        <div class="content">
          <header>
            <p></p>
            <i class="uil uil-times"></i>
          </header>
          <form action="#">
            <div class="row title">
              <label>Title</label>
              <input type="text" spellcheck="false">
            </div>
            <div class="row description">
              <label>Description</label>
              <textarea spellcheck="false"></textarea>
            </div>
            <button></button>
          </form>
        </div>
      </div>
    </div>
    <div class="wrapper">
      <li class="add-box">
        <div class="icon"><i class="uil uil-plus"></i></div>
        <p>Add new note</p>
      </li>
    </div>

    <div class="container">
      <a href="logout.php"> <button class="btn">Logout</button></a>
    </div>

    <script src="notes_script.js"></script>
    
  </body>
</html>

Does anyone know the WordPress Error “Uncaught ReferenceError: cnArgs is not defined”

So, i’m tasked with extracting Sites from a WordPress Multisite and make them SingleSites on Raidboxes. I have all the content, themes and plugins on the new Site and it works, but there is a navbar issue, where it’s all over the site and not collapsed. The Devtools Console shows the Error:

Uncaught ReferenceError: cnArgs is not defined
    at Object.init (front.min.js?ver=2.4.9:1:7245)
    at front.min.js?ver=2.4.9:1:8664

I’m guessing that this might be the origin of the navbar issue.

I did some research but couldn’t find anything about “cnArgs” so i went over the libraries and tried to find differences. All i could find is that on the old Page is a much older jQuery version. I Downgraded on the new Raidbox using the “jQuery Version Control” plugin for WordPress but i still get the same Issue.

Next.js: Passing JWT token to getServerSideProps for authenticated routes

I’m working on a Next.js project and have implemented authentication using JWT tokens. I’m facing an issue when trying to pass the JWT token to the getServerSideProps function for authenticated routes.

Here’s an overview of my project setup:

I have a Next.js application with multiple pages.
I use JWT tokens for authentication.
The JWT token is stored in the browser’s localStorage.
The problem:
I need to include the JWT token in requests made from one page to another, particularly when navigating to authenticated routes. However, it seems that the getServerSideProps function does not have direct access to the browser’s localStorage or the ability to set headers.

I have considered the following approach, but I’m not sure how to implement it:

Passing the JWT token as a query parameter:
One option is to include the JWT token as a query parameter in the URL when navigating between pages. However, I’m concerned about the security implications of exposing the token in the URL.

I’m looking for guidance on the best practice for passing the JWT token to the getServerSideProps function in Next.js, considering security and authentication requirements. Here are my specific questions:

How can I securely pass the JWT token to the getServerSideProps function without exposing it in the URL?
Is it possible to access the localStorage from within the getServerSideProps function?
If direct access to the localStorage is not possible, what are the alternative methods for passing the JWT token between pages?
Any insights, code examples, or recommended approaches would be greatly appreciated. Thank you!

Get AST of a file inside other file

I’m creating a custom eslint rule.
To do so I’m going over the AST of the file and I need to have AST of other file.
How can I do so?

I have tried to import fs library to open the other file I need but the import state shows an error.

What is the proper way to check string or list of strings length in JS?

I have a React app and on a few pages I have to make requests to post data to the API and at least one of the strings I send have to be of a certain length. I have to write a function that takes either a single string or a list of strings and the required length and check the strings if their length is equal to the required length. If everything is ok, return true, else open a react-tostify notification and return false. Further development (like showing the first string that was of the incorrect length) might be done in the future. I’ve come up with a solution, but I think it could do with a little tweeking. I’ve also asked ChatGPT for advice. What do you think? How would you improve it?

Here’s what I’ve come up with:

export const CheckCodeLength = (requiredLength: number, codeToCheck?: string, listOfCodes?: string[]) => {
    if (codeToCheck)
    {
        if (codeToCheck.length === requiredLength) return true;
        toast.error(Resources.Toasts.incorrectCodeLength());
        return false;
    }

    if (listOfCodes)
    {
        if (listOfCodes.filter(code => code.length === requiredLength).length === 0) return true;
        toast.error(Resources.Toasts.incorrectCodeLength());
        return false;
    }
}

Here’s what Chat came up with (console.log is in place of toast.error):

function checkStringLength(length, input) {
  if (typeof input === 'string') {
    if (input.length !== length) {
      console.log('String length mismatch:', input);
    }
  } else if (Array.isArray(input)) {
    for (let i = 0; i < input.length; i++) {
      if (input[i].length !== length) {
        console.log('String length mismatch at index', i, ':', input[i]);
      }
    }
  } else {
    console.log('Invalid input type');
  }
}