Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currying function constructor

I'd like to know if it is possible to achieve this in javascript:

function Hello() { }

Hello.prototype.echo = function echo() {
  return 'Hello ' + this.firstname + '!';
};

// execute the curryed new function
console.log(new Hello()('firstname').echo())

Is it possible to curry var o = new Class()(param1)(param2)(...) ?

Thank you in advance for your help.

like image 751
Alphapage Avatar asked May 16 '26 18:05

Alphapage


2 Answers

Using the answer of georg with an array of the properties and a counter for assigning an arbitrary count of properties.

function Hello() {
    var args = ['firstname', 'lastname'],
        counter = 0,
        self = function (val) {
            self[args[counter++]] = val;
            return self;
        };
    Object.setPrototypeOf(self, Hello.prototype);
    return self;
}

Hello.prototype.echo = function echo() {
    return 'Hello ' + this.firstname + ' ' + (this.lastname || '') + '!';
};

console.log(new Hello()('Bob').echo());
console.log(new Hello()('Marie')('Curie').echo());
like image 167
Nina Scholz Avatar answered May 18 '26 08:05

Nina Scholz


For example:

function Hello() {
    let self = function (key, val) {
        self[key] = val;
        return self;
    };
    Object.setPrototypeOf(self, Hello.prototype);
    return self;
}

Hello.prototype.echo = function echo() {
    return 'Hello ' + this.firstname + this.punct;
};

console.log(new Hello()('firstname', 'Bob')('punct', '...').echo())
like image 27
georg Avatar answered May 18 '26 08:05

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!