### Safely get nested object value with path Source: https://context7.com/silvermine/toolbox/llms.txt The `get` function safely retrieves a value from a nested object using a path string or an array of keys. It is similar to Lodash's `_.get`. It handles cases where intermediate properties might be null or undefined, returning `undefined` or a specified default value if the path does not exist. No external dependencies are required. ```typescript import { get } from '@silvermine/toolbox'; const user = { name: 'John', address: { city: 'New York', coordinates: { lat: 40.7128, lng: -74.0060 } }, tags: ['developer', 'designer'] }; get(user, 'name'); // 'John' get(user, 'address.city'); // 'New York' get(user, 'address.coordinates.lat'); // 40.7128 get(user, ['address', 'city']); // 'New York' get(user, 'tags[0]'); // 'developer' get(user, 'tags[1]'); // 'designer' get(user, 'address.country'); // undefined get(user, 'address.country', 'USA'); // 'USA' (default value) get(user, 'nonexistent.deep.path', 'default'); // 'default' ``` -------------------------------- ### Create Number Range with range Source: https://context7.com/silvermine/toolbox/llms.txt The `range` function generates an array of numbers within a specified range. It can take one, two, or three arguments: `end` (exclusive), `start` (inclusive) and `end` (exclusive), or `start` (inclusive), `end` (exclusive), and `step`. It supports both ascending and descending ranges, and negative steps. ```typescript import { range } from '@silvermine/toolbox'; range(5); // [0, 1, 2, 3, 4] range(1, 5); // [1, 2, 3, 4] range(0, 10, 2); // [0, 2, 4, 6, 8] range(5, 0); // [5, 4, 3, 2, 1] (auto-decrements) range(0, -5); // [0, -1, -2, -3, -4] range(10, 0, -2); // [10, 8, 6, 4, 2] // Useful for iteration for (const i of range(3)) { console.log(`Iteration ${i}`); } // Generate indices const items = ['a', 'b', 'c', 'd', 'e']; const evenIndices = range(0, items.length, 2); const evenItems = evenIndices.map(i => items[i]); // ['a', 'c', 'e'] ``` -------------------------------- ### Get internal [[Class]] tag of an object in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `getTagString` function retrieves the internal `[[Class]]` tag of any given JavaScript value using `Object.prototype.toString.call()`. It returns a string representation of the object's internal type, such as '[object String]', '[object Number]', '[object Array]', etc. This provides a reliable way to determine the specific type of primitive values, built-in objects, and custom instances. ```typescript import { getTagString } from '@silvermine/toolbox'; getTagString('hello'); // '[object String]' getTagString(123); // '[object Number]' getTagString(true); // '[object Boolean]' getTagString(null); // '[object Null]' getTagString(undefined); // '[object Undefined]' getTagString([]); // '[object Array]' getTagString({}); // '[object Object]' getTagString(() => {}); // '[object Function]' getTagString(new Date()); // '[object Date]' getTagString(/regex/); // '[object RegExp]' getTagString(new Map()); // '[object Map]' getTagString(new Set()); // '[object Set]' getTagString(Promise.resolve()); // '[object Promise]' getTagString(new Number(5)); // '[object Number]' getTagString(new String('hi')); // '[object String]' ``` -------------------------------- ### Check if Value is an Array using isArray (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isArray` type guard determines if a value is specifically an array. It distinguishes true arrays from array-like objects, such as those with a `length` property. This is helpful for ensuring a value can be treated as an array, for example, when flattening nested structures. ```typescript import { isArray } from '@silvermine/toolbox'; function ensureArray(value: T | T[]): T[] { if (isArray(value)) { return value; } return [value]; } isArray([1, 2, 3]); // true isArray([]); // true isArray('array'); // false isArray({ length: 3 }); // false (array-like objects are not arrays) ``` -------------------------------- ### Create new object with specified properties Source: https://context7.com/silvermine/toolbox/llms.txt The `pick` function creates a new object containing only the specified properties from a source object. It can accept properties as an array of strings or as individual arguments. This is useful for creating subsets of objects, such as public-facing data structures, without including sensitive information. The function infers the return type correctly in TypeScript. ```typescript import { pick } from '@silvermine/toolbox'; interface User { id: number; name: string; email: string; password: string; createdAt: Date; } const user: User = { id: 1, name: 'John', email: 'john@example.com', password: 'secret123', createdAt: new Date() }; // Create safe public user object const publicUser = pick(user, ['id', 'name', 'email']); // { id: 1, name: 'John', email: 'john@example.com' } // Using spread syntax const minimal = pick(user, 'id', 'name'); // { id: 1, name: 'John' } // Type is correctly inferred as Pick ``` -------------------------------- ### StringMap Type and Type Guard in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt Defines an interface for objects with string keys and string values, including a type guard for runtime validation. Useful for configuration objects where all values are expected to be strings. ```typescript import { StringMap, isStringMap } from '@silvermine/toolbox'; const config: StringMap = { apiKey: 'abc123', environment: 'production', region: 'us-east-1' }; // Type guard usage function processConfig(input: unknown): void { if (isStringMap(input)) { // TypeScript now knows input is StringMap console.log(input.apiKey); // Safe access } } processConfig({ name: 'test', value: 'data' }); // Valid processConfig({ name: 'test', count: 42 }); // Fails type guard (number value) ``` -------------------------------- ### KeyValueStringObject Type and Type Guard in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt A recursive interface for nested objects where values can be strings, string arrays, or other KeyValueStringObject instances, along with a type guard for validation. Ideal for deeply nested configuration or data structures. ```typescript import { KeyValueStringObject, isKeyValueStringObject } from '@silvermine/toolbox'; const config: KeyValueStringObject = { name: 'MyApp', tags: ['production', 'v2'], database: { host: 'localhost', options: { ssl: 'true', poolSize: '10' } } }; // Validate nested configuration if (isKeyValueStringObject(config)) { console.log('Valid configuration structure'); } ``` -------------------------------- ### Delay execution with Promises in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `delay` function returns a Promise that resolves after a specified number of milliseconds. It can be used for simple delays, delaying a return value, implementing rate limiting, or creating retries with backoff. ```typescript import { delay } from '@silvermine/toolbox'; // Simple delay async function example() { console.log('Starting...'); await delay(1000); // Wait 1 second console.log('Done!'); } // Delay with return value async function delayedValue() { const result = await delay(500, 'Hello'); console.log(result); // 'Hello' after 500ms return result; } // Rate limiting async function rateLimitedRequests(urls: string[]) { const results = []; for (const url of urls) { const response = await fetch(url); results.push(await response.json()); await delay(100); // Wait 100ms between requests } return results; } // Retry with delay async function retryWithDelay(fn: () => Promise, attempts: number): Promise { for (let i = 0; i < attempts; i++) { try { return await fn(); } catch (e) { if (i < attempts - 1) await delay(1000 * (i + 1)); else throw e; } } throw new Error('Unreachable'); } ``` -------------------------------- ### Group Array Items with groupBy Source: https://context7.com/silvermine/toolbox/llms.txt The `groupBy` function groups array items based on a key. The key can be a property name (string) or a function that returns the key for each item. Items that result in an `undefined` key are excluded from the output. The function returns an object where keys are the grouping criteria and values are arrays of corresponding items. ```typescript import { groupBy } from '@silvermine/toolbox'; interface User { id: number; name: string; department: string; role: string; } const users: User[] = [ { id: 1, name: 'Alice', department: 'Engineering', role: 'Developer' }, { id: 2, name: 'Bob', department: 'Engineering', role: 'Manager' }, { id: 3, name: 'Charlie', department: 'Sales', role: 'Representative' }, { id: 4, name: 'Diana', department: 'Engineering', role: 'Developer' } ]; // Group by property name const byDepartment = groupBy(users, 'department'); // { // Engineering: [{ id: 1, ... }, { id: 2, ... }, { id: 4, ... }], // Sales: [{ id: 3, ... }] // } // Group by function const byFirstLetter = groupBy(users, (user) => user.name[0]); // { A: [Alice], B: [Bob], C: [Charlie], D: [Diana] } // Items with undefined keys are excluded const byOptional = groupBy(users, (user) => user.department === 'Engineering' ? 'tech' : undefined ); // { tech: [Alice, Bob, Diana] } - Charlie excluded ``` -------------------------------- ### StringUnknownMap Type and Type Guard in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt Provides an interface for objects with string keys and values of any type, along with a type guard. This is useful for flexible data structures or when dealing with external API responses where value types may vary. ```typescript import { StringUnknownMap, isStringUnknownMap } from '@silvermine/toolbox'; // Useful for API response typing interface UserAPIResponse { id: number; name: string; metadata: StringUnknownMap; } const response: UserAPIResponse = { id: 1, name: 'John', metadata: { lastLogin: new Date(), preferences: { theme: 'dark' }, tags: ['admin', 'verified'], score: 100 } }; // Type guard for unknown data function parseJSON(data: unknown): StringUnknownMap | null { if (isStringUnknownMap(data)) { return data; } return null; } ``` -------------------------------- ### Create CSP-safe template functions in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `makeTemplate` function generates a string interpolation function similar to Lodash's `_.template`, but without using `eval` for enhanced security (CSP-safe). It supports basic interpolation (`<%= %>`), HTML-escaped interpolation (`<%- %>`), and nested property access. It can also be configured with custom delimiters. ```typescript import { makeTemplate } from '@silvermine/toolbox'; // Basic interpolation with <%= %> const greeting = makeTemplate('Hello, <%= name %>!'); greeting({ name: 'World' }); // 'Hello, World!' // HTML-escaped interpolation with <%- %> const safeHtml = makeTemplate('

<%- content %>

'); safeHtml({ content: '' }); // '

<script>alert("xss")</script>

' // Nested property access const template = makeTemplate('User: <%= user.name %>, Email: <%= user.email %>'); template({ user: { name: 'John', email: 'john@example.com' } }); // 'User: John, Email: john@example.com' // Missing values become empty strings (no errors) const safe = makeTemplate('Hello, <%= missing %>!'); safe({}); // 'Hello, !' // Custom delimiters const custom = makeTemplate('Hello, {{name}}!', { escape: /\{\{-([\s\S]+?)\}}/g, interpolate: /\{\{([\s\S]+?)\}}/g }); custom({ name: 'World' }); // 'Hello, World!' ``` -------------------------------- ### StringArrayOfStringsMap Type and Type Guard in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt Defines an interface for objects with string keys and string array values, including a type guard for runtime validation. This is useful for mapping identifiers to lists of strings, such as permissions. ```typescript import { StringArrayOfStringsMap, isStringArrayOfStringsMap } from '@silvermine/toolbox'; const permissions: StringArrayOfStringsMap = { admin: ['read', 'write', 'delete'], user: ['read'], guest: [] }; // Validate unknown data function validatePermissions(input: unknown): StringArrayOfStringsMap | null { if (isStringArrayOfStringsMap(input)) { return input; } return null; } validatePermissions({ roles: ['a', 'b'] }); // Valid validatePermissions({ roles: [1, 2] }); // Returns null (number values) ``` -------------------------------- ### Split Array into Chunks with chunk Source: https://context7.com/silvermine/toolbox/llms.txt The `chunk` function splits a given array into smaller arrays (chunks) of a specified size. It's particularly useful for batch processing operations. The last chunk may contain fewer elements than the specified size if the array length is not perfectly divisible by the chunk size. ```typescript import { chunk } from '@silvermine/toolbox'; const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; chunk(numbers, 3); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] chunk(numbers, 5); // [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] chunk(numbers, 1); // [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] // Useful for batch processing const items = ['a', 'b', 'c', 'd', 'e', 'f']; const batches = chunk(items, 2); for (const batch of batches) { console.log(`Processing batch: ${batch.join(', ')}`); } // Processing batch: a, b // Processing batch: c, d // Processing batch: e, f ``` -------------------------------- ### Sort object keys alphabetically for JSON stringification in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `sortKeysReplacer` is a function designed to be used as the `replacer` argument in `JSON.stringify`. It ensures that object keys are sorted alphabetically before serialization, resulting in deterministic JSON output. This is useful for generating consistent cache keys, comparing objects, or ensuring predictable test outputs. ```typescript import { sortKeysReplacer } from '@silvermine/toolbox'; const obj = { z: 1, a: 2, m: { c: 3, b: 4 } }; // Without sortKeysReplacer - order depends on insertion order JSON.stringify(obj); // '{"z":1,"a":2,"m":{"c":3,"b":4}}' // With sortKeysReplacer - alphabetically sorted JSON.stringify(obj, sortKeysReplacer); // '{"a":2,"m":{"b":4,"c":3},"z":1}' // Useful for: // - Cache keys based on object contents // - Comparing objects by their JSON representation // - Consistent hashing of objects // - Deterministic output in tests function createCacheKey(query: object): string { return JSON.stringify(query, sortKeysReplacer); } createCacheKey({ limit: 10, offset: 0 }); // '{"limit":10,"offset":0}' createCacheKey({ offset: 0, limit: 10 }); // '{"limit":10,"offset":0}' (same!) ``` -------------------------------- ### Check if Value is Promise-Like using isPromiseLike (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isPromiseLike` type guard checks if a value conforms to the basic structure of a Promise by having a `then` method. This allows handling various asynchronous patterns, including custom Promise implementations or objects that expose a `then` interface. ```typescript import { isPromiseLike } from '@silvermine/toolbox'; function awaitValue(value: T | PromiseLike): Promise { if (isPromiseLike(value)) { return Promise.resolve(value); } return Promise.resolve(value); } isPromiseLike(Promise.resolve()); // true isPromiseLike({ then: (cb: Function) => cb(42) }); // true isPromiseLike({ then: 'not a function' }); // false isPromiseLike({}); // false ``` -------------------------------- ### Optional Utility Type in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt A utility type that makes specified required properties of an interface optional while leaving other properties unchanged. This is useful for creating types for operations like object creation where some fields might not be provided initially. ```typescript import { Optional } from '@silvermine/toolbox'; interface User { id: number; name: string; email: string; phone: string; } // Make email and phone optional for creation type CreateUserInput = Optional; function createUser(input: CreateUserInput): User { return { id: input.id, name: input.name, email: input.email ?? 'not-provided@example.com', phone: input.phone ?? '000-000-0000' }; } // Valid: email and phone are now optional createUser({ id: 1, name: 'John' }); createUser({ id: 2, name: 'Jane', email: 'jane@example.com' }); ``` -------------------------------- ### Remove Falsy Values with compact Source: https://context7.com/silvermine/toolbox/llms.txt The `compact` function creates a new array with all falsy values removed. Falsy values in JavaScript include `false`, `null`, `0`, `''` (empty string), `undefined`, and `NaN`. This function is helpful for cleaning up arrays that might contain these values, especially when dealing with optional data. ```typescript import { compact } from '@silvermine/toolbox'; const mixed = [0, 1, false, 2, '', 3, null, undefined, 4, NaN]; compact(mixed); // [1, 2, 3, 4] const strings = ['hello', '', 'world', null, 'foo']; compact(strings); // ['hello', 'world', 'foo'] // Useful for filtering optional values interface User { name?: string; email?: string } const users: (User | null)[] = [ { name: 'Alice', email: 'alice@example.com' }, null, { name: 'Bob' }, undefined ]; const validUsers = compact(users); // [{ name: 'Alice', ... }, { name: 'Bob' }] ``` -------------------------------- ### Extract Property Value with pluck Source: https://context7.com/silvermine/toolbox/llms.txt The `pluck` function extracts a specific property value from each object in an array. It takes an array of objects and a property name (string) or a function that returns the property name as input. The output is a new array containing only the extracted property values. Type inference is supported for the returned array. ```typescript import { pluck } from '@silvermine/toolbox'; interface Product { id: number; name: string; price: number; } const products: Product[] = [ { id: 1, name: 'Apple', price: 1.50 }, { id: 2, name: 'Banana', price: 0.75 }, { id: 3, name: 'Orange', price: 2.00 } ]; const names = pluck(products, 'name'); // ['Apple', 'Banana', 'Orange'] const prices = pluck(products, 'price'); // [1.50, 0.75, 2.00] const ids = pluck(products, 'id'); // [1, 2, 3] // Type is correctly inferred const typedNames: string[] = pluck(products, 'name'); const typedPrices: number[] = pluck(products, 'price'); ``` -------------------------------- ### UnionKeys Utility Type (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt Extracts all keys from a union type, including keys that only exist on some union members. This is beneficial when you need to iterate over or check for the existence of any possible key within a union of object types. ```typescript import { UnionKeys } from '@silvermine/toolbox'; type Admin = { id: number; role: string; permissions: string[] }; type Guest = { id: number; sessionId: string }; type User = Admin | Guest; // Standard keyof would only give 'id' (common to both) // UnionKeys gives all keys: 'id' | 'role' | 'permissions' | 'sessionId' type AllUserKeys = UnionKeys; function hasKey(user: User, key: UnionKeys): boolean { return key in user; } ``` -------------------------------- ### Check if value is empty with TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `isEmpty` type guard determines if a value is considered empty. It returns true for null, undefined, booleans, numbers, empty arrays, empty strings, empty Sets, and objects with no keys. This function has no external dependencies. ```typescript import { isEmpty } from '@silvermine/toolbox'; function validateInput(value: unknown): void { if (isEmpty(value)) { throw new Error('Input cannot be empty'); } } isEmpty(null); // true isEmpty(undefined); // true isEmpty(true); // true (booleans are considered empty) isEmpty(0); // true (numbers are considered empty) isEmpty(''); // true isEmpty([]); // true isEmpty({}); // true isEmpty(new Set()); // true isEmpty('hello'); // false isEmpty([1, 2]); // false isEmpty({ a: 1 }); // false isEmpty(new Set([1])); // false ``` -------------------------------- ### Check if Value is an Array of Strings using isArrayOfStrings (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isArrayOfStrings` type guard checks if a value is an array where every element is a string. This is crucial for validating inputs that are expected to be collections of text, like tags or user-provided data, preventing errors from mixed or non-string types. ```typescript import { isArrayOfStrings } from '@silvermine/toolbox'; function validateTags(input: unknown): string[] { if (isArrayOfStrings(input)) { return input.map(tag => tag.toLowerCase()); } throw new Error('Tags must be an array of strings'); } isArrayOfStrings(['a', 'b', 'c']); // true isArrayOfStrings([]); // true isArrayOfStrings(['a', 1, 'b']); // false isArrayOfStrings([null, 'a']); // false ``` -------------------------------- ### Escape HTML special characters in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `escapeHTML` function converts special HTML characters (like `<`, `>`, `&`, ` ```typescript import { escapeHTML } from '@silvermine/toolbox'; escapeHTML(''); // '<script>alert("xss")</script>' escapeHTML('Hello & goodbye'); // 'Hello & goodbye' escapeHTML('
'); // '<div class="test">' escapeHTML("It's a test"); // 'It's a test' // Non-strings pass through unchanged escapeHTML(123); // 123 escapeHTML(null); // null escapeHTML({ a: 1 }); // { a: 1 } ``` -------------------------------- ### PropsWithType Utility Type (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt Extracts property names from an object that have a specific type. This utility is helpful for dynamically selecting properties based on their data type, enabling more flexible and type-safe functions. ```typescript import { PropsWithType } from '@silvermine/toolbox'; interface Product { id: number; name: string; description: string; price: number; quantity: number; } // Get only numeric fields type NumericProductFields = PropsWithType; // Result: 'id' | 'price' | 'quantity' function sumNumericField(products: Product[], field: NumericProductFields): number { return products.reduce((sum, p) => sum + p[field], 0); } const products: Product[] = [ { id: 1, name: 'A', description: 'Desc A', price: 10, quantity: 5 }, { id: 2, name: 'B', description: 'Desc B', price: 20, quantity: 3 } ]; sumNumericField(products, 'price'); // 30 sumNumericField(products, 'quantity'); // 8 // sumNumericField(products, 'name'); // Error: 'name' is not assignable ``` -------------------------------- ### Check if Value is a Set using isSet (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isSet` type guard verifies if a value is a native JavaScript `Set` object. This is useful when working with collections and needing to differentiate between arrays and Sets, particularly when converting between them or ensuring unique values. ```typescript import { isSet } from '@silvermine/toolbox'; function getUniqueValues(input: T[] | Set): T[] { if (isSet(input)) { return Array.from(input); } return [...new Set(input)]; } isSet(new Set()); // true isSet(new Set([1, 2, 3])); // true isSet([]); // false isSet(new Map()); // false ``` -------------------------------- ### Check if Value is an Object using isObject (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isObject` type guard verifies if a value is an object, importantly excluding `null`. It considers arrays and functions as valid objects. This is useful for operations like merging configurations or data structures where the input must be a non-null object. ```typescript import { isObject } from '@silvermine/toolbox'; function merge(target: unknown, source: unknown): object { if (!isObject(target) || !isObject(source)) { throw new Error('Both arguments must be objects'); } return { ...target, ...source }; } isObject({}); // true isObject({ a: 1 }); // true isObject([]); // true (arrays are objects) isObject(() => {}); // true (functions are objects) isObject(null); // false isObject(undefined); // false isObject('string'); // false ``` -------------------------------- ### Check if Value is Not Null or Undefined using isNotNullOrUndefined (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isNotNullOrUndefined` type guard is a convenient way to check if a value is neither `null` nor `undefined`. It's useful for filtering out 'nullish' values from arrays or ensuring that variables have a defined value before proceeding. ```typescript import { isNotNullOrUndefined } from '@silvermine/toolbox'; function filterNullish(arr: (T | null | undefined)[]): T[] { return arr.filter(isNotNullOrUndefined); } const mixed = [1, null, 2, undefined, 3]; const numbers = filterNullish(mixed); // [1, 2, 3] isNotNullOrUndefined('value'); // true isNotNullOrUndefined(0); // true isNotNullOrUndefined(null); // false isNotNullOrUndefined(undefined); // false ``` -------------------------------- ### Check if Value is Null using isNull (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isNull` type guard specifically checks if a value is `null`. It differentiates `null` from `undefined` and other falsy values like `0` or empty strings. This is helpful for handling optional parameters or default values safely. ```typescript import { isNull } from '@silvermine/toolbox'; function getValue(value: T | null, defaultValue: T): T { if (isNull(value)) { return defaultValue; } return value; } isNull(null); // true isNull(undefined); // false isNull(0); // false isNull(''); // false ``` -------------------------------- ### Remove Duplicates with uniq Source: https://context7.com/silvermine/toolbox/llms.txt The `uniq` function removes duplicate values from an array. It can optionally accept a boolean flag to optimize for already sorted arrays, using a faster algorithm in that case. It also supports a custom comparison function (iteratee) to determine uniqueness based on specific properties or computed values. ```typescript import { uniq } from '@silvermine/toolbox'; // Basic deduplication uniq([1, 2, 2, 3, 3, 3, 4]); // [1, 2, 3, 4] uniq(['a', 'b', 'a', 'c', 'b']); // ['a', 'b', 'c'] // Optimized for sorted arrays const sorted = [1, 1, 2, 2, 2, 3, 4, 4, 5]; uniq(sorted, true); // [1, 2, 3, 4, 5] - faster algorithm // With iteratee for custom comparison interface User { id: number; name: string } const users: User[] = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice (duplicate)' } ]; uniq(users, false, (user) => user.id); // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }] ``` -------------------------------- ### Flatten Arrays with flatten Source: https://context7.com/silvermine/toolbox/llms.txt The `flatten` function takes multiple arrays as arguments and combines them into a single, one-dimensional array. It does not deeply flatten nested arrays. This is useful for merging results from different sources or simplifying nested array structures. ```typescript import { flatten } from '@silvermine/toolbox'; const arrays = [[1, 2], [3, 4], [5, 6]]; flatten(...arrays); // [1, 2, 3, 4, 5, 6] const mixed = [['a', 'b'], ['c'], ['d', 'e', 'f']]; flatten(...mixed); // ['a', 'b', 'c', 'd', 'e', 'f'] // Combine results from multiple sources const admins = ['admin1', 'admin2']; const users = ['user1', 'user2', 'user3']; const guests = ['guest1']; const allUsers = flatten(admins, users, guests); // ['admin1', 'admin2', 'user1', 'user2', 'user3', 'guest1'] ``` -------------------------------- ### RequireOptional Utility Type in TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt A utility type that makes specified optional properties of an interface required. This is useful for defining types for functions or operations where certain previously optional parameters must now be provided. ```typescript import { RequireOptional } from '@silvermine/toolbox'; interface Config { host: string; port?: number; timeout?: number; } // Require port for database connections type DatabaseConfig = RequireOptional; function connectDatabase(config: DatabaseConfig): void { // port is guaranteed to exist console.log(`Connecting to ${config.host}:${config.port}`); } connectDatabase({ host: 'localhost', port: 5432 }); // Valid // connectDatabase({ host: 'localhost' }); // Error: port is required ``` -------------------------------- ### isString Type Guard (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt A type guard that checks if a value is a string, including String objects. It helps narrow down the type of a variable to 'string' within conditional blocks, ensuring type safety. ```typescript import { isString } from '@silvermine/toolbox'; function formatValue(value: unknown): string { if (isString(value)) { return value.toUpperCase(); } return String(value); } isString('hello'); // true isString(new String('hello')); // true isString(123); // false isString(null); // false ``` -------------------------------- ### StrictUnion Utility Type (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt Creates exclusive unions where an object can only have properties from one type within the union, not a mix. This enforces stricter type checking for union types, preventing accidental property overlaps. ```typescript import { StrictUnion } from '@silvermine/toolbox'; interface Circle { kind: 'circle'; radius: number; } interface Rectangle { kind: 'rectangle'; width: number; height: number; } // Without StrictUnion, TypeScript allows mixing properties // With StrictUnion, you must provide all properties from exactly one type type Shape = StrictUnion; const circle: Shape = { kind: 'circle', radius: 5 }; // Valid const rect: Shape = { kind: 'rectangle', width: 10, height: 20 }; // Valid // const invalid: Shape = { kind: 'circle', radius: 5, width: 10 }; // Error! ``` -------------------------------- ### Check if value is a map with values of specific type with TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `isMapWithValuesOfType` type guard checks if a value is an object with string keys and all its values satisfy a given type guard. This is useful for validating that an object conforms to a specific `Record` type where `T` is determined by another type guard. It depends on the provided type guard for value checking. ```typescript import { isMapWithValuesOfType, isNumber, isString } from '@silvermine/toolbox'; // Check for Record const scores: unknown = { alice: 100, bob: 85, charlie: 92 }; if (isMapWithValuesOfType(isNumber, scores)) { const total = Object.values(scores).reduce((a, b) => a + b, 0); console.log(`Total: ${total}`); } // Check for Record const labels: unknown = { title: 'Hello', subtitle: 'World' }; if (isMapWithValuesOfType(isString, labels)) { console.log(labels.title.toUpperCase()); } isMapWithValuesOfType(isNumber, { a: 1, b: 2 }); // true isMapWithValuesOfType(isNumber, { a: 1, b: 'two' }); // false isMapWithValuesOfType(isString, {}); // true (empty object) ``` -------------------------------- ### Check if value is function arguments object with TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `isArguments` type guard checks if a value is the arguments object of a function. It is useful for converting arguments to an array or performing other operations on them. This function has no external dependencies. ```typescript import { isArguments } from '@silvermine/toolbox'; function toArray(value: unknown): unknown[] { if (isArguments(value)) { return Array.from(value); } return [value]; } function example() { console.log(isArguments(arguments)); // true } isArguments([1, 2, 3]); // false isArguments({ 0: 'a', 1: 'b', length: 2 }); // false ``` -------------------------------- ### Writable Utility Type (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt Removes readonly modifiers from all properties of an interface, allowing mutation of otherwise immutable objects. This is useful when you need to modify an object that was initially defined as readonly, perhaps during an initialization phase. ```typescript import { Writable } from '@silvermine/toolbox'; interface ImmutableConfig { readonly host: string; readonly port: number; readonly ssl: boolean; } function buildConfig(partial: Partial): ImmutableConfig { const config: Writable = { host: 'localhost', port: 8080, ssl: false }; // Can mutate because we're using Writable if (partial.host) config.host = partial.host; if (partial.port) config.port = partial.port; if (partial.ssl !== undefined) config.ssl = partial.ssl; return config; // Return as immutable } const config = buildConfig({ ssl: true }); // config.host = 'other'; // Error: readonly property ``` -------------------------------- ### Check if Value is a Native Promise using isPromise (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isPromise` type guard checks if a value is a native JavaScript `Promise` object. It distinguishes actual Promises from objects that merely resemble Promises (promise-like). This is essential for correctly handling asynchronous operations. ```typescript import { isPromise } from '@silvermine/toolbox'; async function resolveValue(value: T | Promise): Promise { if (isPromise(value)) { return value; } return value; } isPromise(Promise.resolve()); // true isPromise(new Promise(() => {})); // true isPromise({ then: () => {} }); // false (use isPromiseLike) isPromise(async () => {}); // false (async function, not promise) ``` -------------------------------- ### isNumber Type Guard (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt A type guard that checks if a value is a number, including Number objects. It considers NaN and Infinity as numbers, but can be used in conjunction with Number.isFinite for more specific checks. ```typescript import { isNumber } from '@silvermine/toolbox'; function calculateTotal(values: unknown[]): number { return values.reduce((sum: number, val) => { if (isNumber(val) && Number.isFinite(val)) { return sum + val; } return sum; }, 0); } isNumber(42); // true isNumber(3.14); // true isNumber(new Number(5)); // true isNumber(NaN); // true (use Number.isNaN for NaN check) isNumber(Infinity); // true (use Number.isFinite for finite check) isNumber('42'); // false ``` -------------------------------- ### Check if Value is a Function using isFunction (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isFunction` type guard checks if a value is a JavaScript function. This includes arrow functions, regular functions, and classes. It is useful for safely invoking callbacks or executing code dynamically, ensuring the provided value is indeed callable. ```typescript import { isFunction } from '@silvermine/toolbox'; function invokeIfCallable(value: unknown, ...args: unknown[]): unknown { if (isFunction(value)) { return value(...args); } return value; } isFunction(() => {}); // true isFunction(function() {}); // true isFunction(class {}); // true isFunction({}); // false isFunction(null); // false ``` -------------------------------- ### Check if Value is a Boolean Primitive using isBoolean (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isBoolean` type guard verifies if a given value is a boolean primitive (true or false). It does not consider Boolean objects or string representations of booleans as true. This is useful for safely parsing boolean flags or configuration values. ```typescript import { isBoolean } from '@silvermine/toolbox'; function parseFlag(value: unknown, defaultValue: boolean): boolean { if (isBoolean(value)) { return value; } return defaultValue; } isBoolean(true); // true isBoolean(false); // true isBoolean(1); // false isBoolean('true'); // false isBoolean(new Boolean(true)); // false (only primitives) ``` -------------------------------- ### RequireDefined Utility Type (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt Makes specified properties of an interface required and removes 'undefined' from their type. This is useful for ensuring that certain properties are always present and have a defined value before they are used, preventing runtime errors. ```typescript import { RequireDefined } from '@silvermine/toolbox'; interface User { id: number; name: string; email: string | undefined; } // Require email to be defined (not undefined) type VerifiedUser = RequireDefined; function sendEmail(user: VerifiedUser): void { // email is guaranteed to be string, not undefined console.log(`Sending email to ${user.email}`); } const user: VerifiedUser = { id: 1, name: 'John', email: 'john@example.com' }; sendEmail(user); ``` -------------------------------- ### Check if Value is Undefined using isUndefined (TypeScript) Source: https://context7.com/silvermine/toolbox/llms.txt The `isUndefined` type guard determines if a value is `undefined`. It correctly identifies both `undefined` and `void 0`. This is commonly used to check for the presence of a value or the default state of uninitialized variables. ```typescript import { isUndefined } from '@silvermine/toolbox'; function hasValue(value: T | undefined): value is T { return !isUndefined(value); } isUndefined(undefined); // true isUndefined(void 0); // true isUndefined(null); // false isUndefined(0); // false ``` -------------------------------- ### Check if value is a valid enum member with TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `isEnumValue` type guard verifies if a given value is a valid member of a provided enum. This is useful for validating user input or ensuring that a variable holds an expected enum value. It requires the enum definition and the value to check. ```typescript import { isEnumValue } from '@silvermine/toolbox'; enum Status { Active = 'active', Inactive = 'inactive', Pending = 'pending' } function parseStatus(value: unknown): Status { if (isEnumValue(Status, value)) { return value; } throw new Error(`Invalid status: ${value}`); } isEnumValue(Status, 'active'); // true isEnumValue(Status, 'inactive'); // true isEnumValue(Status, 'unknown'); // false isEnumValue(Status, 0); // false // Works with numeric enums too enum Priority { Low = 0, Medium = 1, High = 2 } isEnumValue(Priority, 1); // true isEnumValue(Priority, 5); // false ``` -------------------------------- ### Check if an object property is defined with TypeScript Source: https://context7.com/silvermine/toolbox/llms.txt The `hasDefined` type guard checks if an optional or possibly-undefined property exists on an object and is not `undefined`. This is useful in TypeScript to narrow down the type of a property within a conditional block, ensuring type safety. It takes the object and the property key as arguments. ```typescript import { hasDefined } from '@silvermine/toolbox'; interface Config { host: string; port?: number; ssl?: boolean; } function connect(config: Config): void { if (hasDefined(config, 'port')) { // TypeScript knows config.port is number, not number | undefined console.log(`Connecting to ${config.host}:${config.port}`); } else { console.log(`Connecting to ${config.host} with default port`); } } const config: Config = { host: 'localhost', port: 3000 }; hasDefined(config, 'port'); // true hasDefined(config, 'ssl'); // false const partial: Config = { host: 'localhost' }; hasDefined(partial, 'port'); // false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.