Skip to content

Commit

Permalink
Merge pull request #736 from CommitChange/add-event-stack
Browse files Browse the repository at this point in the history
Add EventStack from #456
  • Loading branch information
wwahammy authored Aug 16, 2023
2 parents 72d219b + 80b2e79 commit 021e2a2
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
41 changes: 41 additions & 0 deletions javascripts/src/lib/EventStack.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
})
})

})
34 changes: 34 additions & 0 deletions javascripts/src/lib/EventStack.ts
Original file line number Diff line number Diff line change
@@ -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<TEventObjects extends EventObjectBase> {

private events:Array<TEventObjects> = []

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);
}


}

0 comments on commit 021e2a2

Please sign in to comment.