Compel a customer to invoke a particular function

Is there a way to ensure that the build method is always called by the client at the end of the command chain?

const foo = new Foo();
foo.bar().a() // I need to guarantee that the `build` method is invoked.

Check out the following code snippet:

interface IFoo {
    bar(): IBar;
    build(): string;
}

class Foo {
    public commands;

    constructor() {
        this.commands = []
    }

    public bar(): any {
        return new Bar(this);
    }

    public build(): any {
        return this.commands.join(' ')
    }

}

interface IBar {
    a(): IFoo
}

class Bar {
    private foo: Foo;

    constructor(foo){
        this.foo = foo;
    }

    public a(): IFoo {
        this.foo.commands.push('something')
        return
    }
}

Answer №1

In alignment with the point made by Peter, it is advisable to structure your API in a way that limits its utility to consumers, ensuring it functions according to your specifications:

Explore the functionalities using the TS Playground

class Base {
  protected commands: string[];

  constructor (commands?: string[]) {
   this.commands = commands ?? [];
  }

  public build (): string {
    return this.commands.join(' ');
  }

  private toString (): string {
    return this.build();
  }

  private toJSON (): string[] {
    return this.commands;
 }
}

class Foo extends Base {
  public bar (): Bar {
    return new Bar(this.commands);
  }
 }

 class Bar extends Base {
  public a (): Foo {
    this.commands.push('something');
    return new Foo(this.commands);
  }
}


// Example usage:

const foo = new Foo();
const bar = foo.bar();
const anotherFoo = foo.bar().a();
const command = anotherFoo.build();

anotherFoo.commands; /*
         ^^^^^^^^
This property 'commands' is protected and can only be accessed within the 'Base' class and its subclasses.(2445) */

console.log(command); // "something"
console.log(JSON.stringify(anotherFoo)); // '["something"]'
console.log(String(anotherFoo)); // "something"

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

Waiting for all promises to resolve: A step-by-step guide

I need to make two different API calls and perform calculations based on the results of both. To wait for both promises to resolve, I am using Promise.all(). const getHashTagList = async () => { loader.start(); try { await getAllHashTag ...

After mapping the elements of the array twice, generate a new array

Two differently formatted bits of data may be received, each requiring different character stripping methods. The variable names are temporary and will be changed once the function is operational. const cut = flatten.map(obj => { return obj.file. ...

Consolidate multiple sorting functions into a single function to effectively sort by column

Can someone help me simplify my sorting function for array columns? Currently, I have multiple functions like the one below for each column: sort() { if (this.sortAsc == false) { this.tab.sort((a, b) => { return a.name.localeCompare( ...

Struggling to compile Typescript with mocha using the Visual Studio Code Debugger

I'm currently troubleshooting unit testing using Visual Studio Code and mocha, but I encounter an error when mocha is launched. TSError: ⨯ Unable to compile TypeScript: mfa/test/index.test.ts(4,20): error TS2307: Cannot find module 'assert&ap ...

Prevent event bubbling when clicking

I have a code snippet that I'm struggling with. <p>haha</p> <button class="btn btn-light" onclick="nextSibling.classList.toggle('d-none');"> <i class="fa fa-ellipsis-h"></i> </button> <div class= ...

Create unique names by merging a selection of words

I'm looking to create a feature where users can input 2 or 3 words into text fields, and upon submission, those words will be combined in various ways. It's similar to a business name generator where you enter words and receive potential business ...

AngularJS - issue with directive functionality on dynamically inserted classes

Check out this plnkr - I've got a button that toggles the class toggled on the body element. I've also developed a directive to trigger an alert when the toggled class is applied to the body element, but for some reason it's not working. H ...

What is the best way to link one element to another element?

Apologies for the mismatched title, but here's my issue: I need to create hidden checkboxes for each Polymer's paper-button div in jsp/style related problems. <%int i; %> <form ACTION="Computation.jsp"> <% for(i=0; i<n; ...

FingerprintJS is experiencing an issue with the navigator object not being defined, resulting in

I am currently working on extracting browser fingerprint using fingerprintjs2, an npm package in Javascript. However, I encountered the following error: ReferenceError: navigator is not defined Error Logs: https://i.sstatic.net/lWL9Y.png Code Snippet: ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

The console displays "undefined" when formatting API data

I am attempting to format the data retrieved from an API since there is a lot of unnecessary information. However, when I try to display the formatted data in the console, it always shows as "undefined" or "null." I am importing and calling the fetch API ...

When working with TypeScript, how do you determine the appropriate usage between "let" and "const"?

For TypeScript, under what circumstances would you choose to use "let" versus "const"? ...

In AngularJS expressions, you can compare two dates and use ng-hide based on the comparison

Is it possible to compare two Date strings using Angular JS Expressions? HTML <body ng-controller="app"> <div>{{Today}}</div> <div>{{ItemDate}}</div> <div>{{ItemDate<Today}}</div> </body> ...

Creating a classification for a higher order function

In the code snippet below, I have a controller that acts as a higher order method: const CourseController = { createCourse: ({ CourseService }) => async (httpRequest) => { const course = await CourseService.doCreateCourse(httpRequest. ...

Display HTML using JavaScript/jQuery

I am trying to figure out how to print a document by passing custom HTML code. Below is the code I have tried, but unfortunately it's not working: function Clickheretoprint() { var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes, ...

Exploring the power of QueryTask in ArcGIS JS API 3 for running multiple queries

When using QueryTask in ArcGIS JS Api 3, I encountered a challenge where I needed to execute multiple queries in one call. After referencing the documentation, I realized that this functionality was not directly supported. This is my current implementatio ...

Using knex.js to pipe data to an express server

I'm encountering an issue with knex.js and express. Here is the code snippet in question: userRouter.get('/:userId', function (req, res) { DB('users').where({ id: req.params.userId }).first('name').pipe(res); }); ...

Optimizing Your HTML/CSS/JavaScript Project: Key Strategies for Modular

When it comes to web frontend projects (html/css/javascript), they are often perceived as more complex to read and maintain compared to Java/C#/C/C++ projects. Is it possible to outline some optimal strategies for enhancing the readability, modularizatio ...

Including code that is tailored specifically for the Internet Explorer browser on Windows Phone devices

While testing the Google Maps API on different browsers and devices, I encountered issues with Windows Phone. It turns out that Google Maps is not supported on Windows Phones, resulting in errors. How can I set it up so that instead of displaying the map ...

Issue with Angular 9 application: Unable to properly render form fields within a Material Design Dialog

I'm currently developing a "Tasks" application using Angular 9 and PHP. I've encountered an error that says Cannot find control with name: <control name> when attempting to pre-fill the update form with data. Here is the form template: &l ...