Skip to content

Commit

Permalink
Refactor Command#handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
lahmatiy committed Dec 12, 2021
1 parent 3c1a9b4 commit 9853d10
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions lib/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,6 @@ const defaultVersionAction = instance => console.log(instance.meta.version);
const lastCommandHost = new WeakMap();
const lastAddedOption = new WeakMap();

const handlers = ['init', 'applyConfig', 'finishContext', 'action'].reduce((res, name) => {
res.initial[name] = name === 'action' ? self : noop;
res.setters[name] = function(fn) {
this.handlers[name] = fn.bind(null);

return this;
};
return res;
}, { initial: {}, setters: {} });

export default class Command {
constructor(usage = '') {
const [name, params] = usage.trim().split(/(\s+.*)$/);
Expand All @@ -34,12 +24,34 @@ export default class Command {
help: null
};

this.handlers = { ...handlers.initial };
Object.assign(this, handlers.setters);
this.handlers = {
init: noop,
applyConfig: noop,
finishContext: noop,
action: self
};

this.help();
}

// handlers
init(fn) {
this.handlers.init = fn.bind(null);
return this;
}
applyConfig(fn) {
this.handlers.applyConfig = fn.bind(null);
return this;
}
finishContext(fn) {
this.handlers.finishContext = fn.bind(null);
return this;
}
action(fn) {
this.handlers.action = fn.bind(null);
return this;
}

// definition chaining
extend(fn, ...args) {
fn(this, ...args);
Expand Down

0 comments on commit 9853d10

Please sign in to comment.