Determine whether one class is a parent class of another class

I'm working with an array of classes (not objects) and I need to add new classes to the array only if a subclass is not already present. However, the current code is unable to achieve this since these are not initialized objects.


import {A} from './a';
import {B} from './b';

import {otherList} from './list';


export const getList =()=>{
  const list = [A,B];
  
  otherList.forEach((element) => {
    if (list.findIndex((item) => element instanceof item) === -1) {
      list.push(element);
    }
  });
  return list;
}

Answer №1

In JavaScript, inheritance is achieved by creating the prototype from the constructor of the superclass.

For example, consider the following classes:

class A { }
class B extends A { }
class C extends B { }

You can determine subclass relationships using the .prototype property:

console.log(A.prototype instanceof Object);
console.log(B.prototype instanceof Object);
console.log(B.prototype instanceof A);
console.log(C.prototype instanceof A);
console.log(C.prototype instanceof B);
console.log(C.prototype instanceof C); // false

The first five checks return true, except for the last one.

To create a function that checks if one class is a subclass or the same class as another, you can do this:

declare type Class = new (...args: any[]) => any;
function isSubClassOf(cls: Class, superCls: Class): boolean {
    return cls === superCls || cls.prototype instanceof superCls;
}

The following checks all return true, except the last one:

console.log(isSubClassOf(C, A));
console.log(isSubClassOf(C, B));
console.log(isSubClassOf(C, C));
console.log(isSubClassOf(B, A));
console.log(isSubClassOf(A, A));
console.log(isSubClassOf(A, C)); // false

You can use this function in your code like so:

if (list.findIndex((item) => isSubClassOf(element, item)) === -1) {
   list.push(element);
}

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

Creating a JSON object hashtable using jsHashtable: A step-by-step guide

I have a good understanding of how to create a hashtable from scratch using jshashtable. For instance: <script type="text/javascript" src="jshashtable.js"></script> <script type="text/javascript"> var typesHash = new Hashtable(); ...

In what specific way can I collect the contents from the open file along with the names present in the files and store them into my string vector?

#include <iostream> #include <string> #include <fstream> #include <vector> #include <iomanip> using namespace std; int main() { char answer = 'y'; while (answer == 'y') do { ...

Firebase - Accessing data for a specific item

Apologies for the lengthy question. I have a collection of events that I retrieve like this: export class HomePageComponent implements OnInit { events: FirebaseListObservable<EventModel[]>; constructor( private authService: AuthService, ...

NodeJS error: Attempted to set headers after they have already been sent to the client

As a beginner, I have encountered an error message stating that the API is trying to set the response more than once. I am aware of the asynchronous nature of Node.js but I am struggling to debug this issue. Any assistance would be greatly appreciated. rou ...

Using TypeScript with Next.js getStaticProps causes errors

Currently, I am grappling with utilizing getStaticProps along with TypeScript. Initially, I attempted to achieve this using a function declaration: import { Movie } from './movies/movie' import { GetStaticProps } from 'next' export asy ...

Delete the generated thumbnails from the input JavaScript file

One issue I'm facing is that I have written JavaScript code to generate a thumbnail when a user uploads an image. Now, I would like to implement a feature that allows the user to click on an "X" button to delete the uploaded image. This is the existi ...

React.js TypeScript Error: Property 'toLowerCase' cannot be used on type 'never'

In my ReactJS project with TSX, I encountered an issue while trying to filter data using multiple key values. The main component Cards.tsx is the parent, and the child component is ShipmentCard.tsx. The error message I'm receiving is 'Property &a ...

Ways to layer two divs on each other and ensure button functionality is maintained

In the process of developing a ReactJS project, I encountered the challenge of overlapping my search bar autocomplete data with the result div located directly below it. For a more detailed understanding, please take a look at the provided image. Here&apo ...

Why do browsers fail to cache Java scripts (Ajax) properly?

After creating a cascade drop-down list box with JQuery, the user can choose a state from the first drop-down and then the second drop-down will be filled with the relevant cities based on the selected state. However, I am facing an issue with caching in ...

Custom attribute in ReactJS component - I am not defined in my custom attribute in React component

I am currently working with ReactJS and I am facing an issue regarding accessing a custom attribute -name- of my ReactJS component. Despite trying to use e.target.name, it keeps returning "undefined" on my console. I cannot seem to figure out why this is ...

Explore all sorts of data such as search term within a JavaScript JSON array

In my JSON array of objects, I have data displayed in an HTML table. Above the table, there is a search input where users can enter search terms. [ { "id": 1, "title": "My fridge door closed", "description": "The fridge door was closed yesterday.", "point ...

The powerful combination of harp.gl and Angular NG

We've integrated harp.gl into our ng Angular application, but we're encountering issues when trying to connect to data sources that previously worked in our yarn demo. The datasource is created as follows: const dataSource = new OmvDataSour ...

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Creating a sleek navigation bar and sliding feature within the header of your Ionic 2

I am looking to create a sliding header for my website where the gallery hides and the navbar moves to the top as I scroll down, similar to the gif provided. Any help or ideas on how to achieve this would be greatly appreciated. Thank you. https://i.sstat ...

Guide on accessing a modal component in Angular?

I have an Edit Button on my component called SearchComponent. When the user clicks this button, it currently redirects them to another component named EditFormComponent using navigateByUrl('url-link'). However, I would like to enhance the user ex ...

Issue encountered: ENOENT error - The specified file or directory does not exist. This error occurred while attempting to access a directory using the

I don't have much experience with nodejs or express, but I have an API running on http://localhost:3000. One of the endpoints triggers a function that uses the file system to read a file synchronously. However, when I send a post request using Postman ...

JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles. The function randomly selects a border color for each circle, and this feature is functioning correctly. To enhance the appearance, I decided to add a box shadow to the circl ...

The div within the button is failing to properly adjust to height settings

Check out this Fiddle I'm currently working on a social thumbs up button and I've encountered some challenges. In my button design, I have included a second div to accommodate the right side of it. However, despite trying to adjust its height us ...

Reset the dropdown menu in React by setting a disabled option as the default selection

One issue I'm facing is trying to reset some dependent dropdowns that are controlled by react state. The functionality works fine, except when the default option is set as disabled. I came across this code snippet in a fiddle from another stackoverfl ...

Delete an entry from the list

I have a fully functional Ajax call and function that fills up a datalist. This datalist is utilized to choose from a limited list and add it to a UL element on the page. Once an option is added from the datalist to the actual list, I aim to eliminate that ...