Exploring the functionalities of objects in Typescript through the use of the for...in loop

After successfully converting the JavaScript function to Typescript, I encountered an issue with the line

if (!(key * key) in frequencyCounter2) {
. The error message displayed was:
"The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."

I attempted to typecast key as a number to resolve the problem, but unfortunately, it did not work. Is it generally not recommended to perform this operation when working with Typescript?

// The function sameOn accepts two arrays and should return true if every value in the array has its corresponding 
// value squared in the second array. The frequency of values must be the same.
function sameOn(arrA: number[], arrB: number[]): boolean {
    // complexity O(n): If arr is 1000 lines, this runs 2000 times
    if (arrA.length !== arrB.length) {
        return false;
    }
    type CountType = {
        [key: number] : number
    }

    const frequencyCounter1: CountType = {};
    const frequencyCounter2: CountType = {};

    for (const val of arrA) {
        frequencyCounter1[val] = (frequencyCounter1[val] || 0) +1;
    }
    for (const val of arrB) {
        frequencyCounter2[val] = (frequencyCounter2[val] || 0) +1;
    }

    for (const key in frequencyCounter1) {               
        if (!(key * key) in frequencyCounter2) {
            return false;
        }
        if (frequencyCounter2[key * key] !== frequencyCounter1[key]) {
            return false;
        }
    }
    return true;
}

sameOn([1,2,3,2], [4,1,9,4]) // returns true

Answer №1

This particular code snippet:

if (!(key * key) in frequencyCounter2) {

is actually looking for a boolean value in frequenceCounter2. This is because key * key generates a number, and then !number converts that number to a boolean.

If you want to check if the key generated by key * key is not present in the frequencyCounter2, you should use additional parentheses:

if (!((key * key) in frequencyCounter2)) {
//   ^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^−−−−−−−−−

Alternatively, you could simply rearrange your parentheses like this:

if (!(key * key in frequencyCounter2)) {
// Not here −−−^−−−−−−−−−−−−−−−−−−−−^− here

as the key * key operation is evaluated before checking the presence in frequencyCounter2.


This seems to indicate a possible bug in the original JavaScript code, where it would look for either "true" or "false" in frequencyCounter2 without any errors being raised. :-)

Answer №2

The updated function looks like this:

function checkEquality(arr1: number[], arr2: number[]): boolean {
    if (arr1.length !== arr2.length) {
        return false;
    }
    
    const counter1 = {};
    const counter2 = {};

    arr1.forEach((val) => {
        counter1[val] = (counter1[val] || 0) + 1;
    });

    arr2.forEach((val) => {
        counter2[val] = (counter2[val] || 0) + 1;
    });

    for (const key in counter1) {
        const squareKey = Number(key) * Number(key);
                  
        if (!(String(squareKey) in counter2)) {
            return false;
        }
        if (counter2[squareKey] !== counter1[key]) {
            return false;
        }
    }
    
    return true;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The onchange() function for a multi-checkbox dropdown is failing to work as

Issue with Multiple Drop Down Checkbox Functionality: The first parameter is always received as undefined, and the onchange event only captures the value of the first checkbox selected. <select name="multicheckbox[]" multiple="multiple" class="4colacti ...

Can a jQuery object be generated from any random HTML string? For example, is it possible to create a new link variable like this: var $newlink = $('<a>new link</a>')?

I'm looking to create an object without it being attached to the dom. By passing a HTML string, I want to insert the element into the dom and still have a reference to it. ...

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

Obtain the content window using angularJS

I've been attempting to retrieve the content window of an iframe element. My approach in JQuery has been as follows: $('#loginframe')[0].contentWindow However, since I can't use JQuery in Angular, I've been trying to achieve thi ...

Exploring the Concepts of PHP Classes

I am currently exploring the predefined classes in PHP and learning how to effectively utilize them. It is important for me to accurately describe these entities, like the DateTime class. Upon observing a method within the DateTime class denoted as DateTi ...

Incorporating Moralis into Ionic Angular with TypeScript

I'm currently developing an app using Ionic Angular (TypeScript) that will be compatible with both Android and iOS devices. I've decided to incorporate the Moralis SDK to establish a connection with the Metamask wallet. Here's a summary of ...

Conceal/reveal specific sections of a table cell using jQuery

Here is a table I have: A header Another header First (some-text-initially-hidden) click row Upon clicking, it changes to: A header Another header First (some-text-should-be visible now) click row However, the text "some-text-initially-hi ...

Encountering an issue while attempting to integrate mongoose with vue and receiving an error

Whenever I attempt to import this code, the page throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'split') import { User } from '@/assets/schemas' export default { name: 'HomeView', mount ...

Resizing a webpage to fit within an IFRAME

Having just started learning HTML, CSS, and JavaScript, I am attempting to incorporate a page as a submenu item on my website. Below is the code that I have so far: <!DOCTYPE html> <html> <meta name="viewport" content="width=1024"> ...

Refresh a webpage content dynamically without the need to reload the entire page

How can I implement YouTube's page navigation system that does not require the entire page to reload when switching pages? Do I need to incorporate Javascript or utilize an API for this functionality? ...

Error message 2339 - The property 'toggleExpand' is not recognized on the specified type 'AccHeaderContextProps | undefined'

When utilizing the context to share data, I am encountering a type error in TypeScript stating Property 'toggleExpand' does not exist on type 'AccHeaderContextProps | undefined'.ts(2339). However, all the props have been declared. inter ...

Command for DiscordJS to verify users

I have a requirement to develop a verification command using discord.js v12. This command will assign a verified role based on the configuration specified in a config file. Config file: { "token": "my-token", "status": " ...

Mapping arrays from objects using Next.js and Typescript

I am trying to create a mapping for the object below using { ...product.images[0] }, { ...product.type[0] }, and { ...product.productPackages[0] } in my code snippet. This is the object I need to map: export const customImage = [ { status: false, ...

Admin-on-rest sidebar navigation menu

Hello everyone! I am new to ReactJS and admin-on-rest. I am currently studying from this documentation and I am interested in creating a navigation submenu similar to the one shown here. I have tried searching on Google but haven't found what I need. ...

When the document is fully loaded on a page that has been dynamically loaded

Currently utilizing the following: $("#someDiv").load("ajax.html") The contents of "ajax.html" include a document.ready call: <script>$(function() { alert('works') })</script> I'm interested to know exactly when this callbac ...

Tips for generating a numeric whole number input field with Vuetify

After researching the topic on Vuetify's specific number input component, I am attempting to create a numeric input field. The value for both input and output is currently unknown, meaning it could be either undefined or null in order to allow cleari ...

The express.js and passport.js middleware in my application are functioning properly and executing as expected, however, there seems to be an issue with the

I have been working on developing a node/express server and decided to implement passport-local for user authentication using a local MongoDB server. I am encountering an issue where the page does not redirect as expected after submitting the login form wi ...

jQuery page hanging during DOM update with large data set

I am currently using a jQuery post method with the following structure: $.post("/SearchCompetitor/Index", { username: _username }, StartLoading()) .done(function (data) { if (data !== "UsernameErro ...

What could be causing my list of files to not properly append to FormData?

I have been working on this issue for the past three days. Despite trying various solutions from different sources, including seeking help from other websites, I am still unable to resolve it. My current challenge involves sending a post request with a Fo ...

Adjust mouse coordinates to be relative to the coordinates of the <canvas> element

I'm currently facing the challenge of determining the exact location of the mouse on a canvas grid while still maintaining resizability. As of now, I have the mouse coordinates based on its position on the screen (x and y). The issue arises from the ...