duminghong Technical Notes and Courses

website·Indexed 31 days ago

https://blog.duminghong.com

A collection of technical documentation and tutorials covering TypeScript (classes, generics, interfaces, and function overloading), JavaScript asynchronous programming (Promise, async/await, and the Event Loop), CSS layout techniques, and Node.js environment management tools like cross-env, dotenv-flow, and js-yaml. It also includes practical guides for WeChat Mini Program development and audio visualization using AudioContext.

Tokens
32K
Snippets
165
Records
205
Agent score
50%

What's inside duminghong Blog

  1. Introduction to TypeScript Generics

    Generics allow developers to create reusable components (functions, interfaces, or classes) without specifying a concrete type at definition time. Instead, the type is dynamically specified when the component is used, ensuring both flexibility and type safety. This avoids code duplication (DRY principle) and prevents the loss of type information that occurs when using any.
  2. Overview of dotenv-flow for environment management

    dotenv-flow is an enhanced environment variable management tool based on dotenv. Unlike the standard dotenv which only loads a single .env file, dotenv-flow natively supports multiple environments (development, test, production) and local private overrides, allowing for automatic switching based on the environment and support for variable nesting.
  3. Understand Promise State Absorption in JavaScript

    Promise state absorption occurs when one Promise 'absorbs' the state of another. When the source Promise's state changes, the absorbing Promise follows suit, adopting the same state (fulfilled or rejected) and the corresponding value or reason. This ensures consistency and sequential execution of asynchronous operations.
  4. Understand the Browser Multi-Process Architecture

    Modern browsers use a multi-process architecture to improve security, stability, and performance. Each process has its own independent memory space. The primary processes include:

    • Browser Process: Manages the browser UI (address bar, bookmarks), handles non-page user interactions, manages the lifecycle of other processes, and coordinates inter-process communication (IPC).
    • Network Process: Handles all network requests (HTTP, WebSocket), DNS resolution, resource loading, and caching.
    • Renderer Process: Responsible for rendering webpage content (HTML, CSS, JS). Typically, each tab has its own renderer process (Site Isolation) and operates within a sandbox for security.
    • GPU Process: Handles GPU-related tasks like 3D rendering, hardware acceleration, and WebGL, synthesizing output from renderer processes to the screen.
    • Plugin Process: Runs plugins (e.g., PDF readers) in isolation so that a plugin crash does not crash the browser.
    • Extension Process: Runs browser extensions isolated from webpage content.
    • Service Worker Process: Runs Service Worker scripts for offline caching, background sync, and push notifications, independent of the renderer process.
    • Utility Process: Handles system-level tasks like audio processing or video decoding.
    • Crash Handler Process: Monitors other processes and collects crash reports.
  5. Use async/await to simplify asynchronous JavaScript

    async/await is syntactic sugar built on top of Promises. It allows developers to write asynchronous code that looks and behaves like synchronous code, improving readability and maintainability. It is particularly useful for replacing complex Promise chains, simplifying error handling with try/catch, and managing asynchronous logic within loops and conditional statements.
    async function fetchData() {
      try {
        // Wait for the asynchronous operation to complete
        const data = await someAsyncOperation();
        return data;
      } catch (error) {
        // Handle errors
        throw error;
      }
    }
  6. Understand the JavaScript Event Loop execution flow

    The Event Loop is the core mechanism of the browser's main rendering thread that enables asynchronous behavior in a single-threaded environment. It follows a continuous cycle of fetching a task, executing it, and then rendering the page.

    The execution sequence is as follows:

    1. Check if the Task Queue is empty.
    2. If not empty, take one task from the Task Queue and execute it.
    3. After the task completes, check and fully clear the Microtask Queue.
    4. If a screen update is required, enter the Rendering Phase.
    5. Repeat from step 1.
  7. Understand Iconfont concepts and trade-offs

    Icon fonts are icons created as font characters. They are widely used in flat design for their ability to scale without loss of quality and fast loading times compared to images.

    Advantages:

    • Scalability: Can be resized freely without blurring.
    • Performance: Smaller file size than image sets, leading to faster loads.
    • Styling: Colors can be changed easily via CSS.

    Disadvantages:

    • Color Limits: Limited to single colors or CSS3 gradients.
    • Complexity: Creating custom font icons is time-consuming and has higher maintenance costs.
  8. Understand Promise and Thenable objects

    A Promise is a JavaScript object used for asynchronous operations that represents the eventual completion (or failure) and its resulting value.

    An object is considered thenable or PromiseLike if it possesses a then method. While all strict Promises are thenables, not all thenables are strict Promises (they must adhere to the Promise/A+ specification to be 'true' Promises).

    // Check if an object is PromiseLike
    function isPromiseLike(value) {
      return value && typeof value.then === 'function'
    }
  9. Understand the JavaScript Event Loop mechanism

    The Event Loop is the core working mechanism of the browser's rendering main thread. It enables asynchronous behavior in JavaScript's single-threaded environment by implementing a continuous loop consisting of three primary stages: fetching a task, executing the task, and rendering the page.
  10. Choose between function overloading and union types

    While both handle multiple input types, the choice depends on whether the return type needs to change based on the input.

    • Use Function Overloading when different input types must result in different, specific return types. This provides precise type inference for the caller.
    • Use Union Types when different input types share the same return type or when a broad union return type is acceptable. This results in cleaner, more concise code.
    // Overloading: Precise return type inference
    function process(value: string): string;
    function process(value: number): number;
    function process(value: string | number): string | number {
      return typeof value === 'string' ? value.toUpperCase() : value * 2;
    }
    const res1 = process("hello"); // Type is 'string'
    const res2 = process(123);      // Type is 'number'
    
    // Union Type: Broad return type inference
    function processUnion(value: string | number): string | number {
      return typeof value === 'string' ? value.toUpperCase() : value * 2;
    }
    const res3 = processUnion("hello"); // Type is 'string | number'
    const res4 = processUnion(123);     // Type is 'string | number'
  11. Define and use Enums for semantic constants

    Enums allow you to define a set of named constants. Numeric enums support reverse mapping (getting the name from the value), while string enums are preferred for API-related scenarios for better clarity.
    // Numeric Enum (supports reverse mapping)
    enum Direction {
      Up,    // 0
      Down,  // 1
    }
    console.log(Direction.Up); // 0
    console.log(Direction[0]); // "Up"
    
    // String Enum (recommended for APIs)
    enum HttpStatus {
      OK = "OK",
      NotFound = "NOT_FOUND"
    }
  12. Create a custom Iconfont manually

    To create a custom icon font manually using font editing software, follow these steps: 1. Create a new font file. 2. Copy a character from an existing font and paste it into the new font to establish a baseline. 3. Import your icon image (e.g., a logo) into the font software. 4. Position the image, delete the original character glyph, and save. 5. Test the resulting font in a web page. Because different browsers require different formats, you must convert the final font into four formats (.woff, .ttf, .eot, .svg) using online tools like FontSquirrel, FreeFontConverter, or Font2Web.