Building a TypeScript function using a dictionary with function names and argument types

In possession of a dictionary

{
   "function_name":"myFunc",
   "arguments":["a1","a2"]
}

A desire to create a function where the name matches that in the dictionary above (i.e myFunc ) with respective arguments (i.e ["a1","a2"]).

The ultimate goal is to generate:

myFunc(a1,a2){

}

Actual Scenario: Intention to integrate this function into a class instance and utilize it

and expanding on this idea.

If the function is async, then it should be awaitable.

Illustration:

When a smart contract calls a function, the usual method involves (Using the greeter smart contract as reference )

contract.functions.greet().then(k => console.log(k))

The type of the contract function is:

 readonly functions: { [ name: string ]: ContractFunction };
 export type ContractFunction<T = any> = (...args: Array<any>) => Promise<T>;

using ethers library.

The objective is to dynamically generate the greet function using the contract ABI :

[
    {
      "inputs": [
        {
          "internalType": "string",
          "name": "_greeting",
          "type": "string"
        },
      ],
      "stateMutability": "nonpayable",
      "type": "constructor"
    },
    {
      "inputs": [],
      "name": "greet",
      "outputs": [
        {
          "internalType": "string",
          "name": "",
          "type": "string"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "string",
          "name": "_greeting",
          "type": "string"
        }
      ],
      "name": "setGreeting",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    }
  ]

Parsing the JSON data to extract the function name and arguments was successful. As a final step, the aim is to bind this generated function to the contract and execute it.

Answer №1

It seems like you're attempting to achieve something similar to the code snippet below:

class SomeClass {
  obj = {
    functionName: "add",
    args: [10, 20],
  };

  add(a, b) {
    return a + b;
  }

  invokeFunc() {
    const { functionName, args } = this.obj;
    return this[functionName](...args);
  }
}

const instance = new SomeClass();
console.log(instance.invokeFunc());

As the function to be called is accessible through the this object, you can call it and spread (...) all the arguments.

Regarding async functions, it's not explicitly indicated within the object. You could introduce a type field in the object and conditionally use await for asynchronous functions.

Answer №2

Check out this demo to see how it works.

For more information, visit this link which could provide some valuable insights

let dynamicFunctions = [{
  "isAsync":false,
  "function_name": "myFunction",
  "arguments": ["arg1", "arg2"],
  content: "return arg1*arg2"
},
{
  "isAsync":true,
  "function_name": "asyncMyFunction",
  "arguments": ["arg1", "arg2"],
  content: "return arg1+arg2"
}]

class Functions {
constructor(func){
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  func.forEach(element=> {
    let customFunc = null;
    if (element.isAsync)
     customFunc = new AsyncFunction(...element.arguments, element.content);
    else customFunc = new Function(...element.arguments, element.content);
    
    this[element.function_name] = customFunc;
  });

}

}

var myClass = new Functions(dynamicFunctions);
myClass.asyncMyFunction(1,2).then(result=> console.log("Result from async function:", result))
console.log("Result from sync function:", myClass.myFunction(1,2));

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

Encountering difficulty selecting a dropdown sub-menu using Selenium WebDriver

I'm currently working on automating a website with selenium webdriver. The issue I'm encountering is that when I try to click on a menu item, the submenu pops up (actually a misplaced dropdown, UI issue), and although I can locate the element of ...

Simple steps for calling a lit component in React using the ScopedElementsMixin:1. Import

Looking to incorporate the web component Button (lit) into my project using a similar tag approach. For instance, if the <button-test> tag is present on the website, then it should be converted to <button-test-12345>. This is why ScopedElements ...

Unable to open file after downloading via AJAX

I am facing an issue while trying to download a file using an Ajax request. Although the file is successfully downloaded, I am unable to open it. I am seeking assistance with the provided details below. Thank you. On a JSP page, there is a list ...

I seem to be facing a challenge with retrieving results in my app when using mongoose - what could be causing this issue

mongoose.connect('mongodb://localhost:27017/codealong'); When I attempt to connect to MongoDB and post data, the process is successful but I do not receive any results in my browser. Instead, all I see is an empty square bracket [ ]. These are ...

Tips for transferring data from a file located outside an Angular library to files within the Angular library

In the repository below, you will find a library named posts-lib. This library contains a file named posts.services.ts which is responsible for making http calls and retrieving a list of posts to display on the screen. Additionally, there is a component na ...

Is it better to set Angular2 @Inputs as public, or should we opt for a stricter API by keeping them private?

I am currently utilizing Angular2 with Typescript Imagine having the following code in the template of my app component: ... <coffee-cup [coffee]="" ... Here is my coffee-cup component: @Component({ selector: 'coffee-cup', ... }) ex ...

Optimizing Static File Caching in Yii

Having a frustrating issue with Yii where my local development environment caches CSS and JS files. Despite making changes to the file, the edits do not reflect in the output and sometimes causes corruption leading to broken functionality. This problem see ...

Guide on developing a JavaScript script for implementing across numerous Bootstrap modals within a single webpage

I have been working on setting up a page with 14 different modals. Initially, all the modals were opening normally, but I recently discovered a way to make them draggable when opened. After some trial and error, I managed to implement this feature successf ...

Exporting numerous modules from an NPM package

Currently, I am working on a large Node and Typescript project called Project A. This project consists of numerous modules that I intend to reuse in another project, Project B. In order to achieve this reusability, I have configured the tsconfig.json file ...

Ensure that the line above is shorter in length compared to the following line

Is there a way to ensure that the previous line of text is always shorter than the next one, even if the length of the text is unknown? For example: Lorem ipsum dolor sit amet, consectetur adipiscing et libero posuere pellentesque. Vivamus quis nulla jus ...

Angular 2 dropdown list that allows users to add a personalized value in the HTML code

Here is the scenario I am dealing with We are displaying a fixed dropdown list to the user For example, a dropdown list has 4 options such as apple, orange, grape, pineapple and 'create your own' If the user is not satisfied with the provided ...

Issue with retrieving all phone numbers from a contact in Ionic

Hope you're doing well! I'm encountering an issue with Ionic Contacts. Currently, I'm able to retrieve all the contacts using my code but I need help extracting all the phone numbers associated with each contact. For example, if John has 3 ...

Invoke a function from a different vue.js component using the this.$refs property

I'm facing an issue with triggering a sibling element. What I've tried so far <b-img @click="callFileLoader"/> <b-file type="file" ref="fileUploader"></b-file> ... methods:{ callFileLoader () { this.$refs.fileUploader.c ...

Testing a service resolution in a controller through unit testing

As I attempt to create a test for my home module, I keep encountering an error that reads "unknown provider: service." Interestingly, when I modify resolveSomething in my home module to output a string, the app functions as expected, indicating that the re ...

Is there a proper method for populating an HTML text with values from a form?

As a newcomer, I could really use some guidance here :) I'm trying to populate text with various words, numbers, and calculation results from a form. This is my initial attempt for just one field/word, and it appears to be functioning correctly. Do y ...

The Chrome developer console is alerting that the Typescript file needs to be updated and is currently

Just made an update to my typescript file in my app and ran it. Source maps are enabled. When I check in Chrome by pressing F12 and browsing to the script, I see the .ts file without the recent function I added, but the .js file does have it. I tried fo ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Working with Three.js: Utilizing the SpotLight and dat.gui

I have implemented a SpotLight in my scene along with an OctahedronGeometry as a visual aid for the user. The SpotLight can be moved using transformControls by selecting it, which is working properly. However, the issue arises when I try to edit the setti ...

Developing a nested data table using Angular and mongoose framework

I'm struggling to display the contents of a nested array field within a mat-table. Below is the code I currently have (stored in employee.component.ts): employee: Employee; usages: Usage[]; dataSource: MatTableDataSource<Usage>; displ ...

Get the HTML file converted to a DOCX format that is compatible with Mac Pages

I am currently working on a Next.js application using TypeScript, and I want to give users the ability to download a page as a DOCX file. Initially, I was excited to discover that this could be easily accomplished by following this method. However, after ...