Multiple arguments composible function implementation using reduceRight() - javascript

I am trying to re-implement function composition using reduceRight. Here is a function composition that I am trying to re-implement:
const compose = function([func1, func2, func3]) {
return function(value1, value2) {
return func1(func2(func3(value1, value2)));
};
};
const func3 = (x, y) => {
return y > 0 ? x + 3 : x - 3;
};
const func2 = x => {
return x ** 2;
};
const func1 = x => {
return x - 8;
};
const fn = compose([func1, func2, func3]);
console.log(fn('3', 1)); // 1081
console.log(fn('3', -1)); // -8
The following code is re-implementation of the above function. It looks like the argument y is getting undefined I am not sure why.
const compose = (...args) => value =>
args.reduceRight((acc, fn) => fn(acc), value);
const func3 = (x, y) => {
return y > 0 ? x + 3 : x - 3;
};
const func2 = x => {
return x ** 2;
};
const func1 = x => {
return x - 8;
};
const fnOne = compose(
func1,
func2,
func3
)('3', 1);
console.log(fnOne);//-8
const fnTwo = compose(
func1,
func2,
func3
)('3', -1);
console.log(fnTwo);//-8

Similar to compose, you could use rest parameter syntax get an an array of values. Then destructure the func3 arguments to get x and y like this:
const compose = (...args) => (...values) =>
args.reduceRight((acc, fn) => fn(acc), values);
// an array of values is passed here
// destructure to get the x and y values
const func3 = ([x, y]) => y > 0 ? x + 3 : x - 3;
const func2 = x => x ** 2;
const func1 = x => x - 8;
const fnOne = compose(
func1,
func2,
func3
)('3', 1);
console.log(fnOne);//1081
const fnTwo = compose(
func1,
func2,
func3
)('3', -1);
console.log(fnTwo);//-8

Related

How to create a composition from functions

I have 5 functions: func1(), func2(), func3(), func4(), func5(). I need to implement the compositionFunc() function, which can take any number of functions as arguments, and create a composition from them. The compositionFunc() function takes my 5 functions as arguments. The compositionFunc() function returns a function that takes its initial value as an argument. This nested function successively passing through an array of functions with each iteration returns the result of calling the accumulated value of the current function-argument. The result of one function can be passed as an argument to another function. How can i do this?
const func1 = (arg1) => {
return arg1;
};
const func2 = (arg2) => {
return arg2;
};
const func3 = (arg3) => {
return arg3;
};
const func4 = (arg4) => {
return arg4;
};
const func5 = (arg5) => {
return arg5;
};
const compositionFunc = () => {
...
};
you can define a function like this
const pipe = (...functions) => args => functions.reduce((res, f) => f(res), args)
const combine = (...functions) => args => functions.reduceRight((res, f) => f(res), args)
const plus1 = x => x + 1
const double = x => x * 2
const pipeFunction = pipe(plus1, double)
const combineFunction = combine(plus1, double)
console.log(combineFunction(1)) // (1 * 2) + 1
console.log(pipeFunction(1)) // (1 + 1) * 2
A simple reduce can accomplish that:
function pipe(input, ...func) {
return func.reduce((a, f) => f(a), input);
}
You pass it an initial value + chain of functions.
Example:
function f1(val) {
return val + 1;
}
function f2(val) {
return val * 10;
}
console.log(pipe(2, f1, f2)); //=> 30

How to implement function composition in JavaScript?

Below are three functions that need to be composed and give us the output 30:
const add = (a) => a + 10;
const mul = (a) => a * 10;
const divide = (a) => a / 5;
// How to implement `compositionFunction`?
compositionFunction(add, mul, divide)(5);
//=> 30
Expected output is 30 because:
5 + 10 = 15
15 * 10 = 150
150 / 5 = 30
Something like this
const add = (a) => a + 10 ;
const mul = (a) => a * 10 ;
const divide = (a) => a / 5 ;
// How to use this function -----
const customComposeFn = (...f) => v => f.reduce((res, f) => f(res), v)
console.log(customComposeFn(add, mul, divide)(5));
There are two flavours of function composition:
left-to-right function composition aka pipe
right-to-left function composition aka compose
Here's a recursive implementation just for fun:
This assumes that there are at least two functions to compose
const compose = (...fn) => {
const [[f, g], x] = [fn.slice(-2), fn.slice(0, -2)];
const h = a => f(g(a));
return x.length ? compose(...x, h) : h;
}
const pipe = (...fn) => {
const [f, g, ...x] = fn;
const h = a => g(f(a));
return x.length ? pipe(h, ...x) : h;
}
Let's try:
const foo = x => x + 'foo';
const bar = x => x + 'bar';
const baz = x => x + 'baz';
pipe(foo, bar, baz)('');
//=> 'foobarbaz'
compose(foo, bar, baz)('');
//=> 'bazbarfoo'
const add = (a) => a + 10;
const mul = (a) => a * 10;
const divide = (a) => a / 5;
const customComposeFn = (...fn) => {
return function (arg) {
if (fn.length > 0) {
const output = fn[0](arg);
return customComposeFn(...fn.splice(1))(output);
} else {
return arg;
}
};
};
const res = customComposeFn(add, mul, divide)(5);
console.log(`res`, res);
Here's what I would do:
function customComposeFn(...funcs) {
return function(arg) {
let f, res = arg;
while (f = funcs.shift()) {
res = f(res)
}
return res;
}
}
const add = a => a + 10;
const mul = a => a * 10;
const divide = a => a / 5;
// How to use this function -----
console.log(customComposeFn(add, mul, divide)(5));

How does reduce work in this scenario?

I was looking into pipe functions and I came across this reduce function which takes the _pipe function as the parameter. The _pipe function has two params a,b and then returns another function.
How does reduce work here?
add3 = x => x + 3;
add5 = x => x + 5;
const _pipe = (a, b) => (arg) => b(a(arg))
const pipe = (...ops) => ops.reduce(_pipe)
const add = pipe(add3, add5)
add(10)
output
18
look at pipe function definition:
const pipe = (...ops) => ops.reduce(_pipe)
It receives array of functions called ops (this is called rest params).
Then we call reduce for ops array. Reducer function has 2 params: accumulator and current value.
Here is our _pipe written with human readable variables:
const _pipe = (accumulator, currentValue) => (arg) => currentValue(accumulator(arg));
So the result of _pipe will be curried functions from ops array.
If it's [add3, add5] then result will be (arg) => add3(add5(arg))
If it's [add3, add5, add2] then result is: (arg) => add2(accumulator(arg)) where accumulator is (arg) => add3(add5(arg)).
You simply compose all functions from array using reduce. Then pass initial value which is 10.
It's like: add3(add5(10)) = 18
the reduce function is equivalent to
add3 = x => x + 3;
add5 = x => x + 5;
const _pipe = (a, b) => (arg) => b(a(arg))
const pipe = (...ops) => {
// create a base function
let sum = x => x;
// for every operation
for (let op of ops) {
// call _pipe with sum and it
// equivalent to sum = x => sum(op(x))
sum = _pipe(sum, op)
}
// return the resulting function
return x => sum(x)
}
const add = pipe(add3, add5)
console.log(add(10))

Define function properties before function

I have an object foo that I want to call as a function foo(...). I can do that like this:
foo = n => n * foo.factor;
foo.factor = 2;
foo(2) // returns 4
But for this to work I need to write the function (n => n * foo.factor) before other properties. How can I write it after? I want to do something like this:
foo = { factor: 2 }
// write function
foo(2) // returns 4
Maybe use a small utility:
const functionize = (obj, fn) => Object.assign(fn, obj);
So one can do:
let foo = { factor: 2 };
foo = functionize(foo, n => n * foo.factor);
foo(2);
Or you just use a regular function:
foo.factor = 2;
function foo(n) { return foo.factor * n; }
I wish there was a way to define my object as a function and then later change its body...
const foo = (...args) => (foo.body || () => null)(...args);
foo.factor = 2;
foo.body = n => foo.factor * n;
foo(2);
You could do it with a simple helper:
const annotate = (f, annotations) => {
Object.assign(f, annotations);
return f;
};
...which you'd use like this:
foo = annotate(n => n * foo.factor, {factor: 2});
foo(2); // returns 4
But I wouldn't. Instead, I'd create a function builder:
const makeFoo = factor => n => n * factor;
and then:
const foo = makeFoo(2);
foo(2); // returns 4
Live example:
const makeFoo = factor => n => n * factor;
const foo2 = makeFoo(2);
console.log(foo2(2)); // returns 4
const foo4 = makeFoo(4);
console.log(foo4(2)); // returns 8

Mapping a function on a generator in JavaScript

I have a generator called generateNumbers in JavaScript and another generator generateLargerNumbers which takes each value generated by generateNumbers and applies a function addOne to it, as such:
function addOne(value) {
return value + 1
}
function* generateNumbers() {
yield 1
yield 2
yield 3
}
function* generateLargerNumbers() {
for (const number of generateNumbers()) {
yield addOne(number)
}
}
Is there any terser way to do this without building an array out of the generated values? I'm thinking something like:
function* generateLargerNumbers() {
yield* generateNumbers().map(addOne) // obviously doesn't work
}
higher-order generators
You can choose to manipulate the generator functions themselves
const Generator =
{
map: (f,g) => function* (...args)
{
for (const x of g (...args))
yield f (x)
},
filter: (f,g) => function* (...args)
{
for (const x of g (...args))
if (f (x))
yield x
}
}
// some functions !
const square = x =>
x * x
const isEven = x =>
(x & 1) === 0
// a generator !
const range = function* (x = 0, y = 1)
{
while (x < y)
yield x++
}
// higher order generator !
for (const x of Generator.map (square, Generator.filter (isEven, range)) (0,10))
console.log('evens squared', x)
higher-order iterators
Or you can choose to manipulate iterators
const Iterator =
{
map: (f, it) => function* ()
{
for (const x of it)
yield f (x)
} (),
filter: (f, it) => function* ()
{
for (const x of it)
if (f (x))
yield x
} ()
}
// some functions !
const square = x =>
x * x
const isEven = x =>
(x & 1) === 0
// a generator !
const range = function* (x = 0, y = 1)
{
while (x < y)
yield x++
}
// higher-order iterators !
for (const x of Iterator.map (square, Iterator.filter (isEven, range (0, 10))))
console.log('evens squared', x)
recommendation
In most cases, I think it's more practical to manipulate the iterator because of it's well-defined (albeit kludgy) interface. It allows you to do something like
Iterator.map (square, Iterator.filter (isEven, [10,11,12,13]))
Whereas the other approach is
Generator.map (square, Generator.filter (isEven, Array.from)) ([10,11,12,13])
Both have a use-case, but I find the former much nicer than the latter
persistent iterators
JavaScript's stateful iterators annoy me – each subsequent call to .next alters the internal state irreversibly.
But! there's nothing stopping you from making your own iterators tho and then creating an adapter to plug into JavaScript's stack-safe generator mechanism
If this interests you, you might like some of the other accompanying examples found here: Loop to a filesystem structure in my object to get all the files
The only gain isn't that we can reuse a persistent iterator, it's that with this implementation, subsequent reads are even faster than the first because of memoisation – score: JavaScript 0, Persistent Iterators 2
// -------------------------------------------------------------------
const Memo = (f, memo) => () =>
memo === undefined
? (memo = f (), memo)
: memo
// -------------------------------------------------------------------
const Yield = (value, next = Return) =>
({ done: false, value, next: Memo (next) })
const Return = value =>
({ done: true, value })
// -------------------------------------------------------------------
const MappedIterator = (f, it = Return ()) =>
it.done
? Return ()
: Yield (f (it.value), () => MappedIterator (f, it.next ()))
const FilteredIterator = (f, it = Return ()) =>
it.done
? Return ()
: f (it.value)
? Yield (it.value, () => FilteredIterator (f, it.next ()))
: FilteredIterator (f, it.next ())
// -------------------------------------------------------------------
const Generator = function* (it = Return ())
{
while (it.done === false)
(yield it.value, it = it.next ())
return it.value
}
// -------------------------------------------------------------------
const Range = (x = 0, y = 1) =>
x < y
? Yield (x, () => Range (x + 1, y))
: Return ()
const square = x =>
x * x
const isEven = x =>
(x & 1) === 0
// -------------------------------------------------------------------
for (const x of Generator (MappedIterator (square, FilteredIterator (isEven, Range (0,10)))))
console.log ('evens squared', x)
There isn't a built-in way to map over Generator objects, but you could roll your own function:
const Generator = Object.getPrototypeOf(function* () {});
Generator.prototype.map = function* (mapper, thisArg) {
for (const val of this) {
yield mapper.call(thisArg, val);
}
};
Now you can do:
function generateLargerNumbers() {
return generateNumbers().map(addOne);
}
const Generator = Object.getPrototypeOf(function* () {});
Generator.prototype.map = function* (mapper, thisArg) {
for (const val of this) {
yield mapper.call(thisArg, val);
}
};
function addOne(value) {
return value + 1
}
function* generateNumbers() {
yield 1
yield 2
yield 3
}
function generateLargerNumbers() {
return generateNumbers().map(addOne)
}
console.log(...generateLargerNumbers())
How about composing an iterator object, instead of using the nested generators?
function* generateNumbers(){
yield 1;
yield 2;
yield 3;
}
function generateGreaterNumbers(){
return { next(){ var r = this.gen.next(); r.value+=1; return r; }, gen: generateNumbers() };`
}
If you need to actually pass values to your generator then you can't do it with for...of, you have to pass each value through
const mapGenerator = (generatorFunc, mapper) =>
function*(...args) {
let gen = generatorFunc(...args),
i = 0,
value;
while (true) {
const it = gen.next(value);
if (it.done) return mapper(it.value, i);
value = yield mapper(it.value, i);
i++;
}
};
function* generator() {
console.log('generator received', yield 1);
console.log('generator received', yield 2);
console.log('generator received', yield 3);
return 4;
}
const mapGenerator = (generatorFunc, mapper) =>
function*(...args) {
let gen = generatorFunc(...args),
i = 0,
value;
while (true) {
const it = gen.next(value);
if (it.done) return mapper(it.value, i);
value = yield mapper(it.value, i);
i++;
}
};
const otherGenerator = mapGenerator(generator, x => x + 1)
const it = otherGenerator();
console.log(
it.next().value,
it.next('a').value,
it.next('b').value,
it.next('c').value
);

Categories