30 Seconds of Code

repository·master·Indexed 11 days ago

https://github.com/chalarangelo/30-seconds-of-code

A collection of short, high-impact coding articles and concise snippets designed to help developers improve their skills through practical explanations and examples.

Tokens
344.7K
Snippets
1.2K
Records
1.4K
Agent score
97%

What's inside 30 Seconds of Code

  1. Explore 30 seconds of code articles and collections

    master

    You can access a wide variety of coding articles designed to improve development skills via the official website. The platform allows you to:

    • Search: Find specific articles or collections using names, tags, languages, or descriptions.
    • Browse: View all available articles or browse by individual collections organized by topic.
    • View Details: Click on any article card to see the full content, which includes code snippets, detailed explanations, and usage examples.
  2. Understand DNS and common DNS record types

    master

    The Domain Name System (DNS) translates human-readable domain names (e.g., www.google.com) into machine-readable IP addresses (e.g., 142.250.186.46).

    Common DNS record types include:

    • A record: Maps a domain name to an IPv4 address.
    • AAAA record: Maps a domain name to an IPv6 address.
    • CNAME record: Creates an alias that points to another domain or subdomain (cannot point directly to an IP address).
    • ANAME record: Allows pointing the root of a domain to a hostname or domain name.
    • TXT record: Used for adding text notes, often for ownership verification, validation, or security.
    • MX record: Specifies the mail server responsible for incoming and outgoing emails for a domain. It must point to a mail server name, not an IP address.
  3. What is partial function application in JavaScript?

    master

    Partial application is a functional programming technique used to fix a number of arguments to a function, producing another function of smaller arity.

    This is useful for improving function reusability by pre-filling specific arguments, allowing you to derive specialized functions from more general ones. You can choose to either prepend (fix the start of the argument list) or append (fix the end of the argument list) the arguments.

  4. What is the Porter stemming algorithm?

    master

    The Porter stemming algorithm is a process used in Natural Language Processing (NLP) to reduce English words to their base or 'stem' forms by stripping away common suffixes that carry little semantic meaning.

    While it is limited to English and may not always produce linguistically accurate roots, it is a widely used, simple algorithm for building text-based search engines or basic NLP tools. The algorithm operates through a series of 5 main steps (with steps 1 and 5 subdivided into sub-steps) that apply specific rules to transform word endings.

  5. What is a Boolean trap and how to identify it

    master

    A Boolean trap is an anti-pattern where a function or constructor accepts a boolean argument without providing context for what true or false actually represents. This forces developers to consult documentation to understand the code, increasing cognitive load and reducing maintainability.

    Signs of a Boolean trap:

    • Ambiguous meaning: A boolean argument where the purpose of the flag is not clear from the function name (e.g., results.reload(false)—does false mean 'don't reload', 'don't do it immediately', or 'don't animate'?).
    • Hidden intent: A constructor that takes a boolean that represents a specific state or privilege (e.g., new User(true)—does true mean 'is admin', 'is active', or 'is guest'?).
    • Double negatives: Using a boolean to negate a function name, which makes the logic harder to parse (e.g., input.setInvalid(false)).
    // Ambiguous: What does `false` stand for?
    results.reload(false);
    
    // Ambiguous: What does `true` stand for?
    const user = new User(true);
    
    // Hard to parse: Double negative
    input.setInvalid(false);
  6. What is memoization and when to use it

    master

    Memoization is a technique used to speed up code by using a cache to store results of previously completed units of work. This avoids repeating expensive computations for the same inputs.

    Criteria for use:

    • Performance: Use it for slow-performing, costly, or time-consuming function calls.
    • Frequency: Use it when you anticipate multiple calls of the same function under the same circumstances.
    • Memory Constraints: Avoid it if the function is called under very different circumstances frequently, as results are stored in memory.
  7. Compare JavaScript cloning methods

    master

    When deep cloning objects in JavaScript, choose your method based on the data types you need to support.

    • shallowClone: Uses the spread operator ({ ...obj }). Only copies top-level properties; nested objects remain references to the original.
    • deepClone: A recursive custom implementation. Handles nested objects/arrays but often fails on built-in types, circular references, or prototype chains unless specifically engineered.
    • jsonClone: Uses JSON.parse(JSON.stringify(obj)). Fast but destructive: it drops functions, undefined, Symbol properties, and converts Date objects to strings. It throws an error on circular references.
    • structuredClone(): The native built-in method. It is the most robust for deep cloning, correctly handling built-in types (Map, Set, Date, RegExp) and circular references. However, it throws a DataCloneError if it encounters functions or DOM nodes.
    const shallowClone = obj => ({ ...obj });
    
    const deepClone = obj => {
      if (obj === null) return null;
      let clone = Object.assign({}, obj);
      Object.keys(clone).forEach(
        key =>
          (clone[key] =
            typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
      );
      if (Array.isArray(obj)) {
        clone.length = obj.length;
        return Array.from(clone);
      }
      return clone;
    };
    
    const jsonClone = obj => JSON.parse(JSON.stringify(obj));
  8. Iterate over Maps and Objects

    master

    Both Maps and Objects can be iterated, but they use different mechanisms:

    • Objects: Iteration typically requires helper methods like Object.keys(), Object.values(), or Object.entries(). These methods create arrays of the keys, values, or entries.
    • Maps: Maps are built for iteration. They provide built-in methods like .entries() (which returns a lazy iterator) and are directly iterable using for...of loops. This is generally more efficient for large datasets because iterators are lazy.
    // Object iteration
    const obj = { a: 1, b: 2, c: 3 };
    const objEntries = Object.entries(obj);
    for (const [key, value] of objEntries)
      console.log(`${key}: ${value}`);
    
    // Map iteration
    const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
    // Maps are directly iterable with for...of
    for (const [key, value] of map)
      console.log(`${key} => ${value}`);
  9. Enable pattern reusability through building blocks

    master

    To improve developer experience, design your API to allow users to create reusable patterns. This is achieved by providing atomic building blocks that can be composed into more complex structures. Once a pattern is defined, it should be easily combinable with other patterns using operators like or or repeat.

    // Creating a reusable block
    const hex = or(digit, range('a', 'f'));
    
    // Reusing the block in different contexts
    const threeHexes = new RegExp(repeat(hex, 3));
    const sixHexes = new RegExp(repeat(hex, 6));