Reputation: 3451
I have the following code with getOffsetCustom depending on getCursor. I can get to both getOffsetCustom and getCursor as exports, but can't figure out how to have the getCursor inside of getOffsetCustom.
I'm using this file for run node without and build system. Is this the best way to expose utility functions?
module.exports = {
getCursor: (rec) => Buffer.from(rec.toString()).toString("base64"),
getOffsetCustom: (data, afterCursor) => {
const offsetBasedOnFind = data.findIndex(
(rec) => getCursor(rec.id) === afterCursor
);
return offsetBasedOnFind === -1 ? 0 : offsetBasedOnFind + 1;
},
};
Upvotes: 0
Views: 859
Reputation: 664538
Three approaches:
Just reference module.exports
:
module.exports = {
getCursor: (rec) => Buffer.from(rec.toString()).toString("base64"),
getOffsetCustom: (data, afterCursor) => {
const offsetBasedOnFind = data.findIndex(rec =>
module.exports.getCursor(rec.id) === afterCursor
// ^^^^^^^^^^^^^^^
);
return offsetBasedOnFind === -1 ? 0 : offsetBasedOnFind + 1;
},
};
Use methods (instead of arrow functions) and this
:
module.exports = {
getCursor(rec) {
return Buffer.from(rec.toString()).toString("base64");
},
getOffsetCustom (data, afterCursor) {
const offsetBasedOnFind = data.findIndex(rec =>
this.getCursor(rec.id) === afterCursor
// ^^^^^
);
return offsetBasedOnFind === -1 ? 0 : offsetBasedOnFind + 1;
},
};
This requires that the method are always called on the module object though, so for example you can't use destructuring on the import.
Declare normal functions, then export them. This would be the preferred approach:
function getCursor(rec) {
return Buffer.from(rec.toString()).toString("base64");
}
function getOffsetCustom (data, afterCursor) {
const offsetBasedOnFind = data.findIndex(rec =>
getCursor(rec.id) === afterCursor
);
return offsetBasedOnFind === -1 ? 0 : offsetBasedOnFind + 1;
}
Object.assign(exports, {
getCursor,
getOffsetCustom,
});
The only drawback (or advantage?) here is that the exports cannot be hotpatched/mocked from the outside, getOffsetCustom
will always refer to the local getCursor
.
Upvotes: 1