Skip to content

Instantly share code, notes, and snippets.

@adriano-di-giovanni
Created October 3, 2024 10:11
Show Gist options
  • Save adriano-di-giovanni/559305c2c8fd32b25b4bd8142f2e2c9d to your computer and use it in GitHub Desktop.
Save adriano-di-giovanni/559305c2c8fd32b25b4bd8142f2e2c9d to your computer and use it in GitHub Desktop.
Sample code for an Elevator implementation using primitive data types to represent weight. Featured on adrianodigiovanni.com.
import { Elevator } from './elevator';
import { Load } from './load';
describe(Elevator.name, () => {
it('should throw a RangeError when attempting to create an elevator with negative capacity', () => {
expect(() => new Elevator(-1)).toThrow(RangeError);
});
it('should successfully create an elevator with a valid capacity', () => {
const capacity = 400;
const elevator = new Elevator(capacity);
expect(elevator).toBeDefined();
expect(elevator.capacity).toEqual(capacity);
});
it('should initialize with a load weight of 0', () => {
const elevator = new Elevator(400);
expect(elevator.calculateLoadWeight()).toEqual(0);
});
it('should correctly calculate the load weight after a single load is boarded', () => {
const load = new Load(50);
const elevator = new Elevator(400);
elevator.boardLoad(load);
expect(elevator.calculateLoadWeight()).toEqual(load.weight);
});
it('should correctly calculate the load weight after multiple loads are boarded', () => {
const load1 = new Load(50);
const load2 = new Load(65);
const elevator = new Elevator(400);
elevator.boardLoad(load1);
elevator.boardLoad(load2);
expect(elevator.calculateLoadWeight()).toEqual(load1.weight + load2.weight);
});
it('should throw a RangeError when the total load weight exceeds the elevator capacity', () => {
expect(() => {
const load1 = new Load(200);
const load2 = new Load(201);
const elevator = new Elevator(400);
elevator.boardLoad(load1);
elevator.boardLoad(load2);
}).toThrow(RangeError);
});
});
import { Load } from './load';
export class Elevator {
private readonly loads: Load[] = [];
constructor(readonly capacity: number) {
if (capacity < 0) {
throw new RangeError('Capacity must be greater than or equal to 0');
}
}
boardLoad(load: Load): void {
const currentLoadWeight = this.calculateLoadWeight();
const projectedLoadWeight = currentLoadWeight + load.weight;
if (projectedLoadWeight > this.capacity) {
throw new RangeError('Load weight exceeds elevator capacity');
}
this.loads.push(load);
}
calculateLoadWeight(): number {
return this.loads.reduce((loadWeight, load) => loadWeight + load.weight, 0);
}
}
import { Load } from './load';
describe(Load.name, () => {
it('should throw when weight is negative', () => {
expect(() => new Load(-1)).toThrow(RangeError);
});
});
export class Load {
constructor(readonly weight: number) {
if (weight < 0) {
throw new RangeError('Weight must be greater than or equal to 0');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment