using doubleMetaphone for word ryhming facing issue in logic

Making the script for rhyming words but this logic giving the wrong answers. displayRhymingWords() this function giving me wrong results kindly help any one to improve the logic

<script>
function fetchRhyme() {
    const wordInput = document.getElementById('wordInput').value;
    const resultDiv = document.getElementById('result');

    if (!wordInput) {
        resultDiv.innerHTML = '<p>Please enter a word.</p>';
        return;
    }

    const rhymingWords = getRhymingWords(wordInput);
    displayRhymingWords(rhymingWords, resultDiv);
}

function getRhymingWords(targetWord) {
    // You can replace this array with your own list of words
    const wordsArray = ['example', 'apple', 'orange', 'sample', 'rhyme'];

    // Calculate Double Metaphone for the target word
    const targetMetaphone = doubleMetaphone(targetWord);

    // Function to check if two Double Metaphone values match
    const metaphonesMatch = (metaphone1, metaphone2) => metaphone1[0] === metaphone2[0] || metaphone1[1] === metaphone2[0];

    // Find rhyming words
    const rhymingWords = wordsArray.filter(word => {
        const wordMetaphone = doubleMetaphone(word);
        return metaphonesMatch(targetMetaphone, wordMetaphone);
    });

    return rhymingWords;
}

function displayRhymingWords(rhymingWords, resultDiv) {
    if (rhymingWords.length === 0) {
        resultDiv.innerHTML = '<p>No rhyming words found.</p>';
        return;
    }

    const rhymingList = '<ul>' + rhymingWords.map(word => `<li>${word}</li>`).join('') + '</ul>';
    resultDiv.innerHTML = `<p>Rhyming words:</p>${rhymingList}`;
}
</script>


Thanks in advance

I am getting 404 not found when trying to call a api route thats already mapped , i am using nest js

When I make the api call directly from postman it works but , on using my backend to call it throws 404 error , and on postman it shows a 500 internal server error .

the controller below –

//to verify the credentials 
@Get('verify_credentials')
verifyCredentials(@Req() req : any , @Body() body : any): any{
    console.log('checling')
    return this.AccountsService.verify_credentials(body , req);
}

the service logic –

 verify_credentials(body: any , req : any): any {
    const auth = req.rawHeaders[3]
    const userData =    this.httpService.get(`${config.SERVER}/api/v1/accounts/verify_credentials` , {
        headers: {
            'Content-Type': 'application/json',
            'Authorization': auth
        },      
    })
    .pipe(
      map(response => response.data),
    );
    return userData ;}

I tried searching for solutions but could not figure out the problem .

What’s the solution and the right way to convert digits in JavaScript?

following all qa about converting digits in javascript in Stackoverflow. However, I had a problem/ question

method one

    // Function to convert Persian and Arabic digits to English digits
    function convertDigitsToEnglish(value) {
        var persianDigits = '۰۱۲۳۴۵۶۷۸۹';
        var arabicDigits = '٠١٢٣٤٥٦٧٨٩';
        var englishDigits = '0123456789';

        for (var i = 0; i < 10; i++) {
            value = value.replace(new RegExp(persianDigits[i], 'g'), englishDigits[i]);
            value = value.replace(new RegExp(arabicDigits[i], 'g'), englishDigits[i]);
        }

        return value;
    }

method two

var convert_number = (function () {
    var numerals = {
        persian: ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
        arabic: ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
    };

    return {
        toNormal: function (str) {
            if (!str) {
                return '';
            }
            var num, i, len = str.length, result = "";

            for (i = 0; i < len; i++) {
                num = numerals["persian"].indexOf(str[i]);
                num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
                if (num == -1) num = str[i];
                result += num;
            }
            return result;
        }
    }
}

in the method one works only for Persian/Farsi digits! and why doesn’t it work correctly at all for the Arabic language?
arabic digits numbers ٤٥٦‍ (four five and six) numbers are not converted to English/Latin numbers. we defined this in the code and it shouldn’t be a problem and it should work correctly, but it doesn’t and these three numbers can’t be converted, and doesn’t accept these numbers!

in method two. both Persian and Arabic languages converted and no problem with this method.

For better explanations for my question so that nothing is missed. Let’s say this is for a mobile number field.
I have also specified elsewhere that a keyboard the person cannot enter any additional characters such as asterisk, plus, minus, etc., other than the numbers 0 to 9.

        // Remove non-numeric characters
        var numericPhoneValue = convertedValue.replace(/[^0-9]/g, '');

In order for the Arabic and Persian numbers not to be recognized as foreign, I converted them to English numbers with this (upper convert function). So that the user can enter numbers with English, Farsi, and Arabic numbers. And it doesn’t matter what language it is in. Converts to English in any digit. Also, prevents the entry of additional characters.

I also used the pattern solution instead of these (convert), but it is ignored by the browser in different situations, and it is also suitable for English only. And it is not suitable for Persian and Arabic.
Was my method correct? Is there a better, shorter and cleaner way? Why the first method does not work correctly for some Arabic numbers? But does the second method work correctly?

grid locking shows blank white column after unlock the grid ext sencha

I have a problem about grid locking in sencha Ext js, I got blank white column after I unlock or unfreeze the column enter image description here

enter image description here

this is the snipped of the code

`                                                                
    var me = this,
        columnsToUnlock = [];

    // find all the columns to the left of the column to lock
    Ext.each(me.lockedGrid.columnManager.columns, function(column) {
        if (column.locked && !column.fixedLock) {
            columnsToUnlock.push(column);
            if (column.lockedEl && column.lockedEl.hasCls(me.lockedColumnIconCls)) {
                column.lockedEl.removeCls(me.lockedColumnIconCls);
            }
        }
    });
    
    columnsToUnlock.reverse();
    
    Ext.each(columnsToUnlock, function(column) {
        me.unlock(column);

    });
    
    // if not set then height isn't set due which the horizontal scrollbar 
    // isn't visible
    if (me.normalGrid && me.normalGrid.view && me.normalGrid.view.el){
        me.normalGrid.view.el.setStyle('height','inherit');
    }
    `

is there something I missed here?

Is there any other library like whatsapp-web.js in Python or JS

I have recently created a script using whatsapp-web.js that forwards every received message to a specific contact, but the issue i am facing is that when the session expires, it stops working, the script has to be restarted, the QR code rescanned and there’s no way of knowing it has stopped working, as even if it is working normally, it tends to have a delay before it forwards messages.

I am running this script via pm2 on a VPS.

Is there any library in Python or JS in which i can implement the same functionality of forwarding all received messages to a specific contact ?

The libraries i have tried till now:

  1. WebWhatsAPI (Python)
  2. PywhatKit (Python)
  3. whatsapp-autoforward-message (Python)
  4. Official whatsapp library (Python) (Rejected by client due to having to pay per conversation)

Jest with Selenium 4 – compatibility issue with ES6: require is not defined

I just installed today jest in my small project, in which I use Selenium (with Javascript) to do some tests on a simple project.

Since Selenium 4 does only support ES6 now, I have to use modules. But Jest seems to not like them, so I searched on stackoverflow for some solutions, and this is what I got until now.

Aim: test a simple API call that calls a function to transform the result in an array.

What happens: jest throws the error ReferenceError: require is not defined at line 5 of mockApi.test.js: jest.mock('axios')

files:

backendCalls.js

import axios from 'axios'

// returns an object for every coach, 
// a coach has firstName, lastName and some other properties
export async function getCoachesList(area) {
  let res = await axios
    .get('localhost:8080/coaches.json')
    .then(res => res.data)
    .catch(err => {
      console.log(err.toJSON())
    })

  // this function simply takes the result - an object containing 5 objects - 
  // and put them in an array with a for loop
  return putObjInArray(res, area)
}

this is the test file:

mockApi.test.js

import axios from 'axios'
import * as beCalls from '../utils/backendCalls.js'
import { expect, jest, test } from '@jest/globals'

jest.mock('axios')

test('should fetch users', () => {
  const coaches = [
    { firstName: 'Bob', lastName: 'Kelso' },
    { firstName: 'John', lastName: 'Doe' },
  ]
  const resp = { data: coaches }
  axios.get.mockResolvedValue(resp)

  getCoachesList().then(data => expect(data).toEqual(coaches))
})

and finally this is the jest config file:

jest.config.js

export default {
  jest: {
    preset: 'ts-jest',
    testEnvironment: 'node',
    transform: {},
    transformIgnorePatterns: ['node_modules/(?!variables/.*)'],
  },
}

Everything super simple – in my package.json I have this line:

"scripts": {
    "jestTests": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
    [...]  // other stuff
}

It should run smoothly, but when I do

npm run jestTests

it throws an error, saying ReferenceError: require is not defined at line 5 of mockApi.test.js: jest.mock('axios')

Avoiding the fact I can’t believe that in 2023 the ES6 is still not fully implemented (it has been made 10 years ago), what I am doing wrong or what I am missing?

Javascript Newbie: use element in function

The script below doesn’t work and I need some help to find the reason:

<script>
const input1 = document.getElementById("voucher1");
input1.addEventListener("change", updateValue(input1));
function updateValue(field) {
var InputOrgColor = field.style.backgroundColor;
const apiUrl = 'https://hook.eu1.make.com/wr3p7mnuqokj9...wns2n?voucher-id='+field.value;
 if (field.value === ``) {
    field.style.backgroundColor = InputOrgColor;
    document.getElementById("submit").style.visibility = `visible`;
   } else
fetch(apiUrl)
   .then(response => {
    
     if (response.status === 200) {
       field.style.backgroundColor = `#99ffcc`;
       document.getElementById("submit").style.visibility = `visible`;
      } else if (response.status === 201) {
       field.style.backgroundColor = `#ffcccb`;
       document.getElementById("submit").style.visibility = `hidden`;
       alert("Der Gutscheincode wurde nicht gefunden. Bitte überprüfe Deine Eingabe.");
      } else if (response.status === 202) {
       field.style.backgroundColor = `#ffcccb`;
       document.getElementById("submit").style.visibility = `hidden`;
       alert("Der Gutscheincode wurde zwar gefunden, aber der Gutschein ist entweder unbezahlt oder bereits abgesprungen.");
      }
    
  })
};
</script>

Because the function works as expected if I use it directly with the variable “input1” instead of “field”, I think line 2 is the problem. I think using updateValue(input1) doesn’t work, but I don’t get any error report in the browser console.

Thank you for helping a JS newbie. Best,

Coloring a text input red or green, if the inserted code is found or not by API call

Declaration files in Javascript library

I have my own JS library and I add there declaration files (*.d.ts) for my TS projects which use that JS library. There’s something wrong and my TS project ignore that declaration files.


So I tried this stupid example in my TS project.

// project/src/calculateSum.js

function calculateSum(a, b) {
  return a + b
}

module.exports = {
  calculateSum
}
// project/src/types/custom/calculateSum.d.ts

export declare function calculateSum(a: number, b: number): number;
// project/src/app.ts

import { calculateSum } from './calculateSum`

console.log(calculateSum('it should not acceept string', 1))

VS code and TS does not report anny issue with that.

Here my tsconfig.json

{
  "compilerOptions": {
    ...
    "skipLibCheck": true,
      "typeRoots": [
        "node_modules/@types",
        "src/types/custom"
      ]
  },
  "include": [
    "./src/**/*",
  ],
    "exclude": [
      "node_modules"
    ]
}

BTW I have also svg.d.ts inside src/types/custom and it works as expected.

// project/src/types/custom/svg.d.ts
declare module "*.svg" {
    import React = require("react")
    export const AsComponent: React.FC<React.SVGProps<SVGSVGElement>>
    const src: string
    export default src
}

It seems to me that I misunderstood something.

My javascript code wont run properly in the Brave Browser, it works perfectly in Chrome


const displayedValues=document.querySelector(".list-group");
const userInput=document.querySelector("#exampleInputPassword1");

let data;//input data is put into this
let storage1=[];
var clearall=document.querySelector("#clearall");

function storageChecker()
{
    if(localStorage.getItem("depo") === null || localStorage.getItem("depo") === undefined || localStorage.getItem("depo") === "")
    {
        storage1=[];
    }
    else
    {
        storage1=JSON.parse(localStorage.getItem("depo"));
    }

}

function starter()
{
    storageChecker();
    storage1.forEach(function (e){
        const li=document.createElement("li");
        li.className=("list-group-item");  // yeni bir madde olusturuyor
        li.textContent=(e);
        displayedValues.appendChild(li);

        userInput.value="";
    })
}



i am practicing JS, in this code the user enters some text and i take that data and create a new li element. all the data is also stored to the session storage.

storage1.forEach function gives an error in the Brave Browser. Works completely fine in Chrome

Program to convert Infix notation to Expression Tree

how to write a program in JavaScript that takes an infix expression and transforms it to expression tree ?
where the expression may be like ((not a and b) or c).

with and, or, not as the only operators and of course with parenthesis for order

This is what I am able to reach currently

class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

function isOperator(char) {
  return ["AND", "OR", "NOT"].includes(char.toUpperCase());
}

function precedence(operator) {
  switch (operator.toUpperCase()) {
    case "NOT":
      return 3;
    case "AND":
      return 2;
    case "OR":
      return 1;
    default:
      return 0;
  }
}

function infixToExpressionTree(expression) {
  const stack = [];
  const postfix = [];
  const operators = ["AND", "OR", "NOT"];

  const tokens = expression.split(/s+/);

  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];

    if (!isOperator(token)) {
      postfix.push(new Node(token));
    } else {
      while (
        stack.length > 0 &&
        precedence(stack[stack.length - 1]) >= precedence(token)
      ) {
        postfix.push(new Node(stack.pop()));
      }
      stack.push(token);
    }
  }

  while (stack.length > 0) {
    postfix.push(new Node(stack.pop()));
  }

  const treeStack = [];

  postfix.forEach((token) => {
    if (isOperator(token.value)) {
      const right = treeStack.pop();
      const left = treeStack.pop();
      const newNode = new Node(token.value);
      newNode.left = left;
      newNode.right = right;
      treeStack.push(newNode);
    } else {
      treeStack.push(token);
    }
  });

  return treeStack[0];
}

function printTree(node) {
  if (node) {
    console.log(node.value.replace(/[()]/g, ""));
    printTree(node.left);
    printTree(node.right);
  }
}

const expression = "((x AND y) OR (z AND w) AND q)";
const expressionTree = infixToExpressionTree(expression);

printTree(expressionTree);

so can someone please provide any kind of help ?

Promise.race() returning resolved promise instead of first rejected promise

When I run the following code, it Outputs ‘Promise 1’ even though the Promise that should settle first in the race is promise2 and should Output ‘Error Promise 2’. What is the logic behind the output coming as ‘Promise 1’?

As per the mdn docs, “…it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected.”

try{
    // Promise 1
    const promise1 = new Promise((resolve, reject) => {
        setTimeout(() => resolve('Promise 1'), 2000);
    });
    // Promise 2
    const promise2 = new Promise((resolve, reject) => {
        setTimeout(() => reject('Error Promise 2'), 2000);
    });

    // Promise 3
    const promise3 = new Promise((resolve, reject) => {
        setTimeout(() => reject('Error Promise 3'), 2000);
    });

    const result = await Promise.race( [promise2, promise1, promise3]);
    console.log(result);

} catch(err) {
    console.log(err.message);
}

It Outputs :
Promise 1

As per the mdn docs, about Promise.race, it states that-

**It’s useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).
**
Link here.

Is it bad practice to nest stream.pipeline?

I want do download a file, parse it, stringify the results and POST them to a server. To make the code more structured, I’d like to split this into two functions and pipeline them together like this:

function downloadAndParse() {
  return stream.pipeline(
    download(),
    parse(),
    err => {}
  );
}

function stringifyAndUpload() {
  return stream.pipeline(
    stringify(),
    upload(),
    err => {}
  );
}

stream.pipeline(
  downloadAndParse(),
  stringifyAndUpload(),
  err => {
    //...
  }
);

Is there a disadvantage to this approach compared to a single pipeline() with all four operations?

Why does my React UI only update in many cases when I delete the ‘.parcel-cache’ and ‘dist’ folders and restart the server

The problem arises when I make changes to the code within the Body component. Interestingly, I can observe live updates using an autosave extension. However, within the Body component, there is another subcomponent, and when I make changes to it, the updates are not reflected in the UI in real-time.

The peculiar aspect is that, upon stopping the server, deleting the ‘.parcel-cache’ and ‘dist’ folders, and restarting the server, the updates in the subcomponent are then accurately reflected.

I attempted several troubleshooting steps to address the issue:

1 – Added this in script = “start”: “parcel index.html && parcel watch index.html”,
2 – Deleted the ‘node_modules’ folder and ‘package-lock.json’, followed by a reinstallation.
3 – Disabled the auto-save extension and manually saved the changes.
4 – Updated and restarted Visual Studio Code.
5 – My files are not in any cloud; all files are in my local storage

Despite these efforts, the problem persists, and the updates to the subcomponent within the Body component are not reflected in the UI in real-time. I’m seeking assistance to understand why these changes require manual intervention with cache deletion and server restart to take effect.

I am encountering a peculiar issue with my React application. The versions of the key dependencies are as follows:

{
  "name": "food-ordering-app",
  "version": "1.0.0",
  "description": "food ordering app using react and parcel bundle",
  "scripts": {
    "start": "parcel index.html && parcel watch index.html",
    "build": "parcel build index.html",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "parcel": "^2.11.0",
    "postcss": "^8.4.33",
    "process": "^0.11.10",
    "tailwindcss": "^3.4.1"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^6.5.1",
    "@fortawesome/free-brands-svg-icons": "^6.5.1",
    "@fortawesome/free-regular-svg-icons": "^6.5.1",
    "@fortawesome/free-solid-svg-icons": "^6.5.1",
    "@fortawesome/react-fontawesome": "^0.2.0",
    "@reduxjs/toolkit": "^2.0.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^9.1.0",
    "react-router-dom": "^6.21.1"
  }
}

How do I break a string into words and track the index of each word (within the original string)?

I have a string:

const str = 'a string, a long string'

I want to break it down into words (no problem here) and then track the index of each word within the original string.

Actual result:

[
  { word: 'a',      idx: 0 },
  { word: 'string', idx: 2 },
  { word: 'a',      idx: 0 },
  { word: 'long',   idx: 12 },
  { word: 'string', idx: 2 }
]

Desired result:

[
  { word: 'a',      idx: 0 },
  { word: 'string', idx: 2 },
  { word: 'a',      idx: 10 },
  { word: 'long',   idx: 12 },
  { word: 'string', idx: 17 }
]

Code so far:

const str = 'a string, a long string'

const segmenter = new Intl.Segmenter([], { granularity: 'word' })

const getWords = str => {
  const segments = segmenter.segment(str)
  return [...segments]
    .filter(s => s.isWordLike)
    .map(s => s.segment)
}

const words = getWords(str)

const result = words.map(word => ({
  word,
  idx: str.indexOf(word)
}))

console.log(result)