Last active
December 2, 2017 19:48
-
-
Save rjhilgefort/ee4350a9747a91b6795d0e344bc15c3e to your computer and use it in GitHub Desktop.
Class vs Factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ...} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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