Discovering ways to align specific attributes of objects or target specific components within arrays

I am trying to compare objects with specific properties or arrays with certain elements using the following code snippet:

However, I encountered a compilation error. Can anyone help me troubleshoot this issue?

type Pos = [number, number]

type STAR = "*"
type LITERAL<A> = A
type Matcher<A> = STAR | LITERAL<A>

function match<A>(s: A, m: Matcher<A>): boolean {
   if (m === "*") {
       return true;
   } else {
       return s === m;
   }
}

function match2(b: Pos, q: Matcher<Pos>): boolean {
    return match(b[0], q[0]) && match(b[1], q[1]);
}

const poss: Pos[] = [[1, 1], [1, 2], [2, 1]]

let res = poss.filter(_ => match2(_, [1, "*"])) // [[1, 1], [1, 2]]

console.log(res);

The reference equality between item properties and query literals is causing the error.

Edit

The previous solution fixed my initial problem. Now, I want to implement nested queries like the ones shown below:

  interface Pos2 {
    file: string,
    rank: string
  }

  interface Board {
    p1: Pos2,
    p2: Pos2
  }

  function match3<A>(b: A, q: MapMatcher<A>): boolean {
   if (typeof b === 'object' && typeof q === 'object') {
    for (let key in b) {
      if (!match(q[key], b[key])) {
        return false;
       }
     }
     return true;
   } else {
     return false;
   }
  }

  let a2 = {
      file: "a",
      rank: "2"
  }, a3 = {
      file: "a",
      rank: "3"
  }, b1 = {
      file: "b",
      rank: "1"
  }, b2 = {
      file: "b",
      rank: "2"
  };

  let poss2 = [a2,a3,b1,b2]

  let boards = [{
      p1: a2,
      p2: a3
  }, {
      p1: a2,
      p2: b1
  }, {
      p1: a3,
      p2: b2
  }]

  function query<A>(arr: A[], m: MapMatcher<A>): A[] {
      return arr.filter(_ => match3(_, m));
  }

   let q1 = query(poss2, {
          file: "a",
          rank: "*"
      })

  // nested equality
  query(boards, {
      p1: q1,
      p2: "*"
  });

  // reference equality
  match3(boards, {
      p1: a2,
      p2: "*"
  })

The code above does not pass the compiler's checks.

Answer №1

Matcher<Pos> is not the correct type for the q parameter in the function match2(). Upon examination, this type is equivalent to:

type MatcherPos = "*" | [number, number]

You can't pass [1, "*"] into something that expects "*" | [number, number], which results in the following error:

let res = poss.filter(_ => match2(_, [1, "*"])) // error!
//                                   ~~~~~~~~
// Argument of type '[number, string]' is not assignable to parameter of type 'Matcher<Pos>'.

Perhaps you don't need Matcher<Pos>, but instead something like MapMatcher<Pos> where MapMatcher<T> takes an object/array type T and maps each property T[K] to Matcher<T[K]>:

type MapMatcher<T> = { [K in keyof T]: Matcher<T[K]> }

When applied to Pos, it results in a type equivalent to:

type MapMatcherPos = [Matcher<number>, Matcher<number>];

or

type MapMatcherPos = ["*" | number, "*" | number];

If I implement this change,

function match2(b: Pos, q: MapMatcher<Pos>): boolean {
    return match(b[0], q[0]) && match(b[1], q[1]);
}

then everything compiles successfully now:

let res = poss.filter(_ => match2(_, [1, "*"])) // okay

Playground link to code

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 display function in Javascript has a tendency to work sporadically

I’ve been tasked with creating my own tic tac toe game through coding. While I am relatively new to programming, I have a strong passion for it. At the moment, I've set up a basic function to hide only the "O", leaving only the "X" visible on the gr ...

Storing the order of jQuery UI Sortable in the WordPress Admin Panel

My goal is to customize the order of taxonomy terms for each individual post in Wordpress. I have created a metabox on the EDIT POST page that contains custom taxonomy terms and made them sortable using JQuery. Here is my setup on the Wordpress backend: ...

Creating a Parent Container to Maintain the Height of the Tallest Offspring

I've been searching online for solutions, but so far I haven't found one that meets all the requirements. <div class="parent"> <div class="child1">I am 60px tall and always visible; my parent is 100px tall</div> <div ...

Error in Typescript: The property 'children' is not included in the type but is necessary in the 'CommonProps' type definition

Encountering this error for the first time, so please bear with me. While working on a project, I opened a file to make a change. However, instead of actually making any changes, I simply formatted the file using Prettier. Immediately after formatting, t ...

jQuery is failing to properly render dynamic content data identifiers

Need help with a dynamic HTML div <a data-id="17" onclick="getcustomer();"> <div class="note note-success"> <h4 class="block">A</h4> <p>Email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Unable to scroll to the top of the page with JavaScript

I tried the code below but it didn't quite do the trick. Can someone assist me with refreshing the page to the top every time it loads? window.addEventListener('load', function(){ window.scrollTo(0,0) }) window.onload = (event) => { ...

Exploring the capabilities of referencing MongoDB documents with the populate method in Node.js

I have been working on referencing in Node.js using the populate method, but I am unsure about how exactly it works. In my code, I am creating a reference to the user collection from my child collection. I have two collections - one for children and anothe ...

Issue with passing props to screen not displaying on initial load

Greetings, I'm a newcomer to the world of react native and currently facing an issue: const Tab = createMaterialTopTabNavigator(); export const CurriculumMenu = ({navigation, item}) => { const data = item.Title; console.log(data) return ( ...

Step-by-step guide on retrieving news_id and displaying it in an alert when an item

How can I retrieve the item ID when it is clicked in a Listview to display the specific news_id in an alert? Below is the HTML code snippet for my page: <body> <div data-role="page" id="taxmanhomepage" data-theme="e"> <div data-role="h ...

I'm looking for a way to securely transfer data, such as an authentication token, from a web application to an electron-based thin client. My current approach involves utilizing custom URL protocols to

Have you ever wondered how applications like Teams and Zoom produce a pop-up when clicking on a meeting link in the browser, giving you the option to continue in the browser or open in the app? When choosing to open in the app, it launches on the desktop a ...

How can I create a regex pattern that will exclude characters within parentheses?

While working on some regex, I encountered a bug: The scenario is as follows: I have this string - for example "+1/(1/10)+(1/30)+1/50" and I applied the regex /\+.[^\+]*/g to it, which worked perfectly giving me ['+1/(1/10)&apos ...

Activate on click using JavaScript

When a link with the class .active is clicked, I want to use a JavaScript function to deactivate any other active links. The structure of the code should be as follows: <ul class="product"> <li><a href="#myanmar" class="active">Mya ...

When a user clicks on a React listItem, the information for that specific item is displayed using

As a beginner in the coding world, I am currently learning about React and JSON. My project involves working on three interconnected panels. Specifically, I aim to showcase checklist answers on the third panel. First Panel: Displaying: All the ESN ("46 ...

Implementing a post request triggered by a button click in Node.js with Express

How can I invoke a controller from a button click event? I tested it in Postman and it works fine, but I'm having trouble calling it from a button on my front-end. I am using Nodemailer and Node Express to send emails. Here is my code. Can someone p ...

Leveraging Angular Observables for seamless data sharing across components

As I embark on developing my very first Angular app, I have encountered a challenge with filtering a list of book objects based on their gender attribute. The issue lies in sharing data between components – specifically the filteredData variable and the ...

Utilizing a callback function to update the value of a variable that is declared outside of the getJSON function

I'm currently facing an issue with this function I have. function customCheck(username){ var result = "normal"; $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){ if(data.stream == null) re ...

There is no valid injection token found for the parameter 'functions' in the class 'TodosComponent'

While working in my code, I decided to use 'firebase' instead of '@angular/fire'. However, I encountered an issue that displayed the following error message: No suitable injection token for parameter 'functions' of class &apos ...

The issue of Ajax response not triggering the ng-click function

When attempting to pass data through an AJAX return, I encountered an issue with a function that writes an ng-click in Angular 1. The code snippet is as follows: $.ajax({ 'method': 'GET', 'url': base_url +&apos ...

Expanded MUI collapsible table squeezed into a single cell

I'm experimenting with using the MUI table along with Collapse to expand and collapse rows. However, I've noticed that when utilizing collapse, the expanded rows get squished into one cell. How can I adjust the alignment of the cells within the p ...

You have encountered an issue with the runtime-only build of Vue, which does not include the template compiler

Lately, I have been utilizing Vue in a project and encountered an issue where upon compiling, my browser page displays as white with an error message stating "You are using the runtime-only build of Vue where the template compiler is not available. Either ...