Skip to content

Instantly share code, notes, and snippets.

@ahmedazhar05
Last active December 28, 2023 09:43
Show Gist options
  • Save ahmedazhar05/ef7db926fd587296939d29a3d9712d5c to your computer and use it in GitHub Desktop.
Save ahmedazhar05/ef7db926fd587296939d29a3d9712d5c to your computer and use it in GitHub Desktop.
recreating conceptual-functions of- the functional programming paradigm
/*
Function Composition
*/
const compose_rtl = (...functions: ((..._: any[]) => any)[]) => {
const [first, ...rest] = functions;
if(!first) return (...argv) => argv;
return (...args) => first.apply(null, rest.length > 0 ? [compose_rtl(...rest)(...args)] : args);
}
const compose = (...functions: ((..._: any[]) => any)[]) => {
// const last = functions.slice(-1)[0];
// const rest = functions.slice(0, -1);
const [last, ...rest] = functions.slice(0).reverse();
rest.reverse(); // mutation takes place but to a local variable which shouldn't be harmful
if(!last) return (...argv) => argv;
return (...args) => last.apply(null, rest.length > 0 ? [compose(...rest)(...args)] : args);
}
/*
Partial Application
*/
const partial = (fn, ...args) => (...more_args) => fn(...args, ...more_args);
const increment: (x: number) => number = x => {console.log(`increment: inputs=${x};output=${x+1}`); return x + 1};
const decrement: (x: number) => number = x => {console.log(`decrement: inputs=${x};output=${x-1}`); return x - 1};
const double : (x: number) => number = x => {console.log(`double: inputs=${x};output=${x*2}`); return x * 2};
const sum : (x: number, y: number) => number = (x, y) => {console.log(`sum: inputs=${x},${y};output=${x+y}`); return x + y};
const square : (x: number) => number = x => {console.log(`square: inputs=${x};output=${x*x}`); return x * x};
const cube : (x: number) => number = x => {console.log(`cube: inputs=${x};output=${x*x*x}`); return x * x * x};
const stringify: (x: number) => string = x => {console.log(`stringify: inputs=${x};output="${x}"`); return `${x}`};
const add_10 = partial(sum, 10);
const pipeline_rtl = compose_rtl(stringify, cube, decrement, double, increment, add_10);
const pipeline = compose(add_10, increment, double, decrement, cube, stringify);
console.log(pipeline_rtl(5));
console.log(pipeline(5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment