Developing dynamic-sized tuples in TypeScript

Recently, I was attempting to develop a zipper for arrays. For instance, if the user inputs 3 arrays with sizes of 3, 5, and 12, the output array of tuples would be the size of the largest array. The output consists of tuples containing elements at a specified index, with null appearing if there is no index.

I experimented with a generic approach to enhance its usability.

So, I implemented a utility static function:

public static zip<T>(arrays : T[][]) : () => [dynamic tuple here somehow of types T][] {

However, I encountered an issue right from the start - how can I define a function that returns an array of tuples of dynamic size? Is this even feasible? As the TypeScript documentation lacks such an example, I suspect my code may not function correctly, requiring me to implement workarounds like returning 'any'.

Answer №1

Here is the solution you've been looking for:

class NewDemo {
    public static mergeArrays<T>(arrays: Array<Array<T>>): Array<[string, Array<T>]> {

        let maxLength = NewDemo.getMaxArrayLength(arrays);
        let mergedArray: Array<[string, Array<T>]> = [];

        arrays.forEach(arr => {
            for (let i = 0; i < maxLength; i++) {
                if (!mergedArray[i])
                    mergedArray[i] = [`SubArray${i}`, []];

                let element = arr.length > i ? arr[i] : null;
                mergedArray[i][1].push(element);
            }
        });

        return mergedArray;
    }

    private static getMaxArrayLength(arrays: Array<Array<any>>): number {

        let lengths: Array<number> = []
        for (let i = 0; i < arrays.length; i++)
            lengths.push(arrays[i].length);

        return Math.max(...lengths);
    }
}

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

TS7030: In Angular13, ensure that all code paths within the guard and canActivate methods return a value

Having trouble using guards for an unlogged user and constantly facing errors. Error: TS7030 - Not all code paths return a value. Below is my auth.guard.ts file: import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from &a ...

After selecting an item, the Next UI navbar menu seems to have trouble closing

Having trouble with the navbar menu component not closing when an option is selected from the menu. The menu does open and close successfully within the menu icon. I attempted to use onPress() but it doesn't seem to be working as expected. "use c ...

Circular dependency has been detected when using the ESLint with TypeORM

Having two entity typeorm with a bi-directional one-to-one relationship: Departament: @Entity('Departament') export default class Departament { @PrimaryGeneratedColumn() id: string; @Column() departament_name: string; @OneToOne(type ...

Steps to apply a decorator to a function that is not a nestjs route

NestJS Hello there! I am currently facing an issue where I need to apply a decorator to a function that is not serving as an endpoint or route. To illustrate, here is what I have in mind: class Controller { @Get('/') firstMethod() { ...

Is it possible for Typescript to automatically infer object keys based on the value of a previous argument?

Currently, my goal is to create a translation service that includes type checking for both tags and their corresponding placeholders. I have a TagList object that outlines the available tags along with a list of required placeholders for each translated st ...

methods for array filtering in typescript

How do I filter an array in TypeScript? I attempted the following findAllPersonsNotVisited():Observable<Person[]> { var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,"-"); return this.db.list(& ...

The proper way to validate JSON data

After making an API call, I received the following response: [{ "1": { "name": "Euro", "iso": "EUR", "sign": "€" }, "2": { "name": "Dollar", "iso": "USD", "sign": "$" }, "3": { ...

Is there a way to enable code completion for Firebase on VS Code?

After successfully setting up Typescript for code completion following the guidelines provided in this resource, I now want to enable code completion for Firebase in VS Code. However, I am unsure of the steps to achieve this. How can I activate code compl ...

The type of link component that is passed in as the 'component' prop

I have created a custom Button Function Component in TypeScript using Material-UI as the base. After styling and adding features, I exported it as my own Button. Now, when I try to use this Button component in conjunction with the Link component from react ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Transforming objects into nested structures

After making a JSON call, I received the following JSON Object: [ { "feeding_id": 14, "supp_name": "Test 1", "supp_weight": 20000, }, { "feeding_id": 14, "supp_name": "Test 2", "supp_weight": 100 ...

Trouble with Jest when trying to use route alias in Next.js with Typescript

Currently, I am developing a Next.js App (v13.2.3) using Typescript and have set up a path alias in the tsconfig.json. Does anyone know how I can configure the jest environment to recognize this path alias? // tsconfig.json { "compilerOptions": ...

Tips for dynamically loading a child component and passing data from the child component to the parent component

In my current setup, I have organized the components in such a way that a component named landing-home.component loads another component called client-registration-form.component using ViewContainerRef within an <ng-template>, and this rendering occu ...

Tips on how to dynamically uncheck and check the Nebular checkbox post-rendering

I incorporated a nebular theme checkbox into my Angular 8 App. <nb-checkbox [checked]="enable_checked" (checkedChange)="enable($event)">Enable</nb-checkbox> I am able to update the checkbox using the Boolean variable "enable_checked". Initia ...

Most effective methods for validating API data

Currently, I am working on developing an api using nestjs. However, I am facing some confusion when it comes to data validation due to the plethora of options available. For instance, should I validate data at the route level using schema validation (like ...

Traverse through a collection of objects

I am facing a challenge with an array of objects (~650) structured like this: [1: {firstName: "Hello", lastName: "World", shortName: "h.world", ...some other items }, 2: {firstName: "John", lastName: "Doe", shortName: "j.doe", ...some other items }] ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

An issue has occurred with the NullInjector, specifically regarding the AppModule and Storage in Ionic 4

When attempting to launch my Ionic app using npm start, an error message appears stating "NullInjectorError: No provider for Storage!". I have already included Storage in the app.module.ts file as shown below: imports: \[ BrowserModule, IonicModule ...

The React table column definition inexplicably transforms into a string

When working with react-table in Typescript, I encountered an issue while defining the type for my columns within a custom hook. It seems that when importing the hook and passing the columns to my Table component, they are being interpreted as strings inst ...

Error: Unable to execute function abc, it is not defined as a function in this context

Having trouble with a fronted or JavaScript issue where it can't find the defined function in the file. I'm working on integrating Apple Pay and need to call the back-end API based on a specific event. Here is my code. ACC.payDirect = { _autoload ...