Skip to content

Instantly share code, notes, and snippets.

@getify
Last active June 30, 2022 16:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/a3ab66af16531b757a791127adb1e844 to your computer and use it in GitHub Desktop.
Save getify/a3ab66af16531b757a791127adb1e844 to your computer and use it in GitHub Desktop.
fun little experiment... a point-free definition for "copySession()" (essentially a shallow object copy)
// function copySession(sess) {
// return { ...sess };
// }
var copySession = compose(
reduce(
compose(
flip,
binary,
uncurry,
apply,
partial,
)(setProp)
)({}),
Object.entries
);
var s1 = { x: 1, y: 2 };
var s2 = copySession(s1);
s1.z = 3;
s2.w = 4;
s1; // { x: 1, y: 2, z: 3 }
s2; // { x: 1, y: 2, w: 4 }
// But now, this is hawt!
var copySession = compose(
Object.fromEntries,
Object.entries
);
var s1 = { x: 1, y: 2 };
var s2 = copySession(s1);
s1.z = 3;
s2.w = 4;
s1; // { x: 1, y: 2, z: 3 }
s2; // { x: 1, y: 2, w: 4 }
// standard FP utilities
function apply(fn) {
return function appliedFn(args){
return fn( ...args );
};
}
function binary(fn) {
return function onlyTwo(arg1,arg2) {
return fn(arg1,arg2);
};
}
function flip(fn) {
return function flipped(arg1,arg2,...rest) {
return fn(arg2,arg1,...rest);
};
}
function reduce(reducer) {
return function withInitial(initialVal){
return function overArr(arr){
return arr.reduce(reducer,initialVal);
};
};
}
function setProp(name,val,obj) {
var o = Object.assign( {}, obj );
o[name] = val;
return o;
}
function uncurry(fn) {
return function uncurried(...args){
var ret = fn;
for (let i = 0; i < args.length; i++) {
ret = ret( args[i] );
}
return ret;
};
}
function partial(fn) {
return function collectArgs(...presetArgs) {
return function partiallyApplied(...laterArgs){
return fn( ...presetArgs, ...laterArgs );
};
};
}
function compose(...fns) {
return fns.reduceRight( function reducer(fn1,fn2){
return function composed(...args){
return fn2( fn1( ...args ) );
};
} );
}
@JeremyRH
Copy link

This is great. I was going to ask why you wouldn't just Object.assign.bind(null, {}) but realized that will use the same object instance for consecutive calls.
I came up with a solution that uses Object.assign and the Object constructor. Pretty fun experiment.

var copySession = uncurry(
    compose(
        partial(Object.assign),
        Object
    )
)
.bind(null, undefined);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment