Skip to content

Instantly share code, notes, and snippets.

@rjhilgefort
Last active December 2, 2017 19:48
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 rjhilgefort/ee4350a9747a91b6795d0e344bc15c3e to your computer and use it in GitHub Desktop.
Save rjhilgefort/ee4350a9747a91b6795d0e344bc15c3e to your computer and use it in GitHub Desktop.
Class vs Factory
class ConsecutiveFailure {
constructor({
count = 0,
threshold = 10,
logger = console.log,
}) {
this.count = count;
this.threshold = threshold;
this.logger = logger;
}
reset() {
this.count = 0;
}
increment() {
this.count += 1;
}
isOverThreshold() {
return this.count > this.threshold;
}
async report() {
this.increment();
if (this.isOverThreshold()) {
await exit(
debug,
'Too many consecutive failures while trying to sync new changes',
{ threshold: this.threshold }
);
}
}
}
const consecutiveFailure = new ConsecutiveFailure({ threshold: 10 });
consecutiveFailure.increment(); // { count: 1 ...}
consecutiveFailure.increment(); // { count: 2 ...}
consecutiveFailure.reset(); // { count: 0 ...}
const ConsecutiveFailure = ({
count = 0,
threshold = 10,
logger = console.log,
} = {}) => ({
count,
threshold,
logger,
reset() {
this.count = 0;
return this;
},
increment() {
this.count += 1;
return this;
},
isUnderThreshold() {
return this.count <= this.threshold;
},
report() {
this.increment();
if (this.isUnderThreshold()) {
return Promise.resolve(this);
}
return exit(
this.logger,
'Too many consecutive failures while trying to sync new changes',
{ threshold: this.threshold }
);
},
});
const consecutiveFailure = ConsecutiveFailure({ threshold: 10 });
consecutiveFailure.increment(); // { count: 1 ...}
consecutiveFailure.increment(); // { count: 2 ...}
consecutiveFailure.reset(); // { count: 0 ...}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment