feat(): Add higher-order fn to decorate other fns for extended logging

This commit is contained in:
Chris Daßler 2024-06-29 12:20:57 +02:00
parent 94cc6816d5
commit e77fab3b84
2 changed files with 42 additions and 15 deletions

45
pm
View File

@ -2,7 +2,6 @@
const This = require('./this');
const { Command } = require('commander');
const program = new Command();
// Example of subcommands which are implemented as stand-alone executable files.
//
@ -14,6 +13,16 @@ class Pm extends This {
constructor() {
super();
this.version = '0.0.1';
this.description = 'Fake package manager';
// implement commander abilities
this.program = new Command().name(this.scriptName).version(this.version).description(this.description);
}
// override This.discovery()
discovery() {
const methods = this.listMethods();
return methods;
}
start() {
@ -23,20 +32,24 @@ class Pm extends This {
// Properties of ExampleClass: [ 'propertyOne', 'propertyTwo', 'version' ] and Version: 1.1.0
// pm.discovery();
program
.name(this.scriptName)
.version('0.0.1')
.description('Fake package manager')
.command('install [name]', 'install one or more packages')
.alias('i')
.command('search [query]', 'search with optional query')
.alias('s')
.command('update', 'update installed packages', {
executableFile: 'myUpdateSubCommand',
})
.command('list', 'list packages installed', {isDefault: false});
// this.program
// .name(this.scriptName)
// .version('0.0.1')
// .description('Fake package manager')
// .command('install [name]', 'install one or more packages')
// .alias('i')
// .command('search [query]', 'search with optional query')
// .alias('s')
// .command('update', 'update installed packages', {
// executableFile: 'myUpdateSubCommand',
// })
// .command('list', 'list packages installed', { isDefault: false });
program.parse();
//this.program.parse();
// applies logDecorator to this.discovery() and binds it to 'this' to maintain the correct context
const logDecoratedDiscovery = this._logDecorator(this.discovery).bind(this);
logDecoratedDiscovery();
// Try the following on macOS or Linux:
// ./examples/pm
@ -52,4 +65,8 @@ class Pm extends This {
// main
const pm = new Pm();
// // applies logDecorator to this.discovery() and binds it to the instance to maintain the correct context
// const logDecoratedDiscovery = pm._logDecorator(pm.discovery).bind(pm);
// logDecoratedDiscovery();
pm.start();

10
this
View File

@ -34,6 +34,16 @@ class This {
withContext(callback) {
callback(this);
}
// Higher-order function to decorate other functions and provide logging
_logDecorator(fn) {
return function (...args) {
console.log(`Calling ${fn.name} with arguments:`, args);
const result = fn.apply(this, args); // Use apply to maintain context
console.log(`Result of ${fn.name}:`, result);
return result;
};
}
}
module.exports = This;