diff --git a/javascripts/src/lib/EventStack.spec.ts b/javascripts/src/lib/EventStack.spec.ts new file mode 100644 index 000000000..8d780b9cc --- /dev/null +++ b/javascripts/src/lib/EventStack.spec.ts @@ -0,0 +1,41 @@ +// License: LGPL-3.0-or-later +import EventStack from './EventStack'; + +describe('EventStack', () => { + const firstEvent = {type:"first"} + describe('.top', () => { + it('returns undefined if no events have been added', () => { + const stack = new EventStack(); + expect(stack.top).toBeUndefined(); + }) + + it('returns the top event after an event is pushed', () => { + const stack = new EventStack(); + stack.push(firstEvent) + expect(stack.top).toEqual(firstEvent); + }) + }) + + describe('.push', () => { + it("returns event when an event is added", () => { + const stack = new EventStack(); + expect(stack.push(firstEvent)).toEqual(firstEvent) + + }); + + it ("returns undefined when the event isn't added because it's already the top", () => { + const stack = new EventStack(); + stack.push(firstEvent) + expect(stack.push(firstEvent)).toBeUndefined(); + }) + + it("returns and adds event when it doesn't match another object based on deep comparison", () => { + const stack = new EventStack(); + stack.push(firstEvent) + + const secondEvent = {type:"first", but:"different"} + expect(stack.push(secondEvent)).toEqual(secondEvent); + }) + }) + +}) \ No newline at end of file diff --git a/javascripts/src/lib/EventStack.ts b/javascripts/src/lib/EventStack.ts new file mode 100644 index 000000000..8b5d0b0ac --- /dev/null +++ b/javascripts/src/lib/EventStack.ts @@ -0,0 +1,34 @@ +// License: LGPL-3.0-or-later +import last from 'lodash/last'; +import isEqual from 'lodash/isEqual' + + +interface EventObjectBase { + type: string +} + +/** + * A simple class for recording the list of events that occurred for a system + */ +export default class EventStack { + + private events:Array = [] + + push(event: TEventObjects): TEventObjects | undefined { + if (!this.top) { + this.events.push(event) + return event; + } + else if (!isEqual(this.top, event)) { + this.events.push(event); + return event; + } + return undefined; + } + + get top(): TEventObjects | undefined { + return last(this.events); + } + + +} \ No newline at end of file