-
Moving from
vs.
The latter feels less natural (chaining is basically equivalent to "and then ...") Is there a way to use this library the first way? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
You need a monolithic class or object for the chaining pattern to work, and that's counter to the With that said, you might enjoy the functional variant of the library. You can get pretty close to chaining when used alongside lodash's import { addMonths, addMinutes } from "date-fns/fp";
import flow from "lodash.flow";
// example of how you can incorporate your own functions
const customAddHours = (hours) => (date) => {
const d = new Date(date.getTime());
d.setHours(d.getHours() + hours);
return d;
};
const res = flow(
addMonths(2),
addMinutes(20),
customAddHours(7)
)(new Date(2021, 11, 5));
console.log(res.toString()); // Sat Feb 05 2022 07:20:00 GMT-0500 (Eastern Standard Time) |
Beta Was this translation helpful? Give feedback.
-
So... you should almost certainly not use this (read my other answer instead), but you can kinda make a chaining API using JS proxies and the functional package. The following piece of code is not type friendly, will almost certainly break tree-shaking, and won't work in IE 11 (although there might be polyfills around these days). Don't take it too seriously, but I figured it was interesting enough to share as a fun hack. import * as FP from "date-fns/fp";
function dateFnsChain(...args) {
let results = args;
const handler = {
get(target, name) {
return (...args) => {
if (name === "value") return results[0];
results = [target[name].apply(this, [...args, ...results])];
return new Proxy(FP, handler);
};
}
};
return new Proxy(FP, handler);
}
const res = dateFnsChain(new Date(2021, 0, 1))
.addMinutes(10)
.addMonths(2)
.value();
console.log(res.toString()); // Mon Mar 01 2021 00:10:00 GMT-0500 (Eastern Standard Time) |
Beta Was this translation helpful? Give feedback.
You need a monolithic class or object for the chaining pattern to work, and that's counter to the
date-fns
architecture. Every function is an isolated module, which allows tree shaking and smaller bundle sizes (scroll down to the "exports analysis" section to see the size of each function: https://bundlephobia.com/package/date-fns).With that said, you might enjoy the functional variant of the library. You can get pretty close to chaining when used alongside lodash's
flow
function. Keep in mind that the output of each step is sent as input of the next. https://date-fns.org/docs/fp/FP-Guide