Functor in TypeScript

How to create a functor in TypeScript?

EDIT:

A functor is a function in the C ++ world that can contain state - basically a class that will override the operator ().

So, for example, I can do the following:

class myClass {
    var value : string;
    // how?
    functor() : string {
        return value;
    }
}



var a = new myClass();
a.value = "abc";
a(); // to return "abc"
+4
source share
5 answers

So, really, what you are here is a method in a class, for example:

class myClass {
    constructor(private text: string) {

    }

    methodName() : string {
         return this.text;
    }
}

var a = new myClass('Example');
a.methodName(); // 'Example'

If you just need a simple function, you can do this too:

function functor(text : string) : string {
     return "abc";
}

functor('text');

The difference between JS-Style Functor and class output

You can try to play a functor, for example:

function functor(text : string) : () => string {
     return function() {
         return text;
     }
}

var x = functor('Example');
x(); // returns 'Example'

But actually using the class gives you very similar:

var myClass = (function () {
    function myClass(text) {
        this.text = text;
    }
    myClass.prototype.methodName = function () {
        return this.text;
    };
    return myClass;
})();
var a = new myClass('Example');
a.methodName(); // 'Example'

With the advantages of class semantics ... you can extend a class, you can create an interface from a class, etc.

+4
source

TypeScript/JavaScript , - .

function makeFunctor(privateText: string) {
    return function (text: string): string {
        return privateText + text;
    };
}

var a = makeFunctor('abc');
var b = a('def');

// Logs "abcdef"
console.log(b);
+3

, , :

namespace c {
    let str = "private";
    export function func(text: string = str) {
        str = text;
        return text;
    }
}

console.log(c.func()); // private
console.log(c.func('new')); // new
console.log(c.func()); // new

: http://basarat.gitbooks.io/typescript/content/docs/project/namespaces.html

+3

, , function TypeScript, functor - , a, a.functor('text');

:

class myClass {
    // how?
    functor(text : string) : string {
    // /how?
         return "abc";
    }
}

var a = new myClass();
a.functor('text'); // to return "abc"

( JavaScript - ) JavaScript ( JS, ' TS)

-1

Any old one functionmay have a fortune.

class MyClass {
  var state = 0;
  function addstate(value: number) {
    state += value;
    return state;
  }
}

var stateholder = new MyClass();

stateholder.addstate(3); //3
stateholder.addstate(3); //6
-1
source

Source: https://habr.com/ru/post/1610422/


All Articles