Dennis Bauszus
Dennis Bauszus

Reputation: 1792

Function Composition: Augmenting an existing function with additional function in Javascript

I import a library with a function and would like to replace that function with a function that takes the original function as an argument together with an additional function.

The original function might be logThis:

function logThis() {console.log('this'));

I can create a new function which executes logThis and then logs 'that';

function logThisThenThat() {
  logThis();
  console.log('that');
}

I would like to replace logThis with a new function which executes the original function and thereafter another function? Is this possible with function composition or will I have to create a new function with a different name which is made up of the original function and additional functions.

Something along the lines of:

logThis = compose(logThis, logThat);

Upvotes: 1

Views: 115

Answers (3)

manuerumx
manuerumx

Reputation: 1250

You can create a function like this.

function logThis() {
	console.log("this");
}

function logThat() {
	console.log("that");
}

let compose = (...func) => ()=> {
	let functions = func;
	functions.forEach((fn) => fn());
}

logThis = compose(logThis, logThat);
logThis();

Adding (...func) as parameters, you can execute 3, 4 any amount of functions you like/need.

Note: Edit the snippet to match the question. The selected answer by @mark-meyer is correct.

Upvotes: 1

Mark
Mark

Reputation: 92440

If you pass logThis() into your compose() function, you will hold a reference to it in the closure, so it will live on when you make a new logThis(). The name isn't really that important so long as you rename in an order that lets you get the reference to the old logThis() before you point the name at a new function. For example, the right side of logThis = compose(logThis, logThat) runs before the name assignment below, so you capture the function reference before reassigning the name:

function logThis() {console.log('this')};
function logThat() {console.log('that')};

let compose = (f1, f2) => () => {
    f1()
    f2()
}

logThis = compose(logThis, logThat)
logThis()

Upvotes: 1

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

You can override the existing function with a new one.

Keep a copy of the original like this...

_logThis = logThis;

...and then make your new version call the original one...

function logThis() {
    _logThis();
    // your other function call or new code goes here
}

This isn't a particularly good idea though, since that will modify what happens for every single existing call to that method. This needs to be handled with care.

Also, scope is a big factor here. This is a basic example of what you're trying to do.

Upvotes: 1

Related Questions