Skip to content

Commit

Permalink
add Counter utility
Browse files Browse the repository at this point in the history
  • Loading branch information
Eoksni committed Nov 19, 2019
1 parent 6915287 commit 1d2e710
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 0 deletions.
53 changes: 53 additions & 0 deletions frontend/src/counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import * as logger from 'src/services/logger';

export class Counter {
_counter = 0;

constructor({ onEnable, onDisable }) {
assert(onEnable);
this.onEnable = onEnable;
this.onDisable = onDisable;
}

enable = () => {
assert(counter >= 0);
if (counter <= 0) {
counter = 1;

const res = this.onEnable();
if (res) {
if (this.onDisable) {
logger.warn(new Error('both `onEnable` return value and `onDisable` callback were provided, giving priority to latter'));
} else {
this.onDisable = res;
}
} else {
if (this.onDisable) {
// nothing to do
} else {
logger.warn(new Error('both `onEnable` return value and `onDisable` callback were NOT provided'));
}
}
} else {
counter += 1;
}

return this.disable;
}

disable = () => {
assert(counter > 0);
if (counter > 1) {
counter -= 1;
} else if (counter < 1) {
logger.warn(new Error('trying to disable already disabled counter'));
counter = 0;
} else {
counter = 0;

if (this.onDisable) {
this.onDisable();
}
}
}
}
49 changes: 49 additions & 0 deletions frontend/test/counter.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Counter } from 'src/counter';
import _ from 'lodash';

describe("counter tests", function() {
it("should enable and disable", function() {
onEnable = jasmine.createSpy('onEnable');
onDisable = jasmine.createSpy('onDisable');
const counter = new Counter({ onEnable, onDisable });

counter.enable();
expect(onEnable).toHaveBeenCalledTimes(1);
expect(onDisable).not.toHaveBeenCalled();
counter.disable();
expect(onDisable).toHaveBeenCalledTimes(1);
});

it("should enable several times", function() {
onEnable = jasmine.createSpy('onEnable');
onDisable = jasmine.createSpy('onDisable');
const counter = new Counter({ onEnable, onDisable });

counter.enable();
counter.enable();
expect(onEnable).toHaveBeenCalledTimes(1);
counter.disable();
expect(onDisable).not.toHaveBeenCalled();
counter.disable();
expect(onDisable).toHaveBeenCalledTimes(1);
});

it("should chain enable and disable", function() {
onEnable = jasmine.createSpy('onEnable');
onDisable = jasmine.createSpy('onDisable');
const counter = new Counter({ onEnable, onDisable });

counter.enable();
counter.enable();
expect(onEnable).toHaveBeenCalledTimes(1);
counter.disable();
expect(onDisable).not.toHaveBeenCalled();
counter.disable();
expect(onDisable).toHaveBeenCalledTimes(1);

counter.enable();
expect(onEnable).toHaveBeenCalledTimes(2);
counter.disable();
expect(onDisable).toHaveBeenCalledTimes(2);
});
});

0 comments on commit 1d2e710

Please sign in to comment.