Od tablicy do mapy haszującej
by Dawid Ryłko
HTML
<!-- Od tablicy do mapy haszującej -->
<a href="https://dawidrylko.com/od-tablicy-do-mapy-haszujacej-harry-potter-i-transmutacja/" target="_blank">Od tablicy do mapy haszującej</a>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
text-align: center;
}
TypeScript
/**
* @typedef Student
* @description Typ reprezentujący studenta z unikalnym identyfikatorem i imieniem.
* @param id - Unikalny identyfikator studenta.
* @param name - Imię studenta.
*/
type Student = {
id: string;
name: string;
};
/**
* @description Generuje tablicę studentów o podanej liczbie elementów.
* @param count - Liczba studentów do wygenerowania.
* @returns Tablica studentów.
*/
const generateStudents = (count: number): Student[] => {
return Array.from({ length: count }, (_, i) => ({ id: `student_${i}`, name: `Student ${i}` }));
};
/**
* @description Benchmark dla zwykłej tablicy z pętlą for.
*/
const benchmarkFor = (students: Student[], searchCount: number): number => {
const start = performance.now();
for (let i = 0; i < searchCount; i++) {
const randomId = `student_${Math.floor(Math.random() * students.length)}`;
let found: Student | undefined;
for (const student of students) {
if (student.id === randomId) {
found = student;
break;
}
}
}
const end = performance.now();
return end - start;
};
/**
* @description Benchmark dla zwykłej tablicy z metodą find.
*/
const benchmarkArray = (students: Student[], searchCount: number): number => {
const start = performance.now();
for (let i = 0; i < searchCount; i++) {
const randomId = `student_${Math.floor(Math.random() * students.length)}`;
students.find(s => s.id === randomId);
}
const end = performance.now();
return end - start;
};
/**
* @description Benchmark dla mapy haszującej.
*/
const benchmarkMap = (students: Student[], searchCount: number): number => {
// Koszt transformacji
const transformStart = performance.now();
const studentsMap = new Map(students.map(s => [s.id, s]));
const transformEnd = performance.now();
const transformTime = transformEnd - transformStart;
const searchStart = performance.now();
for (let i =...