### Basic Conversion Examples Source: https://radash.uihtm.com/number/to-int.html Examples showing how toInt handles various string inputs. ```typescript import { toInt } from 'radash' console.log(toInt('123')) // 123 console.log(toInt('123.45')) // 123 console.log(toInt('0')) // 0 console.log(toInt('-123')) // -123 console.log(toInt('123abc')) // 123 ``` -------------------------------- ### Capitalize Examples Source: https://radash.uihtm.com/string/capitalize.html Various examples covering basic usage, case handling, special characters, and data structures. ```typescript import { capitalize } from 'radash' console.log(capitalize('hello')) // 'Hello' console.log(capitalize('world')) // 'World' console.log(capitalize('javascript')) // 'Javascript' console.log(capitalize('react')) // 'React' ``` ```typescript import { capitalize } from 'radash' console.log(capitalize('HELLO')) // 'Hello' console.log(capitalize('WORLD')) // 'World' console.log(capitalize('JAVASCRIPT')) // 'Javascript' console.log(capitalize('REACT')) // 'React' ``` ```typescript import { capitalize } from 'radash' console.log(capitalize('hElLo')) // 'Hello' console.log(capitalize('wOrLd')) // 'World' console.log(capitalize('jAvAsCrIpT')) // 'Javascript' console.log(capitalize('rEaCt')) // 'React' ``` ```typescript import { capitalize } from 'radash' console.log(capitalize('hello world')) // 'Hello world' console.log(capitalize('hello-world')) // 'Hello-world' console.log(capitalize('hello_world')) // 'Hello_world' console.log(capitalize('hello.world')) // 'Hello.world' ``` ```typescript import { capitalize } from 'radash' console.log(capitalize('123hello')) // '123hello' (数字开头) console.log(capitalize('!hello')) // '!hello' (符号开头) console.log(capitalize('@world')) // '@world' (符号开头) console.log(capitalize('hello123')) // 'Hello123' ``` ```typescript import { capitalize } from 'radash' console.log(capitalize('')) // '' console.log(capitalize('a')) // 'A' console.log(capitalize('A')) // 'A' console.log(capitalize('z')) // 'Z' ``` ```typescript import { capitalize } from 'radash' console.log(capitalize('café')) // 'Café' console.log(capitalize('naïve')) // 'Naïve' console.log(capitalize('résumé')) // 'Résumé' console.log(capitalize('über')) // 'Über' ``` ```typescript import { capitalize } from 'radash' const words = ['hello', 'world', 'javascript', 'react'] const capitalizedWords = words.map(word => capitalize(word)) console.log(capitalizedWords) // ['Hello', 'World', 'Javascript', 'React'] ``` ```typescript import { capitalize } from 'radash' const user = { firstName: 'john', lastName: 'doe', city: 'new york' } const formattedUser = { firstName: capitalize(user.firstName), lastName: capitalize(user.lastName), city: capitalize(user.city) } console.log(formattedUser) // { firstName: 'John', lastName: 'Doe', city: 'New york' } ``` ```typescript import { capitalize } from 'radash' function formatName(name: string) { return capitalize(name.trim()) } console.log(formatName(' john ')) // 'John' console.log(formatName(' MARY ')) // 'Mary' console.log(formatName(' david ')) // 'David' ``` -------------------------------- ### Install Radash using npm Source: https://radash.uihtm.com/ Use npm to install the Radash library in your project. ```bash npm install radash ``` -------------------------------- ### Installing Radash Source: https://radash.uihtm.com/guide Provides instructions for installing the Radash library using npm, yarn, or pnpm package managers. ```bash npm install radash # or yarn add radash # or pnpm add radash ``` -------------------------------- ### Basic Conversion Example Source: https://radash.uihtm.com/object/listify.html Demonstrates the default output format of listify. ```typescript import { listify } from 'radash' const obj = { name: 'Alice', age: 25, city: 'Beijing' } const list = listify(obj) console.log(list) // [ // { key: 'name', value: 'Alice' }, // { key: 'age', value: 25 }, // { key: 'city', value: 'Beijing' } // ] ``` -------------------------------- ### Template Function Examples Source: https://radash.uihtm.com/string/template.html Various examples demonstrating the usage of the template function with different data types and scenarios. ```APIDOC ## Template Function Examples ### Basic Template Replacement ```typescript import { template } from 'radash' const templateStr = 'Hello {{name}}, you are {{age}} years old.' const data = { name: 'Alice', age: 25 } const result = template(templateStr, data) console.log(result) // 'Hello Alice, you are 25 years old.' ``` ### Handling Missing Placeholders ```typescript import { template } from 'radash' const templateStr = 'Hello {{name}}, welcome to {{company}}!' const data = { name: 'Alice' } // company is missing const result = template(templateStr, data) console.log(result) // 'Hello Alice, welcome to !' ``` ### Handling Nested Objects ```typescript import { template } from 'radash' const templateStr = 'User: {{user.name}}, Email: {{user.email}}, Age: {{user.profile.age}}' const data = { user: { name: 'Alice', email: 'alice@example.com', profile: { age: 25 } } } const result = template(templateStr, data) console.log(result) // 'User: Alice, Email: alice@example.com, Age: 25' ``` ### Handling Array Data ```typescript import { template } from 'radash' const templateStr = 'First item: {{items.0}}, Second item: {{items.1}}' const data = { items: ['apple', 'banana', 'orange'] } const result = template(templateStr, data) console.log(result) // 'First item: apple, Second item: banana' ``` ### Handling Complex Nesting ```typescript import { template } from 'radash' const templateStr = ` User Profile: - Name: {{user.profile.name}} - Email: {{user.profile.email}} - Address: {{user.profile.address.city}}, {{user.profile.address.country}} - Skills: {{user.skills.0}}, {{user.skills.1}} ` const data = { user: { profile: { name: 'Alice', email: 'alice@example.com', address: { city: 'Beijing', country: 'China' } }, skills: ['JavaScript', 'TypeScript', 'React'] } } const result = template(templateStr, data) console.log(result) // User Profile: // - Name: Alice // - Email: alice@example.com // - Address: Beijing, China // - Skills: JavaScript, TypeScript ``` ### Handling Different Value Types ```typescript import { template } from 'radash' const templateStr = 'Name: {{name}}, Age: {{age}}, Active: {{isActive}}, Score: {{score}}' const data = { name: 'Alice', age: 25, isActive: true, score: 95.5 } const result = template(templateStr, data) console.log(result) // 'Name: Alice, Age: 25, Active: true, Score: 95.5' ``` ### Handling Null and Undefined Values ```typescript import { template } from 'radash' const templateStr = 'Name: {{name}}, Email: {{email}}, Phone: {{phone}}' const data = { name: 'Alice', email: null, phone: undefined } const result = template(templateStr, data) console.log(result) // 'Name: Alice, Email: , Phone: ' ``` ### Handling Special Characters ```typescript import { template } from 'radash' const templateStr = 'Message: {{message}}, URL: {{url}}' const data = { message: 'Hello & Welcome!', url: 'https://example.com?param=value' } const result = template(templateStr, data) console.log(result) // 'Message: Hello & Welcome!, URL: https://example.com?param=value' ``` ### Handling Function Values ```typescript import { template } from 'radash' const templateStr = 'Name: {{name}}, Greeting: {{greeting}}' const data = { name: 'Alice', greeting: () => 'Hello!' } const result = template(templateStr, data) console.log(result) // 'Name: Alice, Greeting: function' ``` ### Handling Object Values ```typescript import { template } from 'radash' const templateStr = 'User: {{user}}, Settings: {{settings}}' const data = { user: { name: 'Alice', age: 25 }, settings: { theme: 'dark', notifications: true } } const result = template(templateStr, data) console.log(result) // 'User: [object Object], Settings: [object Object]' ``` ### Handling Array Values ```typescript import { template } from 'radash' const templateStr = 'Tags: {{tags}}, Numbers: {{numbers}}' const data = { tags: ['javascript', 'typescript', 'react'], numbers: [1, 2, 3, 4, 5] } const result = template(templateStr, data) console.log(result) // 'Tags: javascript,typescript,react, Numbers: 1,2,3,4,5' ``` ### Handling Date Values ```typescript import { template } from 'radash' const templateStr = 'Created: {{createdAt}}, Updated: {{updatedAt}}' const data = { createdAt: new Date('2023-01-01'), updatedAt: new Date('2023-12-31') } const result = template(templateStr, data) console.log(result) // 'Created: 2023-01-01T00:00:00.000Z, Updated: 2023-12-31T00:00:00.000Z' ``` ``` -------------------------------- ### Error Handling Examples Source: https://radash.uihtm.com/async/guard.html Provides various examples of using the guard function for different error handling scenarios. ```APIDOC ## Examples This section provides practical examples of using the `guard` function in different contexts. ### Basic Error Handling This example shows how to use `guard` to handle potential errors when fetching user data. ```typescript import { guard } from 'radash' async function fetchUserData(userId: number) { const result = await guard(async () => { const response = await fetch(`/api/users/${userId}`) if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`) } return response.json() }) if (result.error) { console.error('Failed to fetch user:', result.error.message) return null } return result.data } const user = await fetchUserData(123) ``` ### Handling Network Requests This example demonstrates using `guard` to manage errors during an API call. ```typescript import { guard } from 'radash' async function makeApiCall(url: string) { const result = await guard(async () => { const response = await fetch(url) if (!response.ok) { throw new Error(`Request failed: ${response.status}`) } return response.json() }) return result } const apiResult = await makeApiCall('https://api.example.com/data') if (apiResult.error) { console.log('API Error:', apiResult.error.message) } else { console.log('API Data:', apiResult.data) } ``` ### Handling Database Operations This example illustrates using `guard` to catch errors during a simulated database operation. ```typescript import { guard } from 'radash' async function createUser(userData: any) { const result = await guard(async () => { // Simulate database operation if (userData.email.includes('test')) { throw new Error('Test emails are not allowed') } return { id: Date.now(), ...userData, createdAt: new Date() } }) if (result.error) { console.error('User creation failed:', result.error.message) return null } return result.data } const newUser = await createUser({ name: 'John Doe', email: 'john@example.com' }) ``` ### Handling File Operations This example shows how `guard` can be used to handle errors when reading and parsing a file. ```typescript import { guard } from 'radash' async function readFileContent(filePath: string) { const result = await guard(async () => { const fs = await import('fs/promises') const content = await fs.readFile(filePath, 'utf-8') return JSON.parse(content) }) if (result.error) { console.error('File read error:', result.error.message) return null } return result.data } const config = await readFileContent('./config.json') if (config) { console.log('Config loaded:', config) } ``` ### Handling Multiple Asynchronous Operations This example demonstrates how `guard` can be used in conjunction with `Promise.all` to handle errors from multiple concurrent asynchronous operations. ```typescript import { guard } from 'radash' async function processMultipleTasks() { const tasks = [ guard(async () => { await new Promise(resolve => setTimeout(resolve, 100)) return 'Task 1 completed' }), guard(async () => { await new Promise(resolve => setTimeout(resolve, 200)) throw new Error('Task 2 failed') }), guard(async () => { await new Promise(resolve => setTimeout(resolve, 150)) return 'Task 3 completed' }) ] const results = await Promise.all(tasks) results.forEach((result, index) => { if (result.error) { console.log(`Task ${index + 1} failed:`, result.error.message) } else { console.log(`Task ${index + 1} succeeded:`, result.data) } }) } await processMultipleTasks() ``` ### Handling Timeout Operations This example shows how `guard` can be integrated into a function that handles network requests with a timeout. ```typescript import { guard } from 'radash' async function fetchWithTimeout(url: string, timeout: number) { const result = await guard(async () => { const controller = new AbortController() const timeoutId = setTimeout(() => controller.abort(), timeout) try { const response = await fetch(url, { signal: controller.signal }) clearTimeout(timeoutId) if (!response.ok) { throw new Error(`HTTP ${response.status}`) } return response.json() } catch (error) { clearTimeout(timeoutId) throw error } }) return result } const data = await fetchWithTimeout('https://api.example.com/data', 5000) if (data.error) { console.log('Request failed:', data.error.message) } else { console.log('Data received:', data.data) } ``` ``` -------------------------------- ### Basic Radash Usage Source: https://radash.uihtm.com/guide A quick start guide demonstrating basic usage of Radash for array operations, type checking, and function utilities. ```typescript import { map, filter, isArray, debounce } from 'radash' // Array operations const numbers = [1, 2, 3, 4, 5] const doubled = map(numbers, n => n * 2) const evens = filter(numbers, n => n % 2 === 0) // Type checking if (isArray(data)) { console.log('This is an array') } // Function utilities const debouncedSearch = debounce(searchFunction, 300) ``` -------------------------------- ### Basic Deferred Execution Example Source: https://radash.uihtm.com/async/defer.html Shows a simple example of deferring a function's execution. The deferred function runs after all synchronous code, including subsequent console logs. ```typescript import { defer } from 'radash' const deferredFn = defer(() => { console.log('延迟执行') }) console.log('立即执行') deferredFn() console.log('同步执行') // 输出: // 立即执行 // 同步执行 // 延迟执行 ``` -------------------------------- ### Basic Key-Value Mapping Source: https://radash.uihtm.com/object/map-entries.html Examples of simple key transformations using case conversion. ```typescript import { mapEntries } from 'radash' const obj = { name: 'Alice', age: 25, city: 'Beijing' } // 将键转换为大写 const mapped1 = mapEntries(obj, (key, value) => [key.toUpperCase(), value]) console.log(mapped1) // { NAME: 'Alice', AGE: 25, CITY: 'Beijing' } // 将键转换为小写 const mapped2 = mapEntries(obj, (key, value) => [key.toLowerCase(), value]) console.log(mapped2) // { name: 'Alice', age: 25, city: 'Beijing' } ``` -------------------------------- ### Basic type checking examples Source: https://radash.uihtm.com/typed/is-primitive.html Comprehensive examples checking strings, numbers, booleans, null, undefined, symbols, and non-primitive objects. ```typescript import { isPrimitive } from 'radash' // 字符串 console.log(isPrimitive('hello')) // true console.log(isPrimitive('')) // true console.log(isPrimitive('123')) // true // 数字 console.log(isPrimitive(123)) // true console.log(isPrimitive(0)) // true console.log(isPrimitive(-10)) // true console.log(isPrimitive(3.14)) // true console.log(isPrimitive(Infinity)) // true console.log(isPrimitive(-Infinity)) // true console.log(isPrimitive(NaN)) // true // 布尔值 console.log(isPrimitive(true)) // true console.log(isPrimitive(false)) // true // null 和 undefined console.log(isPrimitive(null)) // true console.log(isPrimitive(undefined)) // true // Symbol console.log(isPrimitive(Symbol('test'))) // true console.log(isPrimitive(Symbol())) // true // 非原始类型 console.log(isPrimitive({})) // false console.log(isPrimitive([])) // false console.log(isPrimitive(() => {})) // false console.log(isPrimitive(new Date())) // false console.log(isPrimitive(new RegExp(''))) // false ``` -------------------------------- ### Example: Basic Key-Value Swap Source: https://radash.uihtm.com/object/invert.html Illustrates swapping keys and values for an object containing string and number types. ```typescript import { invert } from 'radash' const obj = { name: 'Alice', age: 25, city: 'Beijing' } const inverted = invert(obj) console.log(inverted) // { 'Alice': 'name', '25': 'age', 'Beijing': 'city' } ``` -------------------------------- ### Example: Handling Configuration Mapping Source: https://radash.uihtm.com/object/invert.html Shows a practical use case of inverting a status map for configuration purposes. ```typescript import { invert } from 'radash' const statusMap = { active: 'ACTIVE', inactive: 'INACTIVE', pending: 'PENDING', suspended: 'SUSPENDED' } const inverted = invert(statusMap) console.log(inverted) // { // 'ACTIVE': 'active', // 'INACTIVE': 'inactive', // 'PENDING': 'pending', // 'SUSPENDED': 'suspended' // } ``` -------------------------------- ### Basic multiplication example Source: https://radash.uihtm.com/curry/partob.html Shows how to partially apply a multiplication function. ```typescript import { partob } from 'radash' const multiply = (a: number, b: number) => a * b const multiplyBy2 = partob(multiply, { a: 2 }) console.log(multiplyBy2({ b: 5 })) // 10 console.log(multiplyBy2({ b: 10 })) // 20 ``` -------------------------------- ### Basic Usage Example Source: https://radash.uihtm.com/array/group.html Demonstrates the fundamental usage of the group function to group users by their city. ```APIDOC ## Basic Usage ### Description Groups an array of user objects by the 'city' property. ### Example ```typescript import { group } from 'radash' const users = [ { id: 1, name: 'Alice', age: 25, city: 'Beijing' }, { id: 2, name: 'Bob', age: 30, city: 'Shanghai' }, { id: 3, name: 'Charlie', age: 35, city: 'Beijing' }, { id: 4, name: 'Diana', age: 28, city: 'Shanghai' } ] const groupedByCity = group(users, user => user.city) // Result: // { // 'Beijing': [ // { id: 1, name: 'Alice', age: 25, city: 'Beijing' }, // { id: 3, name: 'Charlie', age: 35, city: 'Beijing' } // ], // 'Shanghai': [ // { id: 2, name: 'Bob', age: 30, city: 'Shanghai' }, // { id: 4, name: 'Diana', age: 28, city: 'Shanghai' } // ] // } ``` ``` -------------------------------- ### Example: Handling Date Values Source: https://radash.uihtm.com/object/invert.html Shows how Date objects are converted to their ISO string representations when inverted. ```typescript import { invert } from 'radash' const obj = { createdAt: new Date('2023-01-01'), updatedAt: new Date('2023-12-31'), birthday: new Date('1998-05-15') } const inverted = invert(obj) console.log(inverted) // { // '2023-01-01T00:00:00.000Z': 'createdAt', // '2023-12-31T00:00:00.000Z': 'updatedAt', // '1998-05-15T00:00:00.000Z': 'birthday' // } ``` -------------------------------- ### Custom Key-Value Transformation Source: https://radash.uihtm.com/object/map-entries.html Examples showing how to modify keys with prefixes, convert values to strings, or transform both simultaneously. ```typescript import { mapEntries } from 'radash' const obj = { name: 'Alice', age: 25, city: 'Beijing' } // 添加前缀到键名 const mapped1 = mapEntries(obj, (key, value) => [`user_${key}`, value]) console.log(mapped1) // { user_name: 'Alice', user_age: 25, user_city: 'Beijing' } // 转换值为字符串 const mapped2 = mapEntries(obj, (key, value) => [key, String(value)]) console.log(mapped2) // { name: 'Alice', age: '25', city: 'Beijing' } // 同时转换键和值 const mapped3 = mapEntries(obj, (key, value) => [ key.toUpperCase(), typeof value === 'string' ? value.toUpperCase() : value ]) console.log(mapped3) // { NAME: 'ALICE', AGE: 25, CITY: 'BEIJING' } ``` -------------------------------- ### Database Query Accumulation Example Source: https://radash.uihtm.com/async/reduce.html Shows how to aggregate user data and post counts by simulating database queries for multiple users. ```typescript import { reduce } from 'radash' async function aggregateUserData(userIds: number[]) { return reduce(userIds, async (acc, userId) => { const userResponse = await fetch(`/api/users/${userId}`) const user = await userResponse.json() const postsResponse = await fetch(`/api/users/${userId}/posts`) const posts = await postsResponse.json() return { ...acc, users: [...acc.users, user], totalPosts: acc.totalPosts + posts.length, averageAge: (acc.averageAge * acc.users.length + user.age) / (acc.users.length + 1) } }, { users: [], totalPosts: 0, averageAge: 0 }) } const userIds = [1, 2, 3] const aggregated = await aggregateUserData(userIds) console.log(aggregated) ``` -------------------------------- ### Basic Asynchronous Mapping Source: https://radash.uihtm.com/async/map.html Example of using map to fetch data from multiple URLs. ```typescript import { map } from 'radash' const urls = [ 'https://api.example.com/users/1', 'https://api.example.com/users/2', 'https://api.example.com/users/3' ] const users = await map(urls, async (url) => { const response = await fetch(url) return response.json() }) console.log(users) // [user1, user2, user3] ``` -------------------------------- ### snake() examples with different casing Source: https://radash.uihtm.com/string/snake.html Demonstrates snake() conversion for various casing styles including uppercase and mixed case. ```typescript import { snake } from 'radash' console.log(snake('hello world')) // 'hello_world' console.log(snake('Hello World')) // 'hello_world' console.log(snake('HELLO WORLD')) // 'hello_world' console.log(snake('helloWorld')) // 'hello_world' console.log(snake('HelloWorld')) // 'hello_world' console.log(snake('hello_world')) // 'hello_world' console.log(snake('hello-world')) // 'hello_world' ``` -------------------------------- ### Basic Usage Example Source: https://radash.uihtm.com/array/replace-or-append.html Demonstrates the basic usage of replaceOrAppend to update an existing element in an array. ```APIDOC ## Basic Usage ```typescript import { replaceOrAppend } from 'radash' const users = [ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 30 }, { id: 3, name: 'Charlie', age: 35 } ] const updatedUsers = replaceOrAppend( users, { id: 2, name: 'Bob', age: 31 }, // New data user => user.id === 2 // Matching condition ) // Result: // [ // { id: 1, name: 'Alice', age: 25 }, // { id: 2, name: 'Bob', age: 31 }, // Updated // { id: 3, name: 'Charlie', age: 35 } // ] ``` ``` -------------------------------- ### Object Array Reduction Example Source: https://radash.uihtm.com/async/reduce.html Shows how to use the reduce function to aggregate data from an array of user objects. ```typescript import { reduce } from 'radash' const users = [ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 30 }, { id: 3, name: 'Charlie', age: 35 } ] const userStats = await reduce(users, async (acc, user) => { await new Promise(resolve => setTimeout(resolve, 50)) return { totalAge: acc.totalAge + user.age, names: [...acc.names, user.name], count: acc.count + 1 } }, { totalAge: 0, names: [], count: 0 }) console.log(userStats) // { totalAge: 90, names: ['Alice', 'Bob', 'Charlie'], count: 3 } ``` -------------------------------- ### Example: Handling Function Values Source: https://radash.uihtm.com/object/invert.html Illustrates how function values are converted to their string representations when inverted. ```typescript import { invert } from 'radash' const obj = { handler: () => 'hello', validator: function() { return true }, processor: (x: number) => x * 2 } const inverted = invert(obj) console.log(inverted) // { // '() => \'hello\'': 'handler', // 'function() { return true }': 'validator', // '(x) => x * 2': 'processor' // } ``` -------------------------------- ### Example: Handling Special Characters Source: https://radash.uihtm.com/object/invert.html Demonstrates the inversion of strings containing special characters, URLs, and paths. ```typescript import { invert } from 'radash' const obj = { message: 'Hello & Welcome!', url: 'https://example.com?param=value', path: '/api/users/123', symbol: '@#$%^&*()' } const inverted = invert(obj) console.log(inverted) // { // 'Hello & Welcome!': 'message', // 'https://example.com?param=value': 'url', // '/api/users/123': 'path', // '@#$%^&*()': 'symbol' // } ``` -------------------------------- ### Example: Handling String Values Source: https://radash.uihtm.com/object/invert.html Shows the inversion of typical string values, including names, emails, phone numbers, and addresses. ```typescript import { invert } from 'radash' const obj = { firstName: 'Alice', lastName: 'Smith', email: 'alice@example.com', phone: '+86-123-456-7890', address: 'Beijing, China' } const inverted = invert(obj) console.log(inverted) // { // 'Alice': 'firstName', // 'Smith': 'lastName', // 'alice@example.com': 'email', // '+86-123-456-7890': 'phone', // 'Beijing, China': 'address' // } ``` -------------------------------- ### Example: Handling Number Values Source: https://radash.uihtm.com/object/invert.html Illustrates the inversion of various number types, including integers, floats, zero, and negative numbers. ```typescript import { invert } from 'radash' const obj = { id: 1, score: 95.5, rating: 4.8, count: 0, price: -10.99 } const inverted = invert(obj) console.log(inverted) // { // '1': 'id', // '95.5': 'score', // '4.8': 'rating', // '0': 'count', // '-10.99': 'price' // } ``` -------------------------------- ### Handling Number Types Source: https://radash.uihtm.com/number/to-int.html Examples showing how toInt handles existing number types and special numeric values. ```typescript import { toInt } from 'radash' console.log(toInt(123)) // 123 console.log(toInt(123.45)) // 123 console.log(toInt(0)) // 0 console.log(toInt(-123)) // -123 console.log(toInt(Infinity)) // 0 console.log(toInt(-Infinity)) // 0 console.log(toInt(NaN)) // 0 ``` -------------------------------- ### Handling Arrays and Objects Source: https://radash.uihtm.com/number/to-int.html Examples showing how toInt handles complex types like arrays, objects, and functions. ```typescript import { toInt } from 'radash' console.log(toInt([])) // 0 console.log(toInt([1, 2, 3])) // 0 console.log(toInt({})) // 0 console.log(toInt({ key: 123 })) // 0 console.log(toInt(() => {})) // 0 ``` -------------------------------- ### Example: Handling Boolean Values Source: https://radash.uihtm.com/object/invert.html Demonstrates the inversion of boolean values, noting that duplicate true/false values are overwritten. ```typescript import { invert } from 'radash' const obj = { isActive: true, isVerified: false, isPremium: true, isBlocked: false } const inverted = invert(obj) console.log(inverted) // { // 'true': 'isPremium', // 注意:重复的true值被覆盖 // 'false': 'isBlocked' // 重复的false值被覆盖 // } ``` -------------------------------- ### Handling Configuration Objects Source: https://radash.uihtm.com/object/listify.html Demonstrates usage with complex configuration objects. ```typescript import { listify } from 'radash' const config = { server: { host: 'localhost', port: 3000 }, database: { url: 'postgresql://localhost:5432/mydb', pool: { min: 1, max: 10 } }, api: { version: 'v1', rateLimit: { windowMs: 900000, max: 100 } } } const list = listify(config) console.log(list) // [ // { key: 'server', value: { host: 'localhost', port: 3000 } }, // { key: 'database', value: { url: 'postgresql://localhost:5432/mydb', pool: { min: 1, max: 10 } } }, // { key: 'api', value: { version: 'v1', rateLimit: { windowMs: 900000, max: 100 } } } // ] ``` -------------------------------- ### Radash Get Function API Source: https://radash.uihtm.com/object/get.html Documentation for the 'get' function, detailing its syntax, parameters, and return value. ```APIDOC ## GET Function ### Description Safely retrieves nested property values from an object, supporting path strings and default values. ### Method `get` ### Endpoint N/A (This is a utility function, not an API endpoint) ### Parameters #### Function Signature ```typescript function get( obj: any, path: string | string[], fallback?: T ): T ``` #### Parameters - **obj** (any): The object to query. - **path** (string | string[]): The property path, which can be a dot-separated string or an array of strings. - **fallback** (T, optional): The default value to return if the path does not exist. ### Returns Returns the value at the specified path, or the fallback value if the path does not exist. ### Examples #### Basic Property Access ```typescript import { get } from 'radash' const user = { id: 1, name: 'Alice', email: 'alice@example.com' } console.log(get(user, 'name')) // 'Alice' console.log(get(user, 'email')) // 'alice@example.com' console.log(get(user, 'age', 25)) // 25 (default value) ``` #### Nested Property Access ```typescript import { get } from 'radash' const user = { id: 1, profile: { name: 'Alice', address: { city: 'Beijing', country: 'China', details: { street: 'Main Street', zip: '100000' } } } } console.log(get(user, 'profile.name')) // 'Alice' console.log(get(user, 'profile.address.city')) // 'Beijing' console.log(get(user, 'profile.address.details.street')) // 'Main Street' console.log(get(user, 'profile.address.details.phone')) // undefined ``` #### Array Path Access ```typescript import { get } from 'radash' const user = { id: 1, profile: { name: 'Alice', hobbies: ['reading', 'swimming', 'coding'] } } console.log(get(user, 'profile.hobbies.0')) // 'reading' console.log(get(user, 'profile.hobbies.1')) // 'swimming' console.log(get(user, 'profile.hobbies.5')) // undefined console.log(get(user, 'profile.hobbies.5', [])) // [] ``` #### Handling Complex Objects ```typescript import { get } from 'radash' const data = { users: [ { id: 1, name: 'Alice', settings: { theme: 'dark', notifications: { email: true, push: false } } }, { id: 2, name: 'Bob', settings: { theme: 'light', notifications: { email: false, push: true } } } ], config: { api: { baseUrl: 'https://api.example.com', timeout: 5000 } } } console.log(get(data, 'users.0.name')) // 'Alice' console.log(get(data, 'users.1.settings.theme')) // 'light' console.log(get(data, 'config.api.baseUrl')) // 'https://api.example.com' console.log(get(data, 'users.0.settings.notifications.push')) // false ``` #### Using Array Paths ```typescript import { get } from 'radash' const user = { profile: { name: 'Alice', address: { city: 'Beijing' } } } // Using array path console.log(get(user, ['profile', 'name'])) // 'Alice' console.log(get(user, ['profile', 'address', 'city'])) // 'Beijing' console.log(get(user, ['profile', 'age'], 25)) // 25 ``` #### Handling API Responses ```typescript import { get } from 'radash' function processApiResponse(response: any) { return { userId: get(response, 'data.user.id', 0), userName: get(response, 'data.user.name', 'Unknown'), userEmail: get(response, 'data.user.email', ''), userRole: get(response, 'data.user.role', 'user'), lastLogin: get(response, 'data.user.lastLogin', null) } } const apiResponse = { data: { user: { id: 123, name: 'Alice', email: 'alice@example.com' // role and lastLogin are missing } } } const processed = processApiResponse(apiResponse) console.log(processed) // { // userId: 123, // userName: 'Alice', // userEmail: 'alice@example.com', // userRole: 'user', // lastLogin: null // } ``` #### Handling Form Data ```typescript import { get } from 'radash' function processFormData(formData: FormData) { return { firstName: get(formData, 'user.firstName', ''), lastName: get(formData, 'user.lastName', ''), email: get(formData, 'user.email', ''), address: { street: get(formData, 'address.street', ''), city: get(formData, 'address.city', ''), zip: get(formData, 'address.zip', '') }, preferences: { newsletter: get(formData, 'preferences.newsletter', false), notifications: get(formData, 'preferences.notifications', true) } } } // Mock form data const mockFormData = { user: { firstName: 'Alice', lastName: 'Smith', email: 'alice@example.com' }, address: { street: '123 Main St', city: 'Beijing' // zip is missing }, preferences: { newsletter: true // notifications is missing } } const processed = processFormData(mockFormData) console.log(processed) ``` ``` -------------------------------- ### Handling Database Operations with tryit Source: https://radash.uihtm.com/async/tryit.html Demonstrates how to use tryit for database operations, such as creating a new user and handling potential errors. ```typescript import { tryit } from 'radash' const createUser = async (userData: any) => { return await db.query( 'INSERT INTO users (name, email) VALUES (?, ?)', [userData.name, userData.email] ) } const [err, result] = await tryit(createUser, { name: 'Alice', email: 'alice@example.com' }) if (err) { console.error('Failed to create user:', err) return { success: false, error: err.message } } return { success: true, userId: result.insertId } ``` -------------------------------- ### Handling File Operations with tryit Source: https://radash.uihtm.com/async/tryit.html Illustrates using tryit to safely read a configuration file, handling potential file system errors. ```typescript import { tryit } from 'radash' import { readFile } from 'fs/promises' const [err, content] = await tryit(readFile)('config.json', 'utf8') if (err) { console.error('Failed to read file:', err) // 使用默认配置 return defaultConfig } const config = JSON.parse(content) console.log('Config loaded:', config) ``` -------------------------------- ### series(start, end, step) Source: https://radash.uihtm.com/random/series.html Generates a numeric array starting from a value to an end value, incrementing by a specified step. ```APIDOC ## series(start, end, step) ### Description Creates a numeric sequence from a start value to an end value, incrementing by a specified step. ### Parameters #### Arguments - **start** (number) - Required - The starting value of the sequence. - **end** (number) - Required - The ending value of the sequence. - **step** (number) - Optional - The step size, defaults to 1. ### Returns - **number[]** - An array containing numbers from start to end, incremented by step. ### Usage Example ```typescript import { series } from 'radash' const numbers = series(1, 5) // [1, 2, 3, 4, 5] const evenNumbers = series(0, 10, 2) // [0, 2, 4, 6, 8, 10] ``` ``` -------------------------------- ### Basic Usage of tryit Source: https://radash.uihtm.com/async/tryit.html Demonstrates the fundamental usage of tryit to safely call an async function and handle potential errors or results. ```typescript import { tryit } from 'radash' const fetchUser = async (id: number) => { const response = await fetch(`/api/users/${id}`) return response.json() } const [err, user] = await tryit(fetchUser, 123) if (err) { console.error('Failed to fetch user:', err) } else { console.log('User:', user) } ```