Skip to main content

CodeTyper Use Case: Code Breakdown - sampleCodes.ts

This document provides a detailed breakdown of the sampleCodes.ts file, which provides the code snippets for the application.

Data Structure

The sampleCodes object is a collection of code snippets, organized by programming language. Each language is a key in the object, and the value is an array of objects, where each object represents a single code snippet.

Each code snippet object has two properties:

  • name: The name of the code snippet (e.g., "Factorial", "Fibonacci", etc.).
  • code: The code snippet itself, as a string.

Here is an example of a single code snippet object:

{
name: 'Factorial',
code: `function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}

console.log(factorial(5)); // 120`
}

Usage

The sampleCodes object is used by the CodeTyper component to provide the user with a variety of code snippets to practice with. The getRandomCode function in the CodeTyper component selects a random code snippet from the sampleCodes object based on the user's selected language.

const getRandomCode = useCallback((lang: string) => {
const langCodes = sampleCodes[lang as keyof typeof sampleCodes];
const randomIndex = Math.floor(Math.random() * langCodes.length);
return langCodes[randomIndex].code;
}, []);

Conclusion

The sampleCodes.ts file is a simple but important file. It provides the data that is used to populate the code editor, and it is easily extensible to include new programming languages and code snippets.