Last active
November 3, 2024 06:55
-
-
Save zackiles/a1629f69d0e124a4778c8a9c9e644848 to your computer and use it in GitHub Desktop.
Prompt-Context: Style guide for code generators writing modern Javascript & Typescript (JSON)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "StyleGuide": { | |
| "Title": "JavaScript and TypeScript Coding Style Guide", | |
| "Introduction": "This style guide outlines the best practices for writing modern, idiomatic, and maintainable JavaScript and TypeScript code, leveraging the latest ECMAScript features (ES2022 and above). It is designed to ensure code consistency, readability, and adherence to industry standards.", | |
| "Sections": [ | |
| { | |
| "Number": "1", | |
| "Title": "Code Formatting", | |
| "Rules": [ | |
| "Indentation: Use **2 spaces** for indentation.", | |
| "Semicolons: **Omit semicolons** unless absolutely necessary (e.g., to avoid ASI pitfalls).", | |
| "Line Length: Keep lines under **100 characters** where possible for readability.", | |
| "Quotes: Use **single quotes** for strings, unless using template literals.", | |
| "Trailing Commas: Include **trailing commas** in multiline object and array literals.", | |
| "Spacing: Use spaces around operators and after commas. Do not add spaces inside parentheses. Separate the most important or noteworthy, or logical parts of code with spaces." | |
| ] | |
| }, | |
| { | |
| "Number": "2", | |
| "Title": "Modern ECMAScript Features", | |
| "Rules": [ | |
| "Use Latest Features: Embrace new and experimental ECMAScript features from ES2022 onwards.", | |
| "Modules: Use **ESM modules** (`import` and `export` syntax).", | |
| "Top-Level `await`: Utilize top-level `await` in modules where appropriate.", | |
| "Private Class Fields: Use `#` prefix for **private class fields**.", | |
| "Promise Enhancements: Use `Promise.withResolvers()` for cleaner asynchronous code.", | |
| "Logical Assignment Operators: Utilize `&&=`, `||=`, and `??=` for concise logic.", | |
| "Numeric Separators: Use `_` to improve readability of large numbers (e.g., `1_000_000`).", | |
| "Nullish Coalescing Operator: Use `??` to provide defaults for `null` or `undefined`.", | |
| "Optional Chaining: Use `?.` to safely access nested object properties.", | |
| "RegExp Match Indices: Use the `d` flag to get start and end indices of matches.", | |
| "Error Cause: Pass a cause when throwing errors (e.g., `throw new Error('Message', { cause: originalError })`).", | |
| "Object.hasOwn(): Prefer `Object.hasOwn(obj, prop)` over `obj.hasOwnProperty(prop)`." | |
| ] | |
| }, | |
| { | |
| "Number": "3", | |
| "Title": "Modules and Imports", | |
| "Rules": [ | |
| "Node.js Built-ins: Use `'node:'` prefix when importing Node.js built-in modules (e.g., `import fs from 'node:fs'`).", | |
| "JSON Imports: Use the `assert` type for JSON imports (e.g., `import data from './data.json' assert { type: 'json' }`).", | |
| "Import Order: Group imports logically: built-in modules, third-party packages, and local modules.", | |
| "Extensions: Omit file extensions in import paths when possible.", | |
| "Exports:" | |
| ], | |
| "SubRules": [ | |
| "Consolidated Exports: Place all export declarations at the **bottom** of the file for readability.", | |
| "Named Exports: Export functions, classes, or variables that were declared above.", | |
| "Function Declarations: For functions that will be exported, use the `function` declaration syntax instead of arrow functions. Reserve arrow functions for local/private use." | |
| ], | |
| "CodeExample": { | |
| "Language": "javascript", | |
| "Code": "// Imports\nimport fs from 'node:fs';\nimport express from 'express';\n\n// Configuration Variables\nconst PORT = process.env.PORT ?? 3000;\n\n// Code\nfunction getData() {\n // ...\n}\n\n// Local function\nconst helper = () => {\n // ...\n};\n\n// Exports\nexport { getData };" | |
| } | |
| }, | |
| { | |
| "Number": "4", | |
| "Title": "Variables and Constants", | |
| "Rules": [ | |
| "`const` and `let`: Use `const` by default; use `let` only when reassignment is needed. Avoid `var`.", | |
| "Destructuring: Use object and array destructuring for cleaner code.", | |
| "Default Parameters: Use default parameter values in functions instead of mutating arguments.", | |
| "Immutable Data: Favor immutability where possible to prevent side effects.", | |
| "Configuration Variables:" | |
| ], | |
| "SubRules": [ | |
| "Placement: Define important configuration variables at the **top** of the code file, immediately after imports.", | |
| "Shared Configuration: Variables that are used across multiple files should be placed in the `.env` file if appropriate." | |
| ], | |
| "CodeExample": { | |
| "Language": "javascript", | |
| "Code": "// Imports\nimport dotenv from 'dotenv';\n\n// Configuration Variables\nconst MAX_CONNECTIONS = 10;\nconst TIMEOUT = process.env.TIMEOUT ?? 5000;\n\n// Code\nfunction connect() {\n // ...\n}" | |
| } | |
| }, | |
| { | |
| "Number": "5", | |
| "Title": "Functions and Arrow Functions", | |
| "Rules": [ | |
| "Function Declarations: Use `function` declarations for named functions that are exported or reused.", | |
| "Arrow Functions: Use arrow functions for anonymous functions, callbacks, or functions used locally within a module.", | |
| "No Callback Hell: Avoid deeply nested callbacks; use Promises or async functions instead.", | |
| "Pure Functions: Write pure functions that do not cause side effects when possible.", | |
| "Function Naming: Use **camelCase** for function names." | |
| ] | |
| }, | |
| { | |
| "Number": "6", | |
| "Title": "Classes and Objects", | |
| "Rules": [ | |
| "Class Syntax: Use ES6 class syntax for object-oriented programming.", | |
| "Private Fields: Use `#` for private fields and methods in classes.", | |
| "Getters and Setters: Use `get` and `set` for computed properties.", | |
| "Method Shorthand: Use method shorthand in object literals (e.g., `const obj = { method() {} }`).", | |
| "Class Naming: Use **PascalCase** for class names." | |
| ] | |
| }, | |
| { | |
| "Number": "7", | |
| "Title": "Error Handling and Logging", | |
| "Rules": [ | |
| "Error Handling: Use `try`/`catch` blocks for error handling in asynchronous code.", | |
| "Error Causes: Utilize the `cause` property when throwing errors to retain original error information.", | |
| "Logging: Implement meaningful logging and tracing using appropriate logging libraries or built-in console methods.", | |
| "Avoid Silent Failures: Ensure that errors are not swallowed silently." | |
| ] | |
| }, | |
| { | |
| "Number": "8", | |
| "Title": "Comments and Documentation", | |
| "Rules": [ | |
| "JSDoc Comments: Use JSDoc to document functions, classes, and important modules.", | |
| "Avoid Inline Comments: Write self-explanatory code to minimize the need for inline comments.", | |
| "Documentation: Maintain up-to-date README and other documentation files to aid understanding." | |
| ] | |
| }, | |
| { | |
| "Number": "9", | |
| "Title": "TypeScript Practices", | |
| "Rules": [ | |
| "Type Annotations: Use type annotations where they add clarity, especially for function signatures and public interfaces.", | |
| "Type Inference: Leverage TypeScript's type inference to keep code concise.", | |
| "Assume Strict Mode: Code assuming that strict type checking is enabled.", | |
| "Prefer `unknown` over `any`: Use `unknown` instead of `any` to enforce type safety.", | |
| "Type Guards and Casting:" | |
| ], | |
| "SubRules": [ | |
| "Perform type guards and type casting at the earliest point possible, ideally at the boundaries of classes and methods.", | |
| "Avoid scattering type checks throughout the codebase; keep them minimal and localized." | |
| ], | |
| "RulesContinued": [ | |
| "Avoid Overusing Types: Do not add types where they are obvious or unnecessary.", | |
| "Generics: Use generics for functions and classes that operate on multiple types." | |
| ] | |
| }, | |
| { | |
| "Number": "10", | |
| "Title": "Code Practices", | |
| "Rules": [ | |
| "DRY Principle: Don't Repeat Yourself—abstract common logic into reusable functions or modules.", | |
| "Functional Programming: Utilize functional programming paradigms where appropriate (e.g., `map`, `filter`, `reduce`).", | |
| "Control Structures: Prefer `for...of` loops over `.forEach()` for better control flow.", | |
| "Avoid Mutations: Avoid mutating parameters or global variables.", | |
| "Centralized Types:" | |
| ], | |
| "SubRules": [ | |
| "Place shared types in a central `types.ts` file for easy access.", | |
| "Regularly review your code to identify common types that can be moved to `types.ts`.", | |
| "Refactor code to remove duplicated type definitions and import them from `types.ts`." | |
| ], | |
| "RulesContinued": [ | |
| "Reflect and Proxy Usage:" | |
| ], | |
| "SubRulesContinued": [ | |
| "Leverage Reflect and Proxy: Utilize the `Reflect` namespace and `Proxy` object in JavaScript where they provide cleaner, more concise, or more maintainable solutions compared to alternative approaches.", | |
| "Use Cases: Apply `Proxy` for meta-programming tasks such as property validation, logging, or dynamic behavior modification. Use `Reflect` to handle default operations within proxy handlers to maintain standard behavior." | |
| ], | |
| "CodeExample": { | |
| "Language": "javascript", | |
| "Code": "const handler = {\n get(target, prop, receiver) {\n console.log(`Property ${prop} accessed`);\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop, value, receiver) {\n if (typeof value === 'string') {\n throw new TypeError('Only non-string values are allowed');\n }\n return Reflect.set(target, prop, value, receiver);\n }\n};\n\nconst obj = new Proxy({}, handler);\nobj.foo = 42; // Works\nobj.foo = 'bar'; // Throws TypeError" | |
| } | |
| }, | |
| { | |
| "Number": "11", | |
| "Title": "Advanced ECMAScript Features", | |
| "Rules": [ | |
| "Temporal API: Use the upcoming `Temporal` API for date and time operations when available.", | |
| "Pattern Matching: Prepare for potential future syntax like pattern matching.", | |
| "RegExp Enhancements: Utilize new RegExp flags and features as they become standardized.", | |
| "Stage Proposals: Stay informed about ECMAScript stage 3 and 4 proposals that may soon become part of the standard." | |
| ] | |
| }, | |
| { | |
| "Number": "12", | |
| "Title": "Examples of Modern Syntax", | |
| "CodeExample": { | |
| "Language": "javascript", | |
| "Code": "// Top-level await\nconst data = await fetchData();\n\n// Private class fields\nclass User {\n #password;\n constructor(password) {\n this.#password = password;\n }\n}\n\n// Nullish coalescing and optional chaining\nconst username = user.profile?.username ?? 'Guest';\n\n// Logical assignment operators\nconfig.cache ||= createDefaultCache();\n\n// Promise.withResolvers()\nconst { promise, resolve, reject } = Promise.withResolvers();\n\n// Object.hasOwn()\nif (Object.hasOwn(config, 'timeout')) {\n setTimeout(config.timeout);\n}" | |
| } | |
| }, | |
| { | |
| "Number": "13", | |
| "Title": "Naming Conventions", | |
| "Rules": [ | |
| "File Names: Use **kebab-case** for file names (e.g., `my-component.ts`).", | |
| "Functions/Methods/Variables/Instances: Use **camelCase** (e.g., `getData`, `userProfile`).", | |
| "Classes/Models/Schemas: Use **PascalCase** (e.g., `UserModel`, `OrderSchema`).", | |
| "Consistency: Follow the naming conventions unless they conflict with the conventions of a library or codebase being used." | |
| ] | |
| } | |
| ], | |
| "Conclusion": "By adhering to this style guide, you will produce clean, modern, and maintainable code that leverages the full power of the latest JavaScript and TypeScript features. This will facilitate collaboration, ease of understanding, and scalability in your projects." | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment