### Bad JSDoc Example for JavaScript Functions
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-documentation.mdx
Illustrates an insufficient JSDoc example, where comments are too brief or missing detailed information about the function's purpose, parameters, or return values.
```JavaScript
// Adds a and b
function sum(a, b) {
return a + b;
}
// Missing detailed JSDoc comment
```
--------------------------------
### Full Example of Organized Imports in a JavaScript File
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/organizing-imports.mdx
This comprehensive example illustrates a complete `index.js` file with imports organized according to the recommended style guide. It demonstrates the hierarchical ordering of imports, from core packages to API functions, enhancing code readability and maintainability.
```js
import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
// ** import icons
import BackSvg from "@icons/BackSvg";
import SearchSvg from "@icons/SearchSvg";
// ** import assets
import googleSvg from "@svg/google.svg";
import AbsoluteLogo from "@svg/AbsoluteLogo.svg";
import frontGirl from "@illustration/FrontGirl.svg";
import userImage from "@illustration/userImage.webp";
// ** import third party
import { toast } from "react-toastify";
import { CircularProgress } from "@nextui-org/react";
// ** import shared components
import Image from "@shared/Image";
import Button from "@shared/Button";
import Typography from "@shared/Typography";
// ** import components
import AddFoodItem from "@components/AddFoodItem";
import CalendarPopup from "@components/CalendarPopup";
// ** import sub pages/sections
import Section1 from "./Section1";
import Section2 from "./Section2";
import Section3 from "./Section3";
// ** import config
import env from "@src/config";
// ** import state manager
import { useDispatch } from "react-redux";
import { setLocale } from "@src/redux/slices/language";
// ** import utils
import { useStorableState } from "@utils/useStorable";
// ** import hooks
import useStorable from "@src/utils/useStorable";
// ** import apis
import { getUserProfileApi } from "@api/auth";
import { confirmOrderApi } from "@api/cart";
```
--------------------------------
### Good JSDoc Example for JavaScript Functions
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-documentation.mdx
Demonstrates how to effectively use JSDoc to document JavaScript functions, including parameters, their types, and the return type, enhancing clarity and understanding.
```JavaScript
/**
* Adds two numbers together.
* @param {number} a - The first number.
* @param {number} b - The second number.
* @returns {number} The sum of the two numbers.
*/
function sum(a, b) {
return a + b;
}
```
--------------------------------
### Good Practice for Indentation and Formatting in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-documentation.mdx
Demonstrates consistent indentation using spaces and adherence to a style guide, which is crucial for code readability and maintainability.
```JavaScript
function exampleFunction() {
if (condition) {
// code
}
}
```
--------------------------------
### Example Usage of Typography Component with Animation
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/typography.mdx
A practical example demonstrating how to use the Typography component with a specified variant and animation type.
```javascript
Welcome to Our Site
```
--------------------------------
### Good Multi-Line Commenting Practice in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-documentation.mdx
Shows an example of well-structured multi-line comments that provide detailed explanations for complex functions, including their purpose, parameters, and return values, similar to JSDoc.
```JavaScript
/**
* This function calculates the total price of an order
* including tax and discount. It applies a tax rate of 8%,
* and a discount rate is applied if applicable.
*
* @param {number} basePrice - The base price of the order.
* @param {boolean} hasDiscount - Indicates if the order has a discount.
* @returns {number} The total price after applying tax and discount.
*/
function calculateTotalPrice(basePrice, hasDiscount) {
const taxRate = 0.08;
let discount = 0;
if (hasDiscount) {
discount = basePrice * 0.1; // 10% discount
}
return basePrice + (basePrice * taxRate) - discount;
}
```
--------------------------------
### Bad Multi-Line Commenting Practice in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-documentation.mdx
Highlights an example of non-informative and redundant multi-line comments that add little value to understanding the code.
```JavaScript
/*
This function calculates the price.
It has parameters.
It returns a number.
*/
function calculateTotalPrice(basePrice, hasDiscount) {
// The actual function code
}
// Non-informative, redundant comments
```
--------------------------------
### PascalCase Type Naming in TypeScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
Shows good and bad examples for naming custom types using PascalCase, emphasizing consistency and clarity.
```typescript
type UserProfile = {
id: number;
name: string;
email: string;
};
```
```typescript
type user_info = {
userid: number;
username: string;
useremail: string;
};
```
--------------------------------
### Configuration File Naming Conventions
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
This section provides guidelines for naming configuration files to clearly indicate their purpose and environment. Good practices ensure consistency and clarity, while bad examples show ambiguity, inconsistent naming, and mixed naming styles.
```plaintext
development.config.js
production.config.js
test.config.js
```
```js
configDev.js // Inconsistent naming
prodConfig.js // Ambiguity in file purpose
test_conf.js // Mixing naming styles
```
--------------------------------
### Example Directory Structure for Modular React Modals
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
This snippet illustrates a recommended directory structure for organizing different modal components within a React project, promoting a clear and modular file system that enhances project scalability and ease of navigation.
```mdx
.
└── Modal/
├── index.jsx
├── SuccessModal.jsx
├── WarningModal.jsx
├── DangerModal.jsx
├── LoginModal.jsx
```
--------------------------------
### Good Practice for Meaningful Comments in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-documentation.mdx
Provides examples of strategic comments that enhance code clarity by explaining the 'why' behind the code or summarizing complex logic, without being redundant.
```JavaScript
// Loop through users and apply discounts to eligible ones
users.forEach(user => {
if (user.isEligibleForDiscount()) {
applyDiscount(user);
}
});
```
```JavaScript
// Calculate the area of a rectangle
function calculateArea(length, width) {
return length * width;
}
```
--------------------------------
### Implementing Modular Component Structure in React
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
This example demonstrates a good practice for organizing React components into separate files, improving readability and maintainability by importing sub-components rather than defining everything in one large file.
```js
// Good Practice: Modular structure with sub-components
import React from 'react';
import SuccessModal from './SuccessModal';
// ...other imports
const Modal = ({ variant, ...props }) => {
// Component logic
return
{/* Render selected modal based on variant */}
;
};
export default Modal;
```
--------------------------------
### Illustrating Monolithic Code Structure in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
This example demonstrates a bad practice where all components, utilities, and types are placed in a single, large JavaScript file, leading to clutter and confusion and making the codebase difficult to manage.
```js
// Bad Practice: Everything in one file
import React from 'react';
// Imports for components, utilities, types all mixed together...
const MyComponent = () => { /* ... */ };
const AnotherComponent = () => { /* ... */ };
// Multiple components and utility functions defined here...
// thousands of lines of code... 🚂
export default MyComponent;
```
--------------------------------
### Example of Good React Component Structure
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/react-code-structure.mdx
This comprehensive example demonstrates the recommended logical order for imports, constants, state management using Redux, local state with `useState`, lifecycle methods with `useEffect`, and event handler functions within a React functional component. This organization makes the code more readable and maintainable, especially as components grow in complexity.
```jsx
import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import SomeService from './SomeService';
import './Page.css';
const Page = ({ variant, ...props }) => {
// Constants
const MAX_COUNT = 10;
// Redux State
const user = useSelector(state => state.user);
// Local State
const [count, setCount] = useState(0);
const [data, setData] = useState(null);
// useEffect for loading data
useEffect(() => {
SomeService.getData().then(data => setData(data));
}, []);
// useEffect for user-related operations
useEffect(() => {
if (user) {
console.log('User updated:', user);
}
}, [user]);
// Event Handlers
const handleIncrement = () => {
if (count < MAX_COUNT) {
setCount(prevCount => prevCount + 1);
}
};
return (
);
};
```
--------------------------------
### Flexible React Hook Order with Custom Hooks
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/react-code-structure.mdx
Illustrates a scenario where the order of `useState` and custom hooks may be interchanged for functional necessity, especially when a custom hook's output is used as a dependency in another hook or a piece of state. This example shows `useUUID` being called before certain `useState` hooks because its output is required by `useGetAllMenuItems`, demonstrating the need for flexibility in structuring components.
```jsx
import React, { useState } from 'react';
import useGetAllMenuItems from './useGetAllMenuItems';
import useUUID from './useUUID';
const MenuComponent = ({ restaurant_id, tbl_id, limit }) => {
// Custom hook that needs to precede certain state hooks
const uuid = useUUID();
// useState hooks, some of which depend on the custom hook's output
const [searchQuery, setSearchQuery] = useState('');
const [sortby, setSortby] = useState('rating');
const [category, setCategory] = useState('');
// Another custom hook that uses state and the output from useUUID
const { data: menuItems, error } = useGetAllMenuItems(
restaurant_id,
uuid,
tbl_id,
limit,
searchQuery,
sortby,
category,
);
// Component logic and JSX
return (
// JSX rendering using menuItems
);
};
export default MenuComponent;
```
--------------------------------
### Inefficient Algorithm Selection: Linear Search in TypeScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-optimization.mdx
Illustrates the less efficient linear search algorithm for sorted arrays in TypeScript. This example emphasizes that choosing the right algorithm is crucial for performance, as linear search has a higher time complexity (linear) for large datasets.
```typescript
// Linear search on a sorted array is less efficient
function linearSearch(array: number[], target: number): boolean {
// Linear search logic
}
```
--------------------------------
### JavaScript Utility Function for Date Formatting
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
Illustrates how to define a reusable utility function for date formatting in a separate file, promoting modularity and reusability across the application.
```javascript
// utils/formatDate.js
export const formatDate = (date) => {
// Format date logic
};
```
--------------------------------
### Import Configuration Files in React
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/organizing-imports.mdx
Configuration files like environment settings should be imported thereafter. This ensures that application settings are loaded appropriately.
```js
// ** import config
import env from "@src/config";
```
--------------------------------
### Folder Naming Conventions (kebab-case)
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
This section demonstrates the kebab-case convention for naming folders, focusing on lowercase and dash separation. It highlights good practices and common errors such as using camelCase or mixing case styles when adhering to kebab-case.
```plaintext
components/
utilities/
auth-pages/
user-profile/
```
```js
Components/ // Should be lowercase for kebab-case
utilitiesFolder/ // Should use dashes, not camelCase
Auth_Pages/ // Avoid mixing case styles and underscores
UserProfilePage/ // Redundant 'Page' suffix and incorrect case style
```
--------------------------------
### Avoid Repetitive Inline Styling in React
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/typography.mdx
This example demonstrates repetitive inline styling for text elements, which leads to cluttered and difficult-to-maintain code. It is considered a bad practice.
```javascript
Login Page
hello world
```
--------------------------------
### Identifying Vulnerable Dependencies with npm audit
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/secure-coding.mdx
Provides the command to run `npm audit` for identifying and fixing insecure dependencies in Node.js projects, ensuring software supply chain security.
```shell
npm audit
```
--------------------------------
### Environment Variable Naming Conventions
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
This section illustrates recommended and discouraged practices for naming environment variables. Good practice involves using uppercase with underscores for clarity, while bad practice shows inconsistent casing and lack of separators, leading to confusion.
```plaintext
DATABASE_URL
ACCESS_TOKEN_SECRET
REDIS_PORT
```
```js
dbUrl // Not uppercase
accessToken // Should use underscores to separate words
RedisPort // Not following the uppercase convention
```
--------------------------------
### Securely Fetching Secrets with 1Password CLI in Node.js
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/secure-coding.mdx
This code demonstrates how to integrate with 1Password CLI to securely fetch API keys and set them as environment variables in a Node.js application. This method enhances security by avoiding hardcoded secrets or direct `.env` file usage in production.
```javascript
const { op } = require("1password");
(async () => {
const apiKey = await op.getItem("API_KEY");
process.env.API_KEY = apiKey;
})();
```
--------------------------------
### React Generic Modal Component Implementation
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
This snippet defines a generic React `Modal` component that acts as a wrapper for different modal variants (success, warning, danger, login). It uses a `variant` prop to dynamically render the appropriate sub-component and defines various props for customization like title, description, button text, functions, backdrop, and placement. It's designed to be a flexible entry point for different modal types.
```jsx
import React from 'react';
// ** import sub components
import SuccessModal from './SuccessModal';
import WarningModal from './WarningModal';
import DangerModal from './DangerModal';
import LoginModal from './LoginModal';
/**
* @typedef {'success' | 'warning' | 'danger' | 'login'} ModalVariant
* @typedef {'opaque' | 'blur' | 'transparent'} BackdropVariant
* @typedef {'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'} placement
*/
/**
* Modal component.
*
* @param {Object} props - The component props.
* @param {ModalVariant} props.variant - The variant of the header to render.
* @param {string} props.title
* @param {string} props.description
* @param {string} props.yesText
* @param {string}props.noText
* @param {Function} props.btnFunction - The function to call when button is clicked.
* @param {Function} props.yesFunction - The function to call when 'yes' is clicked.
* @param {Function} props.noFunction - The function to call when 'no' is clicked.
* @param {BackdropVariant} props.backdropVariant - The variant of the backdrop to render.
* @param {boolean} props.hideCloseButton - A boolean indicating whether a close button is present.
* @param {boolean} props.outsideClickClose - The boolean indicating whether the modal should close when clicking outside the modal
* @param {placement} props.placement - The placement of the modal
* @returns {JSX.Element|null} The rendered header component.
*
*/
const Modal = ({ variant, ...props }) => {
const variantComponents = {
success: SuccessModal,
warning: WarningModal,
danger: DangerModal,
login: LoginModal
};
const SelectedModal = variantComponents[variant] || null;
return
{SelectedModal && }
;
};
export default Modal;
```
--------------------------------
### PascalCase Interface Naming in TypeScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
Demonstrates proper PascalCase for interface names, contrasting with inconsistent or non-standard naming.
```typescript
interface UserSettings {
theme: string;
notifications: boolean;
}
```
```typescript
interface settings {
Theme: string;
NotificationsEnabled: boolean;
}
```
--------------------------------
### CamelCase Hook Naming in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
Illustrates best practices for naming React hooks, combining 'use' with action and resource for clarity, and showing common pitfalls.
```javascript
function useLocalStorage() { /* ... */ }
function useClickOutside() { /* ... */ }
function useGetUserProfileAPI() { /* ... swr api function */ }
function useUserLoginAPI() { /* ... swr api function */ }
```
```javascript
function getUserProfile() { /* ... */ } // Not clear it's a hook
function loginAPI() { /* ... */ } // Should start with 'use' and describe action
```
--------------------------------
### React DangerModal Component Implementation (Partial)
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
Provides a partial implementation of a danger confirmation modal in React. Similar to the WarningModal, it uses NextUI and Redux, but is intended for critical actions, featuring a danger icon. The provided snippet includes imports, typedefs, and the component's prop definitions.
```jsx
import React from 'react';
// ** import next ui
import { Modal, ModalContent } from '@nextui-org/react';
// ** import shared components
import Typography from '@shared/Typography';
import Button from '@shared/Button';
// ** import assets
import Danger from '@icons/Danger';
// ** import redux
import { useSelector, useDispatch } from 'react-redux';
import { setAlertModel } from '@redux/slices/utils';
/**
* @typedef {'opaque' | 'blur' | 'transparent'} BackdropVariant
* @typedef {'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'} placement
*/
/**
* DangerModal component.
*
* @param {Object} props - The component props.
* @param {string} props.title - The title of the modal.
* @param {string} props.description - The description of the modal.
* @param {string} props.yesText - The text for the 'Yes' button.
* @param {string} props.noText - The text for the 'No' button.
* @param {Function} props.yesFunction - The function to call when 'Yes' is clicked.
* @param {Function} props.noFunction - The function to call when 'No' is clicked.
* @param {BackdropVariant} props.backdropVariant - The variant of the backdrop to render.
```
```APIDOC
Type Definitions:
BackdropVariant: 'opaque' | 'blur' | 'transparent'
placement: 'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'
DangerModal Component Props:
title: string - The title of the modal.
description: string - The description of the modal.
yesText: string - The text for the 'Yes' button.
noText: string - The text for the 'No' button.
yesFunction: Function - The function to call when 'Yes' is clicked.
noFunction: Function - The function to call when 'No' is clicked.
backdropVariant: BackdropVariant - The variant of the backdrop to render.
```
--------------------------------
### LoginModal Component Props API Reference
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
Detailed API reference for the props accepted by the LoginModal React component, including their types, descriptions, and default values. This component is used for user login flows, particularly with external authentication.
```APIDOC
LoginModal Component Props:
title: string - The title for the modal.
description: string - The description for the modal.
btnText: string - The text for the button.
btnFunction: Function - The function to call when the button is clicked.
backdropVariant: 'opaque' | 'blur' | 'transparent' (default: 'blur') - The variant of the backdrop to render.
hideCloseButton: boolean (default: true) - A boolean indicating whether a close button is present.
placement: 'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center' (default: 'center') - The placement of the modal.
outsideClickClose: boolean (default: true) - A boolean indicating whether the outside click closes the modal.
Returns: JSX.Element - The rendered LoginModal component.
```
--------------------------------
### Define Global Colors with CSS Variables
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/colors.mdx
Illustrates how to define a set of global color variables within the :root pseudo-class for centralized color management.
```css
:root {
--primary-color: #5A67D8;
--secondary-color: #ED64A6;
--text-color: #333333;
--background-color: white;
--warning-color: #ffcc00;
}
```
--------------------------------
### React: Get CSS Classes for Typography Types
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/typography.mdx
This JavaScript helper function, `getClassName`, returns a Tailwind CSS class string based on the `type` prop of the Typography component. It defines various font sizes and weights for different heading levels (H1-H6) and a default empty string, ensuring consistent typography across the application.
```JavaScript
const getClassName = () => {
switch (type) {
case "T_Regular_H1":
return "font-poppins font-normal text-[40px] md:text-[62px] tracking-normal";
case "T_Regular_H2":
return "font-poppins font-normal text-[32px] md:text-[49px] tracking-normal";
case "T_Regular_H3":
return "font-poppins font-normal text-[24px] md:text-[39px] tracking-normal";
case "T_Regular_H4":
return "font-poppins font-normal text-[20px] md:text-[25px] tracking-normal";
case "T_Regular_H5":
return "font-poppins font-normal text-[16px] md:text-[20px] tracking-normal";
case "T_Regular_H6":
return "font-poppins font-normal text-[14px] md:text-[16px] tracking-normal";
default:
return "";
}
};
```
--------------------------------
### CamelCase Object Naming in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
Demonstrates good and bad practices for naming object keys using camelCase, emphasizing descriptive and consistent naming.
```javascript
{
firstName: "",
lastName: "",
paymentId: "",
}
```
```javascript
{
first: "", // Not descriptive
lname: "", // Inconsistent naming
id_payment: "", // Mixed naming styles
}
```
--------------------------------
### Importing API Functions in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/organizing-imports.mdx
This snippet demonstrates the recommended way to import API functions or services. It suggests grouping API-related imports together to maintain organization and easy identification within a project.
```js
// ** import apis
import { getUserProfileApi } from "@api/auth";
import { confirmOrderApi } from "@api/cart";
```
--------------------------------
### React: Get CSS Classes for Text Animations
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/typography.mdx
This JavaScript helper function, `getAnimationClass`, returns a Tailwind CSS class string based on the `animate` prop. It provides classes for 'move' (hover:ml-1.5) and 'underline' (hover:underline) animations, both with a smooth transition. This allows for dynamic hover effects on text elements within the Typography component.
```JavaScript
const getAnimationClass = () => {
switch (animate) {
case "move":
return "hover:ml-1.5 transition-all duration-300";
case "underline":
return "hover:underline transition-all duration-300";
default:
return "";
}
};
```
--------------------------------
### DangerModal Component Props API Reference
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
Detailed API reference for the props accepted by the DangerModal React component, including their types, descriptions, and default values. This component is used for critical user confirmations.
```APIDOC
DangerModal Component Props:
title: string - The title for the modal.
description: string - The description for the modal.
yesText: string - The text for the 'Yes' button.
noText: string - The text for the 'No' button.
yesFunction: Function - The function to call when the 'Yes' button is clicked.
noFunction: Function - The function to call when the 'No' button is clicked.
backdropVariant: 'opaque' | 'blur' | 'transparent' (default: 'blur') - The variant of the backdrop to render.
hideCloseButton: boolean (default: true) - A boolean indicating whether a close button is present.
placement: 'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center' (default: 'center') - The placement of the modal.
outsideClickClose: boolean (default: true) - A boolean indicating whether the outside click closes the modal.
Returns: JSX.Element - The rendered DangerModal component.
```
--------------------------------
### JavaScript Form Validation Schema with Yup
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
Shows how to separate form validation logic, using a library like Yup, into its own file. This promotes clean code and easier management of complex validation rules for forms like a login form.
```javascript
// validation/loginValidation.js
import * as Yup;
export const loginValidationSchema = Yup.object().shape({
// Validation schema
});
```
--------------------------------
### Setting Referrer-Policy Meta Tag in React/Next.js Frontend
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/secure-coding.mdx
This snippet shows how to implement the `Referrer-Policy` in frontend frameworks like React (using `react-helmet`) or Next.js (in `_document.js`). It sets a meta tag to control referrer information, protecting sensitive data in URLs from being sent to other domains.
```jsx
// React with react-helmet
// Next.js in _document.js
```
--------------------------------
### Apply Tailwind CSS Classes in JSX Components
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/colors.mdx
Demonstrates the utility-first approach of Tailwind CSS by applying predefined color classes directly to JSX elements.
```js
const MyComponent = () => (
Welcome to My Site
);
```
--------------------------------
### Efficient Algorithm Selection: Binary Search in TypeScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-optimization.mdx
Highlights the use of binary search for sorted arrays in TypeScript, demonstrating an efficient algorithm choice that significantly improves performance (logarithmic time complexity) compared to linear search for large datasets.
```typescript
// Binary search for sorted arrays
function binarySearch(array: number[], target: number): boolean {
// Binary search logic
}
```
--------------------------------
### React WarningModal Component Implementation
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
Implements a customizable warning modal in React using NextUI components and Redux for state management. It displays a warning icon, a title, a description, and two action buttons ('Yes' and 'No') with configurable text and functions. The modal's appearance and behavior, such as backdrop, placement, and dismissability, are controlled via props.
```jsx
import React from 'react';
// ** import next ui
import { Modal, ModalContent } from '@nextui-org/react';
// ** import shared components
import Typography from '@shared/Typography';
import Button from '@shared/Button';
// ** import assets
import WarningSvg from '@icons/WarningSvg';
// ** import redux
import { useSelector, useDispatch } from 'react-redux';
import { setAlertModel } from '@redux/slices/utils';
/**
* @typedef {'opaque' | 'blur' | 'transparent'} BackdropVariant
* @typedef {'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'} placement
*/
/**
* WarningModal component.
*
* @param {Object} props - The component props.
* @param {string} props.title - The title for the warning modal.
* @param {string} props.description - The description for the warning modal.
* @param {string} props.yesText - The text for the 'Yes' button.
* @param {string} props.noText - The text for the 'No' button.
* @param {Function} props.yesFunction - The function to call when 'Yes' is clicked.
* @param {Function} props.noFunction - The function to call when 'No' is clicked.
* @param {BackdropVariant} props.backdropVariant - The variant of the backdrop to render.
* @param {boolean} props.hideCloseButton - A boolean indicating whether a close button is present.
* @param {placement} props.placement - The placement of the modal
* @param {boolean} props.outsideClickClose - A boolean indicating whether the outside click closes the modal
* @returns {JSX.Element} The rendered WarningModal component.
*/
const WarningModal = ({
title,
description,
yesText,
noText,
yesFunction,
noFunction,
backdropVariant = 'blur', // default backdrop is blur
hideCloseButton = true, // default hide close button
placement = 'center', // default placement is center
outsideClickClose = true, // default outside click true
}) => {
const dispatch = useDispatch();
const { alertModel } = useSelector((state) => state.utils);
/**
* Function to handle the 'No' button click.
*/
const cancelFunction = () => {
dispatch(setAlertModel(false));
if (noFunction) {
noFunction();
}
};
/**
* Function to handle the 'Yes' button click.
*/
const confirmFunction = () => {
dispatch(setAlertModel(false));
if (yesFunction) {
yesFunction();
}
};
/**
* Handles the outside click action.
*/
const handleOutsideClick = () => {
if (outsideClickClose) {
cancelFunction();
}
};
return (
dispatch(setAlertModel(false))}
>
{title}
{description}
);
};
export default WarningModal;
```
```APIDOC
Type Definitions:
BackdropVariant: 'opaque' | 'blur' | 'transparent'
placement: 'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'
WarningModal Component Props:
title: string - The title for the warning modal.
description: string - The description for the warning modal.
yesText: string - The text for the 'Yes' button.
noText: string - The text for the 'No' button.
yesFunction: Function - The function to call when 'Yes' is clicked.
noFunction: Function - The function to call when 'No' is clicked.
backdropVariant: BackdropVariant - The variant of the backdrop to render. (default: 'blur')
hideCloseButton: boolean - A boolean indicating whether a close button is present. (default: true)
placement: placement - The placement of the modal (default: 'center')
outsideClickClose: boolean - A boolean indicating whether the outside click closes the modal (default: true)
Returns: JSX.Element - The rendered WarningModal component.
```
--------------------------------
### Import Utilities and Libraries in React
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/organizing-imports.mdx
Utility functions or libraries are imported next. They usually provide helper functions used across components, centralizing common logic.
```js
// ** import utils
import { useStorableState } from "@utils/useStorable";
```
--------------------------------
### React Success Modal Component with Redux Integration
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
This snippet implements the `SuccessModal` component, a specific variant of the generic `Modal`. It integrates with `@nextui-org/react` for the base modal structure and Redux for state management (showing/hiding the modal via `alertModel` state). It handles button clicks and outside clicks, providing a customizable success message display with title, description, and a call-to-action button.
```jsx
import React from 'react';
// ** import next ui
import { Modal, ModalContent } from '@nextui-org/react';
// ** import shared components
import Typography from '@shared/Typography';
import Button from '@shared/Button';
// ** import assets
import SuccessSvg from '@icons/SuccessSvg';
// ** import redux
import { useSelector, useDispatch } from 'react-redux';
import { setAlertModel } from '@redux/slices/utils';
/**
* @typedef {'opaque' | 'blur' | 'transparent'} BackdropVariant
* @typedef {'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'} placement
*/
/**
* SuccessModal component.
*
* @param {Object} props - The component props.
* @param {string} props.title - The title for the modal.
* @param {string} props.description - The description for the modal.
* @param {string} props.btnText - The text for the button.
* @param {Function} props.btnFunction - The function to call when the button is clicked.
* @param {BackdropVariant} props.backdropVariant - The variant of the backdrop to render.
* @param {boolean} props.hideCloseButton - A boolean indicating whether a close button is present.
* @param {placement} props.placement - The placement of the modal
* @param {boolean} props.outsideClickClose - A boolean indicating whether the outside click closes the modal
* @returns {JSX.Element} The rendered SuccessModal component.
*/
const SuccessModal = ({
title,
description,
btnText,
btnFunction,
backdropVariant = 'blur', // default backdrop is blur
hideCloseButton = true, // default hide close button
placement = 'center', // default placement is center
outsideClickClose = true, // default outside click true
}) => {
const dispatch = useDispatch();
const { alertModel } = useSelector((state) => state.utils);
/**
* Handles the close action.
*/
const handleClose = () => {
dispatch(setAlertModel(false));
if (btnFunction) {
btnFunction();
}
};
/**
* Handles the outside click action.
*/
const handleOutsideClick = () => {
if (outsideClickClose) {
dispatch(setAlertModel(false));
}
};
return (
{title}
{description}
);
};
export default SuccessModal;
```
--------------------------------
### Apply CSS Variables in Stylesheets
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/colors.mdx
Shows how to use defined CSS variables (e.g., --primary-color) within standard CSS rules to ensure consistent styling.
```css
.header {
background-color: var(--primary-color);
color: var(--background-color);
}
```
--------------------------------
### TypeScript Type Definition for Modal Variants
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/code-splitting.mdx
Demonstrates defining TypeScript types or interfaces in dedicated files to enforce type safety and improve code clarity, specifically for modal variants.
```typescript
// types/modalTypes.ts
export type ModalVariant = 'success' | 'warning' | 'danger' | 'login';
```
--------------------------------
### Protecting Against XSS Attacks in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/secure-coding.mdx
Illustrates methods to prevent Cross-Site Scripting (XSS) by properly escaping or sanitizing user input before rendering it to the DOM, contrasting with vulnerable direct rendering.
```javascript
// Rendering user input directly to the DOM
document.getElementById("user-content").innerHTML = userInput;
```
```javascript
// Escaping user input before rendering
const safeInput = escapeHtml(userInput);
document.getElementById("user-content").textContent = safeInput;
```
```javascript
// Example: Using DOMPurify to sanitize user input
const cleanInput = DOMPurify.sanitize(userInput);
document.getElementById("user-content").innerHTML = cleanInput;
```
--------------------------------
### Snake_case Database Table Naming
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
Illustrates good practices for naming database tables using snake_case, including the use of a 'tbl_' prefix for clarity.
```plaintext
tbl_users
tbl_payment_history
```
```plaintext
usersTable // Prefix 'tbl_' makes it clear it's a table
paymentHistory // Lacks prefix
```
--------------------------------
### Hooks and Utility File Naming Conventions
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
This section outlines naming conventions for non-component JavaScript or TypeScript files like hooks and utilities, offering both kebab-case and camelCase as valid options. It strongly emphasizes maintaining consistency throughout the project and warns against mixing conventions or using incorrect casing.
```plaintext
use-user-data.js
format-date.ts
user-types.ts
```
```plaintext
useUserData.js
formatDate.ts
userTypes.ts
```
```plaintext
useUserData.js // CamelCase mixed with...
format-date.ts // kebab-case in the same project
UseUserData.js // PascalCase for non-component files
formatDate.TS // Inconsistent file extension casing
```
--------------------------------
### Import State Management Tools in React
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/organizing-imports.mdx
For state management tools (like Redux), import them after your configuration files. This organizes global state dependencies.
```js
// ** import state manager
import { useDispatch } from "react-redux";
import { setLocale } from "@src/redux/slices/language";
```
--------------------------------
### UPPER_CASE_SNAKE_CASE for Constants in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/programming-case-types.mdx
Shows how to properly name constants using UPPER_CASE_SNAKE_CASE for better readability and distinction from variables.
```javascript
const MAX_RETRY_COUNT = 3;
const DEFAULT_TIMEOUT = 1000;
const API_BASE_URL = 'https://api.example.com';
```
```javascript
const maxRetry = 3; // Should be uppercase
const DefaultTimeout = 1000; // Should not use camelCase or PascalCase
const ApiBaseUrl = 'https://...';// Constants should be in uppercase
```
--------------------------------
### Preventing SQL Injection in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/secure-coding.mdx
Demonstrates how to prevent SQL injection by replacing vulnerable string concatenation with secure parameterized queries, protecting against malicious input.
```javascript
// Using string concatenation in SQL queries
const query = `SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`;
```
```javascript
// Using parameterized queries
const query = `SELECT * FROM users WHERE username = ? AND password = ?`;
db.query(query, [username, password]);
```
--------------------------------
### Secure Server-Side Price Validation in JavaScript
Source: https://github.com/jacksonkasi1/docs/blob/main/docs/secure-coding.mdx
This snippet demonstrates a secure approach to handling payment processing by validating product prices on the server-side. Instead of trusting client-supplied values, the server fetches the actual price from a reliable source, preventing parameter tampering and ensuring transaction integrity.
```javascript
// Secure approach
app.post("/process-payment", (req, res) => {
const { productId } = req.body;
const actualPrice = getProductPrice(productId); // Fetch the real price from the server
// Process payment with actualPrice, avoiding tampering
});
```