Skip to content

Commit

Permalink
Aktualizacja test pattern (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
mystertaran authored Dec 21, 2023
1 parent a651e9a commit bcd275c
Show file tree
Hide file tree
Showing 14 changed files with 445 additions and 2 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"create": "node ./scripts/create-template.js",
"create:missing": "node ./scripts/create-template.js missing",
"create:month": "node ./scripts/create-month-templates.js",
"test": "jest ./tasks/$(date +'%Y-%m-%d')/index.test.ts",
"test": "node ./scripts/test.cjs",
"test:all": "jest"
},
"devDependencies": {
Expand All @@ -19,4 +19,4 @@
"tsx": "4.5.0",
"typescript": "5.3.2"
}
}
}
32 changes: 32 additions & 0 deletions scripts/test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const { exec } = require('child_process');
const { existsSync } = require('fs');
const { join } = require('path');

const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const testPath = `./tasks/${year}-${month}-${day}/index.test.ts`;

const fullTestPath = join(process.cwd(), testPath);

if (existsSync(fullTestPath)) {
exec(`jest --colors ${testPath}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
} else {
console.log(`Nie znaleziono folderu z dzisiejszą datą: ${testPath}. Uruchamiam wszystkie testy.`);
exec('jest --colors', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
}
26 changes: 26 additions & 0 deletions tasks/2023-12-01/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { GiftRegistry } from './index';

describe('GiftRegistry', () => {
it('should retrieve all gifts for a given child ID', () => {
const registry = new GiftRegistry();
registry.addGift(1, 'teddy bear');
registry.addGift(1, 'bicycle');
registry.addGift(2, 'car model');
expect(registry.getGiftsForChild(1)).toEqual(['teddy bear', 'bicycle']);
});

it('should handle removal of gifts correctly', () => {
const registry = new GiftRegistry();
registry.addGift(1, 'teddy bear');
registry.addGift(1, 'bicycle');
registry.removeGift(1, 'teddy bear');
expect(registry.getGiftsForChild(1)).toEqual(['bicycle']);
expect(registry.getGiftsForChild(1)).not.toContain('teddy bear');
});

it('should throw an error if trying to remove a gift that does not exist', () => {
const registry = new GiftRegistry();
registry.addGift(1, 'teddy bear');
expect(() => registry.removeGift(1, 'puzzle')).toThrow('Gift not found');
});
});
22 changes: 22 additions & 0 deletions tasks/2023-12-01/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export class GiftRegistry {
private registry: Record<number, string[]> = {};

addGift(childId: number, gift: string) {
if (!this.registry[childId]) {
this.registry[childId] = [];
}
this.registry[childId].push(gift);
}

getGiftsForChild(childId: number): string[] {
return this.registry[childId] || [];
}

removeGift(childId: number, gift: string) {
const gifts = this.registry[childId];
if (!gifts || !gifts.includes(gift)) {
throw new Error('Gift not found!');
}
this.registry[childId] = gifts.filter(item => item !== gift);
}
}
48 changes: 48 additions & 0 deletions tasks/2023-12-02/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { ChristmasQueue } from './index';

describe('ChristmasQueue', () => {
test('should enqueue and dequeue items based on priority', () => {
const pq = new ChristmasQueue<string>();
pq.enqueue('lowPriority', 1);
pq.enqueue('highPriority', 3);
pq.enqueue('mediumPriority', 2);
pq.enqueue('highPriority', 3);
pq.enqueue('lowPriority', 1);

expect(pq.dequeue()).toBe('highPriority');
expect(pq.dequeue()).toBe('highPriority');
expect(pq.dequeue()).toBe('mediumPriority');
expect(pq.dequeue()).toBe('lowPriority');
expect(pq.dequeue()).toBe('lowPriority');

expect(pq.isEmpty()).toBe(true);
});

test('should handle same priority items in FIFO order', () => {
const pq = new ChristmasQueue<string>();
pq.enqueue('firstIn', 2);
pq.enqueue('secondIn', 2);
pq.enqueue('thirdIn', 2);

expect(pq.dequeue()).toBe('firstIn');
expect(pq.dequeue()).toBe('secondIn');
expect(pq.dequeue()).toBe('thirdIn');
});

test('should support complex types', () => {
const pq = new ChristmasQueue<{ giftName: string }>();
pq.enqueue({ giftName: 'game console' }, 1);
pq.enqueue({ giftName: 'snowboard' }, 2);
pq.enqueue({ giftName: 'christmas balls' }, 3);

expect(pq.dequeue()).toStrictEqual({ giftName: 'christmas balls' });
expect(pq.dequeue()).toStrictEqual({ giftName: 'snowboard' });
expect(pq.dequeue()).toStrictEqual({ giftName: 'game console' });
});

test('should throw an error when dequeueing from an empty queue', () => {
const pq = new ChristmasQueue<string>();
expect(pq.isEmpty()).toBe(true);
expect(() => pq.dequeue()).toThrow('There are no letters in the queue!');
});
});
28 changes: 28 additions & 0 deletions tasks/2023-12-02/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export class ChristmasQueue<T> {
private queue: { item: T; priority: number }[] = [];

enqueue(item: T, priority: number): void {
let added = false;
for (let i = 0; i < this.queue.length; i++) {
if (priority > this.queue[i].priority) {
this.queue.splice(i, 0, { item, priority });
added = true;
break;
}
}
if (!added) {
this.queue.push({ item, priority });
}
}

dequeue(): T {
if (this.isEmpty()) {
throw new Error('There are no letters in the queue!');
}
return this.queue.shift()!.item;
}

isEmpty(): boolean {
return this.queue.length === 0;
}
}
31 changes: 31 additions & 0 deletions tasks/2023-12-03/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Lokalizacja, MapaCzasoprzestrzenna, znajdzWorek } from './index';

describe('znajdzWorek', () => {
test('powinien zwrócić lokalizację z najwyższą wartością mapy', () => {
const lokalizacje: Lokalizacja[] = [
{ x: 1, y: 2, z: 3, czas: 4 },
{ x: 5, y: 6, z: 7, czas: 8 },
{ x: 9, y: 10, z: 11, czas: 12 },
];
const mapa: MapaCzasoprzestrzenna = (x, y, z, czas) => x + y + z + czas;
const wynik = znajdzWorek(lokalizacje, mapa);
expect(wynik).toEqual({ x: 9, y: 10, z: 11, czas: 12 });
});

test('powinien zwrócić null, gdy lista lokalizacji jest pusta', () => {
const lokalizacje: Lokalizacja[] = [];
const mapa: MapaCzasoprzestrzenna = jest.fn();
const wynik = znajdzWorek(lokalizacje, mapa);
expect(wynik).toBeNull();
});

test('powinien obsłużyć wartości niepoprawne matematycznie', () => {
const lokalizacje: Lokalizacja[] = [
{ x: -1, y: -2, z: -3, czas: -4 },
{ x: 0, y: 0, z: 0, czas: 0 },
];
const mapa: MapaCzasoprzestrzenna = () => NaN;
const wynik = znajdzWorek(lokalizacje, mapa);
expect(wynik).toBeNull();
});
});
32 changes: 32 additions & 0 deletions tasks/2023-12-03/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export interface Lokalizacja {
x: number;
y: number;
z: number;
czas: number;
}

export type MapaCzasoprzestrzenna = (x: number, y: number, z: number, czas: number) => number;



export function znajdzWorek(lokalizacje: Lokalizacja[], mapa: MapaCzasoprzestrzenna): Lokalizacja | null {
if (lokalizacje.length === 0) {
return null;
}

let maxWartosc = -Infinity;
let najlepszaLokalizacja: Lokalizacja | null = null;

for (const lokalizacja of lokalizacje) {
const { x, y, z, czas } = lokalizacja;
const wartoscMapy = mapa(x, y, z, czas);

if (!isNaN(wartoscMapy) && isFinite(wartoscMapy) && wartoscMapy > maxWartosc) {
maxWartosc = wartoscMapy;
najlepszaLokalizacja = lokalizacja
}
}

return najlepszaLokalizacja;

}
26 changes: 26 additions & 0 deletions tasks/2023-12-04/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { memoize } from './index';

describe('memoize', () => {
it('should memoize function results', () => {
const complexCalculation = jest.fn().mockImplementation((x: number) => x * x);
const memoizedCalculation = memoize(complexCalculation);

expect(memoizedCalculation(2)).toBe(4);
expect(memoizedCalculation(2)).toBe(4);
expect(memoizedCalculation(3)).toBe(9);
expect(complexCalculation).toHaveBeenCalledTimes(2);
});

it('should handle different arguments correctly', () => {
const greeting = jest.fn().mockImplementation((p: string) => `${p}!`);
const memoizedGreeting = memoize(greeting);

expect(memoizedGreeting('John')).toBe('John!');
expect(memoizedGreeting('Paul')).toBe('Paul!');
expect(greeting).toHaveBeenCalledTimes(2);
});

it('should throw an error when non-function is memoized', () => {
expect(() => memoize(42 as never)).toThrow('Function to be memoized must be a function.');
});
});
22 changes: 22 additions & 0 deletions tasks/2023-12-04/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
type MemoizedFunction<T> = (...args: any[]) => T;

export function memoize<T>(func: (...args: any[]) => T): MemoizedFunction<T> {
if (typeof func !== 'function') {
throw new Error('Function to be memoized must be a function.');
}

const cache = new Map<string, T>();

return (...args: any[]): T => {
const key = JSON.stringify(args);

if (cache.has(key)) {
return cache.get(key)!;
}

const result = func(...args);
cache.set(key, result);

return result;
};
}
41 changes: 41 additions & 0 deletions tasks/2023-12-05/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Tutaj skopiuj testy dla zadania. Uruchom je poleceniem `npm test`
import { ChristmasEmitter } from './index';

describe('ChristmasEmitter', () => {
it('should allow to subscribe and emit events', () => {
const emitter = new ChristmasEmitter();
const letterCallback = jest.fn();
const giftCallback = jest.fn();

emitter.on('letter', letterCallback);
emitter.on('gift', giftCallback);
emitter.emit('letter');

expect(letterCallback).toHaveBeenCalled();
expect(giftCallback).not.toHaveBeenCalled();
});

it('should handle multiple subscribers for the same event', () => {
const emitter = new ChristmasEmitter();
const firstMockCallback = jest.fn();
const secondMockCallback = jest.fn();

emitter.on('gift', firstMockCallback);
emitter.on('gift', secondMockCallback);
emitter.emit('gift');

expect(firstMockCallback).toHaveBeenCalled();
expect(secondMockCallback).toHaveBeenCalled();
});

it('should not call callbacks after they have been removed', () => {
const emitter = new ChristmasEmitter();
const mockCallback = jest.fn();

emitter.on('letter', mockCallback);
emitter.off('letter', mockCallback);
emitter.emit('letter');

expect(mockCallback).not.toHaveBeenCalled();
});
});
23 changes: 23 additions & 0 deletions tasks/2023-12-05/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
type Callback = () => void;

export class ChristmasEmitter {
private events: Record<string, Callback[]> = {}


on(event: string, callback: Callback) {
this.events[event] = this.events[event] || [];
this.events[event].push(callback);
}

off(event: string, callback: Callback) {
if (this.events[event]) {
this.events[event] = this.events[event].filter(cb => cb !== callback);
}
}

emit(event: string) {
if (this.events[event]) {
this.events[event].forEach(callback => callback());
}
}
}
Loading

0 comments on commit bcd275c

Please sign in to comment.