Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic function?

I'm trying to figure out the answer to this question:

Without using Javascript's bind function, implement the magic function so that:

var add = function(a, b) { return a + b; }
var addTo = add.magic(2);

var say = function(something) { return something; }
var welcome = say.magic('Hi, how are you?');

addTo(5) == 7;
welcome() == 'Hi, how are you?';

I think I need to use call or apply but I just don't know, if someone could point me in the right direction or provide some literature it would be much appreciated.

like image 374
user2755996 Avatar asked Apr 09 '26 10:04

user2755996


2 Answers

You can use closure, and apply function

Function.prototype.magic = function(){
  var self = this;
  var args = Array.from(arguments);
  
  return function(){
    return self.apply(null, args.concat(Array.from(arguments)));
  }
}


var add = function(a, b) { return a + b; }
var addTo = add.magic(2);

var say = function(something) { return something; }
var welcome = say.magic('Hi, how are you?');

console.log(addTo(5) == 7);
console.log(welcome() == 'Hi, how are you?');

Also you can look to Polyfill for bind function on MDN
like image 172
Grundy Avatar answered Apr 12 '26 00:04

Grundy


Please see below code:

    Object.prototype.magic = function (message) {
        alert(message);
    }
    var add = function (a, b) { return a + b; }
    var addTo = add.magic(2);

    var say = function (something) { return something; }
    var welcome = say.magic('Hi, how are you?');

    addTo(5) == 7;
    welcome() == 'Hi, how are you?';
like image 24
rishikesh tadaka Avatar answered Apr 11 '26 23:04

rishikesh tadaka



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!