Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input?

class MyClass {

public static arr : any[] = [];

// main method
public static doProcess(object : object , justForObjects : boolean = false){
    if (justForObjects){
        // specify the required checking method to use at this point
    } else {

    }

    for (let key in object){
        if (object.hasOwnProperty(key)){
            if (/* specify checking method here */){
                MyClass.doProcess(object[key] , justObjects)
            } else {
                MyClass.arr.push(object[key])
            }
        }
    }

return MyClass.arr;

}

 // methods for checking variable types
 private static is_object(value : any){
     return !!(typeof value === 'object' && !(value instanceof Array) && value);
 }
 private static is_object_or_array(value : any){
     return !!(typeof value === 'object' && value);
 }

}

let object = {
 'main color' : 'black',
 'other colors' : {
     'front color' : 'purple',
     'back color' : 'yellow',
     'inside colors' : {
         'top color' : 'red',
         'bottom color' : 'green'
     }
 }
}

MyClass.doProcess(object , true);

Although it can be achieved in the same for loop (as shown below), I'd prefer to explore alternative ways first.

    for (let key in object){
        if(object.hasOwnProperty(key)){
            if (justForObjects){
                if (MyClass.is_object(object[key])){
                    // execute certain logic
                }
            } else {
                if (MyClass.is_object_or_array(object[key])){
                    // execute different logic
                }
            }
        }

    }

Thank you for your guidance

Answer №1

One way to assign functions to variables is by using the following code:

public static doProcess(obj : object , justForObjects : boolean = false) {

    var check_fn = justForObjects ? MyClass.is_object : MyClass.is_object_or_array;

    for (let key in obj) {
        if (check_fn(obj[key])) ...
    }

}

 // Methods to check the type of variables
 private static is_object(value : any) : boolean { ... }
 private static is_object_or_array(value : any) : boolean { ... }

Answer №2

Consider implementing a recursive solution:

interface CustomObject {
  [property: string]: ObjectValue;
}

type ObjectValue = string | CustomObject | CustomObject[];

class RecursiveClass {
  /**
   *
   *
   * @recursive
   */
  public static processObject(
    obj: CustomObject,
    onlyObjects: boolean = false
  ) {
    for (const key in obj) {
      const value = obj[key];

      if (this.isObjectOrArray(value, onlyObjects)) {
        this.processObject(value as CustomObject, onlyObjects);
        continue;
      } else {
        // perform some action;
        continue;
      }
    }
  }
  /**
   *
   *
   * Check if value is object or array
   */
  private static isObjectOrArray(
    val: ObjectValue,
    onlyObjects: boolean = false
  ) {
    // objects and arrays
    if (!onlyObjects) return !!(typeof val === "object" && val);

    if (Array.isArray(val)) throw new TypeError("Array value is not allowed");

    // only objects
    return !!(typeof val === "object" && !(val instanceof Array) && val);
  }
}

let customObj = {
  "primary color": "blue",
  "other hues": {
    "front tone": "light green",
    "back shade": "dark blue",
    "interior shades": {
      "top hue": "pink",
      "bottom tone": "brown"
    }
  }
} as CustomObject;

RecursiveClass.processObject(customObj, 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

Why does the value of my input get erased when I add a new child element?

I seem to be facing an issue when I try to add an element inside a div. All the values from my inputs, including selected options, get cleared. Here's a visual representation of the problem: https://i.sstatic.net/UpuPV.gif When I click the "Add Key" ...

Increment the name field automatically and track the number of auto-increment variables being sent through serialization

I am trying to implement a functionality where users can add more inputs by pressing a button, each representing an additional 'guest'. The issue I am facing is with auto-incrementing the JavaScript so that new inputs are added with an incremente ...

Rotating objects with Three.js on mobile devices

I came across a related question on Stack Overflow about stopping automatic rotation in Three.js while the mouse is clicked. I am now attempting to achieve the same functionality for rotating an object on smartphones and tablets. Given that I have curren ...

Check the input in the text box against the selected options to validate it

Currently, I am working on an add contacts page where I am facing the challenge of displaying an error message or highlighting input as invalid if a user tries to enter a contact name that already exists. It seems like one solution could be populating a s ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

What is the best way to pass default event argument alongside another argument in React?

This snippet demonstrates the function I wish to call when a certain input type is invoked: _handleOnEnterPress = (e, receiverUserId) => { if (e.keyCode === 13) { // assuming keycode 13 corresponds to 'enter' console.log("pressed ...

Leveraging Typescript's robust type system to develop highly specific filter functions

I'm attempting to utilize the robust TypeScript type system in order to construct a highly typed 'filter' function that works on a collection (not just a simple array). Below is an illustration of what I am striving for: type ClassNames = &a ...

Typescript: The property isComposing is not found on Event type

While working on a React app with Typescript, I encountered a Typescript error both during compile time and in the editor: TS2339: Property isComposing does not exist on type Event This issue arises when handling an OnChange event in an HTML Input element ...

Utilizing Grunt to streamline a personalized project

I have set up Grunt as my "JS Task Runner". Node.js is installed in the directory "C:/Program Files". NPM has been installed in C:/users/Peterson/appdata/roaming/npm. Inside the npm folder, I have Grunt, Bower, and Grunt-cli. I am working on a pro ...

The component's state consistently reverts to its initial state

I am working with a component called DataGrid that has the following state: const [rows, setRows] = useState([ { id: 1, lastName: 'Snow', firstName: 'Jon', status: 'Sold'}, { id: 2, lastName: 'Lanniste ...

Having trouble getting event modifiers to work in Vue when added programmatically

Trying to dynamically add events using v-on through passing an object with event names as keys and handlers as values. It appears that this method does not support or recognize event modifiers such as: v-on=“{‘keydown.enter.prevent’: handler}” T ...

Creating scalable React applications

Can you provide insights on the scalability of React Apps? What recommended approaches are typically employed to effectively handle and generate scalable states in web applications using Reactjs? * ...

Tips for combining values with Reactive Forms

Is there a way to merge two values into a single label using Reactive Forms without utilizing ngModel binding? <label id="identificationCode" name="identificationCode" formControlName="lb ...

Aframe Descend Rotation

I am currently working on a project in Aframe and I'm looking to implement a control/event that enables an entity to rotate downward. While attempting to create a new animation and add it as a child object to the entity, I have achieved successful re ...

Executing an external function on an element as soon as it is created in AngularJS: tips and tricks

I am looking to implement a function from an external library that will be executed on each item as it is created in AngularJS. How can I achieve this? Here is the code snippet of my application. var app = angular.module('app', []); app.contr ...

Lack of MaterialUI Table props causing issues in Storybook

Currently, I am utilizing MaterialUI with some modifications to create a personalized library. My tool of choice for documentation is Storybook, using Typescript. An issue I have encountered is that the storybook table props are not consistently auto-gene ...

How to make a node application run as an executable within an NX workspace

The structure of an NX workspace really caught my attention, which led me to start using it for a new CLI project I was working on. I began by setting up a @nrwl/node:application, but I'm currently facing some issues trying to make it executable. I ...

Angular and Spring setup not showing data despite enabling Cross Origin Support

I'm currently in the process of developing a full stack application using Spring and Angular. After successfully setting up my REST APIs which are functioning properly on port 8080, I encountered an issue when trying to access them from my frontend ( ...

Issue with jQuery: submit() function not behaving as expected when navigating back in history

Incorporating jQuery's submit() method in order to perform basic form verification prior to redirecting the user to the subsequent page. $(document).ready(function(){ $("form").submit(function() { // carry out form validation and set erro ...

Creating a route provider tailored to specific user roles

I have a rather straightforward requirement. There are 3 different User Roles: CATUSER LICUSER ALLUSER The User Role value is stored in the $rootScope.userRole variable. The User Role is predefined before the AngularJS application starts as the Angula ...