### Installing a Specific Package Version with npm Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/semantic-versioning.md Shows how to install a specific version of a package using the npm command-line interface. This command ensures that the exact version specified is installed, which is useful for maintaining consistent environments. ```shell npm install my-package@1.0.0 ``` -------------------------------- ### CSS Styling Example Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/demo/s/test-snippet.md Provides an example of CSS styling for a class named `.something`, setting its display property to flex and its direction to column. This is typical for layout adjustments. ```css .something { display: flex; flex-direction: column; } ``` -------------------------------- ### Binary Tree Usage Examples in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/data-structures-binary-tree.md Demonstrates the usage of the BinaryTree class. It shows how to create a tree, insert nodes, perform different traversals, check node properties like isLeaf and hasChildren, find nodes, and remove nodes. The examples illustrate the expected output for various operations. ```javascript const tree = new BinaryTree(1, 'AB'); tree.insert(1, 11, 'AC'); tree.insert(1, 12, 'BC'); tree.insert(12, 121, 'BG', { right: true }); [...tree.preOrderTraversal()].map(x => x.value); // ['AB', 'AC', 'BC', 'BCG'] [...tree.inOrderTraversal()].map(x => x.value); // ['AC', 'AB', 'BC', 'BG'] tree.root.value; // 'AB' tree.root.hasChildren; // true tree.find(12).isLeaf; // false tree.find(121).isLeaf; // true tree.find(121).parent.value; // 'BC' tree.find(12).left; // null tree.find(12).right.value; // 'BG' tree.remove(12); [...tree.postOrderTraversal()].map(x => x.value); // ['AC', 'AB'] ``` -------------------------------- ### JavaScript Graph Usage Examples Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/data-structures-graph.md Demonstrates the usage of the `Graph` class in JavaScript. This includes creating a graph instance, adding nodes and edges, performing operations like removing edges and nodes, checking for edge existence, and retrieving edge weights. It also shows how to get adjacent nodes and calculate in-degree and out-degree for a given node. ```javascript const g = new Graph(); g.addNode('a'); g.addNode('b'); g.addNode('c'); g.addNode('d'); g.addEdge('a', 'c'); g.addEdge('b', 'c'); g.addEdge('c', 'b'); g.addEdge('d', 'a'); g.nodes.map(x => x.value); // ['a', 'b', 'c', 'd'] [...g.edges.values()].map(({ a, b }) => `${a} => ${b}`); // ['a => c', 'b => c', 'c => b', 'd => a'] g.adjacent('c'); // ['b'] g.indegree('c'); // 2 g.outdegree('c'); // 1 g.hasEdge('d', 'a'); // true g.hasEdge('a', 'd'); // false g.removeEdge('c', 'b'); [...g.edges.values()].map(({ a, b }) => `${a} => ${b}`); // ['a => c', 'b => c', 'd => a'] g.removeNode('c'); g.nodes.map(x => x.value); // ['a', 'b', 'd'] [...g.edges.values()].map(({ a, b }) => `${a} => ${b}`); // ['d => a'] g.setEdgeWeight('d', 'a', 5); g.getEdgeWeight('d', 'a'); // 5 ``` -------------------------------- ### Real-world Node.js test example with describe and beforeEach Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/nodejs-test-module-introduction.md A comprehensive example of testing a 'doubleAndSum' function using Node.js's test module. It utilizes 'describe' to group tests and 'beforeEach' to set up test data before each subtest. ```javascript import test, { describe } from 'node:test'; import assert from 'node:assert/strict'; const doubleAndSum = (arr, mod = 0) => { let sum = 0; Object.entries(arr).forEach(([i, v]) => { if (v % 2 === mod) arr[i] = v * 2; else sum += v; }); return sum; }; describe('doubleAndSum', () => { let arr, sum; test('when mod is 0', async t => { t.beforeEach(() => { arr = [1, 2, 3]; sum = doubleAndSum(arr, 0); }); await t.test('sums the even values', () => { assert.equal(sum, 4); }); await t.test('doubles the even values', () => { assert.equal(arr[1], 4); }); }); test('when mod is 1', async t => { t.beforeEach(() => { arr = [1, 2, 3]; sum = doubleAndSum(arr, 1); }); await t.test('sums the even values', () => { assert.equal(sum, 2); }); await t.test('doubles the odd values', () => { assert.equal(arr[0], 2); assert.equal(arr[2], 6); }); }); }); ``` -------------------------------- ### Example Usage of Singletonify in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/singleton-proxy.md This example demonstrates the practical application of the `singletonify` function. A `MyClass` is defined, and then `singletonify` is used to create a singleton version, `MySingletonClass`. Subsequent instantiations of `MySingletonClass` will always return the first created instance, as shown by the output. ```javascript class MyClass { constructor(msg) { this.msg = msg; } printMsg() { console.log(this.msg); } } MySingletonClass = singletonify(MyClass); const myObj = new MySingletonClass('first'); myObj.printMsg(); // 'first' const myObj2 = new MySingletonClass('second'); myObj2.printMsg(); // 'first' ``` -------------------------------- ### Example Usage of Custom Serializer Attributes (JavaScript) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/complex-object-serialization.md These JavaScript examples show how to instantiate and use the `PostSerializer`. The first example serializes a post without additional options, while the second demonstrates how to include the author's email by passing `{ showEmail: true }` as an option. ```javascript // Considering the post object from the previous examples new PostSerializer(post).serialize(); // { // title: 'Hello, World!', // content: '

Lorem ipsum dolor sit amet.

', // date: 'Sun, Dec 1, 2024' // } new PostSerializer(post, { showEmail: true }).serialize(); // { // title: 'Hello, World!', // content: '

Lorem ipsum dolor sit amet.

', // date: 'Sun, Dec 1, 2024', // author: { // name: 'John Doe', // email: 'j.doe@authornet.io' // } // } ``` -------------------------------- ### Install exact dependencies with npm ci Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/how-to-secure-your-js-code-from-vulnerable-dependencies.md Ensure reproducible builds by installing dependencies exactly as specified in your lockfile using the `npm ci` command. This command is faster than `npm install` and prevents unintentional upgrades by adhering strictly to the `package-lock.json` or `npm-shrinkwrap.json`. ```shell npm ci ``` -------------------------------- ### Interactive Rebase Actions and Todo List Example Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/git/s/interactive-rebase.md Details common actions available during an interactive rebase, such as pick, reword, edit, squash, drop, fixup, exec, and break. The example shows how these actions are represented in the rebase todo list file. ```git-rebase-todo p c191f90c7 Initial commit # Keep this commit pick 3050fc0de Fix network bug # Keep this commit r 7b1e3f2a2 Update README # Edit the commit message d 3e4f5d6a7 Commit sensitive data # Remove this commit edit 9a8b7c6d5 Add new feature # Stop for amending pick 1a2b3c4d5 Fix bug # Keep this commit f 6d5c4b3a2 Add new feature # Squash this fixup commit pick 5a6b7c8d9 Update README # Keep this commit s 4b3c2d1a0 Update README # Squash this commit ``` -------------------------------- ### Intercept 'get' Operation with JavaScript Proxy Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/proxy-introduction.md Demonstrates using a JavaScript Proxy to intercept 'get' operations. This example creates a proxy that returns null for properties not found in the target object, providing a default behavior for property access. It requires a target object and a handler with a 'get' trap. ```javascript const targetObj = { name: 'John', age: 30 }; const handler = { get(target, property) { return property in target ? target[property] : null; } }; const proxyObj = new Proxy(targetObj, handler); proxyObj.name; // 'John' proxyObj.age; // 30 proxyObj.address; // null ``` -------------------------------- ### Build and Development CLI Commands (Bash) Source: https://context7.com/chalarangelo/30-seconds-of-code/llms.txt Provides commands for building, developing, and managing content through the command line using the 'prepare' script. Supports full production builds, development builds with options for fast highlighting, and watch mode for continuous development. ```bash # Full production build (assets + content + all generators) bin/prepare full # Development build (content + Astro content + search index) bin/prepare dev bin/prepare dev --fast-highlight # Use Prism for faster rebuilds # Watch mode for development bin/prepare watch bin/prepare watch --fast-highlight # Prepare specific parts bin/prepare content # Only process content bin/prepare assets # Only process assets bin/prepare assets --force # Force regenerate all assets ``` -------------------------------- ### Get First N Elements of JavaScript Array Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/take-n-elements-from-array-start-or-end.md This function retrieves the first N elements from a JavaScript array. It utilizes `Array.prototype.slice()` with a start index of 0 and an end index of N. It handles cases where N is 0, greater than the array length, or negative, although negative values might produce unexpected results without additional validation. ```javascript const take = (arr, n = 1) => arr.slice(0, n); take([1, 2, 3], 0); // [] take([1, 2, 3], 2); // [1, 2] take([1, 2, 3], 5); // [1, 2, 3] ``` -------------------------------- ### Get Base URL in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/get-base-url-or-url-params.md Retrieves the base URL from a given URL string by removing any query parameters or fragment identifiers. It uses a regular expression to find and remove characters starting from '?' or '#'. ```javascript const getBaseURL = url => url.replace(/[?#].*$/, ''); getBaseURL('http://url.com/page?name=Adam&surname=Smith'); // 'http://url.com/page' ``` -------------------------------- ### package.json Example for SemVer Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/semantic-versioning.md Demonstrates the basic structure of a package.json file, highlighting the 'version' field which adheres to Semantic Versioning (SemVer) standards. This file is crucial for npm to manage package versions and dependencies. ```json { "name": "my-package", "version": "1.0.0" } ``` -------------------------------- ### Example Conventional Commits Template Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/git/s/commit-template.md An example commit message template file that follows the Conventional Commits specification. This template guides users to structure their commit messages with type, scope, description, body, and footers. ```shell # [optional scope]: # feat: add new feature # fix: bug fix # Append a `!` to indicate a breaking change # [optional body] # [optional footer(s)] # BREAKING CHANGE: introduce breaking change # Specification: https://www.conventionalcommits.org/en/v1.0.0/#specification ``` -------------------------------- ### Get Element Ancestors in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/get-ancestors-parents-siblings-children.md Retrieves all ancestor elements of a given HTML element, starting from the element itself up to the document root. It uses a `while` loop and `Node.parentNode` to traverse upwards, adding each ancestor to the beginning of an array using `Array.prototype.unshift()`. ```javascript const getAncestors = el => { let ancestors = []; while (el) { ancestors.unshift(el); el = el.parentNode; } return ancestors; }; getAncestors(document.querySelector('nav')); // [document, html, body, header, nav] ``` -------------------------------- ### Find Python 3 and pip 3 paths Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/python/s/setup-python3-pip3-as-default.md Uses the `which` command to locate the installation paths for Python 3 and pip 3. This is the first step in setting them as defaults. ```shell which python3 which pip3 ``` -------------------------------- ### Get Elements from Start of Array While Condition is Met (JavaScript) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/take-elements-by-condition-from-array-start-or-end.md Retrieves elements from the beginning of an array as long as a provided condition function returns true for each element. It uses `findIndex` to locate the first element that does not meet the condition and `slice` to extract the preceding elements. If no element fails the condition, the entire array is returned. Returns an empty array if the input array is empty or if the condition is not met by any element. ```javascript const takeWhile = (arr, fn) => { const index = arr.findIndex(n => !fn(n)); return index === -1 ? arr : arr.slice(0, index); }; takeWhile([1, 2, 3, 4], n => n < 0); // [] takeWhile([1, 2, 3, 4], n => n < 3); // [1, 2] takeWhile([1, 2, 3, 4], n => n < 5); // [1, 2, 3, 4] ``` -------------------------------- ### Binary Search Tree Traversal Example in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/data-structures-binary-search-tree.md Demonstrates the usage of the `BinarySearchTree` class by inserting several nodes and then performing a pre-order traversal to display the values in the order they are visited. ```javascript const tree = new BinarySearchTree(30); tree.insert(10); tree.insert(15); tree.insert(12); tree.insert(40); tree.insert(35); tree.insert(50); [...tree.preOrderTraversal()].map(x => x.value); // [30, 10, 15, 12, 40, 35, 50] ``` -------------------------------- ### Get Elements from End of Array While Condition is Met (JavaScript) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/take-elements-by-condition-from-array-start-or-end.md Extracts elements from the end of an array as long as a provided condition function returns true for each element. It leverages `findLastIndex` to find the index of the first element (from the end) that does not satisfy the condition and then uses `slice` to get the subsequent elements. If no element fails the condition, the entire array is returned. Returns an empty array if the input array is empty or if the condition is not met by any element. ```javascript const takeRightWhile = (arr, fn) => { const index = arr.findLastIndex(n => !fn(n)); return index === -1 ? arr : arr.slice(index + 1); }; takeRightWhile([1, 2, 3, 4], n => n > 5); // [] takeRightWhile([1, 2, 3, 4], n => n > 2); // [3, 4] takeRightWhile([1, 2, 3, 4], n => n > 0); // [1, 2, 3, 4] ``` -------------------------------- ### Log in to npm (Shell) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/tdd-library-implementation-with-vite-vitest.md This shell command initiates the npm login process, prompting the user for credentials to authenticate with the npm registry. This is a prerequisite for publishing packages. ```shell npm login ``` -------------------------------- ### Check if a value is an async function in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/complete-guide-to-js-type-checking.md Tests if a value is an asynchronous function. This is achieved by using `Object.prototype.toString.call()` to get the internal `[[Class]]` property of the function, which returns '[object AsyncFunction]' for async functions. ```javascript const isAsyncFunction = val => Object.prototype.toString.call(val) === '[object AsyncFunction]'; isAsyncFunction(function() {}); // false isAsyncFunction(async function() {}); // true ``` -------------------------------- ### ObjectCollection: Example Usage Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/indexed-object-collections.md Demonstrates how to instantiate and use the ObjectCollection class. It shows adding objects with various properties, including dynamically generated ones, and implies the collection's ability to manage and potentially index these objects. ```javascript import ObjectCollection from './objectCollection.js'; import ObjectIndex from './objectIndex.js'; const collection = new ObjectCollection(); // Add objects to the collection const fruits = [ 'Grape', 'Pear', 'Peach', 'Plum', 'Kiwi', 'Mango', 'Pineapple', 'Cherry', 'Strawberry', 'Blueberry', 'Watermelon', 'Melon', 'Papaya', 'Lemon', 'Lime' ]; collection.add({ name: 'Banana', status: 'fresh', origin: 'Ecuador' }); collection.add({ name: 'Apple', status: 'fresh', origin: 'USA', price: 2.0 }); collection.add({ name: 'Orange', status: 'fresh', origin: 'Brazil' }); const origin = ['Greece', 'Italy', 'Spain', 'France']; for (const fruit of fruits) { const roll = Math.random(); const statuses = roll < 0.33 ? ['fresh'] : roll < 0.66 ? ['rotten'] : ['fresh', 'rotten']; statuses.forEach(status => { const originIndex = Math.floor(Math.random() * origin.length); ``` -------------------------------- ### Non-mutating Array Element Removal (JavaScript) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/remove-elements-from-array.md Removes a specified number of elements from an array starting at a given index without modifying the original array. It uses `slice()` to get the parts of the array before and after the removed elements, and `concat()` to combine these parts with any new elements to be inserted. The function accepts the array, the starting index, the number of elements to delete, and any elements to insert. ```javascript const shank = (arr, index = 0, delCount = 0, ...elements) => arr .slice(0, index) .concat(elements) .concat(arr.slice(index + delCount)); const names = ['alpha', 'bravo', 'charlie']; const namesAndDelta = shank(names, 1, 0, 'delta'); // [ 'alpha', 'delta', 'bravo', 'charlie' ] const namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ] console.log(names); // ['alpha', 'bravo', 'charlie'] ``` -------------------------------- ### Get Last N Elements of JavaScript Array Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/take-n-elements-from-array-start-or-end.md This function retrieves the last N elements from a JavaScript array. It uses `Array.prototype.slice()` with a negative index to count from the end. The provided solution includes a ternary operator to correctly handle cases where N is 0, returning an empty array. It also addresses potential issues with N exceeding the array length. ```javascript const takeRight = (arr, n = 1) => n === 0 ? [] : arr.slice(-n); takeRight([1, 2, 3], 2); // [2, 3] takeRight([1, 2, 3], 0); // [] takeRight([1, 2, 3], 5); // [1, 2, 3] ``` -------------------------------- ### Basic Test Structure with Vitest Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/test-driven-development-intro.md Demonstrates a fundamental test case using Vitest's describe, it, and expect functions. This snippet shows how to import the function to be tested and assert its expected behavior. ```javascript import { describe, it, expect } from 'vitest'; import { myFunction } from '../src/myFunction.js'; describe('myFunction', () => { it('should return true when called', () => { expect(myFunction()).toBe(true); }); }); ``` -------------------------------- ### Initialize Git Repository (Git) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/git/s/create-repo.md Initializes a new Git repository in the current directory or a specified directory. This command sets up the necessary configuration files for Git to track changes within the project. It's safe to run multiple times, even in an existing repository. ```shell # Usage: git init [] cd ~/my_project git init # Initializes a repo in ~/my_project cd ~ git init my_project # Initializes a repo in ~/my_project ``` -------------------------------- ### Get the type of a value in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/complete-guide-to-js-type-checking.md Retrieves a string representation of the type of a given value. It handles `undefined` and `null` explicitly and for other types, it returns the `name` property of the value's constructor. This provides a more descriptive type name than `typeof` for built-in objects. ```javascript const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name; getType(undefined); // 'undefined' getType(null); // 'null' getType(true); // 'Boolean' getType(1); // 'Number' getType(1n); // 'BigInt' getType('Hello!'); // 'String' getType(Symbol()); // 'Symbol' getType([]); // 'Array' getType({}); // 'Object' getType(() => {}); // 'Function' getType(new Set([1, 2, 3])); // 'Set' ``` -------------------------------- ### Create Multiple Iterators for a SpecialList in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/iterators.md This example shows how to create a SpecialList class in JavaScript that supports multiple iterators. It leverages the native array iterator for default iteration and defines a separate 'values' iterator that filters and maps elements before iterating. This allows for flexible data traversal. ```javascript class SpecialList { constructor(data) { this.data = data; } [Symbol.iterator]() { return this.data[Symbol.iterator](); } values() { return this.data .filter(i => i.complete) .map(i => i.value) [Symbol.iterator](); } } const myList = new SpecialList([ { complete: true, value: 'Lorem ipsum' }, { complete: true, value: 'dolor sit amet' }, { complete: false }, { complete: true, value: 'adipiscing elit' }, ]); for (let item of myList) { console.log(item); // The exact data passed to the SpecialList constructor above } for (let item of myList.values()) { console.log(item); // 'Lorem ipsum', 'dolor sit amet', 'adipiscing elit' } ``` -------------------------------- ### Example Usage of Doubly Linked List in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/data-structures-doubly-linked-list.md This JavaScript code demonstrates how to use the `DoublyLinkedList` class. It shows examples of initializing a list, inserting elements at the beginning, end, and specific positions, accessing the head and tail, removing elements, reversing the list, and clearing it. It also illustrates how to iterate over the list. ```javascript const list = new DoublyLinkedList(); list.insertFirst(1); list.insertFirst(2); list.insertFirst(3); list.insertLast(4); list.insertAt(3, 5); list.size; // 5 list.head.value; // 3 list.head.next.value; // 2 list.tail.value; // 4 list.tail.previous.value; // 5 [...list.map(e => e.value)]; // [3, 2, 1, 5, 4] list.removeAt(1); // 2 list.getAt(1).value; // 1 list.head.next.value; // 1 [...list.map(e => e.value)]; // [3, 1, 5, 4] list.reverse(); [...list.map(e => e.value)]; // [4, 5, 1, 3] list.clear(); list.size; // 0 ``` -------------------------------- ### REPL Server Setup in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/complex-object-autoloading-console.md Initializes a Node.js REPL (Read-Eval-Print Loop) server and loads globally available modules into its context. It also sets up command history persistence. Dependencies include the 'node:repl' module and the autoloaded modules. ```javascript import repl from 'node:repl'; import modules from '#src/scripts/autoload.js'; // Start the REPL server const replServer = repl.start(); // Set up a history file for the REPL replServer.setupHistory('repl.log', () => {}); // Add the autoloaded modules to the REPL context Object.entries(modules).forEach(([moduleName, module]) => { replServer.context[moduleName] = module; }); ``` -------------------------------- ### JavaScript Closure: Counter Object with Encapsulated Value Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/closures.md This example illustrates a more complex use of closures in JavaScript. The `initCounter` function creates and returns an object with methods (`get`, `increment`, `decrement`, `reset`) that all access and manipulate a `value` variable defined within `initCounter`'s scope. This provides encapsulation and allows for multiple independent counters. ```javascript const initCounter = (start = 0) => { let value = start; return { get: () => value, increment: () => ++value, decrement: () => --value, reset: () => value = start }; } const counter = initCounter(5); counter.get(); // 5 counter.increment(); // 6 counter.increment(); // 7 counter.decrement(); // 6 counter.reset(); // 5 ``` -------------------------------- ### Convert Tilde Path to Absolute Path in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/convert-to-absolute-path.md Converts a string starting with a tilde (~) to an absolute path by replacing the tilde with the user's home directory. This function uses a regular expression to match tilde paths and the 'os.homedir()' function to get the home directory. It handles cases where the tilde is followed by a slash, backslash, or is at the end of the string. ```javascript import { homedir } from 'os'; const untildify = str => str.replace(/^~($|\/|\\)/, `${homedir()}$1`); untildify('~/node'); // '/Users/aUser/node' ``` -------------------------------- ### Run specific Node.js test files from the command line Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/nodejs-test-module-introduction.md Demonstrates how to specify individual test files or patterns to run when using the Node.js test runner from the command line. This allows for targeted execution of tests. ```shell node --test my-example.test.js ``` -------------------------------- ### Example Usage of Earley Parser in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/math-expression-parser.md Demonstrates how to instantiate the `EarleyParser` with a given CFG and tokens, and then parse these tokens to obtain an AST. The expected output structure of the AST is also shown. ```javascript const parser = new EarleyParser(cfg); const ast = parser.parse(tokens); /* { type: 'S', children: [ { type: 'S', children: [ { type: 'M', children: [ { type: 'T', value: '2' } ] }, ] }, { type: '+', value: '+' }, { type: 'M', children: [ { type: 'M', children: [ { type: 'T', value: '3' } ] }, { type: '*', value: '*' }, { type: 'T', value: '4' } ] } ] } */ ``` -------------------------------- ### Check if a number is in a given range (JavaScript) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/number-in-range.md Checks if a given number `n` falls within a specified numeric range defined by `start` and `end`. If `end` is null, the range is considered from 0 to `start`. It automatically swaps `start` and `end` if `start` is greater than `end` to ensure a valid range. This function is useful for input validation or filtering. ```javascript const inRange = (n, start, end = null) => { if (end && start > end) [end, start] = [start, end]; return end == null ? n >= 0 && n < start : n >= start && n < end; }; inRange(3, 2, 5); // true inRange(3, 4); // true inRange(2, 3, 5); // false inRange(3, 2); // false ``` -------------------------------- ### Recommended Array Initialization Patterns (JavaScript) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/array-initialization.md Presents recommended, performant patterns for initializing JavaScript arrays with values or dynamic content using Array() constructor, fill(), and map(). ```javascript const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); const initializeMappedArray = (n, mapFn = (_, i) => i) => Array(n).fill(null).map(mapFn); initializeArrayWithValues(4, 2); // [2, 2, 2, 2] initializeMappedArray(4, (_, i) => i * 2); // [0, 2, 4, 6] ``` -------------------------------- ### Resolve file paths using Node.js 'path' module Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/nodejs-static-file-server.md Demonstrates how to use the 'path' module in Node.js to correctly resolve file paths, allowing the server to serve files from a specified directory independent of the server's location. This improves modularity and cross-platform compatibility. ```javascript import { readFile } from 'fs'; import { join } from 'path'; const directoryName = './public'; const requestUrl = 'index.html'; const filePath = join(directoryName, requestUrl); readFile(filePath, (err, data) => { // ... }); ``` -------------------------------- ### Set HTML Ordered List Start Number Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/html/s/start-ordered-list-at-different-number.md This snippet demonstrates how to use the 'start' attribute within an
    tag to specify the initial number for an ordered list. It also shows how to apply this to nested lists and with different list styles. ```html
    1. Lorem
    2. Ipsum
      1. Dolor
      2. Sit
    3. Amet
    4. Consectetur
    ``` ```css ol ol { list-style-type: lower-roman; } ``` -------------------------------- ### Instantiate CFG with Defined Rules in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/math-expression-parser.md This snippet shows how to create an instance of the CFG class, passing in the previously defined array of rules. This initializes the grammar with all its production rules, making it ready for parsing operations. ```javascript const cfg = new CFG(rules); ``` -------------------------------- ### Modular Payment Gateway Example (JavaScript) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/articles/s/code-modularization.md Demonstrates a modular approach to a payment gateway in JavaScript. It separates concerns into different files, such as the main processing logic and validation, showcasing how modules can be exported and imported for use in a larger application. This pattern is beneficial for large projects requiring independent module maintenance. ```javascript // Example: Modularized payment gateway // filepath: /modules/payment/index.js export const processPayment = (amount, method) => { // Payment processing logic console.log(`Processing ${amount} via ${method}`); } // filepath: /modules/payment/validation.js export const validatePaymentDetails = (details) => { // Validation logic return details.cardNumber && details.expiryDate; } ``` -------------------------------- ### Get Colon Time from Date in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/get-colon-time-from-date.md Extracts the time part of a JavaScript Date object in HH:MM:SS format. It utilizes `toTimeString()` to get the time string and `slice(0, 8)` to remove timezone information. No external dependencies are required. ```javascript const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); getColonTimeFromDate(new Date()); // '08:38:00' ``` -------------------------------- ### Build the Code (Shell) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/tdd-library-implementation-with-vite-vitest.md This shell command executes the build script defined in package.json, which uses Vite to bundle the project's code into a distributable format. ```shell npm run build ``` -------------------------------- ### Create Descending HTML List with Reversed and Start Attributes Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/html/s/reversed-list.md This snippet shows how to create a descending numbered list in HTML, starting from a specific number, by combining the 'reversed' and 'start' attributes on an
      element. This allows for custom initial numbering in a reverse-ordered list. ```html
      1. Item 6
      2. Item 5
      3. Item 4
      ``` -------------------------------- ### Initialize Post Model Storage in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/complex-object-collections-in-memory.md Initializes the storage for the Post model by extending the Model class and calling the static 'prepare' method within a static initialization block. This ensures that the Post model has its dedicated instance storage ready upon class definition. ```javascript import Model from '#src/core/model.js'; export default class Post extends Model { static { // Prepare storage for the Post model super.prepare(this); } } ``` -------------------------------- ### Check if a date is between two dates in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/date-comparison.md Verifies if a given date falls chronologically between a start date and an end date. This function combines the 'is before' and 'is after' logic. It requires three Date objects: a start date, an end date, and the date to check, returning true if the date is strictly between the start and end dates. ```javascript const isBetweenDates = (dateStart, dateEnd, date) => date > dateStart && date < dateEnd; isBetweenDates( new Date('2020-10-20'), new Date('2020-10-30'), new Date('2020-10-19') ); // false isBetweenDates( new Date('2020-10-20'), new Date('2020-10-30'), new Date('2020-10-25') ); // true ``` -------------------------------- ### Publish Package to npm (Shell) Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/tdd-library-implementation-with-vite-vitest.md This shell command publishes the current package to the npm registry. Ensure you have logged in using 'npm login' and configured your package.json correctly beforehand. ```shell npm publish ``` -------------------------------- ### Parameterized Tests with Vitest's test.each Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/test-driven-development-intro.md Showcases the use of Vitest's `test.each` and `describe.each` for running the same test logic with multiple sets of data. This is useful for testing edge cases and different inputs efficiently. ```javascript import { describe, it, expect } from 'vitest'; import { isNil } from '../src/isNil.js'; describe('isNil', () => { it.each( [null, undefined] )('should return true %s', (val) => { expect(isNil(val)).toBe(true) }); it.each( [false, '', 0, {}, [], () => {}] )('should return false with %s', val => { expect(isNil(val)).toBe(false); }); }); ``` -------------------------------- ### Get Current URL - JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/current-url.md Retrieves the current URL of the browser window. This function utilizes the `window.location.href` property, which returns the entire URL as a string. No external dependencies are required. ```javascript const currentURL = () => window.location.href; currentURL(); // 'https://www.google.com/' ``` -------------------------------- ### Higher-Order Function Example in JavaScript Source: https://github.com/chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/functional-programming-introduction.md Shows an example of a higher-order function in JavaScript. A higher-order function either accepts a function as an argument or returns a function, enabling more complex and reusable function compositions. ```javascript const isEven = num => num % 2 === 0; // Higher-order function const inverse = fn => (...args) => !fn(...args); const isOdd = inverse(isEven); ```