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

Issues arise when attempting to transmit JSON data from JavaScript to the server using the POST method

I'm having trouble viewing the JSON data I sent to the server using XMLHttpRequest. It seems like the server isn't receiving it because when I run the JavaScript, the alert window pops up but doesn't display anything. Does anyone have a solu ...

Customize and adjust the default color for dark themes in Material-UI

When using Material-UI and switching to a dark theme, you may notice that some components change their color to #424242 while others change to #212121. This color inconsistency stems from the use of theme.palette.grey: theme.palette.grey[800]: '#424 ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

Using an HTML file as the source for an image in the <img src=""> tag is a simple process that can greatly enhance the visual appeal of your webpage

My goal is to utilize an html file as the source for an image file within the <img src=""> tag in order to prevent mixed-content warnings when using an http image over https. For instance: index.html: <img src="./image.html" > image.htm ...

Is it wise to question the validity of req.body in express.js?

https://expressjs.com/en/4x/api.html mentions It is crucial to validate all properties and values in the req.body object as they are derived from user input. Any operation performed on this object should be validated to prevent security risks. For instan ...

Utilizing Dropzone for file uploads in Node.js, Express, and Angular

I'm running into a bit of trouble trying to get the file recognized on the server side with node.js. Especially when trying to access request data, such as req.files or req.body If anyone has any advice, here are some code snippets: HTML: <form ...

Monitor the number of ng-repeat items altering within a directive

I am using the angular-sly-carousel directive to display some data. The data is dynamically added as the user scrolls down, so I need to reload the sly carousel options after scrolling. Is there a way to detect when the length of ng-repeat elements change ...

Iterating through an object using the forEach method (uncommon practice)

Greetings, I have the following object: data = { name: undefined, age: undefined, gender: undefined }; I am looking to iterate through each key and value pair in this object and perform an action. Here is my attempt: this.data.forEach((item: ...

Transmitting payment card details to the node

I'm considering utilizing dibs payment dibspayment I came across this Node.js wrapper for the: DIBS API wrapper for Node.js However, using this would involve sending credit card information through a POST request to my node server. My main concern ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

Invoke a codebehind function using jQuery

I am encountering an issue while trying to complete a simple task. I am attempting to pass values to a code behind method, perform some calculations, and then return the result. Initially, I started with a test method but have not been successful in making ...

Transferring a dynamic HTML file created using R's animation package onto a WordPress platform

After using the animation package in R to create an HTML file, I'm facing some challenges uploading it to my WordPress blog. It appears that additional js or css files may be required for proper functionality, but I'm uncertain about the process. ...

(Discord.JS) Bot failing to send direct message upon user joining the server

When attempting to send a DM message, I am using the following code: bot.on('guildMemberAdd', (member) => { member.send('a'); }); I am experiencing difficulty in understanding why the private message is not being successfully se ...

Effectively enhance constructor by incorporating decorators

Is it possible to properly extend a class constructor with decorators while maintaining the original class name and static attributes and methods? Upon reading the handbook, there is a note that cautions about this scenario: https://www.typescriptlang.or ...

The HTML document is unable to locate the Angular framework

I'm encountering an issue with the code below on my HTML page - every time I run it, I receive an error message saying "angular is not defined". I've already included angular in the head section of the page so I'm puzzled as to why it's ...

What steps can be taken to deter users from repeatedly liking comments, similar to the systems seen on Facebook or YouTube for like/dislike features?

I am currently working with express, react, and MySQL. My goal is to implement a like/dislike system for comments. After doing some research, I found that many suggest disabling the like button after a single click. However, I want users to be able to se ...

Determine whether I am verified or if the XMLHttpRequest has been directed

When making an XMLHttpRequest to an API secured with OAuth authentication, I encountered a situation where calling the API from a browser without being logged in automatically redirected me to the provider's login page. However, when attempting to ca ...

Creating a bespoke validation in AngularJS to verify if the selected date falls within a specific range of weekdays

Hey there! I'm looking to enhance the validation process for a date input field in a unique manner. Currently, my default validation setup looks like this: <div> <input type="text" name="firstName" ng-model="appointmentForm.firstName" ng- ...

Tips for personalizing react-show-more text length with Material-UI Icons

In my SharePoint Framework webpart using React, I am currently utilizing the show more text controller. However, I am interested in replacing the "Show More" and "Show Less" string links with the ExpandMore and ExpandLess Material UI icons. Is there a way ...

Utilize Three.js to Add Depth to 2D Images with Extrusion

After searching online, I have been unable to find a method to extrude a colored image in Three.js. My goal is to create a design similar to a Minecraft item where the image is used to generate an extruded geometry. An example of what I'm trying to ac ...