POV
POV

Reputation: 12015

How return two functions in TypeScript as result?

I have the following function:

public exist(index: number, type: string): boolean {
    return this.forms.filter(form => form.index == index + 1 && form.type == type).length > 0;
  }

This function returns true/false if element exists in array of objects.

How to return two functions instead boolean:_exist() {}, and form() to use this like:

const e = this.exist(1, 'formLogin');
if (e._exist()) {
    console.log(e.form());
}

It means if this.forms.filter return true I can get access to e.form()

I think I need to use closure

I tried to do this:

public exist(index: number, type: string) {

    const lookForm = this.forms.filter(form => form.index == index + 1 && form.type == type);
    const lookFormExist = form.length > 0;

    function form() {
       return lookForm.shift();
    }

    return lookFormExist;
  }

Upvotes: 0

Views: 383

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074666

Just return an object with the functions on it.

Separately: filter(...).length > 0 is never the right way to just check for the presence of something in an array. Use indexOf if it's an === check, or some if you need to use a callback as in your case. But in this case, it seems like you want to use the form, in which case you'd use find:

public exist(index: number, type: string): ExistResult {
  const form = this.forms.find(form => form.index == index + 1 && form.type == type);
  return {_exist() { return !!form; }, form() { return form; }} as ExistResult;
}

...where ExistResult is a type you'd define for this.

However, I wouldn't do that. I'd just return the result of find, and either use the form, or branch if the result was falsy. I'd probably also change the name of the function.

public findForm(index: number, type: string): Form {
  return this.forms.find(form => form.index == index + 1 && form.type == type);
}

then

const form : Form = this.findForm(1, 'formLogin');
if (form) {
    console.log(form);
}

Upvotes: 2

Related Questions