diff --git a/.yarnrc.yml b/.yarnrc.yml index 09e884e21..7c36fdbcc 100644 --- a/.yarnrc.yml +++ b/.yarnrc.yml @@ -18,5 +18,8 @@ packageExtensions: sandpack-vue3@3.1.11: dependencies: '@lezer/common': latest + vitepress@*: + dependencies: + '@vue/server-renderer': '*' yarnPath: .yarn/releases/yarn-4.12.0.cjs diff --git a/docs/.vitepress/components/FlavorDropdown.vue b/docs/.vitepress/components/FlavorDropdown.vue new file mode 100644 index 000000000..9ba68192c --- /dev/null +++ b/docs/.vitepress/components/FlavorDropdown.vue @@ -0,0 +1,201 @@ + + + + + diff --git a/docs/.vitepress/components/FlavorOptionRow.vue b/docs/.vitepress/components/FlavorOptionRow.vue new file mode 100644 index 000000000..80b7b5324 --- /dev/null +++ b/docs/.vitepress/components/FlavorOptionRow.vue @@ -0,0 +1,74 @@ + + + + + diff --git a/docs/.vitepress/en.mts b/docs/.vitepress/en.mts index b2722736c..6cf51c1b1 100644 --- a/docs/.vitepress/en.mts +++ b/docs/.vitepress/en.mts @@ -1,9 +1,31 @@ -import path from 'node:path'; import { type DefaultTheme, defineConfig } from 'vitepress'; -import { getSidebarItems } from './libs/getSidebarItems.mts'; -import { sortByText } from './libs/sortByText.mts'; - -const docsRoot = path.resolve(import.meta.dirname, '..'); +import { buildFlavorSidebar, type SidebarLabels } from './libs/buildFlavorSidebar.mts'; + +const labels: SidebarLabels = { + guide: 'Guide', + reference: 'Reference', + guideItems: { + introduction: 'Introduction', + installation: 'Installation & Usage', + bundleSize: 'Impact on Bundle Size', + performance: 'Performance', + aiIntegration: 'AI Integration', + }, + categories: { + array: 'Array Utilities', + function: 'Function Utilities', + map: 'Map Utilities', + math: 'Math Utilities', + object: 'Object Utilities', + predicate: 'Predicates', + promise: 'Promise Utilities', + set: 'Set Utilities', + server: 'Server Utilities', + string: 'String Utilities', + util: 'Utility Functions', + error: 'Errors', + }, +}; export const en = defineConfig({ lang: 'en', @@ -15,7 +37,7 @@ export const en = defineConfig({ nav: nav(), - sidebar: sidebar(), + sidebar: buildFlavorSidebar({ locale: '', labels }), editLink: { pattern: 'https://github.com/toss/es-toolkit/edit/main/docs/:path', @@ -34,134 +56,7 @@ function nav(): DefaultTheme.NavItem[] { { text: 'Home', link: '/' }, { text: 'Introduction', link: '/intro' }, { text: 'Reference', link: '/reference/array/at' }, - { text: 'Lodash Compatibility', link: '/reference/compat/array/castArray' }, + { text: 'Lodash Compatibility', link: '/compat/intro' }, { text: 'Playground', link: '/playground' }, ]; } - -function sidebar(): DefaultTheme.Sidebar { - return [ - { - text: 'Guide', - items: [ - { text: 'Introduction', link: '/intro' }, - { text: 'Playground', link: '/playground' }, - { text: 'Installation & Usage', link: '/usage' }, - { text: 'Impact on Bundle Size', link: '/bundle-size' }, - { text: 'Performance', link: '/performance' }, - { text: 'Lodash Compatibility', link: '/compatibility' }, - { text: 'AI Integration', link: '/ai-integration' }, - ], - }, - { - text: 'Reference', - items: sortByText([ - { - text: 'Array Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'array'), - }, - { - text: 'Function Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'function'), - }, - { - text: 'Map Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'map'), - }, - { - text: 'Math Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'math'), - }, - { - text: 'Object Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'object'), - }, - { - text: 'Predicates', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'predicate'), - }, - { - text: 'Promise Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'promise'), - }, - { - text: 'String Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'string'), - }, - { - text: 'Set Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'set'), - }, - { - text: 'Server Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'server'), - }, - { - text: 'Utility Functions', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'util'), - }, - { - text: 'Errors', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'error'), - }, - ]), - }, - { - text: 'Lodash Compatibility', - items: [ - { - text: 'Reference', - items: sortByText([ - { - text: 'Array Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'compat', 'array'), - }, - { - text: 'Function Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'compat', 'function'), - }, - { - text: 'Math Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'compat', 'math'), - }, - { - text: 'Object Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'compat', 'object'), - }, - { - text: 'Predicates', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'compat', 'predicate'), - }, - { - text: 'String Utilities', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'compat', 'string'), - }, - { - text: 'Utility Functions', - collapsed: true, - items: getSidebarItems(docsRoot, 'reference', 'compat', 'util'), - }, - ]), - }, - ], - }, - ]; -} diff --git a/docs/.vitepress/ja.mts b/docs/.vitepress/ja.mts index 0f3950c76..24bf73481 100644 --- a/docs/.vitepress/ja.mts +++ b/docs/.vitepress/ja.mts @@ -1,9 +1,31 @@ -import path from 'node:path'; import { type DefaultTheme, defineConfig } from 'vitepress'; -import { getSidebarItems } from './libs/getSidebarItems.mts'; -import { sortByText } from './libs/sortByText.mts'; +import { buildFlavorSidebar, type SidebarLabels } from './libs/buildFlavorSidebar.mts'; -const docsRoot = path.resolve(import.meta.dirname, '..'); +const labels: SidebarLabels = { + guide: 'ガイド', + reference: 'リファレンス', + guideItems: { + introduction: '紹介', + installation: 'インストールと使用方法', + bundleSize: 'バンドルサイズ', + performance: 'パフォーマンス', + aiIntegration: 'AI 連携', + }, + categories: { + array: '配列', + function: '関数', + map: 'Map', + math: '数学', + object: 'オブジェクト', + predicate: '述語', + promise: 'Promise', + set: 'Set', + server: 'サーバー', + string: '文字列', + util: 'ユーティリティ', + error: 'エラー', + }, +}; export const ja = defineConfig({ lang: 'ja', @@ -14,7 +36,7 @@ export const ja = defineConfig({ nav: nav(), - sidebar: sidebar(), + sidebar: buildFlavorSidebar({ locale: 'ja', labels }), editLink: { pattern: 'https://github.com/toss/es-toolkit/edit/main/docs/:path', @@ -33,138 +55,11 @@ function nav(): DefaultTheme.NavItem[] { { text: 'ホーム', link: '/ja' }, { text: '導入', link: '/ja/intro' }, { text: 'リファレンス', link: '/ja/reference/array/at' }, - { text: 'Lodash 互換性', link: '/ja/reference/compat/array/castArray' }, + { text: 'Lodash 互換性', link: '/ja/compat/intro' }, { text: 'プレイグラウンド', link: '/ja/playground' }, ]; } -function sidebar(): DefaultTheme.Sidebar { - return [ - { - text: 'ガイド', - items: [ - { text: '紹介', link: '/ja/intro' }, - { text: 'プレイグラウンド', link: '/ja/playground' }, - { text: 'インストールと使用方法', link: '/ja/usage' }, - { text: 'バンドルサイズ', link: '/ja/bundle-size' }, - { text: 'パフォーマンス', link: '/ja/performance' }, - { text: 'Lodash 互換性', link: '/ja/compatibility' }, - { text: 'AI 連携', link: '/ja/ai-integration' }, - ], - }, - { - text: 'リファレンス', - items: sortByText([ - { - text: '配列', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'array'), - }, - { - text: '関数', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'function'), - }, - { - text: 'Map', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'map'), - }, - { - text: '数学', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'math'), - }, - { - text: 'オブジェクト', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'object'), - }, - { - text: '述語', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'predicate'), - }, - { - text: 'Promise', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'promise'), - }, - { - text: 'Set', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'set'), - }, - { - text: 'サーバー', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'server'), - }, - { - text: '文字列', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'string'), - }, - { - text: 'ユーティリティ', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'util'), - }, - { - text: 'エラー', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'error'), - }, - ]), - }, - { - text: 'Lodash 互換性', - items: [ - { - text: 'リファレンス', - items: sortByText([ - { - text: '配列', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'compat', 'array'), - }, - { - text: '関数', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'compat', 'function'), - }, - { - text: '数学', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'compat', 'math'), - }, - { - text: 'オブジェクト', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'compat', 'object'), - }, - { - text: '述語', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'compat', 'predicate'), - }, - { - text: '文字列', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'compat', 'string'), - }, - { - text: 'ユーティリティ', - collapsed: true, - items: getSidebarItems(docsRoot, 'ja', 'reference', 'compat', 'util'), - }, - ]), - }, - ], - }, - ]; -} - export const search: DefaultTheme.LocalSearchOptions['locales'] = { ja: { translations: { diff --git a/docs/.vitepress/ko.mts b/docs/.vitepress/ko.mts index 04ef54a2d..b20e9f160 100644 --- a/docs/.vitepress/ko.mts +++ b/docs/.vitepress/ko.mts @@ -1,9 +1,31 @@ -import path from 'node:path'; import { type DefaultTheme, defineConfig } from 'vitepress'; -import { getSidebarItems } from './libs/getSidebarItems.mts'; -import { sortByText } from './libs/sortByText.mts'; +import { buildFlavorSidebar, type SidebarLabels } from './libs/buildFlavorSidebar.mts'; -const docsRoot = path.resolve(import.meta.dirname, '..'); +const labels: SidebarLabels = { + guide: '가이드', + reference: '레퍼런스', + guideItems: { + introduction: '소개', + installation: '설치 및 사용 방법', + bundleSize: '번들 사이즈', + performance: '성능', + aiIntegration: 'AI 활용', + }, + categories: { + array: '배열', + function: '함수', + map: 'Map', + math: '숫자', + object: '객체', + predicate: '타입 가드', + promise: 'Promise', + set: 'Set', + server: '서버', + string: '문자열', + util: '유틸리티', + error: '에러', + }, +}; export const ko = defineConfig({ lang: 'ko', @@ -14,7 +36,7 @@ export const ko = defineConfig({ nav: nav(), - sidebar: sidebar(), + sidebar: buildFlavorSidebar({ locale: 'ko', labels }), editLink: { pattern: 'https://github.com/toss/es-toolkit/edit/main/docs/:path', @@ -33,138 +55,11 @@ function nav(): DefaultTheme.NavItem[] { { text: '홈', link: '/ko' }, { text: '소개', link: '/ko/intro' }, { text: '레퍼런스', link: '/ko/reference/array/at' }, - { text: 'Lodash 호환성', link: '/ko/reference/compat/array/castArray' }, + { text: 'Lodash 호환성', link: '/ko/compat/intro' }, { text: '플레이그라운드', link: '/ko/playground' }, ]; } -function sidebar(): DefaultTheme.Sidebar { - return [ - { - text: '가이드', - items: [ - { text: '소개', link: '/ko/intro' }, - { text: '플레이그라운드', link: '/ko/playground' }, - { text: '설치 및 사용 방법', link: '/ko/usage' }, - { text: '번들 사이즈', link: '/ko/bundle-size' }, - { text: '성능', link: '/ko/performance' }, - { text: 'Lodash 호환성', link: '/ko/compatibility' }, - { text: 'AI 활용', link: '/ko/ai-integration' }, - ], - }, - { - text: '레퍼런스', - items: sortByText([ - { - text: '배열', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'array'), - }, - { - text: '함수', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'function'), - }, - { - text: 'Map', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'map'), - }, - { - text: '숫자', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'math'), - }, - { - text: '객체', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'object'), - }, - { - text: '타입 가드', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'predicate'), - }, - { - text: 'Promise', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'promise'), - }, - { - text: 'Set', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'set'), - }, - { - text: '서버', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'server'), - }, - { - text: '문자열', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'string'), - }, - { - text: '유틸리티', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'util'), - }, - { - text: '에러', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'error'), - }, - ]), - }, - { - text: 'Lodash 호환성', - items: [ - { - text: '레퍼런스', - items: sortByText([ - { - text: '배열', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'compat', 'array'), - }, - { - text: '함수', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'compat', 'function'), - }, - { - text: '숫자', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'compat', 'math'), - }, - { - text: '객체', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'compat', 'object'), - }, - { - text: '타입 가드', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'compat', 'predicate'), - }, - { - text: '문자열', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'compat', 'string'), - }, - { - text: '유틸리티', - collapsed: true, - items: getSidebarItems(docsRoot, 'ko', 'reference', 'compat', 'util'), - }, - ]), - }, - ], - }, - ]; -} - export const search: DefaultTheme.LocalSearchOptions['locales'] = { ko: { translations: { diff --git a/docs/.vitepress/libs/buildFlavorSidebar.mts b/docs/.vitepress/libs/buildFlavorSidebar.mts new file mode 100644 index 000000000..ff9febaac --- /dev/null +++ b/docs/.vitepress/libs/buildFlavorSidebar.mts @@ -0,0 +1,62 @@ +import path from 'node:path'; +import { type DefaultTheme } from 'vitepress'; +import { flavors } from './flavors.mts'; +import { getSidebarItems } from './getSidebarItems.mts'; +import { sortByText } from './sortByText.mts'; + +const docsRoot = path.resolve(import.meta.dirname, '..', '..'); + +export interface SidebarLabels { + guide: string; + reference: string; + guideItems: Record; + categories: Record; +} + +/** + * Build a route-keyed sidebar map for one locale. + * + * Each flavor in `flavors` gets its own sub-tree keyed by its URL prefix. + * Both Guide and Reference items are driven by the flavor's own spec, so + * adding a new flavor only requires updating `flavors.mts` and supplying + * the matching labels here. + */ +export function buildFlavorSidebar({ + locale, + labels, +}: { + locale: string; + labels: SidebarLabels; +}): DefaultTheme.Sidebar { + const localePrefix = locale ? `/${locale}` : ''; + const localeArgs = locale ? [locale] : []; + + const sidebar: DefaultTheme.SidebarMulti = {}; + + for (const flavor of flavors) { + const flavorArgs = flavor.prefix ? [flavor.prefix] : []; + const flavorPathPrefix = flavor.prefix ? `${localePrefix}/${flavor.prefix}` : localePrefix; + + sidebar[`${flavorPathPrefix}/`] = [ + { + text: labels.guide, + items: flavor.guideItems.map(({ labelKey, slug }) => ({ + text: labels.guideItems[labelKey] ?? labelKey, + link: `${flavorPathPrefix}/${slug}`, + })), + }, + { + text: labels.reference, + items: sortByText( + flavor.categories.map(category => ({ + text: labels.categories[category] ?? category, + collapsed: true, + items: getSidebarItems(docsRoot, ...localeArgs, ...flavorArgs, 'reference', category), + })) + ), + }, + ]; + } + + return sidebar; +} diff --git a/docs/.vitepress/libs/flavors.mts b/docs/.vitepress/libs/flavors.mts new file mode 100644 index 000000000..d3a499106 --- /dev/null +++ b/docs/.vitepress/libs/flavors.mts @@ -0,0 +1,94 @@ +/** + * Flavor spec for the docs site. + * + * Every flavor follows the same shape: + * /{flavorPrefix}/{guideSlug} ← guide pages (the first item is the intro) + * /{flavorPrefix}/reference/... ← function reference + * + * The default flavor (es-toolkit) uses `prefix: ''`, so its guide pages live at + * the root (`/intro`, `/usage`, ...) and reference at `/reference/...`. + * + * Adding a new flavor (e.g. color, node) means: + * 1. Add an entry below with its `guideItems` and `categories`. + * 2. Provide docs at `/{prefix}/{slug}.md` and `/{prefix}/reference//...`. + * 3. Provide labels in each locale file (`guideItems[labelKey]`, `categories[name]`). + */ +export interface GuideItem { + /** Resolved against `SidebarLabels.guideItems` per locale. */ + labelKey: string; + /** Slug joined to the flavor's URL prefix. */ + slug: string; +} + +export interface FlavorSpec { + value: string; + label: string; + description: string; + prefix: string; + guideItems: readonly GuideItem[]; + categories: readonly string[]; + /** SVG path `d` attributes rendered inside a 24x24 stroke icon. */ + icon: readonly string[]; + /** CSS color (or `var(...)`) applied to the icon stroke. */ + iconColor: string; +} + +// Icon paths are taken from lucide.dev, drawn on a 24x24 viewBox with +// stroke-width=2, stroke-linecap=round, stroke-linejoin=round, fill=none. +const WRENCH_ICON = [ + 'M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z', +]; +const ARROW_LEFT_RIGHT_ICON = ['M8 3 4 7l4 4', 'M4 7h16', 'm16 21 4-4-4-4', 'M20 17H4']; + +export const flavors = [ + { + value: 'esToolkit', + label: 'es-toolkit', + description: 'Strict Utilities', + prefix: '', + guideItems: [ + { labelKey: 'introduction', slug: 'intro' }, + { labelKey: 'installation', slug: 'usage' }, + { labelKey: 'bundleSize', slug: 'bundle-size' }, + { labelKey: 'performance', slug: 'performance' }, + { labelKey: 'aiIntegration', slug: 'ai-integration' }, + ], + categories: [ + 'array', + 'function', + 'map', + 'math', + 'object', + 'predicate', + 'promise', + 'set', + 'server', + 'string', + 'util', + 'error', + ], + icon: WRENCH_ICON, + iconColor: 'var(--vp-c-brand-1)', + }, + { + value: 'compat', + label: 'es-toolkit/compat', + description: 'Lodash compatibility', + prefix: 'compat', + guideItems: [{ labelKey: 'introduction', slug: 'intro' }], + categories: ['array', 'function', 'math', 'object', 'predicate', 'string', 'util'], + icon: ARROW_LEFT_RIGHT_ICON, + iconColor: 'var(--vp-c-warning-1)', + }, +] as const satisfies readonly FlavorSpec[]; + +export function flavorIntroPath({ flavor, localePrefix }: { flavor: FlavorSpec; localePrefix: string }): string { + const introSlug = flavor.guideItems[0]?.slug ?? 'intro'; + const flavorPath = flavor.prefix ? `/${flavor.prefix}` : ''; + return `${localePrefix}${flavorPath}/${introSlug}`; +} + +export function detectFlavor({ relativePath }: { relativePath: string }): FlavorSpec { + const segments = relativePath.split('/'); + return flavors.find(f => f.prefix && segments.includes(f.prefix)) ?? flavors[0]; +} diff --git a/docs/.vitepress/theme/index.js b/docs/.vitepress/theme/index.js index a545a49d1..e95892051 100644 --- a/docs/.vitepress/theme/index.js +++ b/docs/.vitepress/theme/index.js @@ -5,6 +5,7 @@ import Banner from '../components/Banner.vue'; import BundleSizeChart from '../components/BundleSizeChart.vue'; import BundleSizeTable from '../components/BundleSizeTable.vue'; import CompatibilityStatus from '../components/CompatibilityStatus.vue'; +import FlavorDropdown from '../components/FlavorDropdown.vue'; /** @type {import('vitepress').Theme} */ export default { @@ -21,6 +22,7 @@ export default { }, Layout: () => { return h(DefaultTheme.Layout, null, { + 'sidebar-nav-before': () => h(FlavorDropdown), 'layout-bottom': () => h(Banner), }); }, diff --git a/docs/.vitepress/zh_hans.mts b/docs/.vitepress/zh_hans.mts index f268de94a..38db3f393 100644 --- a/docs/.vitepress/zh_hans.mts +++ b/docs/.vitepress/zh_hans.mts @@ -1,9 +1,31 @@ -import path from 'node:path'; import { type DefaultTheme, defineConfig } from 'vitepress'; -import { getSidebarItems } from './libs/getSidebarItems.mts'; -import { sortByText } from './libs/sortByText.mts'; +import { buildFlavorSidebar, type SidebarLabels } from './libs/buildFlavorSidebar.mts'; -const docsRoot = path.resolve(import.meta.dirname, '..'); +const labels: SidebarLabels = { + guide: '指南', + reference: '参考', + guideItems: { + introduction: '简介', + installation: '安装和使用', + bundleSize: '包体积影响', + performance: '性能', + aiIntegration: 'AI 集成', + }, + categories: { + array: '数组工具', + function: '函数工具', + map: 'Map 工具', + math: '数学工具', + object: '对象工具', + predicate: '谓词', + promise: 'Promise 工具', + set: 'Set 工具', + server: '服务端工具', + string: '字符串工具', + util: '工具函数', + error: '错误', + }, +}; // eslint-disable-next-line @typescript-eslint/naming-convention export const zh_hans = defineConfig({ @@ -15,7 +37,7 @@ export const zh_hans = defineConfig({ nav: nav(), - sidebar: sidebar(), + sidebar: buildFlavorSidebar({ locale: 'zh_hans', labels }), editLink: { pattern: 'https://github.com/toss/es-toolkit/edit/main/docs/:path', @@ -34,138 +56,11 @@ function nav(): DefaultTheme.NavItem[] { { text: '主页', link: '/zh_hans/' }, { text: '简介', link: '/zh_hans/intro' }, { text: '参考', link: '/zh_hans/reference/array/at' }, - { text: 'Lodash 兼容性', link: '/zh_hans/reference/compat/array/castArray' }, + { text: 'Lodash 兼容性', link: '/zh_hans/compat/intro' }, { text: '演练场', link: '/zh_hans/playground' }, ]; } -function sidebar(): DefaultTheme.Sidebar { - return [ - { - text: '指南', - items: [ - { text: '简介', link: '/zh_hans/intro' }, - { text: '演练场', link: '/zh_hans/playground' }, - { text: '安装和使用', link: '/zh_hans/usage' }, - { text: '包体积影响', link: '/zh_hans/bundle-size' }, - { text: '性能', link: '/zh_hans/performance' }, - { text: 'Lodash 兼容性', link: '/zh_hans/compatibility' }, - { text: 'AI 集成', link: '/zh_hans/ai-integration' }, - ], - }, - { - text: '参考', - items: sortByText([ - { - text: '数组工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'array'), - }, - { - text: '函数工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'function'), - }, - { - text: 'Map 工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'map'), - }, - { - text: '数学工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'math'), - }, - { - text: '对象工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'object'), - }, - { - text: '谓词', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'predicate'), - }, - { - text: 'Promise 工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'promise'), - }, - { - text: 'Set 工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'set'), - }, - { - text: '服务端工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'server'), - }, - { - text: '字符串工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'string'), - }, - { - text: '工具函数', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'util'), - }, - { - text: '错误', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'error'), - }, - ]), - }, - { - text: 'Lodash 兼容性', - items: [ - { - text: '参考', - items: sortByText([ - { - text: '数组工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'compat', 'array'), - }, - { - text: '函数工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'compat', 'function'), - }, - { - text: '数学工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'compat', 'math'), - }, - { - text: '对象工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'compat', 'object'), - }, - { - text: '谓词', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'compat', 'predicate'), - }, - { - text: '字符串工具', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'compat', 'string'), - }, - { - text: '工具函数', - collapsed: true, - items: getSidebarItems(docsRoot, 'zh_hans', 'reference', 'compat', 'util'), - }, - ]), - }, - ], - }, - ]; -} - export const search: DefaultTheme.LocalSearchOptions['locales'] = { zh_hans: { translations: { diff --git a/docs/compat/intro.md b/docs/compat/intro.md new file mode 100644 index 000000000..1f9f6f6eb --- /dev/null +++ b/docs/compat/intro.md @@ -0,0 +1,66 @@ +# es-toolkit/compat + +`es-toolkit/compat` mirrors [Lodash](https://lodash.com)'s interface and behavior 1:1. It exists so you can lift an existing Lodash codebase into `es-toolkit` without rewriting call sites, and migrate to the strict API at your own pace. + +If your project does not already use Lodash, please use [`es-toolkit`](/intro) instead. + +::: tip ✅ 100% compatibility since v1.39.3 +`es-toolkit/compat` passes Lodash's own test suite, so behavior is identical while staying lighter and faster. +::: + +```ts +// Same call signature as lodash, but coming from es-toolkit/compat +import { chunk } from 'es-toolkit/compat'; + +chunk([1, 2, 3, 4], 0); +// Returns [], identical to lodash +``` + +## Migration flow + +Recommended path for removing Lodash from an existing codebase: + +1. Swap the import path from `lodash` / `lodash-es` to `es-toolkit/compat`. Leave call sites as they are. +2. Clean up call sites over time and switch the import to [`es-toolkit`](/intro). Once done, you get a smaller bundle and faster runtime. + +## How it differs from `es-toolkit` + +- **API shape**: matches Lodash 1:1, including implicit type coercions, multiple argument shapes, and deprecated helpers. [`es-toolkit`](/intro) only exposes the type-safe, modern forms. +- **Bundle size and speed**: slightly larger and slightly slower than [`es-toolkit`](/intro), because it carries extra logic to match Lodash's behavior. +- **Deprecated functions**: kept in `compat` for parity, not in [`es-toolkit`](/intro). Clean them up during migration. + +For function-level documentation, see the [Compat Reference](/compat/reference/array/castArray). + +## Design Principles + +::: info +Design principles are subject to change. +::: + +Our compatibility layer aims to achieve feature parity with 100% accuracy for: + +- Features that are written as a test case in lodash. +- Features that can be inferred from types of `@types/lodash` or `@types/lodash-es`. +- Feature differences identified while migrating code from lodash to es-toolkit (please report these to our [issues page](https://github.com/toss/es-toolkit/issues)). + +However, the following are out of scope for `es-toolkit/compat`: + +- Implicit type conversions, such as converting an empty string to zero or false. +- Functions that have specialized implementations for specific types of arrays, like [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq). +- Handling cases where internal object prototypes, like `Array.prototype`, have been modified. +- Managing cases with JavaScript realms. +- Method chaining support through "Seq" methods. + +## Implementation Status + +::: info +The following emojis indicate the status of each feature: + +- ✅: Completed (The function is fully implemented and has passed all tests with lodash test code.) +- 📝: In Review (The function is implemented but hasn't been tested with lodash test code yet.) +- ❌: Not Implemented (The function hasn't been implemented.) + +Even if a feature is marked "in review," it might already be under review to ensure it matches lodash perfectly, and it could already offer the same functionality. +::: + + diff --git a/docs/reference/compat/array/castArray.md b/docs/compat/reference/array/castArray.md similarity index 100% rename from docs/reference/compat/array/castArray.md rename to docs/compat/reference/array/castArray.md diff --git a/docs/compat/reference/array/chunk.md b/docs/compat/reference/array/chunk.md new file mode 100644 index 000000000..0a5d457c0 --- /dev/null +++ b/docs/compat/reference/array/chunk.md @@ -0,0 +1,70 @@ +# chunk (Lodash Compatibility) + +::: warning Use [`chunk`](../../../reference/array/chunk.md) from `es-toolkit` + +This `chunk` function operates slower due to handling of `null`, `undefined`, and default `size` values. + +For better performance and a more modern implementation, use [chunk](../../../reference/array/chunk.md) from `es-toolkit` instead. + +::: + +Divides an array into smaller arrays of a specified size. + +```typescript +const chunked = chunk(arr, size); +``` + +## Usage + +### `chunk(arr, size?)` + +Use `chunk` when you want to split a long array into multiple smaller arrays of the same size. If the array cannot be divided evenly, the last array will contain the remaining elements. + +```typescript +import { chunk } from 'es-toolkit/compat'; + +// Divide an array of numbers into chunks of size 2. +chunk([1, 2, 3, 4], 2); +// Returns: [[1, 2], [3, 4]] + +// Divide an array of strings into chunks of size 3. +chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); +// Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] + +// When not evenly divisible +chunk([1, 2, 3, 4, 5], 2); +// Returns: [[1, 2], [3, 4], [5]] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { chunk } from 'es-toolkit/compat'; + +chunk(null, 2); +// Returns: [] + +chunk(undefined, 2); +// Returns: [] +``` + +If size is 0 or negative, returns an empty array. + +```typescript +import { chunk } from 'es-toolkit/compat'; + +chunk([1, 2, 3], 0); +// Returns: [] + +chunk([1, 2, 3], -1); +// Returns: [] +``` + +#### Parameters + +- `arr` (`ArrayLike | null | undefined`): The array to divide. +- `size` (`number`, optional): The size of each smaller array. Default is `1`. + +#### Returns + +(`T[][]`): Returns a two-dimensional array divided by size `size`. diff --git a/docs/compat/reference/array/compact.md b/docs/compat/reference/array/compact.md new file mode 100644 index 000000000..0e68454df --- /dev/null +++ b/docs/compat/reference/array/compact.md @@ -0,0 +1,77 @@ +# compact (Lodash compatible) + +::: warning Use [`compact`](../../../reference/array/compact.md) from `es-toolkit` instead + +This `compact` function operates slowly due to handling `null` or `undefined`, `size` default value processing, and more. + +Use the faster and more modern [compact](../../../reference/array/compact.md) from `es-toolkit` instead. + +::: + +Removes falsy values from an array. + +```typescript +const compacted = compact(arr); +``` + +## Usage + +### `compact(arr)` + +Use `compact` when you want to remove falsy values like `false`, `null`, `0`, `""`, `undefined`, `NaN` from an array. + +```typescript +import { compact } from 'es-toolkit/compat'; + +// Remove falsy values +compact([0, 1, false, 2, '', 3]); +// Returns: [1, 2, 3] + +compact(['a', null, 'b', undefined, 'c', NaN]); +// Returns: ['a', 'b', 'c'] + +// BigInt 0 is also removed +compact([0n, 1n, false, 2n]); +// Returns: [1n, 2n] + +// Works with empty arrays +compact([]); +// Returns: [] + +// When all values are falsy +compact([false, null, 0, '', undefined, NaN]); +// Returns: [] +``` + +Truthy values are preserved. + +```typescript +import { compact } from 'es-toolkit/compat'; + +compact([1, 'hello', true, {}, []]); +// Returns: [1, 'hello', true, {}, []] + +// Non-zero numbers +compact([0, -1, 2, -3]); +// Returns: [-1, 2, -3] +``` + +`null` or `undefined` arrays are treated as empty arrays. + +```typescript +import { compact } from 'es-toolkit/compat'; + +compact(null); +// Returns: [] + +compact(undefined); +// Returns: [] +``` + +#### Parameters + +- `arr` (`ArrayLike | null | undefined`): The array to compact. + +#### Returns + +(`T[]`): Returns a new array with falsy values removed. diff --git a/docs/reference/compat/array/concat.md b/docs/compat/reference/array/concat.md similarity index 100% rename from docs/reference/compat/array/concat.md rename to docs/compat/reference/array/concat.md diff --git a/docs/compat/reference/array/countBy.md b/docs/compat/reference/array/countBy.md new file mode 100644 index 000000000..e6afecbb5 --- /dev/null +++ b/docs/compat/reference/array/countBy.md @@ -0,0 +1,88 @@ +# countBy (Lodash compatible) + +::: warning Use `countBy` from `es-toolkit` instead + +This `countBy` function operates slowly due to complex transformation function processing and type conversion. + +Use the faster and more modern [countBy](../../../reference/array/countBy.md) from `es-toolkit` instead. + +::: + +Counts the occurrences of elements in an array or object, grouped by a criterion. + +```typescript +const counts = countBy(collection, iteratee); +``` + +## Usage + +### `countBy(collection, iteratee?)` + +Use `countBy` when you want to group elements of an array or object by some criterion and count how many elements are in each group. The value returned by the iteratee function becomes the key, and the count of elements with that key becomes the value. + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// Group numbers by floor value +countBy([6.1, 4.2, 6.3], Math.floor); +// Returns: { '4': 1, '6': 2 } + +// Group strings by length +countBy(['one', 'two', 'three'], 'length'); +// Returns: { '3': 2, '5': 1 } + +// Group users by age range +const users = [ + { name: 'Alice', age: 25 }, + { name: 'Bob', age: 35 }, + { name: 'Charlie', age: 25 }, +]; +countBy(users, user => Math.floor(user.age / 10) * 10); +// Returns: { '20': 2, '30': 1 } +``` + +Works with objects too. + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// Classify object values by type +const obj = { a: 1, b: 'string', c: 2, d: 'text' }; +countBy(obj, value => typeof value); +// Returns: { 'number': 2, 'string': 2 } +``` + +When used without an iteratee function, groups by the value itself. + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// Group by value itself +countBy([1, 2, 1, 3, 2, 1]); +// Returns: { '1': 3, '2': 2, '3': 1 } + +// Group boolean values +countBy([true, false, true, true]); +// Returns: { 'true': 3, 'false': 1 } +``` + +`null` or `undefined` collections return an empty object. + +```typescript +import { countBy } from 'es-toolkit/compat'; + +countBy(null); +// Returns: {} + +countBy(undefined); +// Returns: {} +``` + +#### Parameters + +- `collection` (`ArrayLike | object | null | undefined`): The array or object to process. +- `iteratee` (`ValueIteratee`, optional): The function that defines the grouping criterion for each element. Can be a function, property name, or partial object. + +#### Returns + +(`Record`): Returns an object with keys for each group and values representing the count of elements in that group. diff --git a/docs/compat/reference/array/difference.md b/docs/compat/reference/array/difference.md new file mode 100644 index 000000000..f943bb938 --- /dev/null +++ b/docs/compat/reference/array/difference.md @@ -0,0 +1,94 @@ +# difference (Lodash compatible) + +::: warning Use `difference` from `es-toolkit` instead + +This `difference` function operates in a complex manner due to handling `null` or `undefined` and processing multiple array arguments. + +Use the faster and more modern [difference](../../../reference/array/difference.md) from `es-toolkit` instead. + +::: + +Computes the difference between the first array and the other arrays, excluding values from the first array that are present in the other arrays. + +```typescript +const result = difference(arr, ...values); +``` + +## Usage + +### `difference(arr, ...values)` + +Use `difference` when you want to remove all values from the first array that are present in the other arrays. The order is preserved from the first array. + +```typescript +import { difference } from 'es-toolkit/compat'; + +// Basic usage +const array1 = [1, 2, 3, 4, 5]; +const array2 = [2, 4]; +const array3 = [5, 6]; +difference(array1, array2, array3); +// Returns: [1, 3] + +// String arrays +difference(['a', 'b', 'c'], ['b'], ['c', 'd']); +// Returns: ['a'] + +// Handling duplicates +difference([1, 2, 2, 3], [2]); +// Returns: [1, 3] +``` + +Handles empty arrays or empty differences. + +```typescript +import { difference } from 'es-toolkit/compat'; + +// Difference with empty array +difference([1, 2, 3], []); +// Returns: [1, 2, 3] + +// When all values are excluded +difference([1, 2, 3], [1, 2, 3]); +// Returns: [] + +// When there are no overlapping values +difference([1, 2], [3, 4]); +// Returns: [1, 2] +``` + +`null` or `undefined` arrays are treated as empty arrays. + +```typescript +import { difference } from 'es-toolkit/compat'; + +difference(null, [1, 2]); +// Returns: [] + +difference(undefined, [1, 2]); +// Returns: [] + +difference([1, 2, 3], null, undefined); +// Returns: [1, 2, 3] (null and undefined are ignored) +``` + +Supports array-like objects. + +```typescript +import { difference } from 'es-toolkit/compat'; + +// Array-like objects +const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; +const arrayLike2 = { 0: 2, 1: 4, length: 2 }; +difference(arrayLike1, arrayLike2); +// Returns: [1, 3] +``` + +#### Parameters + +- `arr` (`ArrayLike | null | undefined`): The base array to compute the difference from. +- `values` (`...ArrayLike[]`): Arrays containing values to exclude. + +#### Returns + +(`T[]`): Returns a new array with values from the first array excluding values present in the other arrays. diff --git a/docs/compat/reference/array/differenceBy.md b/docs/compat/reference/array/differenceBy.md new file mode 100644 index 000000000..0e608739a --- /dev/null +++ b/docs/compat/reference/array/differenceBy.md @@ -0,0 +1,88 @@ +# differenceBy (Lodash compatible) + +::: warning Use `differenceBy` from `es-toolkit` instead + +This `differenceBy` function operates slowly due to complex argument processing and iteratee transformation. + +Use the faster and more modern [differenceBy](../../../reference/array/differenceBy.md) from `es-toolkit` instead. + +::: + +Computes the difference between the first array and other arrays after applying an iteratee function to transform the values for comparison. + +```typescript +const result = differenceBy(array, ...values, iteratee); +``` + +## Usage + +### `differenceBy(array, ...values, iteratee)` + +Use `differenceBy` when you want to remove elements from the first array that have equivalent transformed values in the other arrays. This is useful for comparing arrays of objects by a specific property or transformed value. + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// Compare using Math.floor +differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); +// Returns: [1.2] (2.1 is excluded because Math.floor(2.1) === Math.floor(2.3)) + +// Compare by string length +differenceBy(['one', 'two', 'three'], ['four', 'eight'], 'length'); +// Returns: ['one', 'two'] (three is excluded because it has the same length as eight) + +// Compare objects by property +const users1 = [ + { id: 1, name: 'Alice' }, + { id: 2, name: 'Bob' }, +]; +const users2 = [{ id: 1, name: 'Different Alice' }]; +differenceBy(users1, users2, 'id'); +// Returns: [{ id: 2, name: 'Bob' }] (excludes object with id 1) +``` + +Can exclude from multiple arrays at once. + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// Exclude from multiple arrays +differenceBy([2.1, 1.2, 3.5], [2.3], [1.4], [3.2], Math.floor); +// Returns: [] (all elements are excluded) + +// Compare strings by length from multiple arrays +differenceBy(['a', 'bb', 'ccc'], ['x'], ['yy'], ['zzz'], 'length'); +// Returns: [] (lengths 1, 2, 3 are all excluded) +``` + +Without an iteratee function, it behaves like regular `difference`. + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// Without iteratee function +differenceBy([1, 2, 3], [2, 4]); +// Returns: [1, 3] +``` + +`null` or `undefined` arrays are treated as empty arrays. + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +differenceBy(null, [1, 2], Math.floor); +// Returns: [] + +differenceBy(undefined, [1, 2], x => x); +// Returns: [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The base array to compute the difference from. +- `values` (`...ArrayLike[]`): Arrays containing values to exclude. +- `iteratee` (`ValueIteratee`): The function that transforms each element for comparison. Can be a function, property name, or partial object. + +#### Returns + +(`T[]`): Returns a new array with elements excluded based on the transformed values. diff --git a/docs/compat/reference/array/differenceWith.md b/docs/compat/reference/array/differenceWith.md new file mode 100644 index 000000000..995e0c0b9 --- /dev/null +++ b/docs/compat/reference/array/differenceWith.md @@ -0,0 +1,79 @@ +# differenceWith (Lodash compatible) + +::: warning Use `differenceWith` from `es-toolkit` instead + +This `differenceWith` function operates slowly due to handling `null` or `undefined`, processing multiple arrays, and `ArrayLike` type processing. + +Use the faster and more modern [differenceWith](../../../reference/array/differenceWith.md) from `es-toolkit` instead. + +::: + +Removes elements from the first array that are present in the other arrays using a comparator function. + +```typescript +const result = differenceWith(array, ...values, comparator); +``` + +## Usage + +### `differenceWith(array, ...values, comparator)` + +Use `differenceWith` when you want to compute the difference using a comparator function to compare elements. The last argument becomes the comparator function. + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +// Compare objects by id +const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; +const others = [{ id: 2 }]; +const comparator = (a, b) => a.id === b.id; + +differenceWith(objects, others, comparator); +// Returns: [{ id: 1 }, { id: 3 }] + +// Exclude from multiple arrays at once +const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]; +const values1 = [{ id: 2 }]; +const values2 = [{ id: 3 }]; + +differenceWith(array, values1, values2, comparator); +// Returns: [{ id: 1 }, { id: 4 }] +``` + +Without a comparator function, it behaves like regular `difference`. + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +// Without comparator, uses regular comparison +differenceWith([1, 2, 3], [2], [3]); +// Returns: [1] +``` + +Can use complex comparison logic. + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +const users = [ + { name: 'alice', age: 25 }, + { name: 'bob', age: 30 }, + { name: 'charlie', age: 35 }, +]; +const excludeUsers = [{ name: 'bob', age: 25 }]; // Different age + +// Compare only by name +const compareByName = (a, b) => a.name === b.name; +differenceWith(users, excludeUsers, compareByName); +// Returns: [{ name: 'alice', age: 25 }, { name: 'charlie', age: 35 }] +// bob is excluded (even though age is different, name matches) +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The base array to compute the difference from. +- `...values` (`Array>` + `(a: T, b: T) => boolean`): Arrays containing elements to exclude, with the last argument being the comparator function. + +#### Returns + +(`T[]`): Returns a new array with elements from the first array excluding those found in the other arrays using the comparator function. diff --git a/docs/compat/reference/array/drop.md b/docs/compat/reference/array/drop.md new file mode 100644 index 000000000..5cfe29f5e --- /dev/null +++ b/docs/compat/reference/array/drop.md @@ -0,0 +1,97 @@ +# drop (Lodash Compatibility) + +::: warning Use `drop` from `es-toolkit` + +This `drop` function operates in a complex manner due to handling of `null` or `undefined`, `toInteger` conversion, etc. + +Instead, use the faster and more modern [`drop`](../../../reference/array/drop.md) from `es-toolkit`. + +::: + +Removes a specified number of elements from the beginning of an array. + +```typescript +const result = drop(array, n); +``` + +## Usage + +### `drop(array, n?)` + +Use `drop` when you want to remove several elements from the beginning of an array and get the rest. By default, it removes the first element. + +```typescript +import { drop } from 'es-toolkit/compat'; + +// Basic usage (removes first element) +drop([1, 2, 3, 4, 5]); +// Returns: [2, 3, 4, 5] + +// Remove first 2 elements +drop([1, 2, 3, 4, 5], 2); +// Returns: [3, 4, 5] + +// Remove first 3 elements +drop(['a', 'b', 'c', 'd'], 3); +// Returns: ['d'] +``` + +When specifying 0 or a negative number, it returns the original array as is. + +```typescript +import { drop } from 'es-toolkit/compat'; + +// Remove 0 elements +drop([1, 2, 3], 0); +// Returns: [1, 2, 3] + +// Specify negative number +drop([1, 2, 3], -1); +// Returns: [1, 2, 3] +``` + +When specifying a number larger than the array, it returns an empty array. + +```typescript +import { drop } from 'es-toolkit/compat'; + +// Specify number larger than array size +drop([1, 2, 3], 5); +// Returns: [] + +// Remove from empty array +drop([], 1); +// Returns: [] +``` + +`null` or `undefined` arrays are treated as empty arrays. + +```typescript +import { drop } from 'es-toolkit/compat'; + +drop(null, 1); +// Returns: [] + +drop(undefined, 2); +// Returns: [] +``` + +Array-like objects are also supported. + +```typescript +import { drop } from 'es-toolkit/compat'; + +// Array-like object +const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; +drop(arrayLike, 1); +// Returns: ['b', 'c'] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array from which elements will be removed. +- `n` (`number`, optional): The number of elements to remove. Default is `1`. + +#### Returns + +(`T[]`): Returns a new array with the specified number of elements removed from the beginning. diff --git a/docs/compat/reference/array/dropRight.md b/docs/compat/reference/array/dropRight.md new file mode 100644 index 000000000..0c7964761 --- /dev/null +++ b/docs/compat/reference/array/dropRight.md @@ -0,0 +1,55 @@ +# dropRight (Lodash Compatibility) + +::: warning Use `dropRight` from `es-toolkit` + +This `dropRight` function operates slowly due to handling `null` or `undefined`, `guard` parameter processing, `toInteger` conversion, etc. + +Instead, use the faster and more modern [`dropRight`](../../../reference/array/dropRight.md) from `es-toolkit`. + +::: + +Returns a new array with a specified number of elements removed from the end. + +```typescript +const result = dropRight(array, itemsCount); +``` + +## Usage + +### `dropRight(array, itemsCount)` + +Use `dropRight` when you want to remove a certain number of elements from the end of an array and create a new array with the remaining elements. + +```typescript +import { dropRight } from 'es-toolkit/compat'; + +// Remove the last 2 elements from a number array. +dropRight([1, 2, 3, 4, 5], 2); +// Returns: [1, 2, 3] + +// Remove the last 1 element from a string array. +dropRight(['a', 'b', 'c'], 1); +// Returns: ['a', 'b'] + +// If the number to remove is not specified, the default value 1 is used. +dropRight([1, 2, 3]); +// Returns: [1, 2] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { dropRight } from 'es-toolkit/compat'; + +dropRight(null, 2); // [] +dropRight(undefined, 2); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to remove elements from. +- `itemsCount` (`number`, optional): The number of elements to remove from the end of the array. Default is `1`. + +#### Returns + +(`T[]`): Returns a new array with `itemsCount` elements removed from the end. diff --git a/docs/compat/reference/array/dropRightWhile.md b/docs/compat/reference/array/dropRightWhile.md new file mode 100644 index 000000000..45a62aff5 --- /dev/null +++ b/docs/compat/reference/array/dropRightWhile.md @@ -0,0 +1,65 @@ +# dropRightWhile (Lodash Compatibility) + +::: warning Use `dropRightWhile` from `es-toolkit` + +This `dropRightWhile` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. + +Instead, use the faster and more modern [`dropRightWhile`](../../../reference/array/dropRightWhile.md) from `es-toolkit`. + +::: + +Removes elements from the end of an array based on a predicate function. + +```typescript +const result = dropRightWhile(array, predicate); +``` + +## Usage + +### `dropRightWhile(array, predicate)` + +Use `dropRightWhile` when you want to consecutively remove elements from the end of an array that satisfy a specific condition. Removal stops when the predicate function returns `false`. + +```typescript +import { dropRightWhile } from 'es-toolkit/compat'; + +// Using a function as a predicate. +const users = [ + { user: 'barney', active: true }, + { user: 'fred', active: false }, + { user: 'pebbles', active: false }, +]; + +dropRightWhile(users, user => !user.active); +// Returns: [{ user: 'barney', active: true }] + +// Matching with an object pattern. +dropRightWhile(users, { user: 'pebbles', active: false }); +// Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }] + +// Specifying property and value in array format. +dropRightWhile(users, ['active', false]); +// Returns: [{ user: 'barney', active: true }] + +// Checking condition by property name. +dropRightWhile(users, 'active'); +// Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { dropRightWhile } from 'es-toolkit/compat'; + +dropRightWhile(null, x => x > 0); // [] +dropRightWhile(undefined, x => x > 0); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to remove elements from. +- `predicate` (`ListIteratee`, optional): The predicate function to apply to each element. Can accept a function, object pattern, array pattern, or property name. + +#### Returns + +(`T[]`): Returns a new array starting from the first element that does not satisfy the condition. diff --git a/docs/compat/reference/array/dropWhile.md b/docs/compat/reference/array/dropWhile.md new file mode 100644 index 000000000..59f757c69 --- /dev/null +++ b/docs/compat/reference/array/dropWhile.md @@ -0,0 +1,67 @@ +# dropWhile (Lodash Compatibility) + +::: warning Use `dropWhile` from `es-toolkit` + +This `dropWhile` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. + +Instead, use the faster and more modern [`dropWhile`](../../../reference/array/dropWhile.md) from `es-toolkit`. + +::: + +Removes elements from the beginning of an array based on a predicate function. + +```typescript +const result = dropWhile(array, predicate); +``` + +## Usage + +### `dropWhile(array, predicate)` + +Use `dropWhile` when you want to consecutively remove elements from the beginning of an array that satisfy a specific condition. Removal stops when the predicate function returns `false`. + +```typescript +import { dropWhile } from 'es-toolkit/compat'; + +// Using a function as a predicate. +dropWhile([1, 2, 3, 4, 5], n => n < 3); +// Returns: [3, 4, 5] + +// Matching with an object pattern. +const users = [ + { name: 'alice', active: false }, + { name: 'bob', active: false }, + { name: 'charlie', active: true }, +]; + +dropWhile(users, { active: false }); +// Returns: [{ name: 'charlie', active: true }] + +// Specifying property and value in array format. +dropWhile(users, ['active', false]); +// Returns: [{ name: 'charlie', active: true }] + +// Checking condition by property name. +const items = [{ visible: false }, { visible: false }, { visible: true }]; + +dropWhile(items, 'visible'); +// Returns: [{ visible: false }, { visible: false }, { visible: true }] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { dropWhile } from 'es-toolkit/compat'; + +dropWhile(null, x => x > 0); // [] +dropWhile(undefined, x => x > 0); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to remove elements from. +- `predicate` (`ListIteratee`, optional): The predicate function to apply to each element. Can accept a function, object pattern, array pattern, or property name. Default is `identity`. + +#### Returns + +(`T[]`): Returns a new array starting from the first element that does not satisfy the condition. diff --git a/docs/reference/compat/array/each.md b/docs/compat/reference/array/each.md similarity index 100% rename from docs/reference/compat/array/each.md rename to docs/compat/reference/array/each.md diff --git a/docs/compat/reference/array/eachRight.md b/docs/compat/reference/array/eachRight.md new file mode 100644 index 000000000..3062e6741 --- /dev/null +++ b/docs/compat/reference/array/eachRight.md @@ -0,0 +1,58 @@ +# eachRight (Lodash Compatibility) + +::: warning Use `forEachRight` from `es-toolkit` + +This `eachRight` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. + +Instead, use the faster and more modern [`forEachRight`](../../../reference/array/forEachRight.md) from `es-toolkit`. + +::: + +Performs an iteration operation from right to left on each element of an array or object. + +```typescript +const result = eachRight(collection, iteratee); +``` + +## Usage + +### `eachRight(collection, iteratee)` + +Iterates through each element of an array, object, or string from right to left and executes the given function. For arrays, it iterates in reverse order from the last index; for objects, it iterates through enumerable properties in reverse order. + +```typescript +import { eachRight } from 'es-toolkit/compat'; + +// Iterate array in reverse order +eachRight([1, 2, 3], (value, index) => console.log(value, index)); +// Logs: 3 2, 2 1, 1 0 + +// Iterate object in reverse order +eachRight({ a: 1, b: 2 }, (value, key) => console.log(key, value)); +// Logs: 'b' 2, 'a' 1 + +// Iterate string in reverse order +eachRight('hello', (char, index) => console.log(char, index)); +// Logs: 'o' 4, 'l' 3, 'l' 2, 'e' 1, 'h' 0 +``` + +If the function returns `false`, iteration stops. + +```typescript +import { eachRight } from 'es-toolkit/compat'; + +eachRight([1, 2, 3, 4], value => { + console.log(value); + return value !== 2; // Stop at 2 +}); +// Logs: 4, 3, 2 +``` + +#### Parameters + +- `collection` (`ArrayLike | Record | string | null | undefined`): The collection to iterate over. +- `iteratee` (`(item: any, index: any, collection: any) => unknown`, optional): The function to execute for each element. Default is the `identity` function. + +#### Returns + +(`ArrayLike | Record | string | null | undefined`): Returns the original collection. diff --git a/docs/reference/compat/array/every.md b/docs/compat/reference/array/every.md similarity index 100% rename from docs/reference/compat/array/every.md rename to docs/compat/reference/array/every.md diff --git a/docs/compat/reference/array/fill.md b/docs/compat/reference/array/fill.md new file mode 100644 index 000000000..e8cba52c6 --- /dev/null +++ b/docs/compat/reference/array/fill.md @@ -0,0 +1,82 @@ +# fill (Lodash Compatibility) + +::: warning Use `fill` from `es-toolkit` + +This `fill` function operates with complex behavior due to handling `null` or `undefined`, support for array-like objects, etc. + +Instead, use the faster and more modern [`fill`](../../../reference/array/fill.md) from `es-toolkit`. + +::: + +Fills the elements of an array with a specified value. + +```typescript +const result = fill(array, value, start, end); +``` + +## Usage + +### `fill(array, value, start?, end?)` + +Use `fill` when you want to fill a specific range or the entire array with the same value. It modifies the original array directly. + +```typescript +import { fill } from 'es-toolkit/compat'; + +// Fill entire array +const arr1 = [1, 2, 3]; +fill(arr1, 'a'); +// Returns: ['a', 'a', 'a'] + +// Fill specific range +const arr2 = [1, 2, 3, 4, 5]; +fill(arr2, '*', 1, 4); +// Returns: [1, '*', '*', '*', 5] + +// Use negative indices +const arr3 = [1, 2, 3, 4, 5]; +fill(arr3, 'x', -3, -1); +// Returns: [1, 2, 'x', 'x', 5] +``` + +Array-like objects are also supported. + +```typescript +import { fill } from 'es-toolkit/compat'; + +const arrayLike = { 0: 1, 1: 2, 2: 3, length: 3 }; +fill(arrayLike, 'a', 1, 2); +// Returns: { 0: 1, 1: 'a', 2: 3, length: 3 } +``` + +`null` or `undefined` arrays are treated as empty arrays. + +```typescript +import { fill } from 'es-toolkit/compat'; + +fill(null, 'a'); +// Returns: [] + +fill(undefined, 'a'); +// Returns: [] +``` + +Strings are read-only, so they are returned as is. + +```typescript +import { fill } from 'es-toolkit/compat'; + +fill('abc', 'x'); +// Returns: 'abc' (not modified) +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to fill. +- `value` (`U`): The value to fill the array with. +- `start` (`number`, optional): The start position. Defaults to `0`. +- `end` (`number`, optional): The end position (not included). Defaults to `array.length`. + +#### Returns + +(`ArrayLike`): Returns the array filled with the value. diff --git a/docs/reference/compat/array/filter.md b/docs/compat/reference/array/filter.md similarity index 100% rename from docs/reference/compat/array/filter.md rename to docs/compat/reference/array/filter.md diff --git a/docs/reference/compat/array/find.md b/docs/compat/reference/array/find.md similarity index 100% rename from docs/reference/compat/array/find.md rename to docs/compat/reference/array/find.md diff --git a/docs/reference/compat/array/findIndex.md b/docs/compat/reference/array/findIndex.md similarity index 100% rename from docs/reference/compat/array/findIndex.md rename to docs/compat/reference/array/findIndex.md diff --git a/docs/reference/compat/array/findLast.md b/docs/compat/reference/array/findLast.md similarity index 100% rename from docs/reference/compat/array/findLast.md rename to docs/compat/reference/array/findLast.md diff --git a/docs/reference/compat/array/findLastIndex.md b/docs/compat/reference/array/findLastIndex.md similarity index 100% rename from docs/reference/compat/array/findLastIndex.md rename to docs/compat/reference/array/findLastIndex.md diff --git a/docs/compat/reference/array/first.md b/docs/compat/reference/array/first.md new file mode 100644 index 000000000..41ba59463 --- /dev/null +++ b/docs/compat/reference/array/first.md @@ -0,0 +1,78 @@ +# first (Lodash Compatibility) + +::: warning Use `head` from `es-toolkit` + +This `first` function operates slowly due to handling `null` or `undefined` and array-like object conversion. The `head` function from `es-toolkit` operates faster and simpler without this additional processing. + +Use the faster and more modern [head](../../../reference/array/head.md) from `es-toolkit` instead. + +::: + +Returns the first element of an array. + +```typescript +const firstElement = first(array); +``` + +## Usage + +### `first(array)` + +Use `first` when you want to get the first element of an array. Returns `undefined` if the array is empty or is `null` or `undefined`. + +```typescript +import { first } from 'es-toolkit/compat'; + +// Get the first element from a regular array +first([1, 2, 3]); +// Returns: 1 + +// Get the first element from a string array +first(['a', 'b', 'c']); +// Returns: 'a' + +// Empty array +first([]); +// Returns: undefined +``` + +`null` or `undefined` returns `undefined`. + +```typescript +import { first } from 'es-toolkit/compat'; + +first(null); // undefined +first(undefined); // undefined +``` + +Can be used with array-like objects. + +```typescript +import { first } from 'es-toolkit/compat'; + +const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; +first(arrayLike); +// Returns: 'a' + +// Strings are also treated like arrays +first('hello'); +// Returns: 'h' +``` + +For type-guaranteed tuples, returns the exact type. + +```typescript +import { first } from 'es-toolkit/compat'; + +const tuple = [1, 'two', true] as const; +first(tuple); +// Returns: 1 (type is inferred as 1) +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to get the first element from. + +#### Returns + +(`T | undefined`): Returns the first element of the array. Returns `undefined` if the array is empty or invalid. diff --git a/docs/compat/reference/array/flatMap.md b/docs/compat/reference/array/flatMap.md new file mode 100644 index 000000000..ebdbb5b31 --- /dev/null +++ b/docs/compat/reference/array/flatMap.md @@ -0,0 +1,77 @@ +# flatMap (Lodash Compatibility) + +::: warning Use `flatMap` from `es-toolkit` + +This `flatMap` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, and supporting various condition function formats. + +Use the faster and more modern [flatMap](../../../reference/array/flatMap.md) from `es-toolkit` instead. + +::: + +Applies a function to each element and flattens the result. + +```typescript +const result = flatMap(collection, iteratee); +``` + +## Usage + +### `flatMap(collection, iteratee)` + +Applies an iteratee function to each element of a collection and returns an array flattened by one level. Supports arrays, objects, and strings, and can use various forms of iteratees. + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +// Apply a function to an array +function duplicate(n) { + return [n, n]; +} +flatMap([1, 2], duplicate); +// Result: [1, 1, 2, 2] + +// Apply a function to an object +const obj = { a: 1, b: 2 }; +flatMap(obj, (value, key) => [key, value]); +// Result: ['a', 1, 'b', 2] + +// Map with a string property +const users = [ + { user: 'barney', hobbies: ['hiking', 'coding'] }, + { user: 'fred', hobbies: ['reading'] }, +]; +flatMap(users, 'hobbies'); +// Result: ['hiking', 'coding', 'reading'] +``` + +Using without an iteratee flattens the values by one level. + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +const obj = { a: [1, 2], b: [3, 4] }; +flatMap(obj); +// Result: [1, 2, 3, 4] +``` + +Conditional mapping with a partial object is also possible. + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +const users = [ + { user: 'barney', age: 36, active: true }, + { user: 'fred', age: 40, active: false }, +]; +flatMap(users, { active: false }); +// Result: [false, true] (matching result of elements where active is false) +``` + +#### Parameters + +- `collection` (`object | null | undefined`): The collection to iterate over. Can be an array, object, or string. +- `iteratee` (`ListIterator | ObjectIterator | string | object`, optional): The iteratee to apply to each element. Can be a function, property name, or partial object. + +#### Returns + +(`any[]`): Returns a new array flattened by one level after mapping. diff --git a/docs/compat/reference/array/flatMapDeep.md b/docs/compat/reference/array/flatMapDeep.md new file mode 100644 index 000000000..c74d00c1a --- /dev/null +++ b/docs/compat/reference/array/flatMapDeep.md @@ -0,0 +1,77 @@ +# flatMapDeep (Lodash Compatibility) + +::: warning Use [`flatMapDeep`](../../../reference/array/flatMapDeep.md) from `es-toolkit` + +This `flatMapDeep` function operates slowly due to complex collection type handling and deep flattening logic. + +Use the faster and more modern [flatMapDeep](../../../reference/array/flatMapDeep.md) from `es-toolkit` instead. + +::: + +Applies a function to each element and recursively flattens the result. + +```typescript +const result = flatMapDeep(collection, iteratee); +``` + +## Usage + +### `flatMapDeep(collection, iteratee)` + +Applies an iteratee function to each element of a collection and returns an array flattened to infinite depth. All nested array structures are flattened into a one-dimensional array. + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +// Apply a function to an array and deeply flatten +function duplicate(n) { + return [[[n, n]]]; +} +flatMapDeep([1, 2], duplicate); +// Result: [1, 1, 2, 2] + +// Apply a function to an object and deeply flatten +const obj = { a: 1, b: 2 }; +flatMapDeep(obj, (value, key) => [[[key, value]]]); +// Result: ['a', 1, 'b', 2] + +// Map with a string property and deeply flatten +const users = [ + { user: 'barney', hobbies: [['hiking', 'coding']] }, + { user: 'fred', hobbies: [['reading']] }, +]; +flatMapDeep(users, 'hobbies'); +// Result: ['hiking', 'coding', 'reading'] +``` + +Using without an iteratee recursively flattens the values. + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +const obj = { a: [[1, 2]], b: [[[3]]] }; +flatMapDeep(obj); +// Result: [1, 2, 3] +``` + +Conditional mapping with a partial object is also possible. + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +const users = [ + { user: 'barney', active: [true, false] }, + { user: 'fred', active: [false] }, +]; +flatMapDeep(users, { active: [false] }); +// Result: [true, true] (matching result of elements with active array containing [false]) +``` + +#### Parameters + +- `collection` (`object | null | undefined`): The collection to iterate over. Can be an array, object, or string. +- `iteratee` (`ListIterator | ObjectIterator | string | object`, optional): The iteratee to apply to each element. Can be a function, property name, or partial object. + +#### Returns + +(`any[]`): Returns a new array recursively flattened after mapping. diff --git a/docs/compat/reference/array/flatMapDepth.md b/docs/compat/reference/array/flatMapDepth.md new file mode 100644 index 000000000..21987079c --- /dev/null +++ b/docs/compat/reference/array/flatMapDepth.md @@ -0,0 +1,79 @@ +# flatMapDepth (Lodash Compatibility) + +::: warning Use [flatMap](../../../reference/array/flatMap.md) from `es-toolkit` + +This `flatMapDepth` function is implemented in a complex way to support various forms of iteratees and handle `null` or `undefined` for Lodash compatibility. The `flatMap` function in the main library only supports simple function iteratees, so it operates faster. + +Use the faster and more modern [flatMap](../../../reference/array/flatMap.md) from `es-toolkit` instead. + +::: + +Transforms each element of an array with an iteratee function and flattens to the specified depth. + +```typescript +const result = flatMapDepth(collection, iteratee, depth); +``` + +## Usage + +### `flatMapDepth(collection, iteratee, depth)` + +Transforms each element of an array or object with the given function, then flattens the result to the specified depth and returns a new array. Useful when you want to flatten nested array structures only to a desired depth. + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +// Transform an array and flatten to depth 2 +flatMapDepth([1, 2], n => [[n, n]], 2); +// => [1, 1, 2, 2] + +// When limited to depth 1, it's not fully flattened +flatMapDepth([1, 2], n => [[n, n]], 1); +// => [[1, 1], [2, 2]] + +// Extract values from an object and flatten +const users = [ + { user: 'barney', hobbies: [['hiking'], ['coding']] }, + { user: 'fred', hobbies: [['reading']] }, +]; +flatMapDepth(users, 'hobbies', 2); +// => ['hiking', 'coding', 'reading'] +``` + +This function supports various forms of iteratees. + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +// Transform with a function +flatMapDepth([1, 2, 3], n => [[n, n]], 2); + +// Extract values by property name +const objects = [{ items: [['a'], ['b']] }, { items: [['c']] }]; +flatMapDepth(objects, 'items', 2); +// => ['a', 'b', 'c'] + +// Partial matching with an object +const users = [{ active: [[true], [false]] }, { active: [[false]] }]; +flatMapDepth(users, { active: [[false]] }, 2); +// => [true, true] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +flatMapDepth(null, n => [n], 1); // => [] +flatMapDepth(undefined, n => [n], 1); // => [] +``` + +#### Parameters + +- `collection` (`ArrayLike | Record | Record | object | null | undefined`): The array or object to iterate over. +- `iteratee` (`((value: T, index: number, collection: any) => any) | string | object`, optional): The transformation function or property name to execute for each element. Default is `identity`. +- `depth` (`number`, optional): The maximum depth to flatten. Default is `1`. + +#### Returns + +(`T[]`): Returns a new array flattened to the specified depth after transformation with the iteratee. diff --git a/docs/compat/reference/array/flatten.md b/docs/compat/reference/array/flatten.md new file mode 100644 index 000000000..254dda8bb --- /dev/null +++ b/docs/compat/reference/array/flatten.md @@ -0,0 +1,69 @@ +# flatten (Lodash Compatibility) + +::: warning Use `flatten` from `es-toolkit` + +This `flatten` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, and supporting various condition function formats. + +Use the faster and more modern [flatten](../../../reference/array/flatten.md) from `es-toolkit` instead. + +::: + +Flattens an array by one level. + +```typescript +const result = flatten(array, depth); +``` + +## Usage + +### `flatten(value, depth)` + +Flattens a nested array by the specified depth. By default, it flattens only one level, and also supports Arguments objects and objects with Symbol.isConcatSpreadable. + +```typescript +import { flatten } from 'es-toolkit/compat'; + +// Basic flattening (one level) +flatten([1, [2, [3, [4]], 5]]); +// Result: [1, 2, [3, [4]], 5] + +// Specify depth +flatten([1, [2, [3, [4]], 5]], 2); +// Result: [1, 2, 3, [4], 5] + +// Support for Arguments objects +function example() { + return flatten(arguments); +} +example(1, [2, 3], [[4]]); +// Result: [1, 2, 3, [4]] +``` + +Empty arrays, null, or undefined return empty arrays. + +```typescript +import { flatten } from 'es-toolkit/compat'; + +flatten(null); // [] +flatten(undefined); // [] +flatten([]); // [] +``` + +Objects with Symbol.isConcatSpreadable are also flattened like arrays. + +```typescript +import { flatten } from 'es-toolkit/compat'; + +const spreadable = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true }; +flatten([1, spreadable, 3]); +// Result: [1, 'a', 'b', 3] +``` + +#### Parameters + +- `value` (`ArrayLike | null | undefined`): The array to flatten. +- `depth` (`number`, optional): The maximum depth to flatten. Default is `1`. + +#### Returns + +(`T[]`): Returns a new flattened array. diff --git a/docs/compat/reference/array/flattenDeep.md b/docs/compat/reference/array/flattenDeep.md new file mode 100644 index 000000000..1dd148715 --- /dev/null +++ b/docs/compat/reference/array/flattenDeep.md @@ -0,0 +1,64 @@ +# flattenDeep (Lodash Compatibility) + +::: warning Use `flattenDeep` from `es-toolkit` + +This `flattenDeep` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, and supporting various condition function formats. + +Use the faster and more modern [flattenDeep](../../../reference/array/flattenDeep.md) from `es-toolkit` instead. + +::: + +Completely flattens an array. + +```typescript +const result = flattenDeep(array); +``` + +## Usage + +### `flattenDeep(value)` + +Recursively flattens a nested array at all depths. All nesting levels are removed, returning a completely flattened one-dimensional array. + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +// Completely flatten a deeply nested array +flattenDeep([1, [2, [3, [4]], 5]]); +// Result: [1, 2, 3, 4, 5] + +// Completely flatten a complex nested structure +flattenDeep([1, [2, [3, [[[[4]]]]], 5]]); +// Result: [1, 2, 3, 4, 5] + +// Support for mixed types +flattenDeep(['a', ['b', ['c', [['d']]]]]); +// Result: ['a', 'b', 'c', 'd'] +``` + +Empty arrays, null, or undefined return empty arrays. + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +flattenDeep(null); // [] +flattenDeep(undefined); // [] +flattenDeep([]); // [] +``` + +Already flattened arrays are copied as-is. + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +flattenDeep([1, 2, 3, 4, 5]); +// Result: [1, 2, 3, 4, 5] +``` + +#### Parameters + +- `value` (`ListOfRecursiveArraysOrValues | null | undefined`): The array to completely flatten. + +#### Returns + +(`Array`): Returns a new completely flattened array with all nesting removed. diff --git a/docs/compat/reference/array/flattenDepth.md b/docs/compat/reference/array/flattenDepth.md new file mode 100644 index 000000000..182a634dc --- /dev/null +++ b/docs/compat/reference/array/flattenDepth.md @@ -0,0 +1,55 @@ +# flattenDepth (Lodash Compatibility) + +::: warning Use `flatten` from `es-toolkit` + +This `flattenDepth` function operates slowly due to handling `null` or `undefined`. The `flatten` function from `es-toolkit` operates faster and simpler without this additional processing. + +Use the faster and more modern [flatten](../../../reference/array/flatten.md) from `es-toolkit` instead. + +::: + +Flattens an array to the specified depth. + +```typescript +const flattened = flattenDepth(array, depth); +``` + +## Usage + +### `flattenDepth(array, depth)` + +Use `flattenDepth` when you want to flatten a nested array to a desired depth. When you specify a depth, it flattens the nested array only to that depth. + +```typescript +import { flattenDepth } from 'es-toolkit/compat'; + +// Flatten to depth 1 +flattenDepth([1, [2, [3, [4]], 5]], 1); +// Returns: [1, 2, [3, [4]], 5] + +// Flatten to depth 2 +flattenDepth([1, [2, [3, [4]], 5]], 2); +// Returns: [1, 2, 3, [4], 5] + +// If no depth is specified, it defaults to 1 +flattenDepth([1, [2, [3, [4]], 5]]); +// Returns: [1, 2, [3, [4]], 5] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { flattenDepth } from 'es-toolkit/compat'; + +flattenDepth(null, 2); // [] +flattenDepth(undefined, 2); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to flatten. +- `depth` (`number`, optional): The maximum depth to flatten. Default is `1`. + +#### Returns + +(`T[]`): Returns a new array flattened to the specified depth. diff --git a/docs/reference/compat/array/forEach.md b/docs/compat/reference/array/forEach.md similarity index 100% rename from docs/reference/compat/array/forEach.md rename to docs/compat/reference/array/forEach.md diff --git a/docs/compat/reference/array/forEachRight.md b/docs/compat/reference/array/forEachRight.md new file mode 100644 index 000000000..61f4afc83 --- /dev/null +++ b/docs/compat/reference/array/forEachRight.md @@ -0,0 +1,75 @@ +# forEachRight (Lodash Compatibility) + +::: warning Use `forEachRight` from `es-toolkit` + +This `forEachRight` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. + +Instead, use the faster and more modern [`forEachRight`](../../../reference/array/forEachRight.md) from `es-toolkit`. + +::: + +Iterates over elements of an array or object from right to left and executes a function for each element. + +```typescript +forEachRight(collection, callback); +``` + +## Usage + +### `forEachRight(collection, callback)` + +Iterates through each element of an array, object, or string from right to left and executes the given callback function. The iteration stops if the callback returns `false`. + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +// Iterate array in reverse order +forEachRight([1, 2, 3], (value, index) => { + console.log(value, index); +}); +// Output: 3 2, 2 1, 1 0 + +// Iterate string in reverse order +forEachRight('abc', (char, index) => { + console.log(char, index); +}); +// Output: 'c' 2, 'b' 1, 'a' 0 + +// Iterate object in reverse order +forEachRight({ a: 1, b: 2, c: 3 }, (value, key) => { + console.log(value, key); +}); +// Output: 3 'c', 2 'b', 1 'a' +``` + +`null` or `undefined` are returned as is. + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +forEachRight(null, value => console.log(value)); // null +forEachRight(undefined, value => console.log(value)); // undefined +``` + +The iteration stops if the callback returns `false`. + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +forEachRight([1, 2, 3, 4], value => { + console.log(value); + if (value === 2) { + return false; // Stop iteration + } +}); +// Output: 4, 3, 2 +``` + +#### Parameters + +- `collection` (`ArrayLike | Record | string | null | undefined`): The collection to iterate over. Can be an array, object, string, or null/undefined. +- `callback` (`(item: any, index: any, arr: any) => unknown`, optional): The function to execute for each element. Returns `false` to stop iteration. Default is the `identity` function. + +#### Returns + +(`ArrayLike | Record | string | null | undefined`): Returns the original collection as is. diff --git a/docs/compat/reference/array/groupBy.md b/docs/compat/reference/array/groupBy.md new file mode 100644 index 000000000..7a8a3166a --- /dev/null +++ b/docs/compat/reference/array/groupBy.md @@ -0,0 +1,79 @@ +# groupBy (Lodash Compatibility) + +::: warning Use [`groupBy`](../../../reference/array/groupBy.md) from `es-toolkit` + +This `groupBy` function operates slowly due to handling `null` or `undefined`, object support, complex type processing, etc. + +Instead, use the faster and more modern [`groupBy`](../../../reference/array/groupBy.md) from `es-toolkit`. + +::: + +Groups elements of an array or object based on a given condition. + +```typescript +const grouped = groupBy(collection, iteratee); +``` + +## Usage + +### `groupBy(collection, iteratee)` + +Groups each element of an array or object based on a given condition function and returns an object with groups. The condition can be provided in various forms such as a function, property name, partial object, etc. + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +// Group by function +const array = [6.1, 4.2, 6.3]; +const result = groupBy(array, Math.floor); +// result is { '4': [4.2], '6': [6.1, 6.3] } + +// Group by property name +const users = [ + { name: 'john', age: 30 }, + { name: 'jane', age: 25 }, + { name: 'bob', age: 30 }, +]; +const byAge = groupBy(users, 'age'); +// byAge is { '25': [{ name: 'jane', age: 25 }], '30': [{ name: 'john', age: 30 }, { name: 'bob', age: 30 }] } + +// Group from object +const obj = { a: 6.1, b: 4.2, c: 6.3 }; +const groupedObj = groupBy(obj, Math.floor); +// groupedObj is { '4': [4.2], '6': [6.1, 6.3] } +``` + +`null` or `undefined` are treated as empty objects. + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +groupBy(null, x => x); // {} +groupBy(undefined, x => x); // {} +``` + +You can also group by partial object or property-value pair. + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +const products = [ + { category: 'fruit', name: 'apple' }, + { category: 'fruit', name: 'banana' }, + { category: 'vegetable', name: 'carrot' }, +]; + +// Group by partial object +const byCategory = groupBy(products, { category: 'fruit' }); +// Group by property-value pair +const byName = groupBy(products, ['name', 'apple']); +``` + +#### Parameters + +- `collection` (`ArrayLike | Record | null | undefined`): The array or object to group. +- `iteratee` (`Function | PropertyKey | Array | Object`, optional): The condition to group by. Can be a function, property name, property-value pair, or partial object. Default is the `identity` function. + +#### Returns + +(`Record`): Returns an object where each key is the condition value and the value is an array of elements belonging to that group. diff --git a/docs/compat/reference/array/head.md b/docs/compat/reference/array/head.md new file mode 100644 index 000000000..0322fbd3e --- /dev/null +++ b/docs/compat/reference/array/head.md @@ -0,0 +1,61 @@ +# head (Lodash Compatibility) + +::: warning Use [`head`](../../../reference/array/head.md) from `es-toolkit` + +This `head` function operates slowly due to `ArrayLike` object processing and array conversion process. + +Instead, use the faster and more modern [`head`](../../../reference/array/head.md) from `es-toolkit`. + +::: + +Returns the first element of an array. + +```typescript +const firstElement = head(array); +``` + +## Usage + +### `head(array)` + +Returns the first element of an array or array-like object. Returns `undefined` if the array is empty or invalid. + +```typescript +import { head } from 'es-toolkit/compat'; + +// First element of number array +const numbers = [1, 2, 3, 4]; +const first = head(numbers); +// first is 1 + +// First element of string array +const strings = ['a', 'b', 'c']; +const firstChar = head(strings); +// firstChar is 'a' + +// Array-like object +const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; +const firstItem = head(arrayLike); +// firstItem is 'x' +``` + +Empty arrays or invalid inputs return `undefined`. + +```typescript +import { head } from 'es-toolkit/compat'; + +const emptyArray: number[] = []; +const noElement = head(emptyArray); +// noElement is undefined + +head(null); // undefined +head(undefined); // undefined +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array or array-like object to get the first element from. + +#### Returns + +(`T | undefined`): Returns the first element of the array, or `undefined` if the array is empty or invalid. diff --git a/docs/reference/compat/array/includes.md b/docs/compat/reference/array/includes.md similarity index 100% rename from docs/reference/compat/array/includes.md rename to docs/compat/reference/array/includes.md diff --git a/docs/reference/compat/array/indexOf.md b/docs/compat/reference/array/indexOf.md similarity index 100% rename from docs/reference/compat/array/indexOf.md rename to docs/compat/reference/array/indexOf.md diff --git a/docs/compat/reference/array/initial.md b/docs/compat/reference/array/initial.md new file mode 100644 index 000000000..e8bddf95e --- /dev/null +++ b/docs/compat/reference/array/initial.md @@ -0,0 +1,65 @@ +# initial (Lodash Compatibility) + +::: warning Use [`initial`](../../../reference/array/initial.md) from `es-toolkit` + +This `initial` function operates slowly due to `ArrayLike` object processing and array conversion process. + +Instead, use the faster and more modern [`initial`](../../../reference/array/initial.md) from `es-toolkit`. + +::: + +Returns a new array with all elements except the last one from an array. + +```typescript +const result = initial(array); +``` + +## Usage + +### `initial(array)` + +Returns a new array containing all elements except the last one from an array or array-like object. Returns an empty array if the array is empty or has only one element. + +```typescript +import { initial } from 'es-toolkit/compat'; + +// Exclude last element from number array +const numbers = [1, 2, 3, 4]; +const result = initial(numbers); +// result is [1, 2, 3] + +// Exclude last element from string array +const strings = ['a', 'b', 'c', 'd']; +const withoutLast = initial(strings); +// withoutLast is ['a', 'b', 'c'] + +// Array-like object +const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; +const items = initial(arrayLike); +// items is ['x', 'y'] +``` + +Empty arrays or invalid inputs return an empty array. + +```typescript +import { initial } from 'es-toolkit/compat'; + +const emptyArray: number[] = []; +const result = initial(emptyArray); +// result is [] + +const singleItem = [42]; +const onlyOne = initial(singleItem); +// onlyOne is [] + +initial(null); // [] +initial(undefined); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array or array-like object to exclude the last element from. + +#### Returns + +(`T[]`): Returns a new array with the last element excluded. diff --git a/docs/compat/reference/array/intersection.md b/docs/compat/reference/array/intersection.md new file mode 100644 index 000000000..b4161cc83 --- /dev/null +++ b/docs/compat/reference/array/intersection.md @@ -0,0 +1,80 @@ +# intersection (Lodash Compatibility) + +::: warning Use [`intersection`](../../../reference/array/intersection.md) from `es-toolkit` + +This `intersection` function operates slowly due to handling `null` or `undefined`, multiple array support, and duplicate removal process. + +Instead, use the faster and more modern [`intersection`](../../../reference/array/intersection.md) from `es-toolkit`. + +::: + +Finds the intersection of multiple arrays. + +```typescript +const result = intersection(...arrays); +``` + +## Usage + +### `intersection(...arrays)` + +Finds elements that exist in all arrays and returns them as a new array. The result is deduplicated and maintains the order of the first array. + +```typescript +import { intersection } from 'es-toolkit/compat'; + +// Intersection of two arrays +const array1 = [1, 2, 3, 4]; +const array2 = [2, 3, 5, 6]; +const result = intersection(array1, array2); +// result is [2, 3] + +// Intersection of three arrays +const array3 = [3, 4, 7, 8]; +const multiResult = intersection(array1, array2, array3); +// multiResult is [3] + +// String arrays +const strings1 = ['a', 'b', 'c']; +const strings2 = ['b', 'c', 'd']; +const stringResult = intersection(strings1, strings2); +// stringResult is ['b', 'c'] + +// Array-like objects +const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; +const arrayLike2 = { 0: 2, 1: 3, 2: 4, length: 3 }; +const likeResult = intersection(arrayLike1, arrayLike2); +// likeResult is [2, 3] +``` + +`null` or `undefined` arrays are treated as empty arrays. + +```typescript +import { intersection } from 'es-toolkit/compat'; + +const array1 = [1, 2, 3]; +const result1 = intersection(array1, null); +// result1 is [] + +const result2 = intersection(null, undefined); +// result2 is [] +``` + +Duplicate elements are removed from the result. + +```typescript +import { intersection } from 'es-toolkit/compat'; + +const array1 = [1, 1, 2, 3]; +const array2 = [1, 2, 2, 4]; +const result = intersection(array1, array2); +// result is [1, 2] (duplicates removed) +``` + +#### Parameters + +- `...arrays` (`Array | null | undefined>`): The arrays to find the intersection of. Array-like objects, null, or undefined are also allowed. + +#### Returns + +(`T[]`): Returns a new array of elements that exist in all arrays. Duplicates are removed and the order follows the first array. diff --git a/docs/compat/reference/array/intersectionBy.md b/docs/compat/reference/array/intersectionBy.md new file mode 100644 index 000000000..a78a5ebe6 --- /dev/null +++ b/docs/compat/reference/array/intersectionBy.md @@ -0,0 +1,93 @@ +# intersectionBy (Lodash Compatibility) + +::: warning Use [`intersectionBy`](../../../reference/array/intersectionBy.md) from `es-toolkit` + +This `intersectionBy` function operates slowly due to complex condition processing, multiple array support, property path parsing, etc. + +Instead, use the faster and more modern [`intersectionBy`](../../../reference/array/intersectionBy.md) from `es-toolkit`. + +::: + +Finds the intersection of multiple arrays using a given condition function. + +```typescript +const result = intersectionBy(...arrays, iteratee); +``` + +## Usage + +### `intersectionBy(...arrays, iteratee)` + +Finds the intersection of multiple arrays based on values transformed by a given condition function. The condition can be provided in various forms such as a function, property name, partial object, etc. + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +// Intersection by function +const array1 = [2.1, 1.2]; +const array2 = [2.3, 3.4]; +const result = intersectionBy(array1, array2, Math.floor); +// result is [2.1] (2 is common based on Math.floor) + +// Intersection by property +const users1 = [ + { id: 1, name: 'john' }, + { id: 2, name: 'jane' }, +]; +const users2 = [ + { id: 2, name: 'jane' }, + { id: 3, name: 'bob' }, +]; +const byId = intersectionBy(users1, users2, 'id'); +// byId is [{ id: 2, name: 'jane' }] + +// Intersection of three arrays +const array3 = [2.5, 4.1]; +const multiResult = intersectionBy(array1, array2, array3, Math.floor); +// multiResult is [2.1] + +// Array-like objects +const arrayLike1 = { 0: { x: 1 }, 1: { x: 2 }, length: 2 }; +const arrayLike2 = { 0: { x: 2 }, 1: { x: 3 }, length: 2 }; +const byProperty = intersectionBy(arrayLike1, arrayLike2, 'x'); +// byProperty is [{ x: 2 }] +``` + +`null` or `undefined` arrays are treated as empty arrays. + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +const array1 = [{ x: 1 }, { x: 2 }]; +const result = intersectionBy(array1, null, 'x'); +// result is [] +``` + +You can also specify conditions with partial objects or property-value pairs. + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +const products1 = [ + { category: 'fruit', name: 'apple' }, + { category: 'vegetable', name: 'carrot' }, +]; +const products2 = [ + { category: 'fruit', name: 'banana' }, + { category: 'meat', name: 'beef' }, +]; + +// Specify condition with partial object +const byCategory = intersectionBy(products1, products2, { category: 'fruit' }); +// Specify condition with property-value pair +const byCategoryPair = intersectionBy(products1, products2, ['category', 'fruit']); +``` + +#### Parameters + +- `...arrays` (`Array | null | undefined>`): The arrays to find the intersection of. +- `iteratee` (`Function | PropertyKey | Array | Object`): The condition to transform each element. Can be a function, property name, property-value pair, or partial object. + +#### Returns + +(`T[]`): Returns a new array of elements that exist in all arrays based on the transformed values. diff --git a/docs/compat/reference/array/intersectionWith.md b/docs/compat/reference/array/intersectionWith.md new file mode 100644 index 000000000..4b6d6c66b --- /dev/null +++ b/docs/compat/reference/array/intersectionWith.md @@ -0,0 +1,64 @@ +# intersectionWith (Lodash Compatibility) + +::: warning Use [`intersectionWith`](../../../reference/array/intersectionWith.md) from `es-toolkit` + +This `intersectionWith` function operates slowly due to handling `null` or `undefined`, support for various overloads, etc. + +Instead, use the faster and more modern [`intersectionWith`](../../../reference/array/intersectionWith.md) from `es-toolkit`. + +::: + +Creates an array of common elements found in all arrays using a custom comparison function. + +```typescript +const result = intersectionWith(array, ...otherArrays, comparator); +``` + +## Usage + +### `intersectionWith(array, ...otherArrays, comparator)` + +Finds the intersection of the first array with the rest using a custom comparison function. The comparison function determines if elements are equal, and only elements found in all arrays are returned. + +```typescript +import { intersectionWith } from 'es-toolkit/compat'; + +const objects = [ + { id: 1, name: 'john' }, + { id: 2, name: 'jane' }, +]; +const others = [ + { id: 1, name: 'john' }, + { id: 3, name: 'joe' }, +]; + +intersectionWith(objects, others, (a, b) => a.id === b.id); +// => [{ id: 1, name: 'john' }] + +// You can compare with multiple arrays +const array1 = [{ x: 1 }, { x: 2 }]; +const array2 = [{ x: 1 }, { x: 3 }]; +const array3 = [{ x: 1 }, { x: 4 }]; + +intersectionWith(array1, array2, array3, (a, b) => a.x === b.x); +// => [{ x: 1 }] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { intersectionWith } from 'es-toolkit/compat'; + +intersectionWith(null, [1, 2], (a, b) => a === b); // [] +intersectionWith([1, 2], undefined, (a, b) => a === b); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The first array to compare. +- `...otherArrays` (`Array | ((a: T, b: T | U) => boolean)>`): The other arrays to compare and the comparison function as the last element. +- `comparator` (`(a: T, b: T | U) => boolean`): The function to determine if two elements are equal. + +#### Returns + +(`T[]`): Returns a new array of elements commonly found in all arrays. diff --git a/docs/reference/compat/array/invokeMap.md b/docs/compat/reference/array/invokeMap.md similarity index 100% rename from docs/reference/compat/array/invokeMap.md rename to docs/compat/reference/array/invokeMap.md diff --git a/docs/reference/compat/array/join.md b/docs/compat/reference/array/join.md similarity index 100% rename from docs/reference/compat/array/join.md rename to docs/compat/reference/array/join.md diff --git a/docs/compat/reference/array/keyBy.md b/docs/compat/reference/array/keyBy.md new file mode 100644 index 000000000..8a4bbb35f --- /dev/null +++ b/docs/compat/reference/array/keyBy.md @@ -0,0 +1,64 @@ +# keyBy (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [keyBy](../../../reference/array/keyBy.md) + +This `keyBy` function is slow due to handling `null` or `undefined`, various parameter types, etc. + +Use the faster and more modern `es-toolkit`'s [keyBy](../../../reference/array/keyBy.md) instead. + +::: + +Organizes collection elements into an object based on the specified key. + +```typescript +const result = keyBy(collection, iteratee); +``` + +## Usage + +### `keyBy(collection, iteratee)` + +Organizes each element in an array or object into an object using the specified key generation function or property name. If multiple elements have the same key, the last element is used. + +```typescript +import { keyBy } from 'es-toolkit/compat'; + +// Generate keys by property name +const array = [ + { dir: 'left', code: 97 }, + { dir: 'right', code: 100 }, +]; + +keyBy(array, 'dir'); +// => { left: { dir: 'left', code: 97 }, right: { dir: 'right', code: 100 } } + +// Generate keys using a function +keyBy(array, o => String.fromCharCode(o.code)); +// => { a: { dir: 'left', code: 97 }, d: { dir: 'right', code: 100 } } + +// Can also be used with objects +const obj = { + a: { id: 1, name: 'john' }, + b: { id: 2, name: 'jane' }, +}; +keyBy(obj, 'name'); +// => { john: { id: 1, name: 'john' }, jane: { id: 2, name: 'jane' } } +``` + +`null` or `undefined` are treated as empty objects. + +```typescript +import { keyBy } from 'es-toolkit/compat'; + +keyBy(null, 'id'); // {} +keyBy(undefined, 'id'); // {} +``` + +#### Parameters + +- `collection` (`ArrayLike | null | undefined`): The array or object to organize by key. +- `iteratee` (`ValueIterateeCustom`, optional): The function or property name to generate keys. If omitted, the element itself is used as the key. + +#### Returns + +(`Record`): Returns a new object where each element is mapped to the generated key. diff --git a/docs/compat/reference/array/last.md b/docs/compat/reference/array/last.md new file mode 100644 index 000000000..e9aa5f230 --- /dev/null +++ b/docs/compat/reference/array/last.md @@ -0,0 +1,79 @@ +# last (Lodash compatibility) + +::: warning Use `es-toolkit`'s [last](../../../reference/array/last.md) + +This `last` function behaves complexly due to handling `null` or `undefined`. + +Instead, use the faster and more modern `es-toolkit`'s [last](../../../reference/array/last.md). + +::: + +Returns the last element of an array. + +```typescript +const lastElement = last(array); +``` + +## Usage + +### `last(array)` + +Use `last` when you want to get the last element of an array. Returns `undefined` if the array is empty. + +```typescript +import { last } from 'es-toolkit/compat'; + +// Last element of a number array +last([1, 2, 3, 4, 5]); +// Returns: 5 + +// Last element of a string array +last(['a', 'b', 'c']); +// Returns: 'c' + +// Last element of an object array +const users = [{ name: 'Alice' }, { name: 'Bob' }]; +last(users); +// Returns: { name: 'Bob' } +``` + +Empty arrays or `null`, `undefined` return `undefined`. + +```typescript +import { last } from 'es-toolkit/compat'; + +// Empty array +last([]); +// Returns: undefined + +// null array +last(null); +// Returns: undefined + +// undefined array +last(undefined); +// Returns: undefined +``` + +Array-like objects are also supported. + +```typescript +import { last } from 'es-toolkit/compat'; + +// Array-like object +const arrayLike = { 0: 'first', 1: 'second', length: 2 }; +last(arrayLike); +// Returns: 'second' + +// Strings are also array-like objects +last('hello'); +// Returns: 'o' +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to get the last element from. + +#### Returns + +(`T | undefined`): Returns the last element of the array, or `undefined` if the array is empty, `null`, or `undefined`. diff --git a/docs/reference/compat/array/lastIndexOf.md b/docs/compat/reference/array/lastIndexOf.md similarity index 100% rename from docs/reference/compat/array/lastIndexOf.md rename to docs/compat/reference/array/lastIndexOf.md diff --git a/docs/reference/compat/array/map.md b/docs/compat/reference/array/map.md similarity index 100% rename from docs/reference/compat/array/map.md rename to docs/compat/reference/array/map.md diff --git a/docs/reference/compat/array/nth.md b/docs/compat/reference/array/nth.md similarity index 100% rename from docs/reference/compat/array/nth.md rename to docs/compat/reference/array/nth.md diff --git a/docs/compat/reference/array/orderBy.md b/docs/compat/reference/array/orderBy.md new file mode 100644 index 000000000..21e48a7c3 --- /dev/null +++ b/docs/compat/reference/array/orderBy.md @@ -0,0 +1,82 @@ +# orderBy (Lodash Compatibility) + +::: warning Use [orderBy](../../../reference/array/orderBy.md) from `es-toolkit` instead + +This `orderBy` function operates slowly due to handling `null` or `undefined`, complex path navigation, and various sorting criteria. + +Use the faster and more modern [orderBy](../../../reference/array/orderBy.md) from `es-toolkit` instead. + +::: + +Sorts the elements of a collection by multiple criteria. + +```typescript +const result = orderBy(collection, criteria, orders); +``` + +## Usage + +### `orderBy(collection, criteria, orders)` + +Sorts the elements of an array or object according to specified criteria and sort orders. You can use multiple criteria, and specify ascending (`'asc'`) or descending (`'desc'`) order for each criterion. + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +const users = [ + { name: 'fred', age: 48 }, + { name: 'barney', age: 34 }, + { name: 'fred', age: 40 }, + { name: 'barney', age: 36 }, +]; + +// Sort by name ascending, age descending +orderBy(users, ['name', 'age'], ['asc', 'desc']); +// => [ +// { name: 'barney', age: 36 }, +// { name: 'barney', age: 34 }, +// { name: 'fred', age: 48 }, +// { name: 'fred', age: 40 } +// ] + +// Specify sort criteria with functions +orderBy(users, [user => user.name, user => user.age], ['asc', 'desc']); +// => Same result as above + +// Sort by single criterion +orderBy(users, 'age', 'desc'); +// => [{ name: 'fred', age: 48 }, { name: 'fred', age: 40 }, ...] +``` + +For objects, sorts the values. + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +const obj = { + a: { name: 'fred', age: 48 }, + b: { name: 'barney', age: 34 }, +}; + +orderBy(obj, 'age', 'desc'); +// => [{ name: 'fred', age: 48 }, { name: 'barney', age: 34 }] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +orderBy(null, 'name'); // [] +orderBy(undefined, 'age'); // [] +``` + +#### Parameters + +- `collection` (`ArrayLike | object | null | undefined`): The array or object to sort. +- `criteria` (`Criterion | Array>`, optional): The sort criteria. Can use property names, property paths, functions, etc. Defaults to `[null]`. +- `orders` (`unknown | unknown[]`, optional): The sort order for each criterion. Can use `'asc'` (ascending), `'desc'` (descending), `true` (ascending), `false` (descending). Defaults to `[]`. + +#### Returns + +(`T[]`): Returns a new sorted array. diff --git a/docs/compat/reference/array/partition.md b/docs/compat/reference/array/partition.md new file mode 100644 index 000000000..220532398 --- /dev/null +++ b/docs/compat/reference/array/partition.md @@ -0,0 +1,89 @@ +# partition (Lodash Compatibility) + +::: warning Use [partition](../../../reference/array/partition.md) from `es-toolkit` instead + +This `partition` function operates slowly due to handling `null` or `undefined` and various predicate types. + +Use the faster and more modern [partition](../../../reference/array/partition.md) from `es-toolkit` instead. + +::: + +Splits the elements of a collection into two groups based on a condition. + +```typescript +const [truthy, falsy] = partition(collection, predicate); +``` + +## Usage + +### `partition(collection, predicate)` + +Splits the elements of an array or object into two groups based on a given predicate function. The first group contains elements where the predicate is true, and the second group contains elements where the predicate is false. + +```typescript +import { partition } from 'es-toolkit/compat'; + +// Split number array into even and odd +partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); +// => [[2, 4, 6], [1, 3, 5]] + +// Specify condition with property name +const users = [ + { name: 'john', active: true }, + { name: 'jane', active: false }, + { name: 'bob', active: true }, +]; + +partition(users, 'active'); +// => [ +// [{ name: 'john', active: true }, { name: 'bob', active: true }], +// [{ name: 'jane', active: false }] +// ] + +// Filter with object condition +partition(users, { active: true }); +// => [ +// [{ name: 'john', active: true }, { name: 'bob', active: true }], +// [{ name: 'jane', active: false }] +// ] + +// Filter with array condition +partition(users, ['name', 'john']); +// => [ +// [{ name: 'john', active: true }], +// [{ name: 'jane', active: false }, { name: 'bob', active: true }] +// ] +``` + +For objects, partitions the values. + +```typescript +import { partition } from 'es-toolkit/compat'; + +const obj = { + a: { score: 90 }, + b: { score: 40 }, + c: { score: 80 }, +}; + +partition(obj, item => item.score >= 80); +// => [[{ score: 90 }, { score: 80 }], [{ score: 40 }]] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { partition } from 'es-toolkit/compat'; + +partition(null, x => x > 0); // [[], []] +partition(undefined, 'active'); // [[], []] +``` + +#### Parameters + +- `collection` (`ArrayLike | T | null | undefined`): The array or object to partition. +- `predicate` (`((value: T) => unknown) | Partial | [PropertyKey, any] | PropertyKey`, optional): The condition to test each element. Can be a function, partial object, property-value array, or property name. Defaults to `identity`. + +#### Returns + +(`[T[], T[]]`): Returns an array containing an array of elements that satisfy the condition and an array of elements that don't. diff --git a/docs/compat/reference/array/pull.md b/docs/compat/reference/array/pull.md new file mode 100644 index 000000000..991d66b60 --- /dev/null +++ b/docs/compat/reference/array/pull.md @@ -0,0 +1,44 @@ +# pull (Lodash compatibility) + +::: warning Use [pull](../../../reference/array/pull.md) from `es-toolkit` + +This `pull` function is for Lodash compatibility and operates slower due to more complex type handling and overloading. + +Instead, use the faster and more modern [pull](../../../reference/array/pull.md) from `es-toolkit`. + +::: + +Removes all specified values from the array. + +```typescript +const result = pull(array, ...valuesToRemove); +``` + +## Usage + +### `pull(array, ...valuesToRemove)` + +Removes all specified values from the array and modifies the original array. It directly modifies the original array without copying, which can save memory. + +```typescript +import { pull } from 'es-toolkit/compat'; + +// Remove specific values from number array +const numbers = [1, 2, 3, 2, 4, 2, 5]; +pull(numbers, 2, 3); +console.log(numbers); // [1, 4, 5] + +// Remove specific values from string array +const fruits = ['apple', 'banana', 'apple', 'cherry']; +pull(fruits, 'apple'); +console.log(fruits); // ['banana', 'cherry'] +``` + +#### Parameters + +- `array` (`T[]`): The array to modify. +- `...valuesToRemove` (`T[]`): The values to remove from the array. + +#### Returns + +(`T[]`): Returns the modified original array. diff --git a/docs/reference/compat/array/pullAll.md b/docs/compat/reference/array/pullAll.md similarity index 100% rename from docs/reference/compat/array/pullAll.md rename to docs/compat/reference/array/pullAll.md diff --git a/docs/reference/compat/array/pullAllBy.md b/docs/compat/reference/array/pullAllBy.md similarity index 100% rename from docs/reference/compat/array/pullAllBy.md rename to docs/compat/reference/array/pullAllBy.md diff --git a/docs/reference/compat/array/pullAllWith.md b/docs/compat/reference/array/pullAllWith.md similarity index 100% rename from docs/reference/compat/array/pullAllWith.md rename to docs/compat/reference/array/pullAllWith.md diff --git a/docs/compat/reference/array/pullAt.md b/docs/compat/reference/array/pullAt.md new file mode 100644 index 000000000..6b12707a8 --- /dev/null +++ b/docs/compat/reference/array/pullAt.md @@ -0,0 +1,57 @@ +# pullAt (Lodash Compatibility) + +::: warning Use [pullAt](../../../reference/array/pullAt.md) from `es-toolkit` instead + +This `pullAt` function operates slowly due to complex type handling and overloading. + +Use the faster and more modern [pullAt](../../../reference/array/pullAt.md) from `es-toolkit` instead. + +::: + +Removes elements at specified indexes from an array and returns the removed elements. + +```typescript +const removed = pullAt(array, ...indexes); +``` + +## Usage + +### `pullAt(array, ...indexes)` + +Removes elements at specified indexes from an array and returns an array of the removed elements. The original array is modified. + +```typescript +import { pullAt } from 'es-toolkit/compat'; + +// Remove by individual indexes +const array = [1, 2, 3, 4, 5]; +const removed = pullAt(array, 1, 3); +console.log(array); // [1, 3, 5] +console.log(removed); // [2, 4] + +// Remove by array of indexes +const colors = ['red', 'green', 'blue', 'yellow']; +const removedColors = pullAt(colors, [0, 2]); +console.log(colors); // ['green', 'yellow'] +console.log(removedColors); // ['red', 'blue'] +``` + +Non-existent indexes are treated as `undefined`. + +```typescript +import { pullAt } from 'es-toolkit/compat'; + +const numbers = [10, 20, 30]; +const removed = pullAt(numbers, 1, 5); +console.log(numbers); // [10, 30] +console.log(removed); // [20, undefined] +``` + +#### Parameters + +- `array` (`ArrayLike`): The array to modify. +- `...indexes` (`Array`): The indexes of elements to remove. Can pass individual numbers or arrays of numbers. + +#### Returns + +(`ArrayLike`): Returns an array of removed elements. diff --git a/docs/reference/compat/array/reduce.md b/docs/compat/reference/array/reduce.md similarity index 100% rename from docs/reference/compat/array/reduce.md rename to docs/compat/reference/array/reduce.md diff --git a/docs/reference/compat/array/reduceRight.md b/docs/compat/reference/array/reduceRight.md similarity index 100% rename from docs/reference/compat/array/reduceRight.md rename to docs/compat/reference/array/reduceRight.md diff --git a/docs/reference/compat/array/reject.md b/docs/compat/reference/array/reject.md similarity index 100% rename from docs/reference/compat/array/reject.md rename to docs/compat/reference/array/reject.md diff --git a/docs/compat/reference/array/remove.md b/docs/compat/reference/array/remove.md new file mode 100644 index 000000000..b46813a18 --- /dev/null +++ b/docs/compat/reference/array/remove.md @@ -0,0 +1,70 @@ +# remove (Lodash Compatibility) + +::: warning Use `remove` from `es-toolkit` + +This `remove` function is implemented in a complex way to support various forms of predicates for Lodash compatibility. The `remove` function in the main library only supports simple function predicates, so it operates faster. + +Instead, use the faster and more modern [remove](../../../reference/array/remove.md) from `es-toolkit`. + +::: + +Removes elements that match a condition from an array and returns the removed elements. + +```typescript +const removedElements = remove(array, predicate); +``` + +## Usage + +### `remove(array, predicate)` + +Iterates through the array and removes elements that match the given condition from the original array, returning the removed elements as a new array. Note that the original array is directly modified. + +```typescript +import { remove } from 'es-toolkit/compat'; + +// Remove with function condition +const numbers = [1, 2, 3, 4, 5]; +const evens = remove(numbers, n => n % 2 === 0); +console.log(numbers); // => [1, 3, 5] +console.log(evens); // => [2, 4] + +// Remove with partial object matching +const objects = [{ a: 1 }, { a: 2 }, { a: 3 }]; +const removed = remove(objects, { a: 1 }); +console.log(objects); // => [{ a: 2 }, { a: 3 }] +console.log(removed); // => [{ a: 1 }] + +// Remove with property-value pair +const items = [{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }]; +const cherries = remove(items, ['name', 'cherry']); +console.log(items); // => [{ name: 'apple' }, { name: 'banana' }] +console.log(cherries); // => [{ name: 'cherry' }] +``` + +This function supports various forms of predicates. + +```typescript +import { remove } from 'es-toolkit/compat'; + +// Function condition +remove(users, user => user.active === false); + +// Partial object matching +remove(users, { status: 'inactive' }); + +// Property-value array +remove(users, ['type', 'guest']); + +// Check truthy value by property name +remove(users, 'isDeleted'); +``` + +#### Parameters + +- `array` (`ArrayLike`): The array to modify. +- `predicate` (`((value: T, index: number, array: ArrayLike) => boolean) | Partial | [keyof T, unknown] | keyof T`, optional): The condition to execute for each element. Default is `identity`. + +#### Returns + +(`T[]`): Returns a new array consisting of elements that were removed because they matched the condition. diff --git a/docs/reference/compat/array/reverse.md b/docs/compat/reference/array/reverse.md similarity index 100% rename from docs/reference/compat/array/reverse.md rename to docs/compat/reference/array/reverse.md diff --git a/docs/compat/reference/array/sample.md b/docs/compat/reference/array/sample.md new file mode 100644 index 000000000..3f776634b --- /dev/null +++ b/docs/compat/reference/array/sample.md @@ -0,0 +1,54 @@ +# sample (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [sample](../../../reference/array/sample.md) + +This `sample` function operates slowly due to `null` or `undefined` handling, object value processing, etc. + +Instead, use the faster and more modern `es-toolkit`'s [sample](../../../reference/array/sample.md). + +::: + +Gets a random element from an array or object. + +```typescript +const randomItem = sample(collection); +``` + +## Usage + +### `sample(collection)` + +Use `sample` to select a random element from an array or object. For arrays, it returns a random element, and for objects, it returns a random value. + +```typescript +import { sample } from 'es-toolkit/compat'; + +// Get a random element from an array +sample([1, 2, 3, 4, 5]); +// Returns a random number between 1 and 5 + +// Get a random value from an object +sample({ a: 1, b: 2, c: 3 }); +// Returns a random value among 1, 2, 3 + +// Handles strings as well +sample('hello'); +// Returns a random character among 'h', 'e', 'l', 'l', 'o' +``` + +`null` or `undefined` returns `undefined`. + +```typescript +import { sample } from 'es-toolkit/compat'; + +sample(null); // undefined +sample(undefined); // undefined +``` + +#### Parameters + +- `collection` (`ArrayLike | Record | null | undefined`): The array or object to sample from. + +#### Returns + +(`T | string | undefined`): Returns a randomly selected element from the array or object. Returns `undefined` if the collection is empty or `null`, `undefined`. diff --git a/docs/compat/reference/array/sampleSize.md b/docs/compat/reference/array/sampleSize.md new file mode 100644 index 000000000..fe27d3bf7 --- /dev/null +++ b/docs/compat/reference/array/sampleSize.md @@ -0,0 +1,54 @@ +# sampleSize (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [sampleSize](../../../reference/array/sampleSize.md) + +This `sampleSize` function operates slowly due to `null` or `undefined` handling, object support, default value processing, etc. + +Instead, use the faster and more modern `es-toolkit`'s [sampleSize](../../../reference/array/sampleSize.md). + +::: + +Randomly selects a specified number of elements from an array or object. + +```typescript +const sampled = sampleSize(collection, size); +``` + +## Usage + +### `sampleSize(collection, size?)` + +Use `sampleSize` to randomly select elements from an array or object. It uses Floyd's algorithm to sample efficiently without duplicates. + +```typescript +import { sampleSize } from 'es-toolkit/compat'; + +// Randomly select 3 elements from an array. +sampleSize([1, 2, 3, 4, 5], 3); +// Returns: [2, 4, 5] (actual results may vary) + +// Randomly select 2 values from an object. +sampleSize({ a: 1, b: 2, c: 3, d: 4 }, 2); +// Returns: [2, 4] (actual results may vary) +``` + +`null` or `undefined` is handled as an empty array. + +```typescript +import { sampleSize } from 'es-toolkit/compat'; + +sampleSize(null, 2); +// Returns: [] + +sampleSize(undefined, 2); +// Returns: [] +``` + +#### Parameters + +- `collection` (`Record | Record | T | null | undefined`): The array or object to sample from. +- `size` (`number`, optional): The number of elements to select. The default is `1`. + +#### Returns + +(`T[]`): Returns a new array composed of randomly selected elements. diff --git a/docs/compat/reference/array/shuffle.md b/docs/compat/reference/array/shuffle.md new file mode 100644 index 000000000..2f10307f7 --- /dev/null +++ b/docs/compat/reference/array/shuffle.md @@ -0,0 +1,60 @@ +# shuffle (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `shuffle` + +This `shuffle` function includes additional processing for Lodash compatibility and operates slowly. + +Instead, use the faster and more modern `es-toolkit`'s [shuffle](../../../reference/array/shuffle.md). + +::: + +Shuffles the elements of an array or object randomly and returns a new array. + +```typescript +const result = shuffle(collection); +``` + +## Usage + +### `shuffle(collection)` + +Uses the Fisher-Yates algorithm to randomly shuffle the elements of an array or object and returns a new array. The original is not modified. + +```typescript +import { shuffle } from 'es-toolkit/compat'; + +// Shuffle a number array +const numbers = [1, 2, 3, 4, 5]; +const shuffled1 = shuffle(numbers); +// Returns: for example [3, 1, 5, 2, 4] (different order each time) + +// Shuffle a string array +const fruits = ['apple', 'banana', 'cherry', 'date']; +const shuffled2 = shuffle(fruits); +// Returns: for example ['cherry', 'apple', 'date', 'banana'] + +// Shuffle object values +const obj = { a: 1, b: 2, c: 3, d: 4 }; +const shuffled3 = shuffle(obj); +// Returns: for example [3, 1, 4, 2] (object values are randomly shuffled) +``` + +`null` or `undefined` is handled as an empty array. + +```typescript +import { shuffle } from 'es-toolkit/compat'; + +shuffle(null); +// Returns: [] + +shuffle(undefined); +// Returns: [] +``` + +#### Parameters + +- `collection` (`ArrayLike | T | null | undefined`): The array or object to shuffle. + +#### Returns + +(`T[]`): Returns a new array with elements randomly shuffled. diff --git a/docs/reference/compat/array/size.md b/docs/compat/reference/array/size.md similarity index 100% rename from docs/reference/compat/array/size.md rename to docs/compat/reference/array/size.md diff --git a/docs/reference/compat/array/slice.md b/docs/compat/reference/array/slice.md similarity index 100% rename from docs/reference/compat/array/slice.md rename to docs/compat/reference/array/slice.md diff --git a/docs/reference/compat/array/some.md b/docs/compat/reference/array/some.md similarity index 100% rename from docs/reference/compat/array/some.md rename to docs/compat/reference/array/some.md diff --git a/docs/reference/compat/array/sortBy.md b/docs/compat/reference/array/sortBy.md similarity index 100% rename from docs/reference/compat/array/sortBy.md rename to docs/compat/reference/array/sortBy.md diff --git a/docs/reference/compat/array/sortedIndex.md b/docs/compat/reference/array/sortedIndex.md similarity index 100% rename from docs/reference/compat/array/sortedIndex.md rename to docs/compat/reference/array/sortedIndex.md diff --git a/docs/reference/compat/array/sortedIndexBy.md b/docs/compat/reference/array/sortedIndexBy.md similarity index 100% rename from docs/reference/compat/array/sortedIndexBy.md rename to docs/compat/reference/array/sortedIndexBy.md diff --git a/docs/reference/compat/array/sortedIndexOf.md b/docs/compat/reference/array/sortedIndexOf.md similarity index 100% rename from docs/reference/compat/array/sortedIndexOf.md rename to docs/compat/reference/array/sortedIndexOf.md diff --git a/docs/reference/compat/array/sortedLastIndex.md b/docs/compat/reference/array/sortedLastIndex.md similarity index 100% rename from docs/reference/compat/array/sortedLastIndex.md rename to docs/compat/reference/array/sortedLastIndex.md diff --git a/docs/reference/compat/array/sortedLastIndexBy.md b/docs/compat/reference/array/sortedLastIndexBy.md similarity index 100% rename from docs/reference/compat/array/sortedLastIndexBy.md rename to docs/compat/reference/array/sortedLastIndexBy.md diff --git a/docs/reference/compat/array/sortedLastIndexOf.md b/docs/compat/reference/array/sortedLastIndexOf.md similarity index 100% rename from docs/reference/compat/array/sortedLastIndexOf.md rename to docs/compat/reference/array/sortedLastIndexOf.md diff --git a/docs/compat/reference/array/tail.md b/docs/compat/reference/array/tail.md new file mode 100644 index 000000000..92eebf26b --- /dev/null +++ b/docs/compat/reference/array/tail.md @@ -0,0 +1,58 @@ +# tail (Lodash compatibility) + +::: warning Please use [tail](../../../reference/array/tail.md) from `es-toolkit` + +This `tail` function operates slowly due to handling `null` or `undefined`. + +Please use the faster and modern [tail](../../../reference/array/tail.md) from `es-toolkit` instead. + +::: + +Returns all elements of an array except the first one. + +```typescript +const result = tail(array); +``` + +## Usage + +### `tail(array)` + +Use `tail` when you want to create a new array containing all elements except the first one from the input array. If the input array is empty or has only one element, it returns an empty array. + +```typescript +import { tail } from 'es-toolkit/compat'; + +// Remove the first element from a number array. +tail([1, 2, 3]); +// Returns: [2, 3] + +// Remove the first element from a string array. +tail(['a', 'b', 'c']); +// Returns: ['b', 'c'] + +// Array with only one element. +tail([1]); +// Returns: [] + +// Empty array. +tail([]); +// Returns: [] +``` + +`null` or `undefined` is treated as an empty array. + +```typescript +import { tail } from 'es-toolkit/compat'; + +tail(null); // [] +tail(undefined); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to remove the first element from. + +#### Returns + +(`T[]`): Returns a new array containing all elements except the first one. diff --git a/docs/compat/reference/array/take.md b/docs/compat/reference/array/take.md new file mode 100644 index 000000000..2fb31c0c2 --- /dev/null +++ b/docs/compat/reference/array/take.md @@ -0,0 +1,56 @@ +# take (Lodash compatibility) + +::: warning Please use [take](../../../reference/array/take.md) from `es-toolkit` + +This `take` function operates slowly due to additional processing for compatibility with Lodash. + +Please use the faster and modern [take](../../../reference/array/take.md) from `es-toolkit` instead. + +::: + +Takes a specified number of elements from the beginning of an array and creates a new array. + +```typescript +const result = take([1, 2, 3, 4, 5], 3); +// result becomes [1, 2, 3]. +``` + +## Usage + +### `take(array, count)` + +Takes a specified number of elements from the beginning of an array and returns a new array. If `count` is greater than the array length, returns the entire array. + +```typescript +import { take } from 'es-toolkit/compat'; + +// Basic usage +const numbers = [1, 2, 3, 4, 5]; +const result1 = take(numbers, 3); +// Returns: [1, 2, 3] + +// Request count greater than array length +const result2 = take(numbers, 10); +// Returns: [1, 2, 3, 4, 5] (entire array) + +// Request 0 elements +const result3 = take(numbers, 0); +// Returns: [] + +// Handle empty array +const result4 = take([], 3); +// Returns: [] + +// Handle negative number +const result5 = take(numbers, -1); +// Returns: [] +``` + +#### Parameters + +- `array` (`T[]`): The array to take elements from. +- `count` (`number`): The number of elements to take. Default is 1. + +#### Returns + +(`T[]`): A new array containing the specified number of elements from the beginning. diff --git a/docs/compat/reference/array/takeRight.md b/docs/compat/reference/array/takeRight.md new file mode 100644 index 000000000..967290922 --- /dev/null +++ b/docs/compat/reference/array/takeRight.md @@ -0,0 +1,63 @@ +# takeRight (Lodash compatibility) + +::: warning Please use [takeRight](../../../reference/array/takeRight.md) from `es-toolkit` + +This `takeRight` function operates slowly due to handling `null` or `undefined`. + +Please use the faster and modern [takeRight](../../../reference/array/takeRight.md) from `es-toolkit` instead. + +::: + +Takes a specified number of elements from the end of an array. + +```typescript +const result = takeRight(array, count); +``` + +## Usage + +### `takeRight(array, count)` + +Use `takeRight` when you want to create a new array by taking a specified number of elements from the end of an array. If the requested count is greater than the array length, returns the entire array. + +```typescript +import { takeRight } from 'es-toolkit/compat'; + +// Take the last 2 elements from a number array. +takeRight([1, 2, 3, 4, 5], 2); +// Returns: [4, 5] + +// Take the last 3 elements from a string array. +takeRight(['a', 'b', 'c'], 2); +// Returns: ['b', 'c'] + +// When requested count is greater than array length +takeRight([1, 2, 3], 5); +// Returns: [1, 2, 3] + +// Request 0 elements +takeRight([1, 2, 3], 0); +// Returns: [] + +// Request negative number +takeRight([1, 2, 3], -1); +// Returns: [] +``` + +`null` or `undefined` is treated as an empty array. + +```typescript +import { takeRight } from 'es-toolkit/compat'; + +takeRight(null, 2); // [] +takeRight(undefined, 2); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to take elements from. +- `count` (`number`, optional): The number of elements to take. Default is `1`. + +#### Returns + +(`T[]`): Returns a new array containing the specified number of elements from the end. diff --git a/docs/compat/reference/array/takeRightWhile.md b/docs/compat/reference/array/takeRightWhile.md new file mode 100644 index 000000000..cd94c23e0 --- /dev/null +++ b/docs/compat/reference/array/takeRightWhile.md @@ -0,0 +1,71 @@ +# takeRightWhile (Lodash compatibility) + +::: warning Please use [takeRightWhile](../../../reference/array/takeRightWhile.md) from `es-toolkit` + +This `takeRightWhile` function operates slowly due to handling `null` or `undefined`. + +Please use the faster and modern [takeRightWhile](../../../reference/array/takeRightWhile.md) from `es-toolkit` instead. + +::: + +Takes elements from the end of an array while the condition is satisfied. + +```typescript +const result = takeRightWhile(array, predicate); +``` + +## Usage + +### `takeRightWhile(array, predicate)` + +Use `takeRightWhile` when you want to create a new array by taking elements from the end of an array while the condition is satisfied. It stops when the condition evaluates to false. + +```typescript +import { takeRightWhile } from 'es-toolkit/compat'; + +// Using function condition +const numbers = [1, 2, 3, 4, 5]; +takeRightWhile(numbers, x => x > 3); +// Returns: [4, 5] + +// Using object property condition +const users = [ + { user: 'barney', active: true }, + { user: 'fred', active: false }, + { user: 'pebbles', active: false }, +]; + +takeRightWhile(users, o => !o.active); +// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] + +// Matching with partial object +takeRightWhile(users, { active: false }); +// Returns: [{ user: 'pebbles', active: false }] + +// Matching with property-value array +takeRightWhile(users, ['active', false]); +// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] + +// Checking for truthy value by property name +const items = [{ active: false }, { active: true }, { active: true }]; +takeRightWhile(items, 'active'); +// Returns: [{ active: true }, { active: true }] +``` + +`null` or `undefined` is treated as an empty array. + +```typescript +import { takeRightWhile } from 'es-toolkit/compat'; + +takeRightWhile(null, x => x > 0); // [] +takeRightWhile(undefined, x => x > 0); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to process. +- `predicate` (`ListIteratee`, optional): The condition to run for each element. Can be a function, partial object, property-value array, or property name. Default is the identity function. + +#### Returns + +(`T[]`): Returns a new array of elements taken from the end while the condition is satisfied. diff --git a/docs/compat/reference/array/takeWhile.md b/docs/compat/reference/array/takeWhile.md new file mode 100644 index 000000000..fe8c84acf --- /dev/null +++ b/docs/compat/reference/array/takeWhile.md @@ -0,0 +1,71 @@ +# takeWhile (Lodash compatibility) + +::: warning Please use [takeWhile](../../../reference/array/takeWhile.md) from `es-toolkit` + +This `takeWhile` function operates slowly due to handling `null` or `undefined`. + +Please use the faster and modern [takeWhile](../../../reference/array/takeWhile.md) from `es-toolkit` instead. + +::: + +Takes elements from the beginning of an array while the condition is satisfied. + +```typescript +const result = takeWhile(array, predicate); +``` + +## Usage + +### `takeWhile(array, predicate)` + +Use `takeWhile` when you want to create a new array by taking elements from the beginning of an array while the condition is satisfied. It stops when the condition evaluates to false. + +```typescript +import { takeWhile } from 'es-toolkit/compat'; + +// Using function condition +const numbers = [1, 2, 3, 4, 5]; +takeWhile(numbers, x => x < 3); +// Returns: [1, 2] + +// Using object property condition +const users = [ + { user: 'barney', active: false }, + { user: 'fred', active: false }, + { user: 'pebbles', active: true }, +]; + +takeWhile(users, o => !o.active); +// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] + +// Matching with partial object +takeWhile(users, { active: false }); +// Returns: [{ user: 'barney', active: false }] + +// Matching with property-value array +takeWhile(users, ['active', false]); +// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] + +// Checking for truthy value by property name +const items = [{ active: true }, { active: true }, { active: false }]; +takeWhile(items, 'active'); +// Returns: [{ active: true }, { active: true }] +``` + +`null` or `undefined` is treated as an empty array. + +```typescript +import { takeWhile } from 'es-toolkit/compat'; + +takeWhile(null, x => x > 0); // [] +takeWhile(undefined, x => x > 0); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to process. +- `predicate` (`ListIteratee`, optional): The condition to run for each element. Can be a function, partial object, property-value array, or property name. Default is the identity function. + +#### Returns + +(`T[]`): Returns a new array of elements taken from the beginning while the condition is satisfied. diff --git a/docs/compat/reference/array/union.md b/docs/compat/reference/array/union.md new file mode 100644 index 000000000..095208bf5 --- /dev/null +++ b/docs/compat/reference/array/union.md @@ -0,0 +1,62 @@ +# union (Lodash Compatibility) + +::: warning Use [union](../../../reference/array/union.md) from `es-toolkit` + +This `union` function operates slowly due to complex array processing. + +Instead, use the faster and more modern [union](../../../reference/array/union.md) from `es-toolkit`. + +::: + +Creates a new array containing only unique values from multiple arrays. + +```typescript +const result = union(...arrays); +``` + +## Usage + +### `union(...arrays)` + +Use `union` when you want to merge multiple arrays and remove duplicates to create a new array containing only unique values. The order of first appearance of each value is preserved. + +```typescript +import { union } from 'es-toolkit/compat'; + +// Merging number arrays +union([2], [1, 2]); +// Returns: [2, 1] + +// Merging multiple arrays +union([2], [1, 2], [2, 3]); +// Returns: [2, 1, 3] + +// Nested arrays are not flattened +union([1, 3, 2], [1, [5]], [2, [4]]); +// Returns: [1, 3, 2, [5], [4]] + +// Non-array values are ignored +union([0], 3, { '0': 1 }, null, [2, 1]); +// Returns: [0, 2, 1] + +// Array-like objects are also processed +union([0], { 0: 'a', length: 1 }, [2, 1]); +// Returns: [0, 'a', 2, 1] +``` + +`null` or `undefined` are ignored. + +```typescript +import { union } from 'es-toolkit/compat'; + +union([1, 2], null, undefined, [3, 4]); +// Returns: [1, 2, 3, 4] +``` + +#### Parameters + +- `...arrays` (`Array | null | undefined>`): The arrays to merge. Non-array values are ignored. + +#### Returns + +(`T[]`): Returns a new array containing unique values from all arrays. diff --git a/docs/compat/reference/array/unionBy.md b/docs/compat/reference/array/unionBy.md new file mode 100644 index 000000000..dcf696c3a --- /dev/null +++ b/docs/compat/reference/array/unionBy.md @@ -0,0 +1,66 @@ +# unionBy (Lodash Compatibility) + +::: warning Use [unionBy](../../../reference/array/unionBy.md) from `es-toolkit` + +This `unionBy` function operates slowly due to complex processing. + +Instead, use the faster and more modern [unionBy](../../../reference/array/unionBy.md) from `es-toolkit`. + +::: + +Merges multiple arrays and keeps only unique values based on a specified criterion. + +```typescript +const result = unionBy(...arrays, iteratee); +``` + +## Usage + +### `unionBy(...arrays, iteratee)` + +Use `unionBy` when you want to merge multiple arrays and remove duplicates based on a given criterion function to create a new array containing only unique values. The order of first appearance of each value is preserved. + +```typescript +import { unionBy } from 'es-toolkit/compat'; + +// Compare by flooring decimal numbers +unionBy([2.1], [1.2, 2.3], Math.floor); +// Returns: [2.1, 1.2] + +// Compare by object property +unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); +// Returns: [{ x: 1 }, { x: 2 }] + +// Compare with function +unionBy( + [{ id: 1, name: 'a' }], + [ + { id: 2, name: 'b' }, + { id: 1, name: 'c' }, + ], + item => item.id +); +// Returns: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }] + +// Compare with partial object +unionBy([{ x: 1, y: 1 }], [{ x: 1, y: 2 }], { x: 1 }); +// Returns: [{ x: 1, y: 1 }] +``` + +`null` or `undefined` arrays are ignored. + +```typescript +import { unionBy } from 'es-toolkit/compat'; + +unionBy([1, 2], null, undefined, [3, 4], x => x); +// Returns: [1, 2, 3, 4] +``` + +#### Parameters + +- `...arrays` (`Array | null | undefined>`): The arrays to merge. +- `iteratee` (`ValueIteratee`): The criterion to determine uniqueness. Can be a function, property name, partial object, or property-value array. + +#### Returns + +(`T[]`): Returns a new array containing unique values with duplicates removed based on the specified criterion. diff --git a/docs/compat/reference/array/unionWith.md b/docs/compat/reference/array/unionWith.md new file mode 100644 index 000000000..0b703bdf3 --- /dev/null +++ b/docs/compat/reference/array/unionWith.md @@ -0,0 +1,64 @@ +# unionWith (Lodash Compatibility) + +::: warning Use [unionWith](../../../reference/array/unionWith.md) from `es-toolkit` + +This `unionWith` function operates slowly due to complex processing. + +Instead, use the faster and more modern [unionWith](../../../reference/array/unionWith.md) from `es-toolkit`. + +::: + +Merges multiple arrays and keeps only unique values using a comparison function. + +```typescript +const result = unionWith(...arrays, comparator); +``` + +## Usage + +### `unionWith(...arrays, comparator)` + +Use `unionWith` when you want to merge multiple arrays and remove duplicates using a custom comparison function to create a new array containing only unique values. The order of first appearance of each value is preserved. + +```typescript +import { unionWith } from 'es-toolkit/compat'; + +// Using a custom comparison function +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, +]; +const others = [ + { x: 1, y: 1 }, + { x: 1, y: 2 }, +]; + +unionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); +// Returns: [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 1, y: 1 }] + +// Simple equality comparison +unionWith([1, 2], [2, 3], (a, b) => a === b); +// Returns: [1, 2, 3] + +// Compare by string length +unionWith(['ab', 'cd'], ['ef', 'gh', 'ab'], (a, b) => a.length === b.length); +// Returns: ['ab'] +``` + +`null` or `undefined` arrays are ignored. + +```typescript +import { unionWith } from 'es-toolkit/compat'; + +unionWith([1, 2], null, undefined, [3, 4], (a, b) => a === b); +// Returns: [1, 2, 3, 4] +``` + +#### Parameters + +- `...arrays` (`Array | null | undefined>`): The arrays to merge. +- `comparator` (`(a: T, b: T) => boolean`): The comparison function that determines if two values are equal. + +#### Returns + +(`T[]`): Returns a new array containing unique values with duplicates removed using the comparison function. diff --git a/docs/compat/reference/array/uniq.md b/docs/compat/reference/array/uniq.md new file mode 100644 index 000000000..96bcddfe9 --- /dev/null +++ b/docs/compat/reference/array/uniq.md @@ -0,0 +1,51 @@ +# uniq (Lodash Compatibility) + +::: warning Use [uniq](../../../reference/array/uniq.md) from `es-toolkit` + +This `uniq` function operates slowly due to additional processing for Lodash compatibility. + +Instead, use the faster and more modern [uniq](../../../reference/array/uniq.md) from `es-toolkit`. + +::: + +Creates a new array with only unique elements by removing duplicates from an array. + +```typescript +const result = uniq([1, 2, 2, 3, 3, 4]); +// result is [1, 2, 3, 4]. +``` + +## Usage + +### `uniq(array)` + +Returns a new array containing only unique elements by removing duplicates from the array. Only the first occurrence of each element is kept and the order is preserved. + +```typescript +import { uniq } from 'es-toolkit/compat'; + +// Remove duplicates from number array +const numbers = [1, 2, 2, 3, 3, 4, 1]; +const result1 = uniq(numbers); +// Returns: [1, 2, 3, 4] + +// Remove duplicates from string array +const strings = ['a', 'b', 'b', 'c', 'a']; +const result2 = uniq(strings); +// Returns: ['a', 'b', 'c'] + +// Remove duplicates from object array (reference value comparison) +const obj1 = { id: 1 }; +const obj2 = { id: 2 }; +const objects = [obj1, obj2, obj1]; +const result3 = uniq(objects); +// Returns: [{ id: 1 }, { id: 2 }] +``` + +#### Parameters + +- `array` (`T[]`): The array to process. + +#### Returns + +(`T[]`): A new array with duplicates removed. diff --git a/docs/compat/reference/array/uniqBy.md b/docs/compat/reference/array/uniqBy.md new file mode 100644 index 000000000..ab54dd2f1 --- /dev/null +++ b/docs/compat/reference/array/uniqBy.md @@ -0,0 +1,55 @@ +# uniqBy (Lodash Compatibility) + +::: warning Use [uniqBy](../../../reference/array/uniqBy.md) from `es-toolkit` + +This `uniqBy` function operates slowly due to handling of `null` or `undefined`, complex argument type processing, etc. + +Instead, use the faster and more modern [uniqBy](../../../reference/array/uniqBy.md) from `es-toolkit`. + +::: + +Creates a new array of unique elements by removing duplicates based on the values returned by a transformation function. + +```typescript +const result = uniqBy(array, iteratee); +``` + +## Usage + +### `uniqBy(array, iteratee)` + +Applies a transformation function to each element of the array and keeps only the first element among those with the same transformation result. This is useful when removing duplicates based on a specific property in an object array or based on a specific calculation result in a number array. + +```typescript +import { uniqBy } from 'es-toolkit/compat'; + +// Remove duplicates by Math.floor result in number array +uniqBy([2.1, 1.2, 2.3], Math.floor); +// Returns: [2.1, 1.2] + +// Remove duplicates by property in object array +uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); +// Returns: [{ x: 1 }, { x: 2 }] + +// Remove duplicates with function +uniqBy([{ name: 'John' }, { name: 'Jane' }, { name: 'John' }], obj => obj.name); +// Returns: [{ name: 'John' }, { name: 'Jane' }] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { uniqBy } from 'es-toolkit/compat'; + +uniqBy(null, Math.floor); // [] +uniqBy(undefined, 'x'); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to remove duplicates from. +- `iteratee` (`ValueIteratee`): The transformation function to apply to each element. Can be a function, property name, partial object, etc. + +#### Returns + +(`T[]`): Returns a new array with duplicates removed based on the transformation function result. diff --git a/docs/compat/reference/array/uniqWith.md b/docs/compat/reference/array/uniqWith.md new file mode 100644 index 000000000..b5e9b781c --- /dev/null +++ b/docs/compat/reference/array/uniqWith.md @@ -0,0 +1,60 @@ +# uniqWith (Lodash Compatibility) + +::: warning Use [uniqWith](../../../reference/array/uniqWith.md) from `es-toolkit` + +This `uniqWith` function operates slowly due to handling of `null` or `undefined`, complex argument type processing, etc. + +Instead, use the faster and more modern [uniqWith](../../../reference/array/uniqWith.md) from `es-toolkit`. + +::: + +Creates a new array of unique elements by removing duplicates using a comparison function. + +```typescript +const result = uniqWith(array, comparator); +``` + +## Usage + +### `uniqWith(array, comparator)` + +Removes duplicates by comparing each element of the array with a comparison function. When the comparison function returns `true`, the two elements are considered equal, and only the first occurring element is kept. If no comparison function is provided, it uses shallow equality comparison by default. + +```typescript +import { uniqWith } from 'es-toolkit/compat'; + +// Use without comparison function (shallow equality comparison) +uniqWith([1, 2, 2, 3]); +// Returns: [1, 2, 3] + +// Remove duplicates based on odd/even criterion with custom comparison function +uniqWith([1, 2, 3, 4], (a, b) => a % 2 === b % 2); +// Returns: [1, 2] + +// Remove duplicates based on property in object array +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 1, y: 2 }, +]; +uniqWith(objects, (a, b) => a.x === b.x && a.y === b.y); +// Returns: [{ x: 1, y: 2 }, { x: 2, y: 1 }] +``` + +`null` or `undefined` are treated as empty arrays. + +```typescript +import { uniqWith } from 'es-toolkit/compat'; + +uniqWith(null); // [] +uniqWith(undefined); // [] +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to remove duplicates from. +- `comparator` (`(a: T, b: T) => boolean`, optional): The function to compare if two elements are equal. Returns `true` if they are considered equal. Default is shallow equality comparison. + +#### Returns + +(`T[]`): Returns a new array with duplicates removed based on the comparison function result. diff --git a/docs/compat/reference/array/unzip.md b/docs/compat/reference/array/unzip.md new file mode 100644 index 000000000..88ac8508c --- /dev/null +++ b/docs/compat/reference/array/unzip.md @@ -0,0 +1,68 @@ +# unzip (Lodash Compatibility) + +::: warning Use [unzip](../../../reference/array/unzip.md) from `es-toolkit` + +This `unzip` function operates slowly due to handling of `null` or `undefined`, filtering of non-array values, etc. + +Instead, use the faster and more modern [unzip](../../../reference/array/unzip.md) from `es-toolkit`. + +::: + +Collects elements at the same positions in grouped arrays into new arrays. + +```typescript +const result = unzip(array); +``` + +## Usage + +### `unzip(array)` + +Collects elements at the same index in nested arrays and returns them as a new array. Performs the opposite operation of the `zip` function. This is useful when transposing matrices or reorganizing structured data. + +```typescript +import { unzip } from 'es-toolkit/compat'; + +// Unzip arrays with mixed strings, booleans, and numbers +const zipped = [ + ['a', true, 1], + ['b', false, 2], +]; +const result = unzip(zipped); +// Returns: [['a', 'b'], [true, false], [1, 2]] + +// Unzip number arrays +const numbers = [ + [1, 4], + [2, 5], + [3, 6], +]; +unzip(numbers); +// Returns: [[1, 2, 3], [4, 5, 6]] + +// Handle arrays with different lengths +const uneven = [ + ['a', 1], + ['b', 2, true], +]; +unzip(uneven); +// Returns: [['a', 'b'], [1, 2], [undefined, true]] +``` + +`null`, `undefined`, or empty arrays are treated as empty arrays. + +```typescript +import { unzip } from 'es-toolkit/compat'; + +unzip(null); // [] +unzip(undefined); // [] +unzip([]); // [] +``` + +#### Parameters + +- `array` (`T[][] | ArrayLike> | null | undefined`): The nested array to unzip. Elements at the same position in each inner array are collected together. + +#### Returns + +(`T[][]`): Returns a new array with elements at the same positions collected together. diff --git a/docs/compat/reference/array/unzipWith.md b/docs/compat/reference/array/unzipWith.md new file mode 100644 index 000000000..929b50651 --- /dev/null +++ b/docs/compat/reference/array/unzipWith.md @@ -0,0 +1,84 @@ +# unzipWith (Lodash Compatibility) + +::: warning Use `unzipWith` from `es-toolkit` + +This `unzipWith` function operates slowly due to handling of `null` or `undefined`, `ArrayLike` type processing, support for various condition function forms, etc. + +Instead, use the faster and more modern [unzipWith](../../../reference/array/unzipWith.md) from `es-toolkit`. + +::: + +Collects elements at the same positions in grouped arrays and applies a transformation function to create a new array. + +```typescript +const result = unzipWith(array, iteratee); +``` + +## Usage + +### `unzipWith(array, iteratee)` + +Collects elements at the same index in nested arrays and applies a transformation function. Similar to the `unzip` function, but can apply a transformation function to each group. If no transformation function is provided, it performs the default `unzip` operation. + +```typescript +import { unzipWith } from 'es-toolkit/compat'; + +// Add elements at the same positions +unzipWith( + [ + [1, 10, 100], + [2, 20, 200], + ], + (a, b) => a + b +); +// Returns: [3, 30, 300] + +// Use without transformation function (default unzip operation) +unzipWith([ + [1, 4], + [2, 5], + [3, 6], +]); +// Returns: [[1, 2, 3], [4, 5, 6]] + +// String concatenation +unzipWith( + [ + ['a', 'x'], + ['b', 'y'], + ['c', 'z'], + ], + (a, b) => a + b +); +// Returns: ['abc', 'xyz'] + +// Find maximum values +unzipWith( + [ + [1, 10], + [2, 20], + [3, 5], + ], + Math.max +); +// Returns: [3, 20] +``` + +`null`, `undefined`, or empty arrays are treated as empty arrays. + +```typescript +import { unzipWith } from 'es-toolkit/compat'; + +unzipWith(null, (a, b) => a + b); // [] +unzipWith(undefined, (a, b) => a + b); // [] +unzipWith([], (a, b) => a + b); // [] +``` + +#### Parameters + +- `array` (`ArrayLike> | null | undefined`): The nested array to unzip. +- `iteratee` (`(...values: T[]) => R`, optional): The transformation function to apply to each group of elements. If not provided, performs the default `unzip` operation. + +#### Returns + +(`R[]` or `T[][]`): Returns an array of transformed results if a transformation function is provided, or an unzipped array if not. diff --git a/docs/compat/reference/array/without.md b/docs/compat/reference/array/without.md new file mode 100644 index 000000000..05ebcdb4b --- /dev/null +++ b/docs/compat/reference/array/without.md @@ -0,0 +1,49 @@ +# without (Lodash Compatibility) + +::: warning Use [without](../../../reference/array/without.md) from `es-toolkit` + +This `without` function operates slowly due to additional processing for Lodash compatibility. + +Instead, use the faster and more modern [without](../../../reference/array/without.md) from `es-toolkit`. + +::: + +Creates a new array excluding specified values from an array. + +```typescript +const result = without([1, 2, 3, 4, 5], 2, 4); +// result is [1, 3, 5]. +``` + +## Usage + +### `without(array, ...values)` + +Returns a new array with the specified values removed from the array. The original array is not modified. + +```typescript +import { without } from 'es-toolkit/compat'; + +// Remove multiple values from number array +const numbers = [1, 2, 3, 4, 5, 2, 4]; +const result1 = without(numbers, 2, 4); +// Returns: [1, 3, 5] + +// Remove values from string array +const fruits = ['apple', 'banana', 'cherry', 'banana']; +const result2 = without(fruits, 'banana'); +// Returns: ['apple', 'cherry'] + +// Handle empty array +const result3 = without([], 1, 2, 3); +// Returns: [] +``` + +#### Parameters + +- `array` (`T[]`): The original array to process. +- `...values` (`T[]`): The values to remove. + +#### Returns + +(`T[]`): A new array with the specified values removed. diff --git a/docs/compat/reference/array/xor.md b/docs/compat/reference/array/xor.md new file mode 100644 index 000000000..1540a6641 --- /dev/null +++ b/docs/compat/reference/array/xor.md @@ -0,0 +1,61 @@ +# xor (Lodash Compatibility) + +::: warning Use [xor](../../../reference/array/xor.md) from `es-toolkit` + +This `xor` function operates slowly due to handling of `null` or `undefined`, complex duplicate calculation logic, etc. + +Instead, use the faster and more modern [xor](../../../reference/array/xor.md) from `es-toolkit`. + +::: + +Creates a new array of elements that exist in exactly one of the multiple arrays. + +```typescript +const result = xor(...arrays); +``` + +## Usage + +### `xor(...arrays)` + +Computes the symmetric difference of multiple arrays. In other words, returns elements that exist in exactly one of the given arrays. This is useful when you want to find non-overlapping unique elements when comparing two or more arrays. + +```typescript +import { xor } from 'es-toolkit/compat'; + +// Symmetric difference of two arrays +xor([1, 2, 3, 4], [3, 4, 5, 6]); +// Returns: [1, 2, 5, 6] + +// Symmetric difference of three arrays +xor([1, 2], [2, 3], [4, 5]); +// Returns: [1, 3, 4, 5] + +// String arrays +xor(['a', 'b'], ['b', 'c']); +// Returns: ['a', 'c'] + +// Providing only one array +xor([1, 2, 3]); +// Returns: [1, 2, 3] +``` + +`null`, `undefined`, or empty arrays are ignored and only valid arrays are processed. + +```typescript +import { xor } from 'es-toolkit/compat'; + +xor([1, 2], null, [2, 3]); +// Returns: [1, 3] + +xor([], [1, 2], [2, 3]); +// Returns: [1, 3] +``` + +#### Parameters + +- `...arrays` (`Array | null | undefined>`): The arrays to compute the symmetric difference from. `null` or `undefined` are ignored. + +#### Returns + +(`T[]`): Returns a new array of elements that exist in exactly one of the arrays. diff --git a/docs/compat/reference/array/xorBy.md b/docs/compat/reference/array/xorBy.md new file mode 100644 index 000000000..7b4707812 --- /dev/null +++ b/docs/compat/reference/array/xorBy.md @@ -0,0 +1,63 @@ +# xorBy (Lodash Compatibility) + +::: warning Use [xorBy](../../../reference/array/xorBy.md) from `es-toolkit` + +This `xorBy` function operates slowly due to handling of `null` or `undefined`, complex duplicate calculation logic, etc. + +Instead, use the faster and more modern [xorBy](../../../reference/array/xorBy.md) from `es-toolkit`. + +::: + +Creates a new array of elements that exist in exactly one of the multiple arrays based on a transformation function. + +```typescript +const result = xorBy(...arrays, iteratee); +``` + +## Usage + +### `xorBy(...arrays, iteratee)` + +Computes the symmetric difference of multiple arrays based on a transformation function. Returns elements whose transformation result exists in exactly one of the arrays. This is useful when comparing based on a specific property in object arrays or based on a specific calculation result in number arrays. + +```typescript +import { xorBy } from 'es-toolkit/compat'; + +// Compute symmetric difference by Math.floor result +xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); +// Returns: [1.2, 4.3] + +// Compute symmetric difference by object property +xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); +// Returns: [{ x: 2 }] + +// Compute symmetric difference with function +const users1 = [{ name: 'John', age: 30 }]; +const users2 = [ + { name: 'Jane', age: 25 }, + { name: 'John', age: 30 }, +]; +xorBy(users1, users2, user => user.name); +// Returns: [{ name: 'Jane', age: 25 }] + +// Symmetric difference of three arrays +xorBy([1.2, 2.3], [3.4, 4.5], [5.6, 6.7], Math.floor); +// Returns: [1.2, 2.3, 3.4, 4.5, 5.6, 6.7] +``` + +`null` or `undefined` are ignored. + +```typescript +import { xorBy } from 'es-toolkit/compat'; + +xorBy([2.1, 1.2], null, [4.3, 2.4], Math.floor); +// Returns: [1.2, 4.3] +``` + +#### Parameters + +- `...arrays` (`Array | null | undefined | ValueIteratee>`): The arrays to compute the symmetric difference from and the transformation function at the end. Can be a function, property name, partial object, etc. + +#### Returns + +(`T[]`): Returns a new array of elements that exist in exactly one of the arrays based on the transformation function result. diff --git a/docs/compat/reference/array/xorWith.md b/docs/compat/reference/array/xorWith.md new file mode 100644 index 000000000..70c1f7fa6 --- /dev/null +++ b/docs/compat/reference/array/xorWith.md @@ -0,0 +1,66 @@ +# xorWith (Lodash Compatibility) + +::: warning Use [xorWith](../../../reference/array/xorWith.md) from `es-toolkit` + +This `xorWith` function operates slowly due to handling of `null` or `undefined`, complex duplicate calculation logic, etc. + +Instead, use the faster and more modern [xorWith](../../../reference/array/xorWith.md) from `es-toolkit`. + +::: + +Creates a new array of elements that exist in exactly one of the multiple arrays using a comparison function. + +```typescript +const result = xorWith(...arrays, comparator); +``` + +## Usage + +### `xorWith(...arrays, comparator)` + +Computes the symmetric difference of multiple arrays using a comparison function. When the comparison function returns `true`, the two elements are considered equal, and returns elements that exist in exactly one of the arrays. This is useful when dealing with complex objects or when custom comparison logic is needed. + +```typescript +import { xorWith } from 'es-toolkit/compat'; + +// Simple number comparison +xorWith([1, 2], [2, 3], (a, b) => a === b); +// Returns: [1, 3] + +// Compare object properties +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, +]; +const others = [ + { x: 1, y: 1 }, + { x: 1, y: 2 }, +]; +xorWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); +// Returns: [{ x: 2, y: 1 }, { x: 1, y: 1 }] + +// Symmetric difference of three arrays +xorWith([1], [2], [3], (a, b) => a === b); +// Returns: [1, 2, 3] + +// Compare by string length +xorWith(['hello'], ['world', 'hi'], (a, b) => a.length === b.length); +// Returns: ['hi'] +``` + +If no comparison function is provided, it uses shallow equality comparison by default. + +```typescript +import { xorWith } from 'es-toolkit/compat'; + +xorWith([1, 2], [2, 3]); +// Returns: [1, 3] +``` + +#### Parameters + +- `...arrays` (`Array | null | undefined | ((a: T, b: T) => boolean)>`): The arrays to compute the symmetric difference from and the comparison function at the end. The comparison function should return `true` if two elements are equal. + +#### Returns + +(`T[]`): Returns a new array of elements that exist in exactly one of the arrays based on the comparison function result. diff --git a/docs/compat/reference/array/zip.md b/docs/compat/reference/array/zip.md new file mode 100644 index 000000000..59c6c4233 --- /dev/null +++ b/docs/compat/reference/array/zip.md @@ -0,0 +1,48 @@ +# zip (Lodash Compatibility) + +::: warning Use [zip](../../../reference/array/zip.md) from `es-toolkit` + +This `zip` function operates slowly due to additional processing for Lodash compatibility. + +Instead, use the faster and more modern [zip](../../../reference/array/zip.md) from `es-toolkit`. + +::: + +Combines multiple arrays into a single array of tuples. + +```typescript +const result = zip([1, 2], ['a', 'b']); +// result is [[1, 'a'], [2, 'b']]. +``` + +## Usage + +### `zip(...arrs)` + +Takes multiple arrays and groups the elements at each index into a single tuple to create a new array. If the input arrays have different lengths, the result array will have the length of the longest input array, with missing elements filled with `undefined`. + +```typescript +import { zip } from 'es-toolkit/compat'; + +const arr1 = [1, 2, 3]; +const arr2 = ['a', 'b', 'c']; +const result = zip(arr1, arr2); +// Returns: [[1, 'a'], [2, 'b'], [3, 'c']] + +// Arrays with different lengths +const arr3 = [true, false]; +const result2 = zip(arr1, arr2, arr3); +// Returns: [[1, 'a', true], [2, 'b', false], [3, 'c', undefined]] + +// Including empty array +zip([1, 2], [], ['a', 'b']); +// Returns: [[1, undefined, 'a'], [2, undefined, 'b']] +``` + +#### Parameters + +- `...arrs` (`any[][]`): The arrays to combine. + +#### Returns + +(`any[][]`): A new array of tuples containing elements from each index of the input arrays. diff --git a/docs/compat/reference/array/zipObject.md b/docs/compat/reference/array/zipObject.md new file mode 100644 index 000000000..f4dedda52 --- /dev/null +++ b/docs/compat/reference/array/zipObject.md @@ -0,0 +1,50 @@ +# zipObject (Lodash Compatibility) + +::: warning Use [zipObject](../../../reference/array/zipObject.md) from `es-toolkit` + +This `zipObject` function operates slowly due to additional processing for Lodash compatibility. + +Instead, use the faster and more modern [zipObject](../../../reference/array/zipObject.md) from `es-toolkit`. + +::: + +Creates an object using two arrays. The first array is used as property names, and the second array is used as the corresponding values. + +```typescript +const result = zipObject(keys, values); +``` + +## Usage + +### `zipObject(keys, values)` + +Use `zipObject` when you want to create a single object from a key array and a value array. It uses elements from the first array as property names and elements from the second array as their corresponding values. This is especially useful when processing API responses or transforming data. + +```typescript +import { zipObject } from 'es-toolkit/compat'; + +// Basic usage +const keys = ['a', 'b', 'c']; +const values = [1, 2, 3]; +const result = zipObject(keys, values); +// Returns: { a: 1, b: 2, c: 3 } + +// Arrays with different lengths +const keys2 = ['x', 'y', 'z']; +const values2 = [10, 20]; +const result2 = zipObject(keys2, values2); +// Returns: { x: 10, y: 20, z: undefined } + +// Empty arrays provided +const result3 = zipObject([], []); +// Returns: {} +``` + +#### Parameters + +- `keys` (`PropertyKey[]`): The array to use as property names. +- `values` (`T[]`): The array to use as property values. + +#### Returns + +(`Record`): The created object. diff --git a/docs/reference/compat/array/zipObjectDeep.md b/docs/compat/reference/array/zipObjectDeep.md similarity index 100% rename from docs/reference/compat/array/zipObjectDeep.md rename to docs/compat/reference/array/zipObjectDeep.md diff --git a/docs/compat/reference/array/zipWith.md b/docs/compat/reference/array/zipWith.md new file mode 100644 index 000000000..7416a23c3 --- /dev/null +++ b/docs/compat/reference/array/zipWith.md @@ -0,0 +1,47 @@ +# zipWith (Lodash Compatibility) + +::: warning Use [zipWith](../../../reference/array/zipWith.md) from `es-toolkit` + +This `zipWith` function operates slowly due to additional processing for Lodash compatibility. + +Instead, use the faster and more modern [zipWith](../../../reference/array/zipWith.md) from `es-toolkit`. + +::: + +Combines elements from multiple arrays using a combining function into a new array. + +```typescript +const result = zipWith([1, 2], [3, 4], (a, b) => a + b); +// result is [4, 6]. +``` + +## Usage + +### `zipWith(...arrs, iteratee)` + +Takes multiple arrays and combines elements at each index using a provided function to create a new array. If arrays have different lengths, it processes up to the length of the longest array, passing `undefined` for missing values. + +```typescript +import { zipWith } from 'es-toolkit/compat'; + +// Add elements from two arrays +const result1 = zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b); +// Returns: [5, 7, 9] + +// Combine elements from three arrays +const result2 = zipWith([1, 2], [3, 4], [5, 6], (a, b, c) => a + b + c); +// Returns: [9, 12] + +// Arrays with different lengths +const result3 = zipWith([1, 2, 3], [4, 5], (a, b) => (a || 0) + (b || 0)); +// Returns: [5, 7, 3] +``` + +#### Parameters + +- `...arrs` (`any[][]`): The arrays to combine. +- `iteratee` (`Function`): The function to combine elements at each index. + +#### Returns + +(`any[]`): A new array of results from applying the combining function. diff --git a/docs/compat/reference/function/after.md b/docs/compat/reference/function/after.md new file mode 100644 index 000000000..27f70a831 --- /dev/null +++ b/docs/compat/reference/function/after.md @@ -0,0 +1,75 @@ +# after (Lodash Compatibility) + +::: warning Use [`after`](../../../reference/function/after.md) from `es-toolkit` + +This `after` function operates slowly due to complex type validation and integer conversion handling. + +Instead, use the faster and more modern [after](../../../reference/function/after.md) from `es-toolkit`. + +::: + +Creates a function that only executes after being called a specified number of times. + +```typescript +const restrictedFunction = after(n, func); +``` + +## Usage + +### `after(n, func)` + +Use `after` when you want to restrict a function to execute only after it has been called a certain number of times. It's useful for executing callbacks after multiple asynchronous operations are complete or activating a function after an initialization phase. + +```typescript +import { after } from 'es-toolkit/compat'; + +// Basic usage +const logAfterThree = after(3, () => { + console.log('Executed from the 3rd call!'); +}); + +logAfterThree(); // Not executed +logAfterThree(); // Not executed +logAfterThree(); // Logs "Executed from the 3rd call!" +logAfterThree(); // Logs "Executed from the 3rd call!" (continues to execute) +``` + +You can also use it to execute a specific callback after all asynchronous operations are complete. + +```typescript +import { after } from 'es-toolkit/compat'; + +const tasks = ['task1', 'task2', 'task3']; +const allTasksComplete = after(tasks.length, () => { + console.log('All tasks completed!'); +}); + +// Called when each task completes +tasks.forEach(task => { + performAsyncTask(task, () => { + console.log(`${task} complete`); + allTasksComplete(); // Logs "All tasks completed!" on the 3rd call + }); +}); +``` + +When you pass 0 or a negative number, it executes immediately from the first call. + +```typescript +import { after } from 'es-toolkit/compat'; + +const immediate = after(0, () => console.log('Executed immediately')); +immediate(); // "Executed immediately" + +const negative = after(-1, () => console.log('Executed immediately')); +negative(); // "Executed immediately" +``` + +#### Parameters + +- `n` (`number`): The number of calls required before the function executes. +- `func` (`TFunc`): The function to restrict. + +#### Returns + +(`TFunc`): Returns a new restricted function that executes the original function from the nth call onwards. diff --git a/docs/compat/reference/function/ary.md b/docs/compat/reference/function/ary.md new file mode 100644 index 000000000..3c3f516bb --- /dev/null +++ b/docs/compat/reference/function/ary.md @@ -0,0 +1,90 @@ +# ary (Lodash Compatibility) + +::: warning Use [`ary`](../../../reference/function/ary.md) from `es-toolkit` + +This `ary` function operates slowly due to complex parameter validation. + +Instead, use the faster and more modern [ary](../../../reference/function/ary.md) from `es-toolkit`. + +::: + +Creates a function that limits the number of arguments it can receive. + +```typescript +const cappedFunction = ary(func, n); +``` + +## Usage + +### `ary(func, n)` + +Use `ary` when you want to limit the number of arguments a function receives. It's useful for safely using functions that receive too many arguments or ignoring unnecessary arguments in callback functions. + +```typescript +import { ary } from 'es-toolkit/compat'; + +// Basic usage +function greet(name, age, city) { + return `Hello, ${name}! ${age} years old, from ${city}.`; +} + +const limitedGreet = ary(greet, 2); +console.log(limitedGreet('John', 30, 'Seoul', 'extraArg')); +// "Hello, John! 30 years old, from undefined." +// Arguments from the 3rd onwards are ignored +``` + +You can prevent unnecessary arguments from being passed to callback functions when using them with array methods. + +```typescript +import { ary } from 'es-toolkit/compat'; + +// parseInt accepts a second argument (radix), but map's callback passes 3 arguments +const numbers = ['1', '2', '3', '4', '5']; + +// Incorrect usage - parseInt receives the index as radix +console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] + +// Use ary to pass only the first argument +console.log(numbers.map(ary(parseInt, 1))); // [1, 2, 3, 4, 5] +``` + +You can limit functions to receive only the desired number of parameter arguments. + +```typescript +import { ary } from 'es-toolkit/compat'; + +function sum(...args) { + return args.reduce((total, num) => total + num, 0); +} + +const sum0 = ary(sum, 0); +const sum1 = ary(sum, 1); +const sum2 = ary(sum, 2); +const sum3 = ary(sum, 3); + +console.log(sum0(1, 2, 3, 4, 5)); // 0 (no arguments) +console.log(sum1(1, 2, 3, 4, 5)); // 1 (first argument only) +console.log(sum2(1, 2, 3, 4, 5)); // 3 (first two arguments only) +console.log(sum3(1, 2, 3, 4, 5)); // 6 (first three arguments only) +``` + +When passing a negative number or `NaN`, it's treated as 0 and all arguments are ignored. + +```typescript +import { ary } from 'es-toolkit/compat'; + +const func = (a, b, c) => [a, b, c]; + +console.log(ary(func, -1)(1, 2, 3)); // [] (negative treated as 0) +console.log(ary(func, NaN)(1, 2, 3)); // [] (NaN treated as 0) +``` + +#### Parameters + +- `func` (`Function`): The function to cap arguments for. +- `n` (`number`, optional): The maximum number of arguments to allow. If omitted, uses the function's `length` property. + +#### Returns + +(`Function`): Returns a new function that accepts at most `n` arguments. diff --git a/docs/compat/reference/function/attempt.md b/docs/compat/reference/function/attempt.md new file mode 100644 index 000000000..fcac56d67 --- /dev/null +++ b/docs/compat/reference/function/attempt.md @@ -0,0 +1,66 @@ +# attempt (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [`attempt`](../../../reference/util/attempt.md) function or try-catch blocks instead + +This `attempt` function can be confusing because it returns both errors and return values without distinction. + +Instead, use the more direct and clear [`attempt`](../../../reference/util/attempt.md) function or try-catch blocks. + +::: + +A function that executes a function and returns an error object if an error occurs. + +```typescript +const result = attempt(func, ...args); +``` + +## Usage + +### `attempt(func, ...args)` + +Use `attempt` when you want to safely execute a function. It's useful when executing a function that may throw errors, preventing the program from crashing and handling errors as return values. + +```typescript +import { attempt } from 'es-toolkit/compat'; + +// Basic usage - successful case +const result = attempt((x, y) => x + y, 2, 3); +console.log(result); // 5 + +// Error case +const errorResult = attempt(() => { + throw new Error('Something went wrong'); +}); +console.log(errorResult); // Error: Something went wrong +``` + +Here's the difference compared to using try-catch blocks. + +```typescript +// Using attempt +import { attempt } from 'es-toolkit/compat'; + +const result = attempt(riskyFunction, arg1, arg2); +if (result instanceof Error) { + console.log('Error occurred:', result.message); +} else { + console.log('Result:', result); +} + +// Using try-catch (more direct) +try { + const result = riskyFunction(arg1, arg2); + console.log('Result:', result); +} catch (error) { + console.log('Error occurred:', error.message); +} +``` + +#### Parameters + +- `func` (`Function`): The function to execute. +- `args` (`...any[]`): The arguments to pass to the function. + +#### Returns + +(`ReturnType | Error`): Returns the return value if the function succeeds, or an Error object if an error occurs. diff --git a/docs/compat/reference/function/before.md b/docs/compat/reference/function/before.md new file mode 100644 index 000000000..03b95cfed --- /dev/null +++ b/docs/compat/reference/function/before.md @@ -0,0 +1,186 @@ +# before (Lodash Compatibility) + +::: warning Use [`before`](../../../reference/function/before.md) from `es-toolkit` + +This `before` function operates slower due to complex type validation and integer conversion handling. + +Instead, use the faster and more modern [before](../../../reference/function/before.md) from `es-toolkit`. + +::: + +Creates a function that executes the original function up to a specified number of times, then returns the last result for subsequent calls. + +```typescript +const limitedFunction = before(n, func); +``` + +## Usage + +### `before(n, func)` + +Use `before` when you want to restrict a function to execute only up to a certain number of times. This is useful for limiting function call counts or when you want to execute a function only during the initial setup phase. + +```typescript +import { before } from 'es-toolkit/compat'; + +// Basic usage +let count = 0; +const beforeThree = before(3, () => ++count); + +console.log(beforeThree()); // 1 (first call) +console.log(beforeThree()); // 2 (second call) +console.log(beforeThree()); // 2 (from third call onwards, returns last result) +console.log(beforeThree()); // 2 (continues to return last result) +``` + +Alternative using closures: + +```typescript +// Using before +const beforeThree = before(3, myFunction); + +// Using closures (simpler and faster) +function createBefore(limit, callback) { + let callCount = 0; + let lastResult; + + return function (...args) { + if (callCount < limit - 1) { + lastResult = callback.apply(this, args); + callCount++; + } + return lastResult; + }; +} + +const beforeThreeAlternative = createBefore(3, myFunction); +``` + +Using as an initialization function: + +```typescript +import { before } from 'es-toolkit/compat'; + +class Database { + constructor() { + this.isInitialized = false; + + // Initialization executes only once + this.initialize = before(2, () => { + console.log('Initializing database...'); + this.setupConnection(); + this.isInitialized = true; + return 'Initialization complete'; + }); + } + + setupConnection() { + // Actual connection setup logic + } + + query(sql) { + const initResult = this.initialize(); + console.log(initResult); // First call: "Initialization complete", subsequent: same result + + // Query execution logic + return `Query executed: ${sql}`; + } +} + +const db = new Database(); +db.query('SELECT * FROM users'); // Initialization executed +db.query('SELECT * FROM products'); // Initialization not executed +``` + +Limiting API calls: + +```typescript +import { before } from 'es-toolkit/compat'; + +// Allow API calls up to 5 times maximum +const limitedApiCall = before(6, endpoint => { + console.log(`API call: ${endpoint}`); + return fetch(endpoint).then(res => res.json()); +}); + +// First 5 calls execute actual API calls +limitedApiCall('/api/data1'); // Actual call +limitedApiCall('/api/data2'); // Actual call +limitedApiCall('/api/data3'); // Actual call +limitedApiCall('/api/data4'); // Actual call +limitedApiCall('/api/data5'); // Actual call +limitedApiCall('/api/data6'); // Returns last result (no API call) +``` + +Limiting event listeners: + +```typescript +import { before } from 'es-toolkit/compat'; + +// Process click events up to 3 times +const limitedClickHandler = before(4, event => { + console.log('Click processed:', event.target.id); + return `Processed: ${Date.now()}`; +}); + +document.getElementById('button').addEventListener('click', limitedClickHandler); +// Only the first 3 clicks are processed, subsequent calls return the last result +``` + +Handling parameters and return values: + +```typescript +import { before } from 'es-toolkit/compat'; + +const limitedCalculator = before(3, (operation, a, b) => { + const result = operation === 'add' ? a + b : a - b; + console.log(`Calculation: ${a} ${operation} ${b} = ${result}`); + return result; +}); + +console.log(limitedCalculator('add', 5, 3)); // "Calculation: 5 add 3 = 8", returns: 8 +console.log(limitedCalculator('subtract', 10, 4)); // "Calculation: 10 subtract 4 = 6", returns: 6 +console.log(limitedCalculator('multiply', 7, 2)); // No calculation, returns: 6 (last result) +``` + +Passing 0 or 1 prevents the function from executing: + +```typescript +import { before } from 'es-toolkit/compat'; + +const neverCalled = before(0, () => { + console.log('This function will not execute'); + return 'result'; +}); + +const onceOnly = before(1, () => { + console.log('This function will also not execute'); + return 'result'; +}); + +console.log(neverCalled()); // undefined +console.log(onceOnly()); // undefined +``` + +Resource cleanup optimization: + +```typescript +import { before } from 'es-toolkit/compat'; + +// Function references are automatically cleaned up to prevent memory leaks +const limitedProcessor = before(2, data => { + // Complex data processing + return processComplexData(data); +}); + +// After the 2nd call, the original function reference is removed (garbage collection) +``` + +#### Parameters + +- `n` (`number`): The maximum number of times to execute the function. It executes up to n-1 times, and from the nth call onwards, returns the last result. +- `func` (`Function`): The function to restrict. + +#### Returns + +(`Function`): Returns a new function that executes the original function up to the specified number of times, and thereafter returns the last result. diff --git a/docs/reference/compat/function/bind.md b/docs/compat/reference/function/bind.md similarity index 100% rename from docs/reference/compat/function/bind.md rename to docs/compat/reference/function/bind.md diff --git a/docs/reference/compat/function/bindKey.md b/docs/compat/reference/function/bindKey.md similarity index 100% rename from docs/reference/compat/function/bindKey.md rename to docs/compat/reference/function/bindKey.md diff --git a/docs/compat/reference/function/curry.md b/docs/compat/reference/function/curry.md new file mode 100644 index 000000000..2f2a7a5b8 --- /dev/null +++ b/docs/compat/reference/function/curry.md @@ -0,0 +1,222 @@ +# curry (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `curry` or manual closures +This `curry` function performs slowly due to complex placeholder handling, arity validation, and argument composition logic. + +If you don't need placeholders, use the faster `es-toolkit`'s [`curry`](../../../reference/function/curry.md) or simple closures instead. +::: + +Curries a function so it can accept arguments one at a time or multiple at once. + +```typescript +const curriedFunction = curry(func, arity); +``` + +## Usage + +### `curry(func, arity)` + +Use `curry` when you want to curry a function to make partial application easier. It's useful for providing arguments step by step or using placeholders to provide arguments at specific positions later. + +```typescript +import { curry } from 'es-toolkit/compat'; + +// Basic usage +function add(a, b, c) { + return a + b + c; +} + +const curriedAdd = curry(add); + +// Can be called in various ways +console.log(curriedAdd(1)(2)(3)); // 6 +console.log(curriedAdd(1, 2)(3)); // 6 +console.log(curriedAdd(1)(2, 3)); // 6 +console.log(curriedAdd(1, 2, 3)); // 6 +``` + +Comparison with main library curry: + +```typescript +// compat version (flexible, but slower) +import { curry } from 'es-toolkit/compat'; +const curriedCompat = curry(add); +curriedCompat(1, 2)(3); // supported +curriedCompat(1)(curry.placeholder, 3)(2); // placeholder support + +// main library version (faster, but one at a time only) +import { curry } from 'es-toolkit'; +const curriedMain = curry(add); +curriedMain(1)(2)(3); // supported +curriedMain(1, 2)(3); // not supported +``` + +Using placeholder feature: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function greet(greeting, name, punctuation) { + return `${greeting}, ${name}${punctuation}`; +} + +const curriedGreet = curry(greet); + +// Skip middle arguments with placeholder +const greetWithExclamation = curriedGreet(curry.placeholder, curry.placeholder, '!'); +console.log(greetWithExclamation('Hello', 'John')); // "Hello, John!" + +const sayHello = curriedGreet('Hello'); +console.log(sayHello(curry.placeholder, '~')('Jane')); // "Hello, Jane~" +``` + +Using in functional programming: + +```typescript +import { curry } from 'es-toolkit/compat'; + +// Create mapping functions +const map = curry((fn, array) => array.map(fn)); +const filter = curry((predicate, array) => array.filter(predicate)); + +const numbers = [1, 2, 3, 4, 5]; + +// Create reusable functions +const double = x => x * 2; +const isEven = x => x % 2 === 0; + +const mapDouble = map(double); +const filterEven = filter(isEven); + +console.log(mapDouble(numbers)); // [2, 4, 6, 8, 10] +console.log(filterEven(numbers)); // [2, 4] + +// Function composition +const processNumbers = nums => mapDouble(filterEven(nums)); +console.log(processNumbers(numbers)); // [4, 8] +``` + +Configuring API client: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function apiRequest(method, baseUrl, endpoint, options) { + return fetch(`${baseUrl}${endpoint}`, { + method, + ...options, + }); +} + +const curriedApiRequest = curry(apiRequest); + +// Create specialized functions with default settings +const apiGet = curriedApiRequest('GET', 'https://api.example.com'); +const apiPost = curriedApiRequest('POST', 'https://api.example.com'); + +// Include authentication headers +const authenticatedPost = apiPost(curry.placeholder, { + headers: { Authorization: 'Bearer token123' }, +}); + +// Usage +apiGet('/users'); // GET https://api.example.com/users +authenticatedPost('/users'); // POST with auth headers +``` + +Mathematical operation functions: + +```typescript +import { curry } from 'es-toolkit/compat'; + +const calculate = curry((operation, a, b) => { + switch (operation) { + case '+': + return a + b; + case '-': + return a - b; + case '*': + return a * b; + case '/': + return a / b; + default: + throw new Error('Unsupported operation'); + } +}); + +// Specialized operation functions +const add = calculate('+'); +const subtract = calculate('-'); +const multiply = calculate('*'); + +console.log(add(5, 3)); // 8 +console.log(subtract(10)(4)); // 6 +console.log(multiply(3, 4)); // 12 + +// Fix second operand with placeholder +const addFive = calculate('+', curry.placeholder, 5); +console.log(addFive(10)); // 15 +``` + +Specifying arity: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function variableArgsFunction(a, b, c, ...rest) { + return [a, b, c, rest]; +} + +// Limit arity to 3 +const curriedFixed = curry(variableArgsFunction, 3); + +console.log(curriedFixed(1)(2)(3)); // [1, 2, 3, []] +console.log(curriedFixed(1, 2)(3)); // [1, 2, 3, []] + +// Use without arity (default: function.length) +const curriedDefault = curry(variableArgsFunction); // arity = 3 +``` + +Simple currying alternative: + +```typescript +// Using curry +const curriedAdd = curry((a, b, c) => a + b + c); + +// Manual closure (faster) +const manualCurry = a => b => c => a + b + c; + +// Both produce the same result +console.log(curriedAdd(1)(2)(3)); // 6 +console.log(manualCurry(1)(2)(3)); // 6 +``` + +Constructor functions are also supported: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function Person(name, age, city) { + this.name = name; + this.age = age; + this.city = city; +} + +const CurriedPerson = curry(Person); +const SeoulPerson = CurriedPerson(curry.placeholder, curry.placeholder, 'Seoul'); + +const person1 = new SeoulPerson('John', 30); +const person2 = new SeoulPerson('Jane', 25); + +console.log(person1.city); // "Seoul" +console.log(person2.city); // "Seoul" +``` + +#### Parameters + +- `func` (`Function`): The function to curry. +- `arity` (`number`, optional): The arity (number of arguments) of the function. If omitted, `func.length` is used. + +#### Returns + +(`Function & { placeholder: symbol }`): Returns the curried function. The `placeholder` property allows you to control argument positions. diff --git a/docs/compat/reference/function/curryRight.md b/docs/compat/reference/function/curryRight.md new file mode 100644 index 000000000..71331c722 --- /dev/null +++ b/docs/compat/reference/function/curryRight.md @@ -0,0 +1,242 @@ +# curryRight (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [`curryRight`](../../../reference/function/curryRight.md) or manual closures instead + +This `curryRight` function operates slowly due to complex placeholder handling, arity validation, and argument composition logic. + +If you don't need placeholders, use the faster `es-toolkit`'s [`curryRight`](../../../reference/function/curryRight.md) or simple closures instead. + +::: + +Curries a function from right to left, creating a function that accepts arguments one at a time or several at a time, starting from the last argument. + +```typescript +const curriedFunction = curryRight(func, arity); +``` + +## Usage + +### `curryRight(func, arity)` + +Use `curryRight` when you want to curry a function from right to left and partially apply arguments starting from the last one. Unlike regular `curry`, it processes arguments starting from the last one first. + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// Basic usage +function subtract(a, b, c) { + return a - b - c; +} + +const curriedSubtract = curryRight(subtract); + +// Currying from right (starting from last argument) +console.log(curriedSubtract(1)(2)(5)); // 5 - 2 - 1 = 2 +console.log(curriedSubtract(1, 2)(5)); // 5 - 2 - 1 = 2 +console.log(curriedSubtract(1)(2, 5)); // 2 - 5 - 1 = -4 +console.log(curriedSubtract(1, 2, 5)); // 1 - 2 - 5 = -6 +``` + +Difference between `curry` and `curryRight`: + +```typescript +import { curry, curryRight } from 'es-toolkit/compat'; + +function divide(a, b, c) { + return a / b / c; +} + +// Regular curry (from left) +const leftCurried = curry(divide); +console.log(leftCurried(12)(3)(2)); // ((12 / 3) / 2) = 2 + +// curryRight (from right) +const rightCurried = curryRight(divide); +console.log(rightCurried(2)(3)(12)); // ((12 / 3) / 2) = 2 +// The last provided 12 becomes the first argument (a) +``` + +Comparison with main library: + +```typescript +// compat version (flexible, but slower) +import { curryRight } from 'es-toolkit/compat'; +const curriedCompat = curryRight(subtract); +curriedCompat(1, 2)(3); // supported +curriedCompat(1)(curryRight.placeholder, 3)(2); // placeholder supported + +// main library version (faster, but one at a time only) +import { curryRight } from 'es-toolkit'; +const curriedMain = curryRight(subtract); +curriedMain(1)(2)(3); // supported +curriedMain(1, 2)(3); // not supported +``` + +Using placeholder feature: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function formatMessage(name, action, time) { + return `${name} did ${action} at ${time}`; +} + +const curriedFormat = curryRight(formatMessage); + +// Skip specific positions with placeholder +const todayAction = curriedFormat('today'); +const todayLoginAction = todayAction(curryRight.placeholder, 'login'); + +console.log(todayLoginAction('John')); +// "John did login at today" + +// Fix time first +const morningFormat = curriedFormat('9 AM'); +console.log(morningFormat('comment', 'Jane')); +// "Jane did comment at 9 AM" +``` + +Using in array processing: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// Take a specific number of items from the end of an array +function takeFromEnd(array, count, separator = ', ') { + return array.slice(-count).join(separator); +} + +const curriedTake = curryRight(takeFromEnd); + +// Create function that separates with comma +const takeWithComma = curriedTake(', '); + +// Get last 3 items +const takeLast3 = takeWithComma(3); + +const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']; +console.log(takeLast3(fruits)); // "orange, grape, kiwi" + +// Use different separator +const takeWithDash = curriedTake(' - '); +console.log(takeWithDash(2, fruits)); // "grape - kiwi" +``` + +Using in function composition: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// Log output function +function logWithPrefix(message, level, timestamp) { + return `[${timestamp}] ${level}: ${message}`; +} + +const curriedLog = curryRight(logWithPrefix); + +// Fix with current time +const currentTimeLog = curriedLog(new Date().toISOString()); + +// Create loggers by level +const errorLog = currentTimeLog('ERROR'); +const infoLog = currentTimeLog('INFO'); +const debugLog = currentTimeLog('DEBUG'); + +// Usage +console.log(errorLog('Database connection failed')); +console.log(infoLog('Server started')); +console.log(debugLog('Processing user request')); +``` + +Functional programming pipeline: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// Data transformation functions +const mapWith = curryRight((array, fn) => array.map(fn)); +const filterWith = curryRight((array, predicate) => array.filter(predicate)); +const reduceWith = curryRight((array, reducer, initial) => array.reduce(reducer, initial)); + +const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + +// Define transformation functions +const double = x => x * 2; +const isEven = x => x % 2 === 0; +const sum = (acc, val) => acc + val; + +// Compose pipeline (right first) +const processNumbers = nums => { + return reduceWith(filterWith(mapWith(nums, double), isEven), sum, 0); +}; + +console.log(processNumbers(numbers)); // Double all numbers, filter even ones, then sum +``` + +API request builder: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function makeRequest(url, method, headers, body) { + return fetch(url, { method, headers, body }); +} + +const curriedRequest = curryRight(makeRequest); + +// Set body first +const withJsonBody = curriedRequest(JSON.stringify({ data: 'test' })); + +// Add headers +const withHeaders = withJsonBody({ + 'Content-Type': 'application/json', + Authorization: 'Bearer token123', +}); + +// Set POST method +const postRequest = withHeaders('POST'); + +// Final usage +postRequest('/api/data') + .then(response => response.json()) + .then(data => console.log(data)); +``` + +Manual currying alternative: + +```typescript +// Using curryRight +const curriedSubtract = curryRight((a, b, c) => a - b - c); + +// Manual closure (faster, from right) +const manualCurryRight = c => b => a => a - b - c; + +// Both give same result +console.log(curriedSubtract(1)(2)(5)); // 2 +console.log(manualCurryRight(1)(2)(5)); // 2 +``` + +Specifying arity: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function variableArgsFunction(a, b, c, ...rest) { + return { a, b, c, rest }; +} + +// Limit arity to 3 (ignore rest) +const curriedFixed = curryRight(variableArgsFunction, 3); + +// Receive in order c, b, a from right +console.log(curriedFixed(3)(2)(1)); // { a: 1, b: 2, c: 3, rest: [] } +``` + +#### Parameters + +- `func` (`Function`): The function to curry from right to left. +- `arity` (`number`, optional): The arity (number of arguments) of the function. If omitted, `func.length` is used. + +#### Returns + +(`Function & { placeholder: symbol }`): Returns a function curried from right to left. The `placeholder` property can be used to control argument positions. diff --git a/docs/compat/reference/function/debounce.md b/docs/compat/reference/function/debounce.md new file mode 100644 index 000000000..1187a168c --- /dev/null +++ b/docs/compat/reference/function/debounce.md @@ -0,0 +1,264 @@ +# debounce (Lodash compatibility) + +::: warning Use [`debounce`](../../../reference/function/debounce.md) from `es-toolkit` + +This `debounce` function has overhead due to complex `maxWait` handling and Lodash-compatible option structure. + +Instead, use the faster and more modern [`debounce`](../../../reference/function/debounce.md) from `es-toolkit`. + +::: + +Creates a debounced function that delays invoking the provided function until after `wait` milliseconds have elapsed since the last time it was invoked. + +```typescript +const debouncedFunction = debounce(func, wait, options); +``` + +## Usage + +### `debounce(func, wait, options)` + +Use `debounce` when you want to delay function invocation. It's useful for preventing excessive calls in search inputs, scroll events, button clicks, etc. + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// Basic usage +const searchFunction = debounce(query => { + console.log('Searching:', query); +}, 300); + +// Only executes if not called again within 300ms +searchFunction('React'); // Not executed +searchFunction('Vue'); // Not executed +searchFunction('Angular'); // Logs "Searching: Angular" after 300ms +``` + +Comparison with main library debounce: + +```typescript +// compat version (Lodash compatible, additional options like maxWait) +import { debounce } from 'es-toolkit/compat'; +const debouncedCompat = debounce(func, 300, { + leading: true, + trailing: false, + maxWait: 1000 +}); + +// Main library version (faster, simpler) +import { debounce } from 'es-toolkit'; +const debouncedMain = debounce(func, 300, { + edges: ['leading'] // Uses edges instead of leading/trailing +}); +``` + +Leading and trailing options: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const func = () => console.log('Executed'); + +// leading: true - Execute immediately on first call +const leadingDebounce = debounce(func, 1000, { leading: true }); +leadingDebounce(); // Immediately logs "Executed" +leadingDebounce(); // Wait 1 second +// No additional execution after 1 second + +// trailing: true (default) - Execute after delay following last call +const trailingDebounce = debounce(func, 1000, { trailing: true }); +trailingDebounce(); // Wait 1 second +trailingDebounce(); // Wait 1 second (cancels previous timer) +// Logs "Executed" after 1 second + +// Both true - Execute at start and end +const bothDebounce = debounce(func, 1000, { + leading: true, + trailing: true, +}); +bothDebounce(); // Immediately logs "Executed" +bothDebounce(); // Wait 1 second +// Logs "Executed" after 1 second (trailing) +``` + +maxWait option: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// Guarantees execution at least every 2 seconds +const debouncedWithMaxWait = debounce(() => console.log('Saved'), 500, { maxWait: 2000 }); + +// Even with rapid consecutive calls, executes every 2 seconds +setInterval(() => { + debouncedWithMaxWait(); +}, 100); // Calls every 100ms but logs "Saved" every 2 seconds +``` + +Real-world search example: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +class SearchComponent { + constructor() { + this.searchInput = document.getElementById('search'); + + // Debounce user input by 300ms + this.debouncedSearch = debounce(this.performSearch.bind(this), 300, { + leading: false, // Don't search immediately on input start + trailing: true, // Search after input stops + }); + + this.searchInput.addEventListener('input', e => { + this.debouncedSearch(e.target.value); + }); + } + + performSearch(query) { + if (query.length < 2) return; + + console.log('API call:', query); + // fetch(`/api/search?q=${query}`)... + } +} +``` + +Scroll event optimization: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// Debounce scroll events by 100ms, but execute at least every 500ms +const optimizedScrollHandler = debounce( + () => { + const scrollTop = window.pageYOffset; + console.log('Scroll position:', scrollTop); + + // Header hide/show logic + if (scrollTop > 100) { + document.header.classList.add('hidden'); + } else { + document.header.classList.remove('hidden'); + } + }, + 100, + { maxWait: 500 } +); + +window.addEventListener('scroll', optimizedScrollHandler); +``` + +API call throttling: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +class AutoSave { + constructor() { + // Debounce by 500ms, save at least every 5 seconds + this.debouncedSave = debounce(this.saveToServer.bind(this), 500, { maxWait: 5000 }); + } + + onTextChange(content) { + this.pendingContent = content; + this.debouncedSave(); + } + + saveToServer() { + if (!this.pendingContent) return; + + console.log('Saving to server:', this.pendingContent); + // fetch('/api/save', { ... }) + + this.pendingContent = null; + } +} +``` + +cancel and flush methods: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const debouncedFunc = debounce(() => { + console.log('Executed'); +}, 1000); + +debouncedFunc(); // Waiting 1 second + +// Cancel pending execution +debouncedFunc.cancel(); + +// Or execute immediately +debouncedFunc(); // Start waiting 1 second +debouncedFunc.flush(); // Immediately logs "Executed" and cancels timer +``` + +Preventing duplicate button clicks: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const handleSubmit = debounce( + async formData => { + console.log('Submitting form...'); + try { + const response = await fetch('/api/submit', { + method: 'POST', + body: formData, + }); + console.log('Submission complete'); + } catch (error) { + console.error('Submission failed:', error); + } + }, + 1000, + { leading: true, trailing: false } // Only handle first click +); + +document.getElementById('submit-btn').addEventListener('click', e => { + const formData = new FormData(e.target.form); + handleSubmit(formData); +}); +``` + +Resize event handling: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const handleResize = debounce( + () => { + const width = window.innerWidth; + const height = window.innerHeight; + + console.log('Window resized:', { width, height }); + + // Recalculate layout + recalculateLayout(); + }, + 250, + { leading: false, trailing: true } +); + +window.addEventListener('resize', handleResize); + +// Cleanup on page unload +window.addEventListener('beforeunload', () => { + handleResize.cancel(); +}); +``` + +#### Parameters + +- `func` (`Function`): The function to debounce. +- `wait` (`number`, optional): The number of milliseconds to delay. Defaults to `0`. +- `options` (`DebounceSettings`, optional): An options object. + - `leading` (`boolean`): If `true`, executes the function at the start of the delay. Defaults to `false`. + - `trailing` (`boolean`): If `true`, executes the function at the end of the delay. Defaults to `true`. + - `maxWait` (`number`): The maximum time the function execution can be delayed. Defaults to `Infinity`. + +#### Returns + +(`DebouncedFunc`): Returns the debounced function. It includes `cancel()` and `flush()` methods. diff --git a/docs/reference/compat/function/defer.md b/docs/compat/reference/function/defer.md similarity index 100% rename from docs/reference/compat/function/defer.md rename to docs/compat/reference/function/defer.md diff --git a/docs/reference/compat/function/delay.md b/docs/compat/reference/function/delay.md similarity index 100% rename from docs/reference/compat/function/delay.md rename to docs/compat/reference/function/delay.md diff --git a/docs/reference/compat/function/flip.md b/docs/compat/reference/function/flip.md similarity index 100% rename from docs/reference/compat/function/flip.md rename to docs/compat/reference/function/flip.md diff --git a/docs/compat/reference/function/flow.md b/docs/compat/reference/function/flow.md new file mode 100644 index 000000000..a2f6c792c --- /dev/null +++ b/docs/compat/reference/function/flow.md @@ -0,0 +1,87 @@ +# flow (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `flow` +This `flow` function has become complex with added array flattening for Lodash compatibility. + +Instead, use the faster and more modern `es-toolkit`'s [flow](../../../reference/function/flow.md). +::: + +Creates a new function that executes the given functions from left to right sequentially. + +```typescript +const combinedFunc = flow(...functions); +``` + +## Usage + +### `flow(...functions)` + +Use `flow` when you want to create a single composed function that executes multiple functions from left to right sequentially. It's useful for creating data transformation pipelines. + +```typescript +import { flow } from 'es-toolkit/compat'; + +// Basic usage +function add(x, y) { + return x + y; +} + +function square(n) { + return n * n; +} + +function double(n) { + return n * 2; +} + +// Executes from left to right: double(square(add(x, y))) +const calculate = flow(add, square, double); +console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 + +// Passing functions as an array +const calculate2 = flow([add, square], double); +console.log(calculate2(2, 3)); // 50 + +// Modern alternative (recommended) +const modernCalculate = (x, y) => double(square(add(x, y))); +console.log(modernCalculate(1, 2)); // 18 + +// Using pipe operator (future JavaScript) +const pipeCalculate = (x, y) => add(x, y) |> square |> double; + +// Or chaining pattern +class Calculator { + constructor(value) { + this.value = value; + } + + add(n) { + this.value += n; + return this; + } + + square() { + this.value *= this.value; + return this; + } + + double() { + this.value *= 2; + return this; + } + + valueOf() { + return this.value; + } +} + +const chainedResult = new Calculator(3).square().double().valueOf(); // 18 +``` + +#### Parameters + +- `...functions` (`Array`): Functions to execute from left to right. Can be passed as arrays. + +#### Returns + +(`Function`): Returns a new composed function that executes all functions from left to right sequentially. diff --git a/docs/compat/reference/function/flowRight.md b/docs/compat/reference/function/flowRight.md new file mode 100644 index 000000000..5bf401add --- /dev/null +++ b/docs/compat/reference/function/flowRight.md @@ -0,0 +1,65 @@ +# flowRight (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `flowRight` +This `flowRight` function has become complex with added array flattening for Lodash compatibility. + +Instead, use the faster and more modern `es-toolkit`'s [flowRight](../../../reference/function/flowRight.md). +::: + +Creates a new function that executes the given functions from right to left sequentially. + +```typescript +const combinedFunc = flowRight(...functions); +``` + +## Usage + +### `flowRight(...functions)` + +Use `flowRight` when you want to create a single composed function that executes multiple functions from right to left sequentially. It's useful for creating data transformation pipelines. + +```typescript +import { flowRight } from 'es-toolkit/compat'; + +// Basic usage +function add(x, y) { + return x + y; +} + +function square(n) { + return n * n; +} + +function double(n) { + return n * 2; +} + +// Executes from right to left: double(square(add(x, y))) +const calculate = flowRight(double, square, add); +console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 + +// Passing functions as an array +const calculate2 = flowRight([double, square], add); +console.log(calculate2(2, 3)); // 50 + +// Modern alternative (recommended) +const modernCalculate = (x, y) => double(square(add(x, y))); +console.log(modernCalculate(1, 2)); // 18 + +// Or using function chaining +const chainedCalculate = (x, y) => [x, y] + .reduce((acc, val, idx) => idx === 0 ? val : acc + val) + .valueOf() + |> (n => n * n) + |> (n => n * 2); +``` + +Generally works in the opposite order of `flow`. It works similarly to function composition, making it intuitive. + +#### Parameters + +- `...functions` (`Array`): Functions to execute from right to left. Can be passed as arrays. + +#### Returns + +(`Function`): Returns a new composed function that executes all functions from right to left sequentially. diff --git a/docs/compat/reference/function/identity.md b/docs/compat/reference/function/identity.md new file mode 100644 index 000000000..785fcfa4f --- /dev/null +++ b/docs/compat/reference/function/identity.md @@ -0,0 +1,62 @@ +# identity (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `identity` +This `identity` function has the same functionality in the main `es-toolkit` library. It simply returns the input value as is. + +Instead, use the faster and more modern `es-toolkit`'s [identity](../../../reference/function/identity.md). +::: + +Returns the received value as is. + +```typescript +const result = identity(value); +``` + +## Usage + +### `identity(value)` + +Use `identity` when you want to return the received value as is. It's mainly used as a default value or placeholder function, and is frequently used in functional programming. + +```typescript +import { identity } from 'es-toolkit/compat'; + +// Basic usage +console.log(identity(5)); // 5 +console.log(identity('hello')); // 'hello' +console.log(identity({ key: 'value' })); // { key: 'value' } + +// Use with array's map (value copy) +const numbers = [1, 2, 3, 4, 5]; +const copied = numbers.map(identity); +console.log(copied); // [1, 2, 3, 4, 5] + +// Use as default value in filtering +const values = [1, 0, '', 'hello', null, undefined, false, true]; +const filtered = values.filter(identity); // Keep only truthy values +console.log(filtered); // [1, 'hello', true] + +// Use as default transformation function +function processData(data, transform = identity) { + return transform(data); +} + +console.log(processData('hello')); // 'hello' +console.log(processData('hello', x => x.toUpperCase())); // 'HELLO' +``` + +In most cases, it can be replaced with a simpler arrow function `x => x`: + +```typescript +// Using arrow function instead of identity (recommended) +const copied = numbers.map(x => x); +const filtered = values.filter(x => x); +``` + +#### Parameters + +- `value` (`T`): The value to return. + +#### Returns + +(`T`): Returns the received value as is. diff --git a/docs/compat/reference/function/memoize.md b/docs/compat/reference/function/memoize.md new file mode 100644 index 000000000..5d56205aa --- /dev/null +++ b/docs/compat/reference/function/memoize.md @@ -0,0 +1,66 @@ +# memoize (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `memoize` +This `memoize` function operates slowly due to `null` checks in the `resolver` function, complex type handling for the `MapCache` interface, and additional overhead for Lodash compatibility. + +Instead, use the faster and more modern `es-toolkit`'s [memoize](../../../reference/function/memoize.md). +::: + +Caches function results to improve performance when called with the same arguments. + +```typescript +const memoizedFunc = memoize(func, resolver); +``` + +## Usage + +### `memoize(func, resolver)` + +Use `memoize` when you want to memoize function results to reuse previous results when called with the same arguments. It's useful for expensive calculations or API calls. + +```typescript +import { memoize } from 'es-toolkit/compat'; + +// Basic usage +function expensiveCalculation(n) { + console.log('Calculating...', n); + return n * n; +} + +const memoizedCalc = memoize(expensiveCalculation); + +console.log(memoizedCalc(5)); // 'Calculating... 5', 25 +console.log(memoizedCalc(5)); // 25 (cached result, no calculation) +console.log(memoizedCalc(10)); // 'Calculating... 10', 100 + +// Using custom resolver +function fetchUserData(userId, includeProfile) { + console.log('Fetching user data...', userId, includeProfile); + return { id: userId, profile: includeProfile ? 'Profile data' : null }; +} + +// Generate cache key considering all arguments +const memoizedFetch = memoize(fetchUserData, (userId, includeProfile) => { + return `${userId}_${includeProfile}`; +}); + +memoizedFetch(1, true); // 'Fetching user data... 1 true' +memoizedFetch(1, true); // Uses cached result +memoizedFetch(1, false); // 'Fetching user data... 1 false' (different cache key) + +// Accessing and modifying cache +console.log(memoizedCalc.cache.get(5)); // 25 +memoizedCalc.cache.set(7, 49); // Manually set cache +console.log(memoizedCalc(7)); // 49 (uses cached value without calculation) +``` + +In most cases, it uses a basic hash map, but you can also use custom cache implementations as needed. + +#### Parameters + +- `func` (`Function`): The function to memoize. +- `resolver` (`Function`, optional): The function to determine the cache key. If not provided, uses the first argument as the key. + +#### Returns + +(`Function & { cache: MapCache }`): Returns the memoized function. The returned function has a `cache` property for direct cache access. diff --git a/docs/reference/compat/function/negate.md b/docs/compat/reference/function/negate.md similarity index 100% rename from docs/reference/compat/function/negate.md rename to docs/compat/reference/function/negate.md diff --git a/docs/compat/reference/function/noop.md b/docs/compat/reference/function/noop.md new file mode 100644 index 000000000..4a190f25e --- /dev/null +++ b/docs/compat/reference/function/noop.md @@ -0,0 +1,60 @@ +# noop (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `noop` + +`es-toolkit` also has a [noop](../../../reference/function/noop.md) function that behaves the same. + +::: + +An empty function that does nothing. + +```typescript +noop(); +``` + +## Usage + +### `noop(...args)` + +Use `noop` when you need a placeholder function that does nothing. It's often used as a default value or callback function. + +```typescript +import { noop } from 'es-toolkit/compat'; + +// Basic usage +noop(); // Does nothing +noop(1, 2, 3); // Accepts arguments but does nothing + +// Use as default callback +function processData(data, callback = noop) { + // Process data + console.log('Processing data...', data); + + // Call callback (noop if not provided) + callback(data); +} + +processData('test'); // Works without errors even if callback not provided + +// Modern alternative (recommended) +function modernProcessData(data, callback = () => {}) { + console.log('Processing data...', data); + callback(data); +} + +// Or use optional callback +function processDataOptional(data, callback) { + console.log('Processing data...', data); + callback?.(data); // Only call if callback is provided +} +``` + +Useful in situations where a default value or placeholder is needed, but in modern JavaScript, it's more common to use optional chaining (`?.`) or default parameters. + +#### Parameters + +- `...args` (`any[]`): Can accept any arguments, but all are ignored. + +#### Returns + +(`void`): Returns nothing. diff --git a/docs/reference/compat/function/nthArg.md b/docs/compat/reference/function/nthArg.md similarity index 100% rename from docs/reference/compat/function/nthArg.md rename to docs/compat/reference/function/nthArg.md diff --git a/docs/compat/reference/function/once.md b/docs/compat/reference/function/once.md new file mode 100644 index 000000000..bd67344c0 --- /dev/null +++ b/docs/compat/reference/function/once.md @@ -0,0 +1,56 @@ +# once (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `once` + +This `once` function has the same functionality as the main library [once](../../../reference/function/once.md) function in `es-toolkit`. + +::: + +Restricts a function to be called only once. + +```typescript +const limitedFunc = once(func); +``` + +## Usage + +### `once(func)` + +Use `once` when you want to restrict a function to be called only once. After the first call, the result is cached and the same value is returned. + +```typescript +import { once } from 'es-toolkit/compat'; + +// Basic usage +let count = 0; +const increment = once(() => { + count++; + console.log('Counter incremented:', count); + return count; +}); + +increment(); // Outputs 'Counter incremented: 1', returns 1 +increment(); // Outputs nothing, returns 1 +increment(); // Outputs nothing, returns 1 + +// Practical example - initialization function +const initialize = once(() => { + console.log('Initializing application...'); + // Expensive initialization operations + return 'Initialization complete'; +}); + +// Even if called multiple times, initialization runs only once +initialize(); // Outputs 'Initializing application...' +initialize(); // Outputs nothing +``` + +It's useful when creating expensive initialization operations or setup functions. For example, it can be used for database connections, API token initialization, etc. + +#### Parameters + +- `func` (`Function`): The function to restrict to only one call. + +#### Returns + +(`Function`): Returns a new function that is called only once. From the second call onwards, it returns the result of the first call. diff --git a/docs/reference/compat/function/overArgs.md b/docs/compat/reference/function/overArgs.md similarity index 100% rename from docs/reference/compat/function/overArgs.md rename to docs/compat/reference/function/overArgs.md diff --git a/docs/compat/reference/function/partial.md b/docs/compat/reference/function/partial.md new file mode 100644 index 000000000..8bd02e632 --- /dev/null +++ b/docs/compat/reference/function/partial.md @@ -0,0 +1,59 @@ +# partial (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `partial` + +This `partial` function is inefficient due to many overloads and union type handling. In most cases, it can be replaced with a simpler arrow function. + +Instead, use the faster and more modern [`partial`](../../../reference/function/partial.md) from `es-toolkit`. + +::: + +Creates a partially applied function by pre-filling some arguments. + +```typescript +const partialFunc = partial(func, ...args); +``` + +## Usage + +### `partial(func, ...args)` + +Use `partial` when you want to create a partially applied function by pre-filling some arguments. It's mainly useful for fixing the first arguments when argument order matters. + +```typescript +import { partial } from 'es-toolkit/compat'; + +// Basic usage +function greet(greeting, name, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// Pre-set the first argument +const sayHello = partial(greet, 'Hello'); +sayHello('Alice', '!'); // 'Hello Alice!' + +// Pre-set multiple arguments +const greetAlice = partial(greet, 'Hello', 'Alice'); +greetAlice('!'); // 'Hello Alice!' + +// Use placeholder to control argument order +const greetWithExclamation = partial(greet, partial.placeholder, 'Alice', '!'); +greetWithExclamation('Hi'); // 'Hi Alice!' +``` + +In most cases, it can be replaced with arrow functions: + +```typescript +// Use arrow functions instead of partial (recommended) +const sayHello = (name, punctuation) => greet('Hello', name, punctuation); +const greetAlice = punctuation => greet('Hello', 'Alice', punctuation); +``` + +#### Parameters + +- `func` (`Function`): The function to partially apply. +- `...args` (`any[]`): The arguments to pre-fill. Use `partial.placeholder` to control argument order. + +#### Returns + +(`Function`): Returns a new function with pre-filled arguments. diff --git a/docs/compat/reference/function/partialRight.md b/docs/compat/reference/function/partialRight.md new file mode 100644 index 000000000..443f38866 --- /dev/null +++ b/docs/compat/reference/function/partialRight.md @@ -0,0 +1,59 @@ +# partialRight (Lodash Compatibility) + +::: warning Use `es-toolkit`'s `partialRight` + +This `partialRight` function is inefficient due to many overloads and union type handling. In most cases, it can be replaced with a simpler arrow function. + +Instead, use the faster and more modern [`partialRight`](../../../reference/function/partialRight.md) from `es-toolkit`. + +::: + +Creates a partially applied function by pre-filling arguments from the right. + +```typescript +const partialFunc = partialRight(func, ...args); +``` + +## Usage + +### `partialRight(func, ...args)` + +Use `partialRight` when you want to create a partially applied function by pre-filling arguments from the right. It's mainly useful for fixing the last arguments when argument order matters. + +```typescript +import { partialRight } from 'es-toolkit/compat'; + +// Basic usage +function greet(greeting, name, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// Pre-set the last argument +const greetWithExclamation = partialRight(greet, '!'); +greetWithExclamation('Hello', 'Alice'); // 'Hello Alice!' + +// Pre-set multiple arguments +const sayHiToAlice = partialRight(greet, 'Alice', '!'); +sayHiToAlice('Hi'); // 'Hi Alice!' + +// Use placeholder to control argument order +const greetAliceWithCustom = partialRight(greet, 'Alice', partialRight.placeholder); +greetAliceWithCustom('Hello', '?'); // 'Hello Alice?' +``` + +In most cases, it can be replaced with arrow functions: + +```typescript +// Use arrow functions instead of partialRight (recommended) +const greetWithExclamation = (greeting, name) => greet(greeting, name, '!'); +const sayHiToAlice = greeting => greet(greeting, 'Alice', '!'); +``` + +#### Parameters + +- `func` (`Function`): The function to partially apply. +- `...args` (`any[]`): The arguments to pre-fill. Use `partialRight.placeholder` to control argument order. + +#### Returns + +(`Function`): Returns a new function with arguments pre-filled from the right. diff --git a/docs/reference/compat/function/rearg.md b/docs/compat/reference/function/rearg.md similarity index 100% rename from docs/reference/compat/function/rearg.md rename to docs/compat/reference/function/rearg.md diff --git a/docs/compat/reference/function/rest.md b/docs/compat/reference/function/rest.md new file mode 100644 index 000000000..2ddfff9ad --- /dev/null +++ b/docs/compat/reference/function/rest.md @@ -0,0 +1,54 @@ +# rest (Lodash Compatibility) + +::: warning Use `rest` from `es-toolkit` instead + +This `rest` function may have reduced performance due to additional logic such as default value handling and index validation. + +Use faster, more modern [rest](../../../reference/function/rest.md) from `es-toolkit` instead. + +::: + +Creates a function that groups the remaining arguments from a specified index into an array. + +```typescript +const restFunc = rest(func, start); +``` + +## Usage + +### `rest(func, start)` + +Use `rest` when you want to transform function arguments by grouping the remaining arguments from a specified index into an array. It's useful for creating variadic functions. + +```typescript +import { rest } from 'es-toolkit/compat'; + +// Basic usage - group the last arguments into an array +function logMessage(level, message, ...details) { + console.log(`[${level}] ${message}`, details); +} + +const restLogger = rest(logMessage, 2); +restLogger('ERROR', 'Error occurred', 'Detail 1', 'Detail 2'); +// Internally calls logMessage('ERROR', 'Error occurred', [['Detail 1', 'Detail 2']]) + +// Different index example +function process(action, target, ...args) { + return { action, target, args }; +} + +const restProcess = rest(process, 1); +restProcess('update', 'user', 'name', 'John', 'age', 25); +// { action: 'update', target: ['user', 'name', 'John', 'age', 25], args: [] } +``` + +Use this when you want the last arguments of a function to be received as an array. In modern JavaScript, it's more common to use rest parameter syntax (`...args`). + +#### Parameters + +- `func` (`Function`): The function to transform. +- `start` (`number`, optional): The index from which to start grouping arguments into an array. Default is `func.length - 1`. + +#### Returns + +(`Function`): Returns a new function that groups the remaining arguments from the specified index into an array. diff --git a/docs/reference/compat/function/spread.md b/docs/compat/reference/function/spread.md similarity index 100% rename from docs/reference/compat/function/spread.md rename to docs/compat/reference/function/spread.md diff --git a/docs/compat/reference/function/throttle.md b/docs/compat/reference/function/throttle.md new file mode 100644 index 000000000..a800e9013 --- /dev/null +++ b/docs/compat/reference/function/throttle.md @@ -0,0 +1,52 @@ +# throttle (Lodash Compatibility) + +::: warning Use `throttle` from `es-toolkit` instead + +This `throttle` function uses the debounce function internally for Lodash compatibility, making it somewhat complex. It also has more complex default and option handling. + +Use faster, more modern [throttle](../../../reference/function/throttle.md) from `es-toolkit` instead. + +::: + +Limits function calls to execute at most once per specified time interval. + +```typescript +const throttledFunc = throttle(func, wait, options); +``` + +## Usage + +### `throttle(func, wait, options)` + +Use `throttle` when you want to limit function calls to execute at most once per specified time interval. It's useful for limiting the frequency of event handlers or API calls. + +```typescript +import { throttle } from 'es-toolkit/compat'; + +// Basic usage - execute at most once per second +const throttledLog = throttle(() => { + console.log('Event occurred!'); +}, 1000); + +// Example with options +const throttledScroll = throttle(handleScroll, 100, { + leading: true, // Execute immediately on first call + trailing: false, // Don't execute on last call +}); + +window.addEventListener('scroll', throttledScroll); +``` + +It's essential for performance when handling rapidly occurring events like scroll or resize events. + +#### Parameters + +- `func` (`Function`): The function to throttle. +- `wait` (`number`, optional): The wait time in milliseconds. Default is `0`. +- `options` (`ThrottleSettings`, optional): Throttling options. + - `leading` (`boolean`): Whether to execute on the first call. Default is `true`. + - `trailing` (`boolean`): Whether to execute after the last call. Default is `true`. + +#### Returns + +(`DebouncedFunc`): Returns the throttled function. You can cancel pending executions with the `cancel()` method. diff --git a/docs/compat/reference/function/unary.md b/docs/compat/reference/function/unary.md new file mode 100644 index 000000000..1d5989565 --- /dev/null +++ b/docs/compat/reference/function/unary.md @@ -0,0 +1,46 @@ +# unary (Lodash Compatibility) + +::: warning Use `ary` from `es-toolkit` instead + +This `unary` function is implemented as a special case of the `ary` function. If you need more control, it's more efficient to use [ary](../../../reference/function/ary.md) from `es-toolkit` directly. + +Use faster, more modern [ary](../../../reference/function/ary.md) from `es-toolkit` instead. + +::: + +Limits a function to accept at most one argument. + +```typescript +const limitedFunc = unary(func); +``` + +## Usage + +### `unary(func)` + +Use `unary` when you want to limit a function to accept at most one argument. Any additional arguments passed will be ignored. + +```typescript +import { unary } from 'es-toolkit/compat'; + +function greet(name, greeting, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// Convert to a function that accepts only the first argument +const greetOne = unary(greet); +greetOne('Alice', 'Hello', '!'); // Works the same as greet('Alice') + +// Useful when used with array's map function +const numbers = ['1', '2', '3']; +numbers.map(parseInt); // [1, NaN, NaN] - unexpected result +numbers.map(unary(parseInt)); // [1, 2, 3] - correct result +``` + +#### Parameters + +- `func` (`(...args: any[]) => any`): The function to limit arguments for. + +#### Returns + +(`(...args: any[]) => any`): Returns a new function that accepts at most one argument. diff --git a/docs/reference/compat/function/wrap.md b/docs/compat/reference/function/wrap.md similarity index 100% rename from docs/reference/compat/function/wrap.md rename to docs/compat/reference/function/wrap.md diff --git a/docs/reference/compat/math/add.md b/docs/compat/reference/math/add.md similarity index 100% rename from docs/reference/compat/math/add.md rename to docs/compat/reference/math/add.md diff --git a/docs/reference/compat/math/ceil.md b/docs/compat/reference/math/ceil.md similarity index 100% rename from docs/reference/compat/math/ceil.md rename to docs/compat/reference/math/ceil.md diff --git a/docs/compat/reference/math/clamp.md b/docs/compat/reference/math/clamp.md new file mode 100644 index 000000000..3e0f3c940 --- /dev/null +++ b/docs/compat/reference/math/clamp.md @@ -0,0 +1,82 @@ +# clamp (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [clamp](../../../reference/math/clamp.md) + +This `clamp` function operates slowly due to NaN validation and handling. + +Use the faster and more modern `es-toolkit`'s [clamp](../../../reference/math/clamp.md) instead. + +::: + +Clamps a number within the specified range. + +```typescript +const clamped = clamp(number, lower, upper); +``` + +## Usage + +### `clamp(number, lower, upper)` + +Use `clamp` when you want to restrict a number between a specified minimum and maximum value. + +```typescript +import { clamp } from 'es-toolkit/compat'; + +// Basic usage +clamp(3, 2, 4); +// Returns: 3 (within range) + +clamp(0, 5, 10); +// Returns: 5 (clamped to minimum) + +clamp(15, 5, 10); +// Returns: 10 (clamped to maximum) + +// Handles negative numbers +clamp(-5, -10, -1); +// Returns: -5 + +clamp(-15, -10, -1); +// Returns: -10 (clamped to minimum) +``` + +### `clamp(number, upper)` + +When only one argument is provided, it's used as the maximum value. + +```typescript +import { clamp } from 'es-toolkit/compat'; + +// Specifying only maximum +clamp(5, 3); +// Returns: 3 (clamped to maximum) + +clamp(2, 3); +// Returns: 2 (within range) + +clamp(1, 5); +// Returns: 1 +``` + +NaN values are treated as 0. + +```typescript +import { clamp } from 'es-toolkit/compat'; + +clamp(5, NaN, 10); +// Returns: 5 (NaN is treated as 0, so range is 0-10) + +clamp(5, 2, NaN); +// Returns: 2 (NaN is treated as 0, so range is 0-2) +``` + +#### Parameters + +- `number` (`number`): The number to clamp. +- `lower` (`number`): The minimum value. If only the second parameter is provided, it becomes the maximum value. +- `upper` (`number`, optional): The maximum value. + +#### Returns + +(`number`): Returns the number clamped within the specified range. diff --git a/docs/reference/compat/math/divide.md b/docs/compat/reference/math/divide.md similarity index 100% rename from docs/reference/compat/math/divide.md rename to docs/compat/reference/math/divide.md diff --git a/docs/reference/compat/math/floor.md b/docs/compat/reference/math/floor.md similarity index 100% rename from docs/reference/compat/math/floor.md rename to docs/compat/reference/math/floor.md diff --git a/docs/compat/reference/math/inRange.md b/docs/compat/reference/math/inRange.md new file mode 100644 index 000000000..c58ea17f3 --- /dev/null +++ b/docs/compat/reference/math/inRange.md @@ -0,0 +1,101 @@ +# inRange (Lodash Compatibility) + +::: warning Use [inRange](../../../reference/math/inRange.md) from `es-toolkit` + +This `inRange` function works slowly due to complex type conversion and null/undefined handling. + +Use the faster and more modern [inRange](../../../reference/math/inRange.md) from `es-toolkit` instead. + +::: + +Checks if a number is within a specified range. + +```typescript +const result = inRange(value, minimum, maximum); +``` + +## Usage + +### `inRange(value, minimum, maximum?)` + +Use `inRange` when you want to check if a number is within a specific range. The minimum value is inclusive and the maximum value is exclusive. + +```typescript +import { inRange } from 'es-toolkit/compat'; + +// Basic usage +inRange(3, 2, 4); +// Returns: true (2 ≤ 3 < 4) + +inRange(1, 2, 5); +// Returns: false (1 < 2) + +inRange(5, 2, 5); +// Returns: false (5 is not included) + +// Range boundary values +inRange(2, 2, 4); +// Returns: true (minimum value is included) + +inRange(4, 2, 4); +// Returns: false (maximum value is not included) +``` + +### `inRange(value, maximum)` + +When only two arguments are provided, it treats the range as from 0 to maximum. + +```typescript +import { inRange } from 'es-toolkit/compat'; + +inRange(3, 5); +// Returns: true (0 ≤ 3 < 5) + +inRange(-1, 5); +// Returns: false (-1 < 0) + +inRange(0, 5); +// Returns: true (0 ≤ 0 < 5) + +inRange(5, 5); +// Returns: false (5 is not included) +``` + +If the minimum value is greater than the maximum value, they are automatically swapped. + +```typescript +import { inRange } from 'es-toolkit/compat'; + +inRange(3, 5, 2); +// Returns: true (range becomes 2~5, and 2 ≤ 3 < 5) + +inRange(1, 5, 2); +// Returns: false (1 < 2) +``` + +Invalid values are appropriately converted. + +```typescript +import { inRange } from 'es-toolkit/compat'; + +// String number conversion +inRange(3, '2', '4'); +// Returns: true + +// Falsy values are treated as 0 +inRange(1, null, 5); +// Returns: true (null is treated as 0, so range is 0~5) + +inRange(3, false, 5); +// Returns: true (false is treated as 0) +``` + +#### Parameters + +- `value` (`number`): The number to check if it's within the range. +- `minimum` (`number`): The minimum value of the range (inclusive). If `maximum` is not provided, this value becomes the maximum. +- `maximum` (`number`, optional): The maximum value of the range (exclusive). + +#### Returns + +(`boolean`): Returns `true` if the value is within the specified range, otherwise `false`. diff --git a/docs/reference/compat/math/max.md b/docs/compat/reference/math/max.md similarity index 100% rename from docs/reference/compat/math/max.md rename to docs/compat/reference/math/max.md diff --git a/docs/compat/reference/math/maxBy.md b/docs/compat/reference/math/maxBy.md new file mode 100644 index 000000000..281b29926 --- /dev/null +++ b/docs/compat/reference/math/maxBy.md @@ -0,0 +1,114 @@ +# maxBy (Lodash Compatibility) + +::: warning Use [maxBy](../../../reference/array/maxBy.md) from es-toolkit + +This `maxBy` function works slowly due to iteratee function processing and type conversion. + +Use the faster and more modern [maxBy](../../../reference/array/maxBy.md) from `es-toolkit` instead. + +::: + +Finds the element with the maximum value based on a condition. + +```typescript +const maxItem = maxBy(array, iteratee); +``` + +## Usage + +### `maxBy(array, iteratee)` + +Finds the element in an array that has the largest value when computed by a function. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +// Find element with maximum property in object array +const people = [ + { name: 'John', age: 25 }, + { name: 'Jane', age: 30 }, + { name: 'Bob', age: 35 }, +]; + +maxBy(people, person => person.age); +// Returns: { name: 'Bob', age: 35 } + +// Can also use property name +maxBy(people, 'age'); +// Returns: { name: 'Bob', age: 35 } +``` + +Transform values with a function to find the maximum. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +maxBy(items, x => x.a); +// Returns: { a: 3 } + +const numbers = [-1, -2, -3]; +maxBy(numbers, x => Math.abs(x)); +// Returns: -3 (element with largest absolute value) +``` + +Access array elements by index. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const arrays = [ + [1, 2], + [3, 4], + [0, 5], +]; +maxBy(arrays, 0); // Array with maximum first element +// Returns: [3, 4] + +maxBy(arrays, 1); // Array with maximum second element +// Returns: [0, 5] +``` + +Find elements matching specific property values. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const users = [ + { name: 'John', age: 25, active: true }, + { name: 'Jane', age: 30, active: false }, + { name: 'Bob', age: 35, active: true }, +]; + +// First element among those with active: true +maxBy(users, ['active', true]); +// Returns: { name: 'John', age: 25, active: true } + +// Specify condition as object +maxBy(users, { active: true }); +// Returns: { name: 'John', age: 25, active: true } +``` + +Empty arrays return undefined. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +maxBy([], x => x.a); +// Returns: undefined + +maxBy(null); +// Returns: undefined + +maxBy(undefined); +// Returns: undefined +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to search. +- `iteratee` (`ValueIteratee`, optional): The function, property name, or condition to apply to each element. + +#### Returns + +(`T | undefined`): Returns the element with the largest value based on the condition. Returns `undefined` if the array is empty. diff --git a/docs/compat/reference/math/mean.md b/docs/compat/reference/math/mean.md new file mode 100644 index 000000000..82d92b984 --- /dev/null +++ b/docs/compat/reference/math/mean.md @@ -0,0 +1,76 @@ +# mean (Lodash Compatibility) + +::: warning Use [mean](../../../reference/math/mean.md) from es-toolkit + +This `mean` function works slowly due to type conversion and null/undefined handling. + +Use the faster and more modern [mean](../../../reference/math/mean.md) from `es-toolkit` instead. + +::: + +Calculates the average value of an array. + +```typescript +const average = mean(array); +``` + +## Usage + +### `mean(array)` + +Calculates the average value of a number array. + +```typescript +import { mean } from 'es-toolkit/compat'; + +// Number array +mean([1, 2, 3, 4, 5]); +// Returns: 3 + +mean([10, 20, 30]); +// Returns: 20 + +mean([1.5, 2.5, 3.5]); +// Returns: 2.5 +``` + +Empty arrays return NaN. + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean([]); +// Returns: NaN + +mean(null); +// Returns: NaN + +mean(undefined); +// Returns: NaN +``` + +Invalid values are treated as 0 and included in the calculation. + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean([1, undefined, 2, null, 3]); +// Returns: 1.2 (1 + 2 + 3) / 5 = 1.2 +``` + +Strings will be concatenated. + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean(['1', '2', '3']); +// Returns: 41 (123 / 3 = 41) +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array containing numbers to calculate the average from. + +#### Returns + +(`number`): Returns the average value of the array. Returns `NaN` if the array is empty. diff --git a/docs/compat/reference/math/meanBy.md b/docs/compat/reference/math/meanBy.md new file mode 100644 index 000000000..ebe1a6ff4 --- /dev/null +++ b/docs/compat/reference/math/meanBy.md @@ -0,0 +1,103 @@ +# meanBy (Lodash Compatibility) + +::: warning Use [meanBy](../../../reference/math/meanBy.md) from es-toolkit + +This `meanBy` function works slowly due to iteratee function processing and type conversion. + +Use the faster and more modern [meanBy](../../../reference/math/meanBy.md) from `es-toolkit` instead. + +::: + +Calculates the average of values that meet a condition. + +```typescript +const average = meanBy(array, iteratee); +``` + +## Usage + +### `meanBy(array, iteratee)` + +Calculates the average of the results of applying a function to each element in an array. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +// Average of specific property in object array +const people = [ + { name: 'John', age: 25 }, + { name: 'Jane', age: 30 }, + { name: 'Bob', age: 35 }, +]; + +meanBy(people, person => person.age); +// Returns: 30 + +// Can also use property name +meanBy(people, 'age'); +// Returns: 30 +``` + +Transform values with a function to calculate the average. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const numbers = [1.5, 2.7, 3.2, 4.8]; +meanBy(numbers, x => Math.floor(x)); +// Returns: 2.5 (1 + 2 + 3 + 4) / 4 + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +meanBy(items, x => x.a); +// Returns: 2 +``` + +Access array elements by index. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const arrays = [[2], [3], [1]]; +meanBy(arrays, 0); // Average of first elements +// Returns: 2 +``` + +Calculate only for elements matching specific property values. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const users = [ + { name: 'John', age: 25, active: true }, + { name: 'Jane', age: 30, active: false }, + { name: 'Bob', age: 35, active: true }, +]; + +// Only active users +meanBy(users, { active: true }); +// Returns: 0.6666666 (2 out of 3 users are active) +``` + +Empty arrays return NaN. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +meanBy([], x => x.a); +// Returns: NaN + +meanBy(null); +// Returns: NaN + +meanBy(undefined); +// Returns: NaN +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to process. +- `iteratee` (`ValueIteratee`, optional): The function, property name, or condition to apply to each element. + +#### Returns + +(`number`): Returns the average of values that meet the condition. Returns `NaN` if the array is empty. diff --git a/docs/reference/compat/math/min.md b/docs/compat/reference/math/min.md similarity index 100% rename from docs/reference/compat/math/min.md rename to docs/compat/reference/math/min.md diff --git a/docs/compat/reference/math/minBy.md b/docs/compat/reference/math/minBy.md new file mode 100644 index 000000000..d719373db --- /dev/null +++ b/docs/compat/reference/math/minBy.md @@ -0,0 +1,114 @@ +# minBy (Lodash Compatibility) + +::: warning Use [minBy](../../../reference/array/minBy.md) from es-toolkit + +This `minBy` function works slowly due to iteratee function processing and type conversion. + +Use the faster and more modern [minBy](../../../reference/array/minBy.md) from `es-toolkit` instead. + +::: + +Finds the element with the minimum value based on a condition. + +```typescript +const minItem = minBy(array, iteratee); +``` + +## Usage + +### `minBy(array, iteratee)` + +Finds the element in an array that has the smallest value when computed by a function. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +// Find element with minimum property in object array +const people = [ + { name: 'John', age: 25 }, + { name: 'Jane', age: 30 }, + { name: 'Bob', age: 35 }, +]; + +minBy(people, person => person.age); +// Returns: { name: 'John', age: 25 } + +// Can also use property name +minBy(people, 'age'); +// Returns: { name: 'John', age: 25 } +``` + +Transform values with a function to find the minimum. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +minBy(items, x => x.a); +// Returns: { a: 1 } + +const numbers = [-1, -2, -3]; +minBy(numbers, x => Math.abs(x)); +// Returns: -1 (element with smallest absolute value) +``` + +Access array elements by index. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const arrays = [ + [1, 2], + [3, 4], + [0, 5], +]; +minBy(arrays, 0); // Array with minimum first element +// Returns: [0, 5] + +minBy(arrays, 1); // Array with minimum second element +// Returns: [1, 2] +``` + +Find elements matching specific property values. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const users = [ + { name: 'John', age: 25, active: true }, + { name: 'Jane', age: 30, active: false }, + { name: 'Bob', age: 35, active: true }, +]; + +// First element among those with active: true +minBy(users, ['active', true]); +// Returns: { name: 'Jane', age: 30, active: false } + +// Specify condition as object +minBy(users, { active: true }); +// Returns: { name: 'Jane', age: 30, active: false } +``` + +Empty arrays return undefined. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +minBy([], x => x.a); +// Returns: undefined + +minBy(null); +// Returns: undefined + +minBy(undefined); +// Returns: undefined +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to search. +- `iteratee` (`ValueIteratee`, optional): The function, property name, or condition to apply to each element. + +#### Returns + +(`T | undefined`): Returns the element with the smallest value based on the condition. Returns `undefined` if the array is empty. diff --git a/docs/reference/compat/math/multiply.md b/docs/compat/reference/math/multiply.md similarity index 100% rename from docs/reference/compat/math/multiply.md rename to docs/compat/reference/math/multiply.md diff --git a/docs/reference/compat/math/parseInt.md b/docs/compat/reference/math/parseInt.md similarity index 100% rename from docs/reference/compat/math/parseInt.md rename to docs/compat/reference/math/parseInt.md diff --git a/docs/reference/compat/math/random.md b/docs/compat/reference/math/random.md similarity index 100% rename from docs/reference/compat/math/random.md rename to docs/compat/reference/math/random.md diff --git a/docs/compat/reference/math/range.md b/docs/compat/reference/math/range.md new file mode 100644 index 000000000..e482d8598 --- /dev/null +++ b/docs/compat/reference/math/range.md @@ -0,0 +1,99 @@ +# range (Lodash Compatibility) + +::: warning Use [range](../../../reference/math/range.md) from es-toolkit + +This `range` function works slowly due to complex argument processing and type conversion. + +Use the faster and more modern [range](../../../reference/math/range.md) from `es-toolkit` instead. + +::: + +Creates an array of numbers in a range. + +```typescript +const numbers = range(start, end, step); +``` + +## Usage + +### `range(end)` + +Creates an array of numbers from 0 to end, incrementing by 1. + +```typescript +import { range } from 'es-toolkit/compat'; + +range(4); +// Returns: [0, 1, 2, 3] + +range(0); +// Returns: [] + +range(-4); +// Returns: [0, -1, -2, -3] +``` + +### `range(start, end)` + +Creates an array of numbers from start to end, incrementing by 1. + +```typescript +import { range } from 'es-toolkit/compat'; + +range(1, 5); +// Returns: [1, 2, 3, 4] + +range(5, 1); +// Returns: [5, 4, 3, 2] (automatically decrements by -1) + +range(-2, 3); +// Returns: [-2, -1, 0, 1, 2] +``` + +### `range(start, end, step)` + +Creates an array of numbers from start to end, incrementing by step. + +```typescript +import { range } from 'es-toolkit/compat'; + +range(0, 20, 5); +// Returns: [0, 5, 10, 15] + +range(0, -4, -1); +// Returns: [0, -1, -2, -3] + +range(1, 4, 0); +// Returns: [1, 1, 1] +``` + +Decimal steps are also possible. + +```typescript +import { range } from 'es-toolkit/compat'; + +range(0, 1, 0.2); +// Returns: [0, 0.2, 0.4, 0.6, 0.8] + +range(1, 0, -0.25); +// Returns: [1, 0.75, 0.5, 0.25] +``` + +When used as an iteratee, it's handled with a guard object. + +```typescript +import { range } from 'es-toolkit/compat'; + +[1, 2, 3].map(range); +// Returns: [[0], [0, 1], [0, 1, 2]] +``` + +#### Parameters + +- `start` (`number`): The start value of the range (inclusive). If `end` is not provided, this becomes the end value. +- `end` (`number`, optional): The end value of the range (exclusive). +- `step` (`number`, optional): The increment step. Default is 1 or -1. + +#### Returns + +(`number[]`): Returns an array of numbers in the specified range. diff --git a/docs/compat/reference/math/rangeRight.md b/docs/compat/reference/math/rangeRight.md new file mode 100644 index 000000000..21090fcdb --- /dev/null +++ b/docs/compat/reference/math/rangeRight.md @@ -0,0 +1,99 @@ +# rangeRight (Lodash Compatibility) + +::: warning Use [rangeRight](../../../reference/math/rangeRight.md) from es-toolkit + +This `rangeRight` function works slowly due to complex argument processing and type conversion. + +Use the faster and more modern [rangeRight](../../../reference/math/rangeRight.md) from `es-toolkit` instead. + +::: + +Creates an array of numbers in a range in reverse order. + +```typescript +const numbers = rangeRight(start, end, step); +``` + +## Usage + +### `rangeRight(end)` + +Creates an array of numbers from 0 to end, incrementing by 1, then reverses the order. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(4); +// Returns: [3, 2, 1, 0] + +rangeRight(0); +// Returns: [] + +rangeRight(-4); +// Returns: [-3, -2, -1, 0] +``` + +### `rangeRight(start, end)` + +Creates an array of numbers from start to end, incrementing by 1, then reverses the order. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(1, 5); +// Returns: [4, 3, 2, 1] + +rangeRight(5, 1); +// Returns: [2, 3, 4, 5] (automatically decrements by -1, then reverses) + +rangeRight(-2, 3); +// Returns: [2, 1, 0, -1, -2] +``` + +### `rangeRight(start, end, step)` + +Creates an array of numbers from start to end, incrementing by step, then reverses the order. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(0, 8, 2); +// Returns: [6, 4, 2, 0] + +rangeRight(0, -4, -1); +// Returns: [-3, -2, -1, 0] + +rangeRight(1, 4, 0); +// Returns: [1, 1, 1] +``` + +Decimal steps are also possible. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(0, 1, 0.2); +// Returns: [0.8, 0.6, 0.4, 0.2, 0] + +rangeRight(1, 0, -0.25); +// Returns: [0.25, 0.5, 0.75, 1] +``` + +When used as an iteratee, it's handled with a guard object. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +[1, 2, 3].map(rangeRight); +// Returns: [[0], [1, 0], [2, 1, 0]] +``` + +#### Parameters + +- `start` (`number`): The start value of the range (inclusive). If `end` is not provided, this becomes the end value. +- `end` (`number`, optional): The end value of the range (exclusive). +- `step` (`number`, optional): The increment step. Default is 1 or -1. + +#### Returns + +(`number[]`): Returns an array of numbers in the specified range in reverse order. diff --git a/docs/reference/compat/math/round.md b/docs/compat/reference/math/round.md similarity index 100% rename from docs/reference/compat/math/round.md rename to docs/compat/reference/math/round.md diff --git a/docs/reference/compat/math/subtract.md b/docs/compat/reference/math/subtract.md similarity index 100% rename from docs/reference/compat/math/subtract.md rename to docs/compat/reference/math/subtract.md diff --git a/docs/compat/reference/math/sum.md b/docs/compat/reference/math/sum.md new file mode 100644 index 000000000..fa54fe909 --- /dev/null +++ b/docs/compat/reference/math/sum.md @@ -0,0 +1,73 @@ +# sum (Lodash Compatibility) + +::: warning Use [sum](../../../reference/math/sum.md) from es-toolkit + +This `sum` function works slowly due to type conversion and null/undefined handling. + +Use the faster and more modern [sum](../../../reference/math/sum.md) from `es-toolkit` instead. + +::: + +Adds all values in an array. + +```typescript +const total = sum(array); +``` + +## Usage + +### `sum(array)` + +Adds all numbers in an array to get the total sum. + +```typescript +import { sum } from 'es-toolkit/compat'; + +// Number array +sum([1, 2, 3]); +// Returns: 6 + +sum([1.5, 2.5, 3]); +// Returns: 7 + +// Empty array +sum([]); +// Returns: 0 +``` + +Handles BigInt and strings as well. + +```typescript +import { sum } from 'es-toolkit/compat'; + +// BigInt array +sum([1n, 2n, 3n]); +// Returns: 6n + +// String array (concatenated) +sum(['1', '2']); +// Returns: '12' +``` + +Invalid values are ignored. + +```typescript +import { sum } from 'es-toolkit/compat'; + +sum([1, undefined, 2]); +// Returns: 3 (undefined ignored) + +sum(null); +// Returns: 0 + +sum(undefined); +// Returns: 0 +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array containing values to add. + +#### Returns + +(`number`): Returns the total sum of all values. diff --git a/docs/compat/reference/math/sumBy.md b/docs/compat/reference/math/sumBy.md new file mode 100644 index 000000000..9207018d5 --- /dev/null +++ b/docs/compat/reference/math/sumBy.md @@ -0,0 +1,103 @@ +# sumBy (Lodash Compatibility) + +::: warning Use [sumBy](../../../reference/math/sumBy.md) from es-toolkit + +This `sumBy` function works slowly due to iteratee function processing and type conversion. + +Use the faster and more modern [sumBy](../../../reference/math/sumBy.md) from `es-toolkit` instead. + +::: + +Adds values that meet a condition. + +```typescript +const total = sumBy(array, iteratee); +``` + +## Usage + +### `sumBy(array, iteratee)` + +Adds the results of applying a function to each element in an array. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +// Number array +sumBy([1, 2, 3], value => value); +// Returns: 6 + +sumBy([1.5, 2.5, 3.5], value => Math.floor(value)); +// Returns: 6 (1 + 2 + 3) + +// Empty array +sumBy([], value => value); +// Returns: 0 +``` + +### `sumBy(array)` + +If no function is provided, it adds the array values directly. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +sumBy([1, 2, 3]); +// Returns: 6 + +sumBy([1n, 2n, 3n]); +// Returns: 6n +``` + +Add specific properties from object arrays. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +const people = [ + { name: 'John', age: 25 }, + { name: 'Jane', age: 30 }, + { name: 'Bob', age: 35 }, +]; + +sumBy(people, person => person.age); +// Returns: 90 + +// Can also use property name +sumBy(people, 'age'); +// Returns: 90 +``` + +Concatenates strings as well. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +const items = [{ a: '1' }, { a: '2' }]; +sumBy(items, obj => obj.a); +// Returns: '12' +``` + +Invalid values are ignored. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +sumBy([1, undefined, 2], value => value); +// Returns: 3 (undefined ignored) + +sumBy(null); +// Returns: 0 + +sumBy(undefined); +// Returns: 0 +``` + +#### Parameters + +- `array` (`ArrayLike | null | undefined`): The array to process. +- `iteratee` (`((value: T) => number) | string`, optional): The function or property name to apply to each element. + +#### Returns + +(`number`): Returns the total sum of values that meet the condition. diff --git a/docs/reference/compat/object/assign.md b/docs/compat/reference/object/assign.md similarity index 100% rename from docs/reference/compat/object/assign.md rename to docs/compat/reference/object/assign.md diff --git a/docs/reference/compat/object/assignIn.md b/docs/compat/reference/object/assignIn.md similarity index 100% rename from docs/reference/compat/object/assignIn.md rename to docs/compat/reference/object/assignIn.md diff --git a/docs/reference/compat/object/assignInWith.md b/docs/compat/reference/object/assignInWith.md similarity index 100% rename from docs/reference/compat/object/assignInWith.md rename to docs/compat/reference/object/assignInWith.md diff --git a/docs/reference/compat/object/assignWith.md b/docs/compat/reference/object/assignWith.md similarity index 100% rename from docs/reference/compat/object/assignWith.md rename to docs/compat/reference/object/assignWith.md diff --git a/docs/reference/compat/object/at.md b/docs/compat/reference/object/at.md similarity index 100% rename from docs/reference/compat/object/at.md rename to docs/compat/reference/object/at.md diff --git a/docs/compat/reference/object/clone.md b/docs/compat/reference/object/clone.md new file mode 100644 index 000000000..b48b42e36 --- /dev/null +++ b/docs/compat/reference/object/clone.md @@ -0,0 +1,89 @@ +# clone (Lodash compatibility) + +::: warning Use `clone` from `es-toolkit` instead + +This `clone` function is relatively slow due to complex logic that handles special object types. + +Use the faster and more modern [clone](../../../reference/object/clone.md) from `es-toolkit` instead. + +::: + +Creates a shallow copy of an object. + +```typescript +const cloned = clone(value); +``` + +## Usage + +### `clone(value)` + +Use `clone` when you want to create a shallow copy of a value. It can copy various types of objects and primitive values. + +```typescript +import { clone } from 'es-toolkit/compat'; + +// Copying primitive values +const num = 42; +const clonedNum = clone(num); +// Returns: 42 (same value) + +// Copying arrays +const arr = [1, 2, 3]; +const clonedArr = clone(arr); +// Returns: [1, 2, 3] (new array instance) + +// Copying objects +const obj = { a: 1, b: 'hello' }; +const clonedObj = clone(obj); +// Returns: { a: 1, b: 'hello' } (new object instance) + +// Copying Date objects +const date = new Date('2023-01-01'); +const clonedDate = clone(date); +// Returns: new Date('2023-01-01') (new Date instance) + +// Copying regular expressions +const regex = /hello/gi; +regex.lastIndex = 3; +const clonedRegex = clone(regex); +// Returns: /hello/gi with lastIndex = 3 + +// Copying Map +const map = new Map([ + ['a', 1], + ['b', 2], +]); +const clonedMap = clone(map); +// Returns: new Map([['a', 1], ['b', 2]]) + +// Copying Set +const set = new Set([1, 2, 3]); +const clonedSet = clone(set); +// Returns: new Set([1, 2, 3]) +``` + +Nested objects are only shallowly copied. + +```typescript +import { clone } from 'es-toolkit/compat'; + +const nested = { + a: 1, + b: { + c: 2, + }, +}; +const clonedNested = clone(nested); + +console.log(clonedNested !== nested); // true (different objects) +console.log(clonedNested.b === nested.b); // true (nested objects have same reference) +``` + +#### Parameters + +- `value` (`T`): The value to clone. + +#### Returns + +(`T`): Returns the cloned value. diff --git a/docs/compat/reference/object/cloneDeep.md b/docs/compat/reference/object/cloneDeep.md new file mode 100644 index 000000000..c674c4767 --- /dev/null +++ b/docs/compat/reference/object/cloneDeep.md @@ -0,0 +1,88 @@ +# cloneDeep (Lodash compatibility) + +::: warning Use `cloneDeep` from `es-toolkit` instead + +This `cloneDeep` function is relatively slow due to complex logic that handles special object types. + +Use the faster and more modern [cloneDeep](../../../reference/object/cloneDeep.md) from `es-toolkit` instead. + +::: + +Creates a deep copy of an object. + +```typescript +const cloned = cloneDeep(value); +``` + +## Usage + +### `cloneDeep(value)` + +Use `cloneDeep` when you want to create a deep copy of a value. It copies nested objects and arrays completely as new instances. + +```typescript +import { cloneDeep } from 'es-toolkit/compat'; + +// Copying primitive values +const num = 42; +const clonedNum = cloneDeep(num); +// Returns: 42 (same value) + +// Deep copying arrays +const arr = [1, [2, 3], { a: 4 }]; +const clonedArr = cloneDeep(arr); +clonedArr[1][0] = 99; +console.log(arr[1][0]); // 2 (original is not changed) +console.log(clonedArr[1][0]); // 99 + +// Deep copying objects +const obj = { + a: 1, + b: { + c: 2, + d: { + e: 3, + }, + }, +}; +const clonedObj = cloneDeep(obj); +clonedObj.b.d.e = 99; +console.log(obj.b.d.e); // 3 (original is not changed) +console.log(clonedObj.b.d.e); // 99 + +// Deep copying Date objects +const date = new Date('2023-01-01'); +const clonedDate = cloneDeep(date); +// Returns: new Date('2023-01-01') (new Date instance) + +// Complex nested structures +const complex = { + arr: [1, { nested: true }], + map: new Map([['key', { value: 1 }]]), + set: new Set([{ item: 1 }]), + date: new Date(), +}; +const clonedComplex = cloneDeep(complex); +// All nested objects are copied as completely new instances +``` + +Circular references are also handled correctly. + +```typescript +import { cloneDeep } from 'es-toolkit/compat'; + +const obj = { a: 1 }; +obj.self = obj; // circular reference + +const cloned = cloneDeep(obj); +console.log(cloned !== obj); // true +console.log(cloned.self === cloned); // true (circular reference preserved) +``` + +#### Parameters + +- `value` (`T`): The value to deep clone. + +#### Returns + +(`T`): Returns the deeply cloned value. diff --git a/docs/reference/compat/object/cloneDeepWith.md b/docs/compat/reference/object/cloneDeepWith.md similarity index 100% rename from docs/reference/compat/object/cloneDeepWith.md rename to docs/compat/reference/object/cloneDeepWith.md diff --git a/docs/reference/compat/object/cloneWith.md b/docs/compat/reference/object/cloneWith.md similarity index 100% rename from docs/reference/compat/object/cloneWith.md rename to docs/compat/reference/object/cloneWith.md diff --git a/docs/reference/compat/object/create.md b/docs/compat/reference/object/create.md similarity index 100% rename from docs/reference/compat/object/create.md rename to docs/compat/reference/object/create.md diff --git a/docs/reference/compat/object/defaults.md b/docs/compat/reference/object/defaults.md similarity index 100% rename from docs/reference/compat/object/defaults.md rename to docs/compat/reference/object/defaults.md diff --git a/docs/reference/compat/object/defaultsDeep.md b/docs/compat/reference/object/defaultsDeep.md similarity index 100% rename from docs/reference/compat/object/defaultsDeep.md rename to docs/compat/reference/object/defaultsDeep.md diff --git a/docs/reference/compat/object/extend.md b/docs/compat/reference/object/extend.md similarity index 100% rename from docs/reference/compat/object/extend.md rename to docs/compat/reference/object/extend.md diff --git a/docs/reference/compat/object/extendWith.md b/docs/compat/reference/object/extendWith.md similarity index 100% rename from docs/reference/compat/object/extendWith.md rename to docs/compat/reference/object/extendWith.md diff --git a/docs/compat/reference/object/findKey.md b/docs/compat/reference/object/findKey.md new file mode 100644 index 000000000..dbce9dd47 --- /dev/null +++ b/docs/compat/reference/object/findKey.md @@ -0,0 +1,61 @@ +# findKey (Lodash compatibility) + +::: warning Use `es-toolkit`'s `findKey` + +This `findKey` function operates in a complex manner due to various condition type handling and compatibility logic. + +Instead, use the faster and more modern [findKey](../../../reference/object/findKey.md) from `es-toolkit`. + +::: + +Finds the key of the first element that matches the predicate. + +```typescript +const key = findKey(obj, predicate); +``` + +## Usage + +### `findKey(obj, predicate)` + +Use `findKey` to find the key of the first element in an object that matches the predicate. You can use various types of predicates such as functions, objects, arrays, and strings. + +```typescript +import { findKey } from 'es-toolkit/compat'; + +// Find key with a function predicate +const users = { + alice: { age: 25, active: true }, + bob: { age: 30, active: false }, + charlie: { age: 35, active: true }, +}; + +findKey(users, user => user.age > 30); +// Returns: 'charlie' + +// Find key with an object predicate +findKey(users, { active: false }); +// Returns: 'bob' + +// Find key with a property path +findKey(users, 'active'); +// Returns: 'alice' +``` + +If no element matches the predicate, it returns `undefined`. + +```typescript +import { findKey } from 'es-toolkit/compat'; + +findKey({ a: 1, b: 2 }, value => value > 5); +// Returns: undefined +``` + +#### Parameters + +- `obj` (`T | null | undefined`): The object to search. +- `predicate` (`ObjectIteratee`, optional): The predicate to apply to each element. Can be a function, object, array, or string. + +#### Returns + +(`string | undefined`): Returns the key of the first element that matches the predicate. Returns `undefined` if no match is found. diff --git a/docs/reference/compat/object/findLastKey.md b/docs/compat/reference/object/findLastKey.md similarity index 100% rename from docs/reference/compat/object/findLastKey.md rename to docs/compat/reference/object/findLastKey.md diff --git a/docs/reference/compat/object/forIn.md b/docs/compat/reference/object/forIn.md similarity index 100% rename from docs/reference/compat/object/forIn.md rename to docs/compat/reference/object/forIn.md diff --git a/docs/reference/compat/object/forInRight.md b/docs/compat/reference/object/forInRight.md similarity index 100% rename from docs/reference/compat/object/forInRight.md rename to docs/compat/reference/object/forInRight.md diff --git a/docs/reference/compat/object/forOwn.md b/docs/compat/reference/object/forOwn.md similarity index 100% rename from docs/reference/compat/object/forOwn.md rename to docs/compat/reference/object/forOwn.md diff --git a/docs/reference/compat/object/forOwnRight.md b/docs/compat/reference/object/forOwnRight.md similarity index 100% rename from docs/reference/compat/object/forOwnRight.md rename to docs/compat/reference/object/forOwnRight.md diff --git a/docs/reference/compat/object/fromPairs.md b/docs/compat/reference/object/fromPairs.md similarity index 100% rename from docs/reference/compat/object/fromPairs.md rename to docs/compat/reference/object/fromPairs.md diff --git a/docs/reference/compat/object/functions.md b/docs/compat/reference/object/functions.md similarity index 100% rename from docs/reference/compat/object/functions.md rename to docs/compat/reference/object/functions.md diff --git a/docs/reference/compat/object/functionsIn.md b/docs/compat/reference/object/functionsIn.md similarity index 100% rename from docs/reference/compat/object/functionsIn.md rename to docs/compat/reference/object/functionsIn.md diff --git a/docs/reference/compat/object/get.md b/docs/compat/reference/object/get.md similarity index 100% rename from docs/reference/compat/object/get.md rename to docs/compat/reference/object/get.md diff --git a/docs/reference/compat/object/has.md b/docs/compat/reference/object/has.md similarity index 100% rename from docs/reference/compat/object/has.md rename to docs/compat/reference/object/has.md diff --git a/docs/reference/compat/object/hasIn.md b/docs/compat/reference/object/hasIn.md similarity index 100% rename from docs/reference/compat/object/hasIn.md rename to docs/compat/reference/object/hasIn.md diff --git a/docs/compat/reference/object/invert.md b/docs/compat/reference/object/invert.md new file mode 100644 index 000000000..35bd7dc39 --- /dev/null +++ b/docs/compat/reference/object/invert.md @@ -0,0 +1,60 @@ +# invert (Lodash compatibility) + +::: warning Use `invert` from `es-toolkit` + +This `invert` function operates slower due to the complex processing required for Lodash compatibility. + +Instead, use the faster and more modern [`invert`](../../../reference/object/invert.md) from `es-toolkit`. + +::: + +Inverts the keys and values of an object. + +```typescript +const inverted = invert(object); +``` + +## Usage + +### `invert(object)` + +Use `invert` when you want to swap the keys and values of an object. The original object's keys become the values in the new object, and the original object's values become the keys in the new object. + +```typescript +import { invert } from 'es-toolkit/compat'; + +// Basic key-value inversion +const object = { a: 1, b: 2, c: 3 }; +invert(object); +// => { '1': 'a', '2': 'b', '3': 'c' } + +// Inverting string values +const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' }; +invert(colors); +// => { '#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue' } + +// Mixed key and value types +const mixed = { a: 1, 2: 'b', c: 3, 4: 'd' }; +invert(mixed); +// => { '1': 'a', 'b': '2', '3': 'c', 'd': '4' } +``` + +When there are duplicate values, the last key is used. + +```typescript +import { invert } from 'es-toolkit/compat'; + +// Case with duplicate values +const object = { a: 1, b: 1, c: 2 }; +invert(object); +// => { '1': 'b', '2': 'c' } +// 'a' is overwritten and lost +``` + +#### Parameters + +- `object` (`object`): The object to invert. + +#### Returns + +(`Record`): Returns a new object with keys and values inverted. diff --git a/docs/reference/compat/object/invertBy.md b/docs/compat/reference/object/invertBy.md similarity index 100% rename from docs/reference/compat/object/invertBy.md rename to docs/compat/reference/object/invertBy.md diff --git a/docs/reference/compat/object/keys.md b/docs/compat/reference/object/keys.md similarity index 100% rename from docs/reference/compat/object/keys.md rename to docs/compat/reference/object/keys.md diff --git a/docs/reference/compat/object/keysIn.md b/docs/compat/reference/object/keysIn.md similarity index 100% rename from docs/reference/compat/object/keysIn.md rename to docs/compat/reference/object/keysIn.md diff --git a/docs/compat/reference/object/mapKeys.md b/docs/compat/reference/object/mapKeys.md new file mode 100644 index 000000000..9306995c8 --- /dev/null +++ b/docs/compat/reference/object/mapKeys.md @@ -0,0 +1,63 @@ +# mapKeys (Lodash compatibility) + +::: warning Use `mapKeys` from `es-toolkit` + +This `mapKeys` function is relatively slow due to handling `null` or `undefined` and the `iteratee` conversion process. + +Use the faster and more modern [`mapKeys`](../../../reference/object/mapKeys.md) from `es-toolkit` instead. + +::: + +Creates a new object by transforming keys while keeping values the same. + +```typescript +const result = mapKeys(obj, iteratee); +``` + +## Usage + +### `mapKeys(object, iteratee)` + +Transforms each key in an object using the `iteratee` function to create a new object. Values remain unchanged while only keys are modified. Useful for transforming or normalizing object keys. + +```typescript +import { mapKeys } from 'es-toolkit/compat'; + +// Add prefix to keys +const obj = { a: 1, b: 2, c: 3 }; +const result = mapKeys(obj, (value, key) => 'prefix_' + key); +// Result: { prefix_a: 1, prefix_b: 2, prefix_c: 3 } + +// Convert keys to uppercase +const data = { name: 'John', age: 30 }; +const uppercased = mapKeys(data, (value, key) => key.toUpperCase()); +// Result: { NAME: 'John', AGE: 30 } + +// Convert array indices to keys +const arr = ['apple', 'banana', 'orange']; +const indexed = mapKeys(arr, (value, index) => `item_${index}`); +// Result: { item_0: 'apple', item_1: 'banana', item_2: 'orange' } + +// Create new keys by combining key and value +const scores = { math: 90, science: 85, english: 92 }; +const detailed = mapKeys(scores, (value, key) => `${key}_score_${value}`); +// Result: { math_score_90: 90, science_score_85: 85, english_score_92: 92 } +``` + +`null` or `undefined` are treated as empty objects. + +```typescript +import { mapKeys } from 'es-toolkit/compat'; + +mapKeys(null, iteratee); // {} +mapKeys(undefined, iteratee); // {} +``` + +#### Parameters + +- `object` (`ArrayLike | T | null | undefined`): The object or array to transform keys from. +- `iteratee` (`ListIteratee | ObjectIteratee`, optional): The function to transform each key. Defaults to the `identity` function. + +#### Returns + +(`Record | Record`): Returns a new object with transformed keys. diff --git a/docs/compat/reference/object/mapValues.md b/docs/compat/reference/object/mapValues.md new file mode 100644 index 000000000..b4bb8481d --- /dev/null +++ b/docs/compat/reference/object/mapValues.md @@ -0,0 +1,71 @@ +# mapValues (Lodash compatibility) + +::: warning Use `mapValues` from `es-toolkit` + +This `mapValues` function is relatively slow due to handling `null` or `undefined` and the `iteratee` conversion process. + +Use the faster and more modern [`mapValues`](../../../reference/object/mapValues.md) from `es-toolkit` instead. + +::: + +Creates a new object by transforming values while keeping keys the same. + +```typescript +const result = mapValues(obj, iteratee); +``` + +## Usage + +### `mapValues(object, iteratee)` + +Transforms each value in an object using the `iteratee` function to create a new object. Keys remain unchanged while only values are modified. Can handle strings, arrays, and objects. Useful for transforming or calculating data. + +```typescript +import { mapValues } from 'es-toolkit/compat'; + +// Transform object values +const obj = { a: 1, b: 2, c: 3 }; +const doubled = mapValues(obj, value => value * 2); +// Result: { a: 2, b: 4, c: 6 } + +// Convert strings to uppercase +const names = { first: 'john', last: 'doe' }; +const uppercased = mapValues(names, value => value.toUpperCase()); +// Result: { first: 'JOHN', last: 'DOE' } + +// Transform each character in a string +const str = 'abc'; +const charMap = mapValues(str, char => char.toUpperCase()); +// Result: { '0': 'A', '1': 'B', '2': 'C' } + +// Convert array to object +const arr = [10, 20, 30]; +const arrMap = mapValues(arr, (value, index) => value + index); +// Result: { '0': 10, '1': 21, '2': 32 } + +// Extract values using property path +const users = { + user1: { profile: { name: 'Alice' } }, + user2: { profile: { name: 'Bob' } }, +}; +const userNames = mapValues(users, 'profile.name'); +// Result: { user1: 'Alice', user2: 'Bob' } +``` + +`null` or `undefined` are treated as empty objects. + +```typescript +import { mapValues } from 'es-toolkit/compat'; + +mapValues(null, iteratee); // {} +mapValues(undefined, iteratee); // {} +``` + +#### Parameters + +- `object` (`string | T[] | T | null | undefined`): The object, array, or string to transform values from. +- `iteratee` (`ValueIteratee`, optional): The function, property path, or matching object to transform each value. Defaults to the `identity` function. + +#### Returns + +(`Record | { [P in keyof T]: U } | Record | Record | Partial`): Returns a new object with transformed values. diff --git a/docs/compat/reference/object/merge.md b/docs/compat/reference/object/merge.md new file mode 100644 index 000000000..9aed0da81 --- /dev/null +++ b/docs/compat/reference/object/merge.md @@ -0,0 +1,82 @@ +# merge (Lodash compatibility) + +::: warning Use `merge` from `es-toolkit` + +This `merge` function is relatively slow as it internally calls the complex `mergeWith` function. + +Use the faster and more modern [`merge`](../../../reference/object/merge.md) from `es-toolkit` instead. + +::: + +Deeply merges multiple objects into a single object. + +```typescript +const result = merge(target, ...sources); +``` + +## Usage + +### `merge(object, ...sources)` + +Deeply merges one or more source objects into the target object. Nested objects and arrays are recursively merged. If a source object property is `undefined`, it won't overwrite the existing value in the target object. Useful for merging object configurations or applying defaults. + +```typescript +import { merge } from 'es-toolkit/compat'; + +// Basic object merge +const target = { a: 1, b: { x: 1, y: 2 } }; +const source = { b: { y: 3, z: 4 }, c: 5 }; +const result = merge(target, source); +// Result: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } + +// Array merge +const obj1 = { arr: [1, 2] }; +const obj2 = { arr: [3, 4] }; +const merged = merge(obj1, obj2); +// Result: { arr: [3, 4] } (arrays are replaced) + +// Multiple object merge +const base = { a: 1 }; +const ext1 = { b: 2 }; +const ext2 = { c: 3 }; +const ext3 = { d: 4 }; +const combined = merge(base, ext1, ext2, ext3); +// Result: { a: 1, b: 2, c: 3, d: 4 } + +// Nested object merge +const config = { + api: { url: 'https://api.example.com', timeout: 5000 }, + features: { auth: true }, +}; +const overrides = { + api: { timeout: 10000, retries: 3 }, + features: { analytics: true }, +}; +const finalConfig = merge(config, overrides); +// Result: { +// api: { url: 'https://api.example.com', timeout: 10000, retries: 3 }, +// features: { auth: true, analytics: true } +// } +``` + +The target object is modified, so use an empty object to preserve the original. + +```typescript +import { merge } from 'es-toolkit/compat'; + +const original = { a: 1, b: { x: 1 } }; +const source = { b: { y: 2 } }; + +// Preserve original +const result = merge({}, original, source); +// original is not modified +``` + +#### Parameters + +- `object` (`any`): The target object to merge into. This object is modified. +- `...sources` (`any[]`): The source objects to merge from. + +#### Returns + +(`any`): Returns the merged target object. diff --git a/docs/compat/reference/object/mergeWith.md b/docs/compat/reference/object/mergeWith.md new file mode 100644 index 000000000..e421d5f9d --- /dev/null +++ b/docs/compat/reference/object/mergeWith.md @@ -0,0 +1,94 @@ +# mergeWith (Lodash compatibility) + +::: warning Use `mergeWith` from `es-toolkit` + +This `mergeWith` function is relatively slow due to complex type checking, circular reference handling, and special object processing. + +Use the faster and more modern [`mergeWith`](../../../reference/object/mergeWith.md) from `es-toolkit` instead. + +::: + +Deeply merges multiple objects while controlling the merge behavior with a custom function. + +```typescript +const result = mergeWith(target, ...sources, customizer); +``` + +## Usage + +### `mergeWith(object, ...sources, customizer)` + +Deeply merges one or more source objects into the target object, controlling the merge behavior with a customizer function. If the customizer function returns `undefined`, the default merge logic is used. Useful for concatenating arrays or applying special merge rules. + +```typescript +import { mergeWith } from 'es-toolkit/compat'; + +// Add numbers +const obj1 = { a: 1, b: 2 }; +const obj2 = { b: 3, c: 4 }; +const result = mergeWith(obj1, obj2, (objValue, srcValue) => { + if (typeof objValue === 'number' && typeof srcValue === 'number') { + return objValue + srcValue; + } +}); +// Result: { a: 1, b: 5, c: 4 } + +// Concatenate arrays +const arr1 = { items: [1, 2] }; +const arr2 = { items: [3, 4] }; +const merged = mergeWith(arr1, arr2, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return objValue.concat(srcValue); + } +}); +// Result: { items: [1, 2, 3, 4] } + +// Concatenate strings +const str1 = { message: 'Hello' }; +const str2 = { message: 'World' }; +const combined = mergeWith(str1, str2, (objValue, srcValue, key) => { + if (key === 'message' && typeof objValue === 'string') { + return objValue + ' ' + srcValue; + } +}); +// Result: { message: 'Hello World' } + +// Multiple source objects with customizer +const base = { scores: [80] }; +const quiz1 = { scores: [90] }; +const quiz2 = { scores: [85] }; +const final = mergeWith(base, quiz1, quiz2, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return objValue.concat(srcValue); + } +}); +// Result: { scores: [80, 90, 85] } +``` + +The customizer function receives various parameters. + +```typescript +import { mergeWith } from 'es-toolkit/compat'; + +const customizer = (objValue, srcValue, key, object, source, stack) => { + console.log('Merging:', key, objValue, '->', srcValue); + + // Customize only for specific keys + if (key === 'specialField') { + return `${objValue}_${srcValue}`; + } + + // Return undefined to use default merge logic + return undefined; +}; +``` + +#### Parameters + +- `object` (`any`): The target object to merge into. This object is modified. +- `...sources` (`any[]`): The source objects to merge from. +- `customizer` (`MergeWithCustomizer`): The function to customize value assignment. Format: `(objValue, srcValue, key, object, source, stack) => any`. + +#### Returns + +(`any`): Returns the merged target object. diff --git a/docs/compat/reference/object/omit.md b/docs/compat/reference/object/omit.md new file mode 100644 index 000000000..05c18f2fe --- /dev/null +++ b/docs/compat/reference/object/omit.md @@ -0,0 +1,82 @@ +# omit (Lodash compatibility) + +::: warning Use `omit` from `es-toolkit` + +This `omit` function is relatively slow due to deep copying and calling the `unset` function. + +Use the faster and more modern [`omit`](../../../reference/object/omit.md) from `es-toolkit` instead. + +::: + +Creates a new object excluding specified keys from an object. + +```typescript +const result = omit(obj, ...keys); +``` + +## Usage + +### `omit(object, ...paths)` + +Creates a new object excluding specified keys from an object. Supports deep key paths and can specify multiple keys at once using arrays. Useful for removing sensitive information from objects or selecting only needed properties. + +```typescript +import { omit } from 'es-toolkit/compat'; + +// Remove basic keys +const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }; +const publicUser = omit(user, 'password', 'email'); +// Result: { id: 1, name: 'John' } + +// Remove multiple keys with array +const data = { a: 1, b: 2, c: 3, d: 4 }; +const filtered = omit(data, ['a', 'c']); +// Result: { b: 2, d: 4 } + +// Remove deep key paths +const nested = { + user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, + admin: true, +}; +const result = omit(nested, 'user.profile.age', 'admin'); +// Result: { user: { profile: { name: 'John' }, settings: { theme: 'dark' } } } + +// Combine nested arrays and keys +const complex = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; +const simplified = omit(complex, 'a', ['b', 'c'], 'd.f'); +// Result: { d: { e: 4 } } +``` + +You can freely combine arrays, strings, and key paths. + +```typescript +import { omit } from 'es-toolkit/compat'; + +const config = { + api: { url: 'https://api.example.com', key: 'secret', timeout: 5000 }, + ui: { theme: 'dark', language: 'en' }, + debug: true, +}; + +// Specify keys in multiple ways +const cleaned = omit(config, 'api.key', ['debug'], 'ui.language'); +// Result: { api: { url: 'https://api.example.com', timeout: 5000 }, ui: { theme: 'dark' } } +``` + +`null` or `undefined` are treated as empty objects. + +```typescript +import { omit } from 'es-toolkit/compat'; + +omit(null, 'key'); // {} +omit(undefined, 'key'); // {} +``` + +#### Parameters + +- `object` (`T | null | undefined`): The source object to remove keys from. +- `...paths` (`Array>`): The keys to remove. Can specify single keys, arrays of keys, or deep key paths. + +#### Returns + +(`Partial`): Returns a new object with specified keys removed. diff --git a/docs/compat/reference/object/omitBy.md b/docs/compat/reference/object/omitBy.md new file mode 100644 index 000000000..c823633bb --- /dev/null +++ b/docs/compat/reference/object/omitBy.md @@ -0,0 +1,76 @@ +# omitBy (Lodash compatibility) + +::: warning Use `omitBy` from `es-toolkit` + +This `omitBy` function is relatively slow due to array-like object checking, `iteratee` conversion, and key transformation processes. + +Use the faster and more modern [`omitBy`](../../../reference/object/omitBy.md) from `es-toolkit` instead. + +::: + +Creates a new object excluding properties for which the predicate function returns true. + +```typescript +const result = omitBy(obj, predicate); +``` + +## Usage + +### `omitBy(object, predicate)` + +Executes a predicate function for each property of the object and creates a new object excluding properties for which the predicate returns true. Useful for dynamically filtering properties based on conditions. + +```typescript +import { omitBy } from 'es-toolkit/compat'; + +// Remove values of specific type +const data = { a: 1, b: 'remove', c: 3, d: 'keep' }; +const numbers = omitBy(data, value => typeof value === 'string'); +// Result: { a: 1, c: 3 } + +// Remove properties based on condition +const user = { id: 1, name: 'John', age: 0, active: false, email: '' }; +const validData = omitBy(user, value => !value); +// Result: { id: 1, name: 'John' } (removes falsy values) + +// Filter by key name +const settings = { userSetting: true, adminSetting: false, debugMode: true }; +const userOnly = omitBy(settings, (value, key) => key.startsWith('admin')); +// Result: { userSetting: true, debugMode: true } + +// Remove only number properties +const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; +const noNumbers = omitBy(mixed, value => typeof value === 'number'); +// Result: { str: 'hello', bool: true, obj: {} } + +// Can also be used with arrays +const arr = [1, 2, 3, 4, 5]; +const filtered = omitBy(arr, value => value % 2 === 0); +// Result: { '0': 1, '2': 3, '4': 5 } (odd values at even indices) + +// Utilize value, key, and original object +const scores = { math: 90, science: 75, english: 85, art: 60 }; +const passingGrades = omitBy(scores, (value, key, obj) => { + console.log(`${key}: ${value} (average: ${Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length})`); + return value < 80; +}); +// Result: { math: 90, english: 85 } +``` + +`null` or `undefined` are treated as empty objects. + +```typescript +import { omitBy } from 'es-toolkit/compat'; + +omitBy(null, () => true); // {} +omitBy(undefined, () => true); // {} +``` + +#### Parameters + +- `object` (`Record | Record | object | null | undefined`): The source object to filter. +- `predicate` (`ValueKeyIteratee | ValueKeyIteratee`, optional): The predicate function to execute for each property. Properties for which this returns true are removed. Defaults to the `identity` function. + +#### Returns + +(`Record | Record | Partial`): Returns a new object consisting of properties that don't match the condition. diff --git a/docs/compat/reference/object/pick.md b/docs/compat/reference/object/pick.md new file mode 100644 index 000000000..0fff3983d --- /dev/null +++ b/docs/compat/reference/object/pick.md @@ -0,0 +1,73 @@ +# pick (Lodash compatibility) + +::: warning Use `pick` from `es-toolkit` + +This `pick` function is relatively slow due to complex path processing, calling `get`/`set` functions, and handling `null`/`undefined`. + +Use the faster and more modern [`pick`](../../../reference/object/pick.md) from `es-toolkit` instead. + +::: + +Creates a new object by selecting only specified properties from an object. + +```typescript +const result = pick(obj, ...keys); +``` + +## Usage + +### `pick(object, ...props)` + +Use `pick` when you want to create a new object containing only the desired properties from an object. You can pass multiple keys at once using an array, or pass them one by one as individual arguments. Supports deep key paths so you can also select nested properties. + +```typescript +import { pick } from 'es-toolkit/compat'; + +// Basic usage +const obj = { a: 1, b: 2, c: 3, d: 4 }; +const result = pick(obj, ['a', 'c']); +// Result: { a: 1, c: 3 } + +// Pass as individual arguments +const result2 = pick(obj, 'a', 'c'); +// Result: { a: 1, c: 3 } + +// Select deep paths +const nested = { + user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, + admin: true, +}; +const userInfo = pick(nested, 'user.profile.name', 'admin'); +// Result: { user: { profile: { name: 'John' } }, admin: true } + +// Mix arrays and individual keys +const mixed = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; +const selected = pick(mixed, ['a', 'b'], 'c', 'd.e'); +// Result: { a: 1, b: 2, c: 3, d: { e: 4 } } + +// Distinguish between dot notation keys and actual dotted keys +const ambiguous = { + 'a.b': 1, // Actual key 'a.b' + a: { b: 2, c: 3 }, // Nested object +}; +const dotKey = pick(ambiguous, 'a.b'); +// Result: { 'a.b': 1 } (actual key takes priority) +``` + +`null` or `undefined` are treated as empty objects. + +```typescript +import { pick } from 'es-toolkit/compat'; + +pick(null, ['a', 'b']); // {} +pick(undefined, ['a', 'b']); // {} +``` + +#### Parameters + +- `object` (`T | null | undefined`): The object to select properties from. +- `...props` (`Array>`): The property keys to select. Can specify single keys, arrays of keys, or deep key paths. + +#### Returns + +(`Pick | Partial`): Returns a new object containing only the specified properties. diff --git a/docs/compat/reference/object/pickBy.md b/docs/compat/reference/object/pickBy.md new file mode 100644 index 000000000..b6ef34c5a --- /dev/null +++ b/docs/compat/reference/object/pickBy.md @@ -0,0 +1,86 @@ +# pickBy (Lodash compatibility) + +::: warning Use `pickBy` from `es-toolkit` + +This `pickBy` function is relatively slow due to array-like object checking, `iteratee` conversion, and key transformation processes. + +Use the faster and more modern [`pickBy`](../../../reference/object/pickBy.md) from `es-toolkit` instead. + +::: + +Creates a new object selecting only properties for which the predicate function returns true. + +```typescript +const result = pickBy(obj, predicate); +``` + +## Usage + +### `pickBy(object, predicate)` + +Executes a predicate function for each property of the object and creates a new object containing only properties for which the predicate returns true. Useful for dynamically selecting properties based on conditions. + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +// Select only values of specific type +const data = { a: 1, b: 'keep', c: 3, d: 'select' }; +const strings = pickBy(data, value => typeof value === 'string'); +// Result: { b: 'keep', d: 'select' } + +// Select properties based on condition +const user = { id: 1, name: 'John', age: 0, active: true, email: '' }; +const validData = pickBy(user, value => Boolean(value)); +// Result: { id: 1, name: 'John', active: true } (only truthy values) + +// Filter by key name +const settings = { userSetting: true, adminSetting: false, debugMode: true }; +const userOnly = pickBy(settings, (value, key) => key.startsWith('user')); +// Result: { userSetting: true } + +// Select only number properties +const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; +const numbersOnly = pickBy(mixed, value => typeof value === 'number'); +// Result: { num1: 42, num2: 0 } + +// Can also be used with arrays +const arr = [1, 2, 3, 4, 5]; +const evens = pickBy(arr, value => value % 2 === 0); +// Result: { '1': 2, '3': 4 } (indices and values of even numbers) + +// Utilize value, key, and original object +const scores = { math: 90, science: 75, english: 85, art: 60 }; +const highScores = pickBy(scores, (value, key, obj) => { + const average = Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length; + return value > average; +}); +// Result: { math: 90, english: 85 } +``` + +When called without a predicate function, it selects only truthy values. + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +const data = { a: 1, b: '', c: 0, d: 'hello', e: null, f: true }; +const truthyValues = pickBy(data); +// Result: { a: 1, d: 'hello', f: true } +``` + +`null` or `undefined` are treated as empty objects. + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +pickBy(null, () => true); // {} +pickBy(undefined, () => true); // {} +``` + +#### Parameters + +- `object` (`Record | Record | object | null | undefined`): The source object to filter. +- `predicate` (`ValueKeyIterateeTypeGuard | ValueKeyIteratee | ValueKeyIteratee`, optional): The predicate function to execute for each property. Properties for which this returns true are selected. Defaults to the `identity` function. + +#### Returns + +(`Record | Record | Partial`): Returns a new object consisting of properties that match the condition. diff --git a/docs/reference/compat/object/property.md b/docs/compat/reference/object/property.md similarity index 100% rename from docs/reference/compat/object/property.md rename to docs/compat/reference/object/property.md diff --git a/docs/reference/compat/object/propertyOf.md b/docs/compat/reference/object/propertyOf.md similarity index 100% rename from docs/reference/compat/object/propertyOf.md rename to docs/compat/reference/object/propertyOf.md diff --git a/docs/reference/compat/object/result.md b/docs/compat/reference/object/result.md similarity index 100% rename from docs/reference/compat/object/result.md rename to docs/compat/reference/object/result.md diff --git a/docs/reference/compat/object/set.md b/docs/compat/reference/object/set.md similarity index 100% rename from docs/reference/compat/object/set.md rename to docs/compat/reference/object/set.md diff --git a/docs/reference/compat/object/setWith.md b/docs/compat/reference/object/setWith.md similarity index 100% rename from docs/reference/compat/object/setWith.md rename to docs/compat/reference/object/setWith.md diff --git a/docs/reference/compat/object/toDefaulted.md b/docs/compat/reference/object/toDefaulted.md similarity index 100% rename from docs/reference/compat/object/toDefaulted.md rename to docs/compat/reference/object/toDefaulted.md diff --git a/docs/reference/compat/object/toPairs.md b/docs/compat/reference/object/toPairs.md similarity index 100% rename from docs/reference/compat/object/toPairs.md rename to docs/compat/reference/object/toPairs.md diff --git a/docs/reference/compat/object/toPairsIn.md b/docs/compat/reference/object/toPairsIn.md similarity index 100% rename from docs/reference/compat/object/toPairsIn.md rename to docs/compat/reference/object/toPairsIn.md diff --git a/docs/reference/compat/object/transform.md b/docs/compat/reference/object/transform.md similarity index 100% rename from docs/reference/compat/object/transform.md rename to docs/compat/reference/object/transform.md diff --git a/docs/reference/compat/object/unset.md b/docs/compat/reference/object/unset.md similarity index 100% rename from docs/reference/compat/object/unset.md rename to docs/compat/reference/object/unset.md diff --git a/docs/reference/compat/object/update.md b/docs/compat/reference/object/update.md similarity index 100% rename from docs/reference/compat/object/update.md rename to docs/compat/reference/object/update.md diff --git a/docs/reference/compat/object/updateWith.md b/docs/compat/reference/object/updateWith.md similarity index 100% rename from docs/reference/compat/object/updateWith.md rename to docs/compat/reference/object/updateWith.md diff --git a/docs/reference/compat/object/values.md b/docs/compat/reference/object/values.md similarity index 100% rename from docs/reference/compat/object/values.md rename to docs/compat/reference/object/values.md diff --git a/docs/reference/compat/object/valuesIn.md b/docs/compat/reference/object/valuesIn.md similarity index 100% rename from docs/reference/compat/object/valuesIn.md rename to docs/compat/reference/object/valuesIn.md diff --git a/docs/reference/compat/predicate/conforms.md b/docs/compat/reference/predicate/conforms.md similarity index 100% rename from docs/reference/compat/predicate/conforms.md rename to docs/compat/reference/predicate/conforms.md diff --git a/docs/reference/compat/predicate/conformsTo.md b/docs/compat/reference/predicate/conformsTo.md similarity index 100% rename from docs/reference/compat/predicate/conformsTo.md rename to docs/compat/reference/predicate/conformsTo.md diff --git a/docs/reference/compat/predicate/isArguments.md b/docs/compat/reference/predicate/isArguments.md similarity index 100% rename from docs/reference/compat/predicate/isArguments.md rename to docs/compat/reference/predicate/isArguments.md diff --git a/docs/reference/compat/predicate/isArray.md b/docs/compat/reference/predicate/isArray.md similarity index 100% rename from docs/reference/compat/predicate/isArray.md rename to docs/compat/reference/predicate/isArray.md diff --git a/docs/compat/reference/predicate/isArrayBuffer.md b/docs/compat/reference/predicate/isArrayBuffer.md new file mode 100644 index 000000000..3b5ea4937 --- /dev/null +++ b/docs/compat/reference/predicate/isArrayBuffer.md @@ -0,0 +1,46 @@ +# isArrayBuffer (Lodash Compatibility) + +::: warning Use es-toolkit's [isArrayBuffer](../../../reference/predicate/isArrayBuffer.md) + +This `isArrayBuffer` function operates slowly due to complex handling for Lodash compatibility. + +Instead, use the faster and modern [isArrayBuffer](../../../reference/predicate/isArrayBuffer.md) from `es-toolkit`. + +::: + +Checks if a value is an ArrayBuffer. + +```typescript +const result = isArrayBuffer(value); +``` + +## Usage + +### `isArrayBuffer(value)` + +Use `isArrayBuffer` when you want to type-safely check if a value is an ArrayBuffer. It also works as a type guard in TypeScript. + +```typescript +import { isArrayBuffer } from 'es-toolkit/compat'; + +// ArrayBuffer check +const buffer = new ArrayBuffer(16); +isArrayBuffer(buffer); // true + +// Other types return false +isArrayBuffer(new Array()); // false +isArrayBuffer(new Map()); // false +isArrayBuffer({}); // false +isArrayBuffer('hello'); // false +isArrayBuffer(123); // false +isArrayBuffer(null); // false +isArrayBuffer(undefined); // false +``` + +#### Parameters + +- `value` (`unknown`): The value to check if it's an ArrayBuffer. + +#### Returns + +(`value is ArrayBuffer`): Returns `true` if the value is an ArrayBuffer, otherwise `false`. diff --git a/docs/reference/compat/predicate/isArrayLike.md b/docs/compat/reference/predicate/isArrayLike.md similarity index 100% rename from docs/reference/compat/predicate/isArrayLike.md rename to docs/compat/reference/predicate/isArrayLike.md diff --git a/docs/reference/compat/predicate/isArrayLikeObject.md b/docs/compat/reference/predicate/isArrayLikeObject.md similarity index 100% rename from docs/reference/compat/predicate/isArrayLikeObject.md rename to docs/compat/reference/predicate/isArrayLikeObject.md diff --git a/docs/reference/compat/predicate/isBoolean.md b/docs/compat/reference/predicate/isBoolean.md similarity index 100% rename from docs/reference/compat/predicate/isBoolean.md rename to docs/compat/reference/predicate/isBoolean.md diff --git a/docs/compat/reference/predicate/isBuffer.md b/docs/compat/reference/predicate/isBuffer.md new file mode 100644 index 000000000..7083f7938 --- /dev/null +++ b/docs/compat/reference/predicate/isBuffer.md @@ -0,0 +1,43 @@ +# isBuffer (Lodash Compatibility) + +::: warning Use es-toolkit's [isBuffer](../../../reference/predicate/isBuffer.md) instead +This `isBuffer` function operates slowly due to complex processing for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isBuffer](../../../reference/predicate/isBuffer.md) instead. +::: + +Checks if a value is a Buffer instance. + +```typescript +const result = isBuffer(value); +``` + +## Usage + +### `isBuffer(value)` + +Use `isBuffer` when you want to type-safely check if a value is a Buffer instance. It's useful when working with Buffer objects in Node.js environments. It also works as a type guard in TypeScript. + +```typescript +import { isBuffer } from 'es-toolkit/compat'; + +// Check Buffer instance +const buffer = Buffer.from('hello'); +isBuffer(buffer); // true + +// Other types return false +isBuffer('hello'); // false +isBuffer([1, 2, 3]); // false +isBuffer(new Uint8Array([1, 2, 3])); // false +isBuffer({}); // false +isBuffer(null); // false +isBuffer(undefined); // false +``` + +#### Parameters + +- `value` (`unknown`): The value to check if it's a Buffer instance. + +#### Returns + +(`boolean`): Returns `true` if the value is a Buffer instance, `false` otherwise. diff --git a/docs/compat/reference/predicate/isDate.md b/docs/compat/reference/predicate/isDate.md new file mode 100644 index 000000000..1479a99e8 --- /dev/null +++ b/docs/compat/reference/predicate/isDate.md @@ -0,0 +1,46 @@ +# isDate (Lodash Compatibility) + +::: warning Use es-toolkit's [isDate](../../../reference/predicate/isDate.md) instead +This `isDate` function operates slowly due to complex processing for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isDate](../../../reference/predicate/isDate.md) instead. +::: + +Checks if a value is a Date object. + +```typescript +const result = isDate(value); +``` + +## Usage + +### `isDate(value)` + +Use `isDate` when you want to type-safely check if a value is a Date object. It also works as a type guard in TypeScript. + +```typescript +import { isDate } from 'es-toolkit/compat'; + +// Check Date object +const date = new Date(); +isDate(date); // true + +// Invalid Date is also recognized as a Date object +const invalidDate = new Date('invalid'); +isDate(invalidDate); // true + +// Other types return false +isDate('2024-01-01'); // false +isDate(1640995200000); // false +isDate({}); // false +isDate(null); // false +isDate(undefined); // false +``` + +#### Parameters + +- `value` (`unknown`): The value to check if it's a Date object. + +#### Returns + +(`value is Date`): Returns `true` if the value is a Date object, `false` otherwise. diff --git a/docs/reference/compat/predicate/isElement.md b/docs/compat/reference/predicate/isElement.md similarity index 100% rename from docs/reference/compat/predicate/isElement.md rename to docs/compat/reference/predicate/isElement.md diff --git a/docs/reference/compat/predicate/isEmpty.md b/docs/compat/reference/predicate/isEmpty.md similarity index 100% rename from docs/reference/compat/predicate/isEmpty.md rename to docs/compat/reference/predicate/isEmpty.md diff --git a/docs/compat/reference/predicate/isEqual.md b/docs/compat/reference/predicate/isEqual.md new file mode 100644 index 000000000..32f17853c --- /dev/null +++ b/docs/compat/reference/predicate/isEqual.md @@ -0,0 +1,84 @@ +# isEqual (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isEqual](../../../reference/predicate/isEqual.md) + +This `isEqual` function operates slowly due to complex handling for Lodash compatibility. + +Instead, use the faster and modern [isEqual](../../../reference/predicate/isEqual.md) from `es-toolkit`. + +::: + +Performs a deep comparison between two values to determine if they are equal. + +```typescript +const result = isEqual(value1, value2); +``` + +## Usage + +### `isEqual(a, b)` + +Use `isEqual` when you want to perform a deep comparison between two values. It compares complex types like Date, RegExp, objects, and arrays by their content. + +```typescript +import { isEqual } from 'es-toolkit/compat'; + +// Basic type comparison +isEqual(1, 1); // true +isEqual('hello', 'hello'); // true +isEqual(true, true); // true + +// Object deep comparison +isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true +isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true +isEqual({ a: 1 }, { a: 1, b: undefined }); // false + +// Array deep comparison +isEqual([1, 2, 3], [1, 2, 3]); // true +isEqual([1, [2, 3]], [1, [2, 3]]); // true + +// Date object comparison +isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true +isEqual(new Date('2020-01-01'), new Date('2020-01-02')); // false + +// RegExp object comparison +isEqual(/abc/g, /abc/g); // true +isEqual(/abc/g, /abc/i); // false +``` + +It also recursively compares nested objects and arrays. + +```typescript +import { isEqual } from 'es-toolkit/compat'; + +const obj1 = { + user: { + name: 'John', + details: { + age: 30, + hobbies: ['reading', 'gaming'], + }, + }, +}; + +const obj2 = { + user: { + name: 'John', + details: { + age: 30, + hobbies: ['reading', 'gaming'], + }, + }, +}; + +isEqual(obj1, obj2); // true +``` + +#### Parameters + +- `a` (`unknown`): The first value to compare. +- `b` (`unknown`): The second value to compare. + +#### Returns + +(`boolean`): Returns `true` if the values are equal, otherwise `false`. diff --git a/docs/compat/reference/predicate/isEqualWith.md b/docs/compat/reference/predicate/isEqualWith.md new file mode 100644 index 000000000..33a1b94b1 --- /dev/null +++ b/docs/compat/reference/predicate/isEqualWith.md @@ -0,0 +1,92 @@ +# isEqualWith (Lodash Compatibility) + +::: warning Use es-toolkit's [isEqualWith](../../../reference/predicate/isEqualWith.md) instead +This `isEqualWith` function operates slowly due to complex processing for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isEqualWith](../../../reference/predicate/isEqualWith.md) instead. +::: + +Checks if two values are equal using a custom comparison function. + +```typescript +const result = isEqualWith(a, b, customizer); +``` + +## Usage + +### `isEqualWith(a, b, areValuesEqual?)` + +Deeply compares two values using a custom comparison function. If the custom function returns a boolean value, that result is used. If it returns `undefined`, the default equality comparison is used. + +The custom comparison function is also used when comparing values inside complex structures like objects, arrays, Map, Set, etc., ensuring deep comparison. + +```typescript +import { isEqualWith } from 'es-toolkit/compat'; + +// Case-insensitive string comparison +const customizer = (a: any, b: any) => { + if (typeof a === 'string' && typeof b === 'string') { + return a.toLowerCase() === b.toLowerCase(); + } +}; + +isEqualWith('Hello', 'hello', customizer); // true +isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true + +// Compare numbers by absolute value +const absCustomizer = (a: any, b: any) => { + if (typeof a === 'number' && typeof b === 'number') { + return Math.abs(a) === Math.abs(b); + } +}; + +isEqualWith([-1, 2], [1, -2], absCustomizer); // true + +// Complex object comparison +const obj1 = { + name: 'JOHN', + details: { age: 30, city: 'NYC' }, +}; +const obj2 = { + name: 'john', + details: { age: 30, city: 'nyc' }, +}; + +isEqualWith(obj1, obj2, customizer); // true +``` + +Special handling for Map and Set: + +```typescript +import { isEqualWith } from 'es-toolkit/compat'; + +const customizer = (a: any, b: any) => { + if (typeof a === 'string' && typeof b === 'string') { + return a.toLowerCase() === b.toLowerCase(); + } +}; + +const map1 = new Map([['KEY', 'value']]); +const map2 = new Map([['key', 'value']]); +isEqualWith(map1, map2, customizer); // true + +const set1 = new Set(['HELLO']); +const set2 = new Set(['hello']); +isEqualWith(set1, set2, customizer); // true +``` + +#### Parameters + +- `a` (`any`): The first value to compare. +- `b` (`any`): The second value to compare. +- `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): The custom comparison function. + - `x`: Value from the first object `a` + - `y`: Value from the second object `b` + - `property`: The property key used to get `x` and `y` + - `xParent`: The parent object of the first value `x` + - `yParent`: The parent object of the second value `y` + - `stack`: Internal stack (Map) for handling circular references + +#### Returns + +(`boolean`): Returns `true` if the values are equal according to the custom function, `false` otherwise. diff --git a/docs/compat/reference/predicate/isError.md b/docs/compat/reference/predicate/isError.md new file mode 100644 index 000000000..ffc1ab7bb --- /dev/null +++ b/docs/compat/reference/predicate/isError.md @@ -0,0 +1,47 @@ +# isError (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isError](../../../reference/predicate/isError.md) instead +This `isError` function operates slowly due to complex handling for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isError](../../../reference/predicate/isError.md) instead. +::: + +Checks if a value is an Error object. + +```typescript +const result = isError(value); +``` + +## Usage + +### `isError(value)` + +Use `isError` when you want to type-safely check if a value is an Error object. It also works as a type guard in TypeScript. + +```typescript +import { isError } from 'es-toolkit/compat'; + +// Error object checking +isError(new Error()); // true +isError(new TypeError('Type error')); // true +isError(new ReferenceError('Reference error')); // true + +// Custom errors that inherit from Error +class CustomError extends Error {} +isError(new CustomError()); // true + +// Other types return false +isError('Error'); // false +isError({ name: 'Error', message: 'Something went wrong' }); // false +isError({}); // false +isError(null); // false +isError(undefined); // false +``` + +#### Parameters + +- `value` (`unknown`): The value to check if it's an Error object. + +#### Returns + +(`value is Error`): Returns `true` if the value is an Error object, `false` otherwise. diff --git a/docs/reference/compat/predicate/isFinite.md b/docs/compat/reference/predicate/isFinite.md similarity index 100% rename from docs/reference/compat/predicate/isFinite.md rename to docs/compat/reference/predicate/isFinite.md diff --git a/docs/compat/reference/predicate/isFunction.md b/docs/compat/reference/predicate/isFunction.md new file mode 100644 index 000000000..37f016d9e --- /dev/null +++ b/docs/compat/reference/predicate/isFunction.md @@ -0,0 +1,52 @@ +# isFunction (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isFunction](../../../reference/predicate/isFunction.md) instead +This `isFunction` function operates slowly due to complex handling for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isFunction](../../../reference/predicate/isFunction.md) instead. +::: + +Checks if a value is a function. + +```typescript +const result = isFunction(value); +``` + +## Usage + +### `isFunction(value)` + +Use `isFunction` when you want to type-safely check if a value is a function. It also works as a type guard in TypeScript. + +```typescript +import { isFunction } from 'es-toolkit/compat'; + +// Regular functions +isFunction(function () {}); // true +isFunction(() => {}); // true + +// Built-in functions and constructors +isFunction(Array.prototype.slice); // true +isFunction(Proxy); // true +isFunction(Int8Array); // true + +// Async functions and generator functions +isFunction(async function () {}); // true +isFunction(function* () {}); // true + +// Other types return false +isFunction('function'); // false +isFunction({}); // false +isFunction([]); // false +isFunction(null); // false +isFunction(undefined); // false +isFunction(123); // false +``` + +#### Parameters + +- `value` (`unknown`): The value to check if it's a function. + +#### Returns + +(`value is (...args: any[]) => any`): Returns `true` if the value is a function, `false` otherwise. diff --git a/docs/reference/compat/predicate/isInteger.md b/docs/compat/reference/predicate/isInteger.md similarity index 100% rename from docs/reference/compat/predicate/isInteger.md rename to docs/compat/reference/predicate/isInteger.md diff --git a/docs/compat/reference/predicate/isLength.md b/docs/compat/reference/predicate/isLength.md new file mode 100644 index 000000000..231d245ab --- /dev/null +++ b/docs/compat/reference/predicate/isLength.md @@ -0,0 +1,63 @@ +# isLength (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isLength](../../../reference/predicate/isLength.md) instead +This `isLength` function operates slowly due to complex handling for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isLength](../../../reference/predicate/isLength.md) instead. +::: + +Checks if a value is a valid length. + +```typescript +const result = isLength(value); +``` + +## Usage + +### `isLength(value)` + +Use `isLength` when you want to check if a value is a valid length. A valid length is a number type, non-negative integer, and below JavaScript's maximum safe integer (`Number.MAX_SAFE_INTEGER`). It also works as a type guard in TypeScript. + +```typescript +import { isLength } from 'es-toolkit/compat'; + +// Valid lengths +isLength(0); // true +isLength(42); // true +isLength(100); // true +isLength(Number.MAX_SAFE_INTEGER); // true + +// Invalid lengths +isLength(-1); // false (negative) +isLength(1.5); // false (not an integer) +isLength(Number.MAX_SAFE_INTEGER + 1); // false (exceeds safe range) +isLength('3'); // false (string) +isLength(null); // false +isLength(undefined); // false +isLength({}); // false +isLength([]); // false +``` + +It's useful for validating the length property of arrays or strings. + +```typescript +import { isLength } from 'es-toolkit/compat'; + +function validateArrayLength(arr: any[]) { + if (isLength(arr.length)) { + console.log(`Array length ${arr.length} is valid`); + return true; + } + return false; +} + +validateArrayLength([1, 2, 3]); // "Array length 3 is valid" +``` + +#### Parameters + +- `value` (`any`): The value to check if it's a valid length. + +#### Returns + +(`boolean`): Returns `true` if the value is a valid length, `false` otherwise. diff --git a/docs/compat/reference/predicate/isMap.md b/docs/compat/reference/predicate/isMap.md new file mode 100644 index 000000000..4403c20dc --- /dev/null +++ b/docs/compat/reference/predicate/isMap.md @@ -0,0 +1,63 @@ +# isMap (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isMap](../../../reference/predicate/isMap.md) instead + +This `isMap` function operates slowly due to complex handling for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isMap](../../../reference/predicate/isMap.md) instead. + +::: + +Checks if a value is a Map. + +```typescript +const result = isMap(value); +``` + +## Usage + +### `isMap(value)` + +Use `isMap` when you want to type-safely check if a value is a Map. It also works as a type guard in TypeScript. + +```typescript +import { isMap } from 'es-toolkit/compat'; + +// Map checking +const map = new Map(); +isMap(map); // true + +// Other types return false +isMap(new Set()); // false +isMap(new WeakMap()); // false +isMap({}); // false +isMap([]); // false +isMap('map'); // false +isMap(123); // false +isMap(null); // false +isMap(undefined); // false +``` + +It also distinguishes from other similar collections. + +```typescript +import { isMap } from 'es-toolkit/compat'; + +// Map vs Set vs WeakMap +isMap(new Map([['key', 'value']])); // true +isMap(new Set(['value'])); // false +isMap(new WeakMap()); // false + +// Map vs regular objects +isMap({}); // false +isMap({ key: 'value' }); // false +isMap(Object.create(null)); // false +``` + +#### Parameters + +- `value` (`unknown`): The value to check if it's a Map. + +#### Returns + +(`value is Map`): Returns `true` if the value is a Map, `false` otherwise. diff --git a/docs/reference/compat/predicate/isMatch.md b/docs/compat/reference/predicate/isMatch.md similarity index 100% rename from docs/reference/compat/predicate/isMatch.md rename to docs/compat/reference/predicate/isMatch.md diff --git a/docs/reference/compat/predicate/isMatchWith.md b/docs/compat/reference/predicate/isMatchWith.md similarity index 100% rename from docs/reference/compat/predicate/isMatchWith.md rename to docs/compat/reference/predicate/isMatchWith.md diff --git a/docs/reference/compat/predicate/isNaN.md b/docs/compat/reference/predicate/isNaN.md similarity index 100% rename from docs/reference/compat/predicate/isNaN.md rename to docs/compat/reference/predicate/isNaN.md diff --git a/docs/reference/compat/predicate/isNative.md b/docs/compat/reference/predicate/isNative.md similarity index 100% rename from docs/reference/compat/predicate/isNative.md rename to docs/compat/reference/predicate/isNative.md diff --git a/docs/compat/reference/predicate/isNil.md b/docs/compat/reference/predicate/isNil.md new file mode 100644 index 000000000..f751b28ce --- /dev/null +++ b/docs/compat/reference/predicate/isNil.md @@ -0,0 +1,62 @@ +# isNil (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isNil](../../../reference/predicate/isNil.md) instead + +This `isNil` function operates slowly due to complex handling for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isNil](../../../reference/predicate/isNil.md) instead. + +::: + +Checks if a value is `null` or `undefined`. + +```typescript +const result = isNil(value); +``` + +## Usage + +### `isNil(x)` + +Use `isNil` when you want to type-safely check if a value is `null` or `undefined`. It also works as a type guard in TypeScript. + +```typescript +import { isNil } from 'es-toolkit/compat'; + +// null and undefined return true +isNil(null); // true +isNil(undefined); // true + +// All other values return false +isNil(0); // false +isNil(''); // false +isNil(false); // false +isNil([]); // false +isNil({}); // false +isNil('hello'); // false +isNil(42); // false +``` + +It distinguishes from values that are truthy but not `null` or `undefined`. + +```typescript +import { isNil } from 'es-toolkit/compat'; + +// Values that are falsy but not null/undefined +isNil(0); // false +isNil(''); // false +isNil(false); // false +isNil(NaN); // false + +// Only null and undefined return true +isNil(null); // true +isNil(undefined); // true +``` + +#### Parameters + +- `x` (`any`): The value to check if it's `null` or `undefined`. + +#### Returns + +(`x is null | undefined`): Returns `true` if the value is `null` or `undefined`, `false` otherwise. diff --git a/docs/compat/reference/predicate/isNull.md b/docs/compat/reference/predicate/isNull.md new file mode 100644 index 000000000..4f2ca313c --- /dev/null +++ b/docs/compat/reference/predicate/isNull.md @@ -0,0 +1,68 @@ +# isNull (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isNull](../../../reference/predicate/isNull.md) instead + +This `isNull` function is a Lodash compatibility function, but has the same implementation as the main library. + +Use the faster and more modern `es-toolkit`'s [isNull](../../../reference/predicate/isNull.md) instead. + +::: + +Checks if a value is `null`. + +```typescript +const result = isNull(value); +``` + +## Usage + +### `isNull(value)` + +Use `isNull` when you want to type-safely check if a value is exactly `null`. It also works as a type guard in TypeScript. + +```typescript +import { isNull } from 'es-toolkit/compat'; + +// Only null returns true +isNull(null); // true + +// undefined also returns false +isNull(undefined); // false + +// All other values also return false +isNull(0); // false +isNull(''); // false +isNull(false); // false +isNull([]); // false +isNull({}); // false +isNull('null'); // false +isNull(NaN); // false +``` + +You can distinguish between `null` and `undefined`. + +```typescript +import { isNull } from 'es-toolkit/compat'; + +function handleValue(value: string | null | undefined) { + if (isNull(value)) { + console.log('Value is explicitly null'); + } else if (value === undefined) { + console.log('Value is undefined'); + } else { + console.log(`Value exists: ${value}`); + } +} + +handleValue(null); // "Value is explicitly null" +handleValue(undefined); // "Value is undefined" +handleValue('hello'); // "Value exists: hello" +``` + +#### Parameters + +- `value` (`any`): The value to check if it's `null`. + +#### Returns + +(`value is null`): Returns `true` if the value is `null`, `false` otherwise. diff --git a/docs/reference/compat/predicate/isNumber.md b/docs/compat/reference/predicate/isNumber.md similarity index 100% rename from docs/reference/compat/predicate/isNumber.md rename to docs/compat/reference/predicate/isNumber.md diff --git a/docs/reference/compat/predicate/isObject.md b/docs/compat/reference/predicate/isObject.md similarity index 100% rename from docs/reference/compat/predicate/isObject.md rename to docs/compat/reference/predicate/isObject.md diff --git a/docs/reference/compat/predicate/isObjectLike.md b/docs/compat/reference/predicate/isObjectLike.md similarity index 100% rename from docs/reference/compat/predicate/isObjectLike.md rename to docs/compat/reference/predicate/isObjectLike.md diff --git a/docs/compat/reference/predicate/isPlainObject.md b/docs/compat/reference/predicate/isPlainObject.md new file mode 100644 index 000000000..05256f9b1 --- /dev/null +++ b/docs/compat/reference/predicate/isPlainObject.md @@ -0,0 +1,85 @@ +# isPlainObject (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isPlainObject](../../../reference/predicate/isPlainObject.md) instead + +This `isPlainObject` function operates slowly due to complex handling for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isPlainObject](../../../reference/predicate/isPlainObject.md) instead. + +::: + +Checks if a value is a plain object. + +```typescript +const result = isPlainObject(object); +``` + +## Usage + +### `isPlainObject(object)` + +Use `isPlainObject` when you want to check if a value is a plain object. A plain object is an object created by the `{}` literal, `new Object()`, or `Object.create(null)`. It also works as a type guard in TypeScript. + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +// Plain objects +isPlainObject({}); // true +isPlainObject(new Object()); // true +isPlainObject(Object.create(null)); // true +isPlainObject({ name: 'John', age: 30 }); // true + +// Not plain objects +isPlainObject([]); // false (array) +isPlainObject(new Date()); // false (Date instance) +isPlainObject(new Map()); // false (Map instance) +isPlainObject(new Set()); // false (Set instance) +isPlainObject(/regex/); // false (regular expression) +isPlainObject(function () {}); // false (function) +isPlainObject(null); // false +isPlainObject(undefined); // false +isPlainObject('object'); // false (string) +isPlainObject(42); // false (number) +``` + +It distinguishes between class instances and plain objects. + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +class Person { + name: string; + constructor(name: string) { + this.name = name; + } +} + +const person = new Person('John'); +const plainObj = { name: 'John' }; + +isPlainObject(person); // false (class instance) +isPlainObject(plainObj); // true (plain object) +``` + +It also correctly handles custom `Symbol.toStringTag` properties. + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +// Writable Symbol.toStringTag +const obj1 = {}; +obj1[Symbol.toStringTag] = 'CustomObject'; +isPlainObject(obj1); // true + +// Read-only Symbol.toStringTag (built-in objects) +const date = new Date(); +isPlainObject(date); // false +``` + +#### Parameters + +- `object` (`any`): The value to check if it's a plain object. + +#### Returns + +(`boolean`): Returns `true` if the value is a plain object, `false` otherwise. diff --git a/docs/compat/reference/predicate/isRegExp.md b/docs/compat/reference/predicate/isRegExp.md new file mode 100644 index 000000000..e61572d2b --- /dev/null +++ b/docs/compat/reference/predicate/isRegExp.md @@ -0,0 +1,82 @@ +# isRegExp (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isRegExp](../../../reference/predicate/isRegExp.md) instead + +This `isRegExp` function is a Lodash compatibility function, but is a simple type check. + +Use the faster and more modern `es-toolkit`'s [isRegExp](../../../reference/predicate/isRegExp.md) instead. + +::: + +Checks if a value is a regular expression. + +```typescript +const result = isRegExp(value); +``` + +## Usage + +### `isRegExp(value)` + +Use `isRegExp` when you want to type-safely check if a value is a regular expression. It also works as a type guard in TypeScript. + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// Regular expressions +isRegExp(/abc/); // true +isRegExp(new RegExp('abc')); // true +isRegExp(/[a-z]+/g); // true +isRegExp(/pattern/gi); // true + +// Other types return false +isRegExp('/abc/'); // false (string) +isRegExp('pattern'); // false (string) +isRegExp({}); // false (object) +isRegExp([]); // false (array) +isRegExp(null); // false +isRegExp(undefined); // false +isRegExp(123); // false (number) +``` + +It distinguishes between regex strings and actual regex objects. + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// Regular expression vs regex string +isRegExp(/test/); // true +isRegExp('/test/'); // false +isRegExp('\\d+'); // false +isRegExp('/\\d+/g'); // false + +// Various regex flags +isRegExp(/test/i); // true (case insensitive) +isRegExp(/test/g); // true (global search) +isRegExp(/test/m); // true (multiline) +isRegExp(/test/gim); // true (all flags combined) +``` + +It also recognizes dynamically created regular expressions. + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// Regex created with RegExp constructor +const dynamicRegex = new RegExp('\\d{3}-\\d{4}', 'g'); +isRegExp(dynamicRegex); // true + +// Regex created through strings +const pattern = 'hello'; +const flags = 'gi'; +const regex = new RegExp(pattern, flags); +isRegExp(regex); // true +``` + +#### Parameters + +- `value` (`any`): The value to check if it's a regular expression. + +#### Returns + +(`value is RegExp`): Returns `true` if the value is a regular expression, `false` otherwise. diff --git a/docs/reference/compat/predicate/isSafeInteger.md b/docs/compat/reference/predicate/isSafeInteger.md similarity index 100% rename from docs/reference/compat/predicate/isSafeInteger.md rename to docs/compat/reference/predicate/isSafeInteger.md diff --git a/docs/compat/reference/predicate/isSet.md b/docs/compat/reference/predicate/isSet.md new file mode 100644 index 000000000..c36739f9d --- /dev/null +++ b/docs/compat/reference/predicate/isSet.md @@ -0,0 +1,67 @@ +# isSet (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isSet](../../../reference/predicate/isSet.md) instead + +This `isSet` function is a Lodash compatibility function, but has the same implementation as the main library. + +Use the faster and more modern `es-toolkit`'s [isSet](../../../reference/predicate/isSet.md) instead. + +::: + +Checks if a value is a Set. + +```typescript +const result = isSet(value); +``` + +## Usage + +### `isSet(value)` + +Use `isSet` when you want to type-safely check if a value is a Set. It also works as a type guard in TypeScript. + +```typescript +import { isSet } from 'es-toolkit/compat'; + +// Set checking +const set = new Set(); +isSet(set); // true + +// Other types return false +isSet(new Map()); // false +isSet(new WeakSet()); // false +isSet([]); // false +isSet({}); // false +isSet('set'); // false +isSet(123); // false +isSet(null); // false +isSet(undefined); // false +``` + +It also distinguishes from other similar collections. + +```typescript +import { isSet } from 'es-toolkit/compat'; + +// Set vs Map vs WeakSet +isSet(new Set([1, 2, 3])); // true +isSet(new Map([['key', 'value']])); // false +isSet(new WeakSet()); // false + +// Set vs array +isSet(new Set([1, 2, 3])); // true +isSet([1, 2, 3]); // false + +// Set vs regular objects +isSet(new Set()); // true +isSet({}); // false +isSet(Object.create(null)); // false +``` + +#### Parameters + +- `value` (`unknown`): The value to check if it's a Set. + +#### Returns + +(`value is Set`): Returns `true` if the value is a Set, `false` otherwise. diff --git a/docs/reference/compat/predicate/isString.md b/docs/compat/reference/predicate/isString.md similarity index 100% rename from docs/reference/compat/predicate/isString.md rename to docs/compat/reference/predicate/isString.md diff --git a/docs/reference/compat/predicate/isSymbol.md b/docs/compat/reference/predicate/isSymbol.md similarity index 100% rename from docs/reference/compat/predicate/isSymbol.md rename to docs/compat/reference/predicate/isSymbol.md diff --git a/docs/reference/compat/predicate/isTypedArray.md b/docs/compat/reference/predicate/isTypedArray.md similarity index 100% rename from docs/reference/compat/predicate/isTypedArray.md rename to docs/compat/reference/predicate/isTypedArray.md diff --git a/docs/compat/reference/predicate/isUndefined.md b/docs/compat/reference/predicate/isUndefined.md new file mode 100644 index 000000000..84213c57b --- /dev/null +++ b/docs/compat/reference/predicate/isUndefined.md @@ -0,0 +1,92 @@ +# isUndefined (Lodash Compatibility) + +::: warning Use `es-toolkit`'s [isUndefined](../../../reference/predicate/isUndefined.md) instead + +This `isUndefined` function operates slowly due to complex handling for Lodash compatibility. + +Use the faster and more modern `es-toolkit`'s [isUndefined](../../../reference/predicate/isUndefined.md) instead. + +::: + +Checks if a value is `undefined`. + +```typescript +const result = isUndefined(value); +``` + +## Usage + +### `isUndefined(x)` + +Use `isUndefined` when you want to type-safely check if a value is exactly `undefined`. It also works as a type guard in TypeScript. + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +// Only undefined returns true +isUndefined(undefined); // true + +// null also returns false +isUndefined(null); // false + +// All other values also return false +isUndefined(0); // false +isUndefined(''); // false +isUndefined(false); // false +isUndefined([]); // false +isUndefined({}); // false +isUndefined('undefined'); // false +isUndefined(NaN); // false +``` + +You can distinguish between `undefined` and `null`. + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +function handleValue(value: string | null | undefined) { + if (isUndefined(value)) { + console.log('Value is undefined'); + } else if (value === null) { + console.log('Value is explicitly null'); + } else { + console.log(`Value exists: ${value}`); + } +} + +handleValue(undefined); // "Value is undefined" +handleValue(null); // "Value is explicitly null" +handleValue('hello'); // "Value exists: hello" +``` + +It's useful for checking undeclared variables or uninitialized properties. + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +const obj: { name?: string; age?: number } = { name: 'John' }; + +if (isUndefined(obj.age)) { + console.log('Age is not set'); + obj.age = 25; // Set default value +} + +// Default value handling for function parameters +function greet(name: string, title?: string) { + if (isUndefined(title)) { + title = 'Mr./Ms.'; + } + console.log(`Hello, ${title} ${name}!`); +} + +greet('Kim'); // "Hello, Mr./Ms. Kim!" +greet('Kim', 'Dr.'); // "Hello, Dr. Kim!" +``` + +#### Parameters + +- `x` (`any`): The value to check if it's `undefined`. + +#### Returns + +(`x is undefined`): Returns `true` if the value is `undefined`, `false` otherwise. diff --git a/docs/reference/compat/predicate/isWeakMap.md b/docs/compat/reference/predicate/isWeakMap.md similarity index 100% rename from docs/reference/compat/predicate/isWeakMap.md rename to docs/compat/reference/predicate/isWeakMap.md diff --git a/docs/reference/compat/predicate/isWeakSet.md b/docs/compat/reference/predicate/isWeakSet.md similarity index 100% rename from docs/reference/compat/predicate/isWeakSet.md rename to docs/compat/reference/predicate/isWeakSet.md diff --git a/docs/reference/compat/predicate/matches.md b/docs/compat/reference/predicate/matches.md similarity index 100% rename from docs/reference/compat/predicate/matches.md rename to docs/compat/reference/predicate/matches.md diff --git a/docs/reference/compat/predicate/matchesProperty.md b/docs/compat/reference/predicate/matchesProperty.md similarity index 100% rename from docs/reference/compat/predicate/matchesProperty.md rename to docs/compat/reference/predicate/matchesProperty.md diff --git a/docs/compat/reference/string/camelCase.md b/docs/compat/reference/string/camelCase.md new file mode 100644 index 000000000..d3d85190b --- /dev/null +++ b/docs/compat/reference/string/camelCase.md @@ -0,0 +1,48 @@ +# camelCase (Lodash compatibility) + +::: warning Use `camelCase` from `es-toolkit` + +This `camelCase` function operates slower due to handling non-string input values and removing contracted apostrophes. + +Instead, use the faster and more modern [camelCase](../../../reference/string/camelCase.md) from `es-toolkit`. + +::: + +Converts a string to camel case. + +```typescript +const result = camelCase(str); +``` + +## Usage + +### `camelCase(str)` + +Converts a string to camel case. Camel case is a naming convention where the first word starts with a lowercase letter and subsequent words begin with uppercase letters, all without spaces. + +```typescript +import { camelCase } from 'es-toolkit/compat'; + +camelCase('camelCase'); // 'camelCase' +camelCase('some whitespace'); // 'someWhitespace' +camelCase('hyphen-text'); // 'hyphenText' +camelCase('HTTPRequest'); // 'httpRequest' +``` + +Non-string values are also converted to strings before processing. + +```typescript +import { camelCase } from 'es-toolkit/compat'; + +camelCase(123); // '123' +camelCase(null); // '' +camelCase(undefined); // '' +``` + +#### Parameters + +- `str` (`string | object`, optional): The value to convert to camel case. + +#### Returns + +(`string`): Returns the string converted to camel case. diff --git a/docs/compat/reference/string/capitalize.md b/docs/compat/reference/string/capitalize.md new file mode 100644 index 000000000..2ae80f6ab --- /dev/null +++ b/docs/compat/reference/string/capitalize.md @@ -0,0 +1,48 @@ +# capitalize (Lodash compatibility) + +::: warning Use `capitalize` from `es-toolkit` + +This `capitalize` function operates slower due to handling non-string input values. + +Instead, use the faster and more modern [capitalize](../../../reference/string/capitalize.md) from `es-toolkit`. + +::: + +Converts the first character of a string to uppercase and the remaining characters to lowercase. + +```typescript +const result = capitalize(str); +``` + +## Usage + +### `capitalize(str)` + +Converts the first character of a string to uppercase and the remaining characters to lowercase. This is useful for making the first impression of a word better or formatting it as a title. + +```typescript +import { capitalize } from 'es-toolkit/compat'; + +capitalize('fred'); // 'Fred' +capitalize('FRED'); // 'Fred' +capitalize('fRED'); // 'Fred' +``` + +Empty strings and non-string values can also be handled. + +```typescript +import { capitalize } from 'es-toolkit/compat'; + +capitalize(''); // '' +capitalize(123); // '123' +capitalize(null); // '' +capitalize(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to capitalize. + +#### Returns + +(`string`): Returns the string with the first character capitalized and the remaining characters in lowercase. diff --git a/docs/compat/reference/string/deburr.md b/docs/compat/reference/string/deburr.md new file mode 100644 index 000000000..e23a4bb07 --- /dev/null +++ b/docs/compat/reference/string/deburr.md @@ -0,0 +1,47 @@ +# deburr (Lodash compatibility) + +::: warning Use `deburr` from `es-toolkit` + +This `deburr` function operates slower due to handling non-string input values. + +Instead, use the faster and more modern [deburr](../../../reference/string/deburr.md) from `es-toolkit`. + +::: + +Converts special characters and diacritical marks in a string to ASCII characters. + +```typescript +const result = deburr(str); +``` + +## Usage + +### `deburr(str)` + +Converts special characters and diacritical marks in a string to ASCII characters. This is useful for making multilingual text easier to search or sort. + +```typescript +import { deburr } from 'es-toolkit/compat'; + +deburr('Æthelred'); // 'Aethelred' +deburr('München'); // 'Munchen' +deburr('Crème brûlée'); // 'Creme brulee' +``` + +Non-string values are also converted to strings before processing. + +```typescript +import { deburr } from 'es-toolkit/compat'; + +deburr(123); // '123' +deburr(null); // '' +deburr(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to remove special characters from. + +#### Returns + +(`string`): Returns the string with special characters and diacritical marks converted to ASCII characters. diff --git a/docs/reference/compat/string/endsWith.md b/docs/compat/reference/string/endsWith.md similarity index 100% rename from docs/reference/compat/string/endsWith.md rename to docs/compat/reference/string/endsWith.md diff --git a/docs/compat/reference/string/escape.md b/docs/compat/reference/string/escape.md new file mode 100644 index 000000000..14752c36e --- /dev/null +++ b/docs/compat/reference/string/escape.md @@ -0,0 +1,48 @@ +# escape (Lodash compatibility) + +::: warning Use `escape` from `es-toolkit` + +This `escape` function operates slower due to handling non-string input values. + +Instead, use the faster and more modern [escape](../../../reference/string/escape.md) from `es-toolkit`. + +::: + +Converts HTML special characters in a string to HTML entities. + +```typescript +const result = escape(str); +``` + +## Usage + +### `escape(str)` + +Converts the characters `&`, `<`, `>`, `"`, `'` in a string to their corresponding HTML entities. This is useful for preventing XSS attacks when inserting text into HTML documents. + +```typescript +import { escape } from 'es-toolkit/compat'; + +escape('This is a
element.'); // 'This is a <div> element.' +escape('This is a "quote"'); // 'This is a "quote"' +escape("This is a 'quote'"); // 'This is a 'quote'' +escape('This is a & symbol'); // 'This is a & symbol' +``` + +Non-string values are also converted to strings before processing. + +```typescript +import { escape } from 'es-toolkit/compat'; + +escape(123); // '123' +escape(null); // '' +escape(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to escape HTML special characters. + +#### Returns + +(`string`): Returns the string with HTML special characters converted to entities. diff --git a/docs/compat/reference/string/escapeRegExp.md b/docs/compat/reference/string/escapeRegExp.md new file mode 100644 index 000000000..b8b2d4b31 --- /dev/null +++ b/docs/compat/reference/string/escapeRegExp.md @@ -0,0 +1,49 @@ +# escapeRegExp (Lodash compatibility) + +::: warning Use `escapeRegExp` from `es-toolkit` + +This `escapeRegExp` function operates slower due to handling non-string input values. + +Instead, use the faster and more modern [escapeRegExp](../../../reference/string/escapeRegExp.md) from `es-toolkit`. + +::: + +Escapes regular expression special characters in a string. + +```typescript +const result = escapeRegExp(str); +``` + +## Usage + +### `escapeRegExp(str)` + +Escapes regular expression special characters `^`, `$`, `\`, `.`, `*`, `+`, `?`, `(`, `)`, `[`, `]`, `{`, `}`, `|` in a string. This is useful when you want to treat a string literally when dynamically creating regular expressions. + +```typescript +import { escapeRegExp } from 'es-toolkit/compat'; + +escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); +// '\\[es-toolkit\\]\\(https://es-toolkit\\.dev/\\)' + +escapeRegExp('$^{}.+*?()[]|\\'); +// '\\$\\^\\{\\}\\.\\+\\*\\?\\(\\)\\[\\]\\|\\\\' +``` + +Non-string values are also converted to strings before processing. + +```typescript +import { escapeRegExp } from 'es-toolkit/compat'; + +escapeRegExp(123); // '123' +escapeRegExp(null); // '' +escapeRegExp(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to escape regular expression special characters. + +#### Returns + +(`string`): Returns the string with regular expression special characters escaped. diff --git a/docs/compat/reference/string/kebabCase.md b/docs/compat/reference/string/kebabCase.md new file mode 100644 index 000000000..06e0ecc66 --- /dev/null +++ b/docs/compat/reference/string/kebabCase.md @@ -0,0 +1,48 @@ +# kebabCase (Lodash compatibility) + +::: warning Use `kebabCase` from `es-toolkit` + +This `kebabCase` function operates slower due to handling non-string input values and removing contracted apostrophes. + +Instead, use the faster and more modern [kebabCase](../../../reference/string/kebabCase.md) from `es-toolkit`. + +::: + +Converts a string to kebab case. + +```typescript +const result = kebabCase(str); +``` + +## Usage + +### `kebabCase(str)` + +Converts a string to kebab case. Kebab case is a naming convention where each word is written in lowercase and connected with a dash (-) character. It's commonly used in URLs and CSS class names. + +```typescript +import { kebabCase } from 'es-toolkit/compat'; + +kebabCase('camelCase'); // 'camel-case' +kebabCase('some whitespace'); // 'some-whitespace' +kebabCase('hyphen-text'); // 'hyphen-text' +kebabCase('HTTPRequest'); // 'http-request' +``` + +Non-string values are also converted to strings before processing. + +```typescript +import { kebabCase } from 'es-toolkit/compat'; + +kebabCase(123); // '123' +kebabCase(null); // '' +kebabCase(undefined); // '' +``` + +#### Parameters + +- `str` (`string | object`, optional): The value to convert to kebab case. + +#### Returns + +(`string`): Returns the string converted to kebab case. diff --git a/docs/compat/reference/string/lowerCase.md b/docs/compat/reference/string/lowerCase.md new file mode 100644 index 000000000..018376013 --- /dev/null +++ b/docs/compat/reference/string/lowerCase.md @@ -0,0 +1,48 @@ +# lowerCase (Lodash compatibility) + +::: warning Use `lowerCase` from `es-toolkit` + +This `lowerCase` function operates slower due to handling non-string input values and removing contracted apostrophes. + +Instead, use the faster and more modern [lowerCase](../../../reference/string/lowerCase.md) from `es-toolkit`. + +::: + +Converts a string to lowercase words separated by spaces. + +```typescript +const result = lowerCase(str); +``` + +## Usage + +### `lowerCase(str)` + +Converts a string to lowercase words separated by spaces. Each word is converted to lowercase and connected with space characters. This is useful for creating human-readable text. + +```typescript +import { lowerCase } from 'es-toolkit/compat'; + +lowerCase('camelCase'); // 'camel case' +lowerCase('some whitespace'); // 'some whitespace' +lowerCase('hyphen-text'); // 'hyphen text' +lowerCase('HTTPRequest'); // 'http request' +``` + +Non-string values are also converted to strings before processing. + +```typescript +import { lowerCase } from 'es-toolkit/compat'; + +lowerCase(123); // '123' +lowerCase(null); // '' +lowerCase(undefined); // '' +``` + +#### Parameters + +- `str` (`string | object`, optional): The value to convert to lowercase format. + +#### Returns + +(`string`): Returns the string with lowercase words separated by spaces. diff --git a/docs/compat/reference/string/lowerFirst.md b/docs/compat/reference/string/lowerFirst.md new file mode 100644 index 000000000..4541bd18e --- /dev/null +++ b/docs/compat/reference/string/lowerFirst.md @@ -0,0 +1,48 @@ +# lowerFirst (Lodash compatibility) + +::: warning Use `lowerFirst` from `es-toolkit` + +This `lowerFirst` function operates slower due to handling non-string input values. + +Instead, use the faster and more modern [lowerFirst](../../../reference/string/lowerFirst.md) from `es-toolkit`. + +::: + +Converts the first character of a string to lowercase. + +```typescript +const result = lowerFirst(str); +``` + +## Usage + +### `lowerFirst(str)` + +Converts the first character of a string to lowercase. The remaining characters are kept as is. This is useful for creating camelCase variable names or when you only want to lowercase the first character. + +```typescript +import { lowerFirst } from 'es-toolkit/compat'; + +lowerFirst('fred'); // 'fred' +lowerFirst('Fred'); // 'fred' +lowerFirst('FRED'); // 'fRED' +lowerFirst(''); // '' +``` + +Non-string values are also converted to strings before processing. + +```typescript +import { lowerFirst } from 'es-toolkit/compat'; + +lowerFirst(123); // '123' +lowerFirst(null); // '' +lowerFirst(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to convert the first character to lowercase. + +#### Returns + +(`string`): Returns the string with the first character converted to lowercase. diff --git a/docs/compat/reference/string/pad.md b/docs/compat/reference/string/pad.md new file mode 100644 index 000000000..4432115ed --- /dev/null +++ b/docs/compat/reference/string/pad.md @@ -0,0 +1,60 @@ +# pad (Lodash compatibility) + +::: warning Use `pad` from `es-toolkit` + +This `pad` function operates slower due to handling `null` or `undefined`. + +Instead, use the faster and more modern [pad](../../../reference/string/pad.md) from `es-toolkit`. + +::: + +Pads a string on both sides with padding characters to reach the specified length. + +```typescript +const padded = pad(str, length, chars); +``` + +## Usage + +### `pad(str, length, chars)` + +Use `pad` when you want to pad a string on both sides to match a desired length. If the padding characters don't divide evenly, extra characters are placed on the right. + +```typescript +import { pad } from 'es-toolkit/compat'; + +// Pad with default spaces +pad('abc', 8); +// Returns: ' abc ' + +// Pad with specified characters +pad('abc', 8, '_-'); +// Returns: '_-abc_-_' + +// Return as is if already long enough +pad('abc', 3); +// Returns: 'abc' + +// Return as is if length is shorter +pad('abc', 2); +// Returns: 'abc' +``` + +`null` or `undefined` are treated as empty strings. + +```typescript +import { pad } from 'es-toolkit/compat'; + +pad(null, 5); // ' ' +pad(undefined, 3, '*'); // '***' +``` + +#### Parameters + +- `str` (`string`, optional): The string to pad. +- `length` (`number`, optional): The target length. Defaults to `0`. +- `chars` (`string`, optional): The characters to use for padding. Defaults to space `' '`. + +#### Returns + +(`string`): Returns the string padded to the specified length. diff --git a/docs/reference/compat/string/padEnd.md b/docs/compat/reference/string/padEnd.md similarity index 100% rename from docs/reference/compat/string/padEnd.md rename to docs/compat/reference/string/padEnd.md diff --git a/docs/reference/compat/string/padStart.md b/docs/compat/reference/string/padStart.md similarity index 100% rename from docs/reference/compat/string/padStart.md rename to docs/compat/reference/string/padStart.md diff --git a/docs/reference/compat/string/repeat.md b/docs/compat/reference/string/repeat.md similarity index 100% rename from docs/reference/compat/string/repeat.md rename to docs/compat/reference/string/repeat.md diff --git a/docs/reference/compat/string/replace.md b/docs/compat/reference/string/replace.md similarity index 100% rename from docs/reference/compat/string/replace.md rename to docs/compat/reference/string/replace.md diff --git a/docs/compat/reference/string/snakeCase.md b/docs/compat/reference/string/snakeCase.md new file mode 100644 index 000000000..e47c0413e --- /dev/null +++ b/docs/compat/reference/string/snakeCase.md @@ -0,0 +1,58 @@ +# snakeCase (Lodash compatibility) + +::: warning Use `snakeCase` from `es-toolkit` + +This `snakeCase` function operates slowly due to normalization logic for handling `null` or `undefined`. + +Instead, use the faster and more modern [snakeCase](../../../reference/string/snakeCase.md) from `es-toolkit`. + +::: + +Converts a string to snake case. + +```typescript +const snakeCased = snakeCase(str); +``` + +## Usage + +### `snakeCase(str)` + +Use `snakeCase` when you want to convert a string to snake*case. Snake case is a naming convention where each word is written in lowercase and connected with underscores (*). + +```typescript +import { snakeCase } from 'es-toolkit/compat'; + +// Convert camel case +snakeCase('camelCase'); +// Returns: 'camel_case' + +// Convert space-separated string +snakeCase('some whitespace'); +// Returns: 'some_whitespace' + +// Convert hyphen-separated string +snakeCase('hyphen-text'); +// Returns: 'hyphen_text' + +// Handle consecutive uppercase letters +snakeCase('HTTPRequest'); +// Returns: 'http_request' +``` + +`null` or `undefined` are treated as empty strings. + +```typescript +import { snakeCase } from 'es-toolkit/compat'; + +snakeCase(null); // '' +snakeCase(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to convert to snake case. + +#### Returns + +(`string`): Returns the converted string in snake case. diff --git a/docs/reference/compat/string/split.md b/docs/compat/reference/string/split.md similarity index 100% rename from docs/reference/compat/string/split.md rename to docs/compat/reference/string/split.md diff --git a/docs/compat/reference/string/startCase.md b/docs/compat/reference/string/startCase.md new file mode 100644 index 000000000..26eb3cf5d --- /dev/null +++ b/docs/compat/reference/string/startCase.md @@ -0,0 +1,58 @@ +# startCase (Lodash compatibility) + +::: warning Use `startCase` from `es-toolkit` + +This `startCase` function runs slower due to normalization logic for handling `null` or `undefined`. + +Instead, use the faster and more modern [startCase](../../../reference/string/startCase.md) from `es-toolkit`. + +::: + +Converts a string to start case. + +```typescript +const startCased = startCase(str); +``` + +## Usage + +### `startCase(str)` + +Use `startCase` when you want to convert a string to Start Case. Start Case is a naming convention where the first letter of each word is capitalized and separated by spaces. + +```typescript +import { startCase } from 'es-toolkit/compat'; + +// Convert regular string +startCase('hello world'); +// Returns: 'Hello World' + +// Keep words that are already uppercase +startCase('HELLO WORLD'); +// Returns: 'HELLO WORLD' + +// Convert hyphen-separated string +startCase('hello-world'); +// Returns: 'Hello World' + +// Convert underscore-separated string +startCase('hello_world'); +// Returns: 'Hello World' +``` + +`null` or `undefined` are treated as empty strings. + +```typescript +import { startCase } from 'es-toolkit/compat'; + +startCase(null); // '' +startCase(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to convert to start case. + +#### Returns + +(`string`): Returns the start case converted string. diff --git a/docs/reference/compat/string/startsWith.md b/docs/compat/reference/string/startsWith.md similarity index 100% rename from docs/reference/compat/string/startsWith.md rename to docs/compat/reference/string/startsWith.md diff --git a/docs/reference/compat/string/template.md b/docs/compat/reference/string/template.md similarity index 100% rename from docs/reference/compat/string/template.md rename to docs/compat/reference/string/template.md diff --git a/docs/reference/compat/string/toLower.md b/docs/compat/reference/string/toLower.md similarity index 100% rename from docs/reference/compat/string/toLower.md rename to docs/compat/reference/string/toLower.md diff --git a/docs/reference/compat/string/toUpper.md b/docs/compat/reference/string/toUpper.md similarity index 100% rename from docs/reference/compat/string/toUpper.md rename to docs/compat/reference/string/toUpper.md diff --git a/docs/compat/reference/string/trim.md b/docs/compat/reference/string/trim.md new file mode 100644 index 000000000..5f02a018d --- /dev/null +++ b/docs/compat/reference/string/trim.md @@ -0,0 +1,55 @@ +# trim (Lodash Compatibility) + +::: warning Use `trim` from `es-toolkit` + +This `trim` function operates slowly due to handling `null` or `undefined` and array-type `chars`. + +Use the faster and more modern [trim](../../../reference/string/trim.md) from `es-toolkit` instead. + +::: + +Removes leading and trailing whitespace or specified characters from a string. + +```typescript +const trimmed = trim(str, chars); +``` + +## Usage + +### `trim(str, chars)` + +Use `trim` when you want to remove whitespace or specific characters from the beginning and end of a string. If `chars` is not specified, only leading and trailing whitespace will be removed. + +```typescript +import { trim } from 'es-toolkit/compat'; + +// Remove leading and trailing whitespace +trim(' hello '); +// Returns: 'hello' + +// Remove specified characters +trim('--hello--', '-'); +// Returns: 'hello' + +// Remove multiple characters with an array +trim('##hello##', ['#', 'o']); +// Returns: 'hell' +``` + +`null` or `undefined` is treated as an empty string. + +```typescript +import { trim } from 'es-toolkit/compat'; + +trim(null); // '' +trim(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to trim. +- `chars` (`string`, optional): The characters to remove. If not specified, whitespace will be removed. + +#### Returns + +(`string`): Returns the string with specified characters removed from the beginning and end. diff --git a/docs/compat/reference/string/trimEnd.md b/docs/compat/reference/string/trimEnd.md new file mode 100644 index 000000000..a25202fb4 --- /dev/null +++ b/docs/compat/reference/string/trimEnd.md @@ -0,0 +1,55 @@ +# trimEnd (Lodash Compatibility) + +::: warning Use `trimEnd` from `es-toolkit` + +This `trimEnd` function operates slowly due to handling `null` or `undefined` and parameter order changes. + +Use the faster and more modern [trimEnd](../../../reference/string/trimEnd.md) from `es-toolkit` instead. + +::: + +Removes trailing whitespace or specified characters from a string. + +```typescript +const trimmed = trimEnd(str, chars); +``` + +## Usage + +### `trimEnd(str, chars)` + +Use `trimEnd` when you want to remove whitespace or specific characters from the end of a string. If `chars` is not specified, only trailing whitespace will be removed. + +```typescript +import { trimEnd } from 'es-toolkit/compat'; + +// Remove trailing whitespace +trimEnd(' abc '); +// Returns: ' abc' + +// Remove specified characters +trimEnd('-_-abc-_-', '_-'); +// Returns: '-_-abc' + +// Only applies to the end of the string +trimEnd('abc', 'a'); +// Returns: 'abc' +``` + +`null` or `undefined` is treated as an empty string. + +```typescript +import { trimEnd } from 'es-toolkit/compat'; + +trimEnd(null); // '' +trimEnd(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to trim from the end. +- `chars` (`string`, optional): The characters to remove. If not specified, whitespace will be removed. + +#### Returns + +(`string`): Returns the string with specified characters removed from the end. diff --git a/docs/compat/reference/string/trimStart.md b/docs/compat/reference/string/trimStart.md new file mode 100644 index 000000000..abf2c02e0 --- /dev/null +++ b/docs/compat/reference/string/trimStart.md @@ -0,0 +1,55 @@ +# trimStart (Lodash Compatibility) + +::: warning Use `trimStart` from `es-toolkit` + +This `trimStart` function operates slowly due to handling `null` or `undefined` and parameter order changes. + +Use the faster and more modern [trimStart](../../../reference/string/trimStart.md) from `es-toolkit` instead. + +::: + +Removes leading whitespace or specified characters from a string. + +```typescript +const trimmed = trimStart(str, chars); +``` + +## Usage + +### `trimStart(str, chars)` + +Use `trimStart` when you want to remove whitespace or specific characters from the beginning of a string. If `chars` is not specified, only leading whitespace will be removed. + +```typescript +import { trimStart } from 'es-toolkit/compat'; + +// Remove leading whitespace +trimStart(' abc '); +// Returns: 'abc ' + +// Remove specified characters +trimStart('-_-abc-_-', '_-'); +// Returns: 'abc-_-' + +// Only applies to the beginning of the string +trimStart('abc', 'c'); +// Returns: 'abc' +``` + +`null` or `undefined` is treated as an empty string. + +```typescript +import { trimStart } from 'es-toolkit/compat'; + +trimStart(null); // '' +trimStart(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to trim from the beginning. +- `chars` (`string`, optional): The characters to remove. If not specified, whitespace will be removed. + +#### Returns + +(`string`): Returns the string with specified characters removed from the beginning. diff --git a/docs/reference/compat/string/truncate.md b/docs/compat/reference/string/truncate.md similarity index 100% rename from docs/reference/compat/string/truncate.md rename to docs/compat/reference/string/truncate.md diff --git a/docs/compat/reference/string/unescape.md b/docs/compat/reference/string/unescape.md new file mode 100644 index 000000000..b5dc2d264 --- /dev/null +++ b/docs/compat/reference/string/unescape.md @@ -0,0 +1,58 @@ +# unescape (Lodash Compatibility) + +::: warning Use `unescape` from `es-toolkit` + +This `unescape` function operates slowly due to conversion logic for handling `null` or `undefined`. + +Use the faster and more modern [unescape](../../../reference/string/unescape.md) from `es-toolkit` instead. + +::: + +Converts HTML entities to their original characters. + +```typescript +const unescaped = unescape(str); +``` + +## Usage + +### `unescape(str)` + +Use `unescape` when you want to convert HTML entities `&`, `<`, `>`, `"`, `'` back to their original characters. This is the reverse operation of the `escape` function. + +```typescript +import { unescape } from 'es-toolkit/compat'; + +// Unescape HTML tags +unescape('This is a <div> element.'); +// Returns: 'This is a
element.' + +// Unescape quotes +unescape('This is a "quote"'); +// Returns: 'This is a "quote"' + +// Unescape apostrophes +unescape('This is a 'quote''); +// Returns: 'This is a 'quote'' + +// Unescape ampersands +unescape('This is a & symbol'); +// Returns: 'This is a & symbol' +``` + +`null` or `undefined` is treated as an empty string. + +```typescript +import { unescape } from 'es-toolkit/compat'; + +unescape(null); // '' +unescape(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to unescape. + +#### Returns + +(`string`): Returns the string with HTML entities converted to their original characters. diff --git a/docs/compat/reference/string/upperCase.md b/docs/compat/reference/string/upperCase.md new file mode 100644 index 000000000..1f5a40b01 --- /dev/null +++ b/docs/compat/reference/string/upperCase.md @@ -0,0 +1,58 @@ +# upperCase (Lodash Compatibility) + +::: warning Use `upperCase` from `es-toolkit` + +This `upperCase` function operates slowly due to normalization logic for handling `null` or `undefined`. + +Use the faster and more modern [upperCase](../../../reference/string/upperCase.md) from `es-toolkit` instead. + +::: + +Converts a string to upper case. + +```typescript +const upperCased = upperCase(str); +``` + +## Usage + +### `upperCase(str)` + +Use `upperCase` when you want to convert a string to upper case (UPPER CASE). Upper case is a naming convention where each word is written in uppercase and connected with spaces. + +```typescript +import { upperCase } from 'es-toolkit/compat'; + +// Convert camel case +upperCase('camelCase'); +// Returns: 'CAMEL CASE' + +// Convert space-separated string +upperCase('some whitespace'); +// Returns: 'SOME WHITESPACE' + +// Convert hyphen-separated string +upperCase('hyphen-text'); +// Returns: 'HYPHEN TEXT' + +// When uppercase letters appear consecutively +upperCase('HTTPRequest'); +// Returns: 'HTTP REQUEST' +``` + +`null` or `undefined` is treated as an empty string. + +```typescript +import { upperCase } from 'es-toolkit/compat'; + +upperCase(null); // '' +upperCase(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to convert to upper case. + +#### Returns + +(`string`): Returns the string converted to upper case. diff --git a/docs/compat/reference/string/upperFirst.md b/docs/compat/reference/string/upperFirst.md new file mode 100644 index 000000000..52ec9ace8 --- /dev/null +++ b/docs/compat/reference/string/upperFirst.md @@ -0,0 +1,54 @@ +# upperFirst (Lodash Compatibility) + +::: warning Use `upperFirst` from `es-toolkit` + +This `upperFirst` function operates slowly due to conversion logic for handling `null` or `undefined`. + +Use the faster and more modern [upperFirst](../../../reference/string/upperFirst.md) from `es-toolkit` instead. + +::: + +Converts the first character of a string to uppercase. + +```typescript +const upperCased = upperFirst(str); +``` + +## Usage + +### `upperFirst(str)` + +Use `upperFirst` when you want to capitalize only the first character of a string. The remaining characters stay unchanged. + +```typescript +import { upperFirst } from 'es-toolkit/compat'; + +// String starting with lowercase +upperFirst('fred'); +// Returns: 'Fred' + +// String already starting with uppercase +upperFirst('Fred'); +// Returns: 'Fred' + +// All uppercase string +upperFirst('FRED'); +// Returns: 'FRED' +``` + +`null` or `undefined` is treated as an empty string. + +```typescript +import { upperFirst } from 'es-toolkit/compat'; + +upperFirst(null); // '' +upperFirst(undefined); // '' +``` + +#### Parameters + +- `str` (`string`, optional): The string to convert the first character to uppercase. + +#### Returns + +(`string`): Returns the string with the first character converted to uppercase. diff --git a/docs/compat/reference/string/words.md b/docs/compat/reference/string/words.md new file mode 100644 index 000000000..1e1d21305 --- /dev/null +++ b/docs/compat/reference/string/words.md @@ -0,0 +1,69 @@ +# words (Lodash Compatibility) + +::: warning Use `words` from `es-toolkit` + +This `words` function operates slowly due to handling `null` or `undefined` and complex Unicode support. + +Use the faster and more modern [words](../../../reference/string/words.md) from `es-toolkit` instead. + +::: + +Splits a string into an array of words. + +```typescript +const wordArray = words(str, pattern); +``` + +## Usage + +### `words(str, pattern)` + +Use `words` when you want to split a string into words. By default, it recognizes English letters, numbers, emojis, etc., to extract words. + +```typescript +import { words } from 'es-toolkit/compat'; + +// Basic word extraction +words('fred, barney, & pebbles'); +// Returns: ['fred', 'barney', 'pebbles'] + +// Extract words from camel case +words('camelCaseWord'); +// Returns: ['camel', 'Case', 'Word'] + +// String with numbers +words('hello123world'); +// Returns: ['hello', '123', 'world'] +``` + +You can also extract words using a custom pattern. + +```typescript +import { words } from 'es-toolkit/compat'; + +// Extract words using regex +words('hello world', /\w+/g); +// Returns: ['hello', 'world'] + +// Use string pattern +words('one-two-three', '-'); +// Returns: ['-'] +``` + +`null` or `undefined` is treated as an empty array. + +```typescript +import { words } from 'es-toolkit/compat'; + +words(null); // [] +words(undefined); // [] +``` + +#### Parameters + +- `str` (`string`, optional): The string to split into words. +- `pattern` (`RegExp | string`, optional): The pattern to match words. Defaults to a built-in Unicode word pattern. + +#### Returns + +(`string[]`): Returns an array of extracted words. diff --git a/docs/reference/compat/util/bindAll.md b/docs/compat/reference/util/bindAll.md similarity index 100% rename from docs/reference/compat/util/bindAll.md rename to docs/compat/reference/util/bindAll.md diff --git a/docs/reference/compat/util/cond.md b/docs/compat/reference/util/cond.md similarity index 100% rename from docs/reference/compat/util/cond.md rename to docs/compat/reference/util/cond.md diff --git a/docs/reference/compat/util/constant.md b/docs/compat/reference/util/constant.md similarity index 100% rename from docs/reference/compat/util/constant.md rename to docs/compat/reference/util/constant.md diff --git a/docs/reference/compat/util/defaultTo.md b/docs/compat/reference/util/defaultTo.md similarity index 100% rename from docs/reference/compat/util/defaultTo.md rename to docs/compat/reference/util/defaultTo.md diff --git a/docs/reference/compat/util/eq.md b/docs/compat/reference/util/eq.md similarity index 100% rename from docs/reference/compat/util/eq.md rename to docs/compat/reference/util/eq.md diff --git a/docs/reference/compat/util/gt.md b/docs/compat/reference/util/gt.md similarity index 100% rename from docs/reference/compat/util/gt.md rename to docs/compat/reference/util/gt.md diff --git a/docs/reference/compat/util/gte.md b/docs/compat/reference/util/gte.md similarity index 100% rename from docs/reference/compat/util/gte.md rename to docs/compat/reference/util/gte.md diff --git a/docs/reference/compat/util/invoke.md b/docs/compat/reference/util/invoke.md similarity index 100% rename from docs/reference/compat/util/invoke.md rename to docs/compat/reference/util/invoke.md diff --git a/docs/reference/compat/util/iteratee.md b/docs/compat/reference/util/iteratee.md similarity index 100% rename from docs/reference/compat/util/iteratee.md rename to docs/compat/reference/util/iteratee.md diff --git a/docs/reference/compat/util/lt.md b/docs/compat/reference/util/lt.md similarity index 100% rename from docs/reference/compat/util/lt.md rename to docs/compat/reference/util/lt.md diff --git a/docs/reference/compat/util/lte.md b/docs/compat/reference/util/lte.md similarity index 100% rename from docs/reference/compat/util/lte.md rename to docs/compat/reference/util/lte.md diff --git a/docs/reference/compat/util/method.md b/docs/compat/reference/util/method.md similarity index 100% rename from docs/reference/compat/util/method.md rename to docs/compat/reference/util/method.md diff --git a/docs/reference/compat/util/methodOf.md b/docs/compat/reference/util/methodOf.md similarity index 100% rename from docs/reference/compat/util/methodOf.md rename to docs/compat/reference/util/methodOf.md diff --git a/docs/reference/compat/util/now.md b/docs/compat/reference/util/now.md similarity index 100% rename from docs/reference/compat/util/now.md rename to docs/compat/reference/util/now.md diff --git a/docs/reference/compat/util/over.md b/docs/compat/reference/util/over.md similarity index 100% rename from docs/reference/compat/util/over.md rename to docs/compat/reference/util/over.md diff --git a/docs/reference/compat/util/overEvery.md b/docs/compat/reference/util/overEvery.md similarity index 100% rename from docs/reference/compat/util/overEvery.md rename to docs/compat/reference/util/overEvery.md diff --git a/docs/reference/compat/util/overSome.md b/docs/compat/reference/util/overSome.md similarity index 100% rename from docs/reference/compat/util/overSome.md rename to docs/compat/reference/util/overSome.md diff --git a/docs/reference/compat/util/stubArray.md b/docs/compat/reference/util/stubArray.md similarity index 100% rename from docs/reference/compat/util/stubArray.md rename to docs/compat/reference/util/stubArray.md diff --git a/docs/reference/compat/util/stubFalse.md b/docs/compat/reference/util/stubFalse.md similarity index 100% rename from docs/reference/compat/util/stubFalse.md rename to docs/compat/reference/util/stubFalse.md diff --git a/docs/reference/compat/util/stubObject.md b/docs/compat/reference/util/stubObject.md similarity index 100% rename from docs/reference/compat/util/stubObject.md rename to docs/compat/reference/util/stubObject.md diff --git a/docs/reference/compat/util/stubString.md b/docs/compat/reference/util/stubString.md similarity index 100% rename from docs/reference/compat/util/stubString.md rename to docs/compat/reference/util/stubString.md diff --git a/docs/reference/compat/util/stubTrue.md b/docs/compat/reference/util/stubTrue.md similarity index 100% rename from docs/reference/compat/util/stubTrue.md rename to docs/compat/reference/util/stubTrue.md diff --git a/docs/reference/compat/util/times.md b/docs/compat/reference/util/times.md similarity index 100% rename from docs/reference/compat/util/times.md rename to docs/compat/reference/util/times.md diff --git a/docs/reference/compat/util/toArray.md b/docs/compat/reference/util/toArray.md similarity index 100% rename from docs/reference/compat/util/toArray.md rename to docs/compat/reference/util/toArray.md diff --git a/docs/reference/compat/util/toFinite.md b/docs/compat/reference/util/toFinite.md similarity index 100% rename from docs/reference/compat/util/toFinite.md rename to docs/compat/reference/util/toFinite.md diff --git a/docs/reference/compat/util/toInteger.md b/docs/compat/reference/util/toInteger.md similarity index 100% rename from docs/reference/compat/util/toInteger.md rename to docs/compat/reference/util/toInteger.md diff --git a/docs/reference/compat/util/toLength.md b/docs/compat/reference/util/toLength.md similarity index 100% rename from docs/reference/compat/util/toLength.md rename to docs/compat/reference/util/toLength.md diff --git a/docs/reference/compat/util/toNumber.md b/docs/compat/reference/util/toNumber.md similarity index 100% rename from docs/reference/compat/util/toNumber.md rename to docs/compat/reference/util/toNumber.md diff --git a/docs/reference/compat/util/toPath.md b/docs/compat/reference/util/toPath.md similarity index 100% rename from docs/reference/compat/util/toPath.md rename to docs/compat/reference/util/toPath.md diff --git a/docs/reference/compat/util/toPlainObject.md b/docs/compat/reference/util/toPlainObject.md similarity index 100% rename from docs/reference/compat/util/toPlainObject.md rename to docs/compat/reference/util/toPlainObject.md diff --git a/docs/reference/compat/util/toSafeInteger.md b/docs/compat/reference/util/toSafeInteger.md similarity index 100% rename from docs/reference/compat/util/toSafeInteger.md rename to docs/compat/reference/util/toSafeInteger.md diff --git a/docs/reference/compat/util/toString.md b/docs/compat/reference/util/toString.md similarity index 100% rename from docs/reference/compat/util/toString.md rename to docs/compat/reference/util/toString.md diff --git a/docs/reference/compat/util/uniqueId.md b/docs/compat/reference/util/uniqueId.md similarity index 100% rename from docs/reference/compat/util/uniqueId.md rename to docs/compat/reference/util/uniqueId.md diff --git a/docs/compatibility.md b/docs/compatibility.md deleted file mode 100644 index 9e6368615..000000000 --- a/docs/compatibility.md +++ /dev/null @@ -1,62 +0,0 @@ -# Compatibility with Lodash - -::: tip ✅ Starting with version 1.39.3, we ensure 100% compatibility with Lodash - -`es-toolkit/compat` functions exactly like all Lodash functions while being lighter and faster. - -- It ensures identical behavior with Lodash's actual test code. -- It has been adopted by popular open-source projects including Storybook, Recharts, and CKEditor, and is recommended by Nuxt. - -For detailed documentation of all available compat functions, check out our [Compat Reference](/reference/compat/array/castArray). - -::: - -```tsx -// es-toolkit/compat aims to provide 100% feature parity with lodash -import { chunk } from 'es-toolkit/compat'; - -chunk([1, 2, 3, 4], 0); -// Returns [], which is identical to lodash -``` - -For maximum compatibility with `lodash`, use `es-toolkit/compat`, a compatibility layer that bridges the gap between the two libraries. - -This module is designed to provide an identical API to `lodash`, making it easier to switch between the two libraries. - -`es-toolkit/compat` has been thoroughly tested with real test cases from `lodash`. - -It's important to note that `es-toolkit/compat` may have a slight performance impact and a larger bundle size compared to the original `es-toolkit`. This module is designed to facilitate a smooth transition and should be replaced with the original `es-toolkit` for optimal performance once the migration is complete. - -## Design Principles - -::: info -Design principles are subject to change. -::: - -Our compatibility layer aims to achieve feature parity with 100% accuracy for: - -- Features that are written as a test case in lodash. -- Features that can be inferred from types of `@types/lodash` or `@types/lodash-es`. -- Feature differences identified while migrating code from lodash to es-toolkit (please report these to our [issues page](https://github.com/toss/es-toolkit/issues)). - -However, the following are out of scope for `es-toolkit/compat`: - -- Implicit type conversions, such as converting an empty string to zero or false. -- Functions that have specialized implementations for specific types of arrays, like [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq). -- Handling cases where internal object prototypes, like `Array.prototype`, have been modified. -- Managing cases with JavaScript realms. -- Method chaining support through "Seq" methods. - -## Implementation Status - -::: info -The following emojis indicate the status of each feature: - -- ✅: Completed (The function is fully implemented and has passed all tests with lodash test code.) -- 📝: In Review (The function is implemented but hasn't been tested with lodash test code yet.) -- ❌: Not Implemented (The function hasn't been implemented.) - -Even if a feature is marked "in review," it might already be under review to ensure it matches lodash perfectly, and it could already offer the same functionality. -::: - - diff --git a/docs/index.md b/docs/index.md index c29ed8e2d..c456c7c6f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -29,7 +29,7 @@ features: details: es-toolkit ships up to 97% less JavaScript code compared to other alternative libraries. - title: Seamless Lodash replacement details: es-toolkit offers a complete compatibility layer to seamlessly replace Lodash. - link: /compatibility + link: /compat/intro - title: Modern implementation details: es-toolkit fully leverages modern JavaScript APIs for straightforward and error-free implementation. - title: Robust types diff --git a/docs/ja/compat/intro.md b/docs/ja/compat/intro.md new file mode 100644 index 000000000..4e1149675 --- /dev/null +++ b/docs/ja/compat/intro.md @@ -0,0 +1,66 @@ +# es-toolkit/compat + +`es-toolkit/compat`は、[Lodash](https://lodash.com)と同じインターフェースと動作を提供するモジュールです。Lodashを使っている既存のコードをそのままにしたまま、少しずつ`es-toolkit`へ移行できるように作られています。 + +既存のプロジェクトでLodashを使っていないなら、[`es-toolkit`](/ja/intro)を使ってください。 + +::: tip ✅ 1.39.3からLodashと100%の互換性を保証しています +Lodash自身のテストコードをそのまま通過します。動作は同じまま、より軽く高速です。 +::: + +```ts +// lodashと同じ呼び出しの形を es-toolkit/compat でそのまま使えます +import { chunk } from 'es-toolkit/compat'; + +chunk([1, 2, 3, 4], 0); +// [] を返します。lodashと同じです。 +``` + +## マイグレーションの流れ + +既存のコードからLodashを取り除くときは、次の流れをおすすめします。 + +1. `lodash` / `lodash-es`のimportパスを`es-toolkit/compat`に変えてください。呼び出し側のコードはそのままで大丈夫です。 +2. 時間をかけて呼び出し側を整理しつつ、importを[`es-toolkit`](/ja/intro)に切り替えてください。すべて移行できれば、バンドルがより小さく、より高速になります。 + +## `es-toolkit`との違い + +- **APIの形**: Lodashと1:1で一致しています。暗黙的な型変換、さまざまな引数の形、非推奨のヘルパーまでそのまま含まれます。[`es-toolkit`](/ja/intro)は型安全で整理された形だけを提供します。 +- **バンドルサイズと速度**: [`es-toolkit`](/ja/intro)より少し大きく、少し遅いです。Lodashと動作を合わせるための追加処理が入っているためです。 +- **非推奨の関数**: Lodashで非推奨になった関数も互換性のために`compat`には残っていますが、[`es-toolkit`](/ja/intro)には含まれません。マイグレーション中に一緒に整理してください。 + +関数ごとの詳細なドキュメントは[互換性リファレンス](/ja/compat/reference/array/castArray)をご覧ください。 + +## 設計原則 + +::: info +`es-toolkit/compat`の設計原則の方向性は変わる可能性があります。 +::: + +`es-toolkit/compat`は、次の機能について`lodash`と100%同じ機能を提供することを目指しています。 + +- `lodash`のテストケースとして書かれている機能 +- `@types/lodash`または`@types/lodash-es`の型から推測できる機能 +- `lodash`から`es-toolkit`へコードをマイグレーションする際に見つかった機能の違い([Issuesページ](https://github.com/toss/es-toolkit/issues)に報告してください) + +ただし、以下は`es-toolkit/compat`の対象外です。 + +- 暗黙的な型変換: 空文字列を0またはfalseに変換するような動作 +- 特殊なケースに最適化された実装: [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq)のように、ソートされた配列だけを受け取る関数 +- `Array.prototype`のような組み込みオブジェクトのプロトタイプが変更されたケースへの対応 +- JavaScript Realmへの対応 +- メソッドチェーン: `_(arr).map(...).filter(...)`のようなメソッドチェーン + +## 実装状況 + +::: info +以下の絵文字で、各機能の現在の状態を表しています。 + +- ✅: 完了(実装されており、lodashのテストコードをすべて通過しています) +- 📝: レビュー中(実装されていますが、lodashのテストコードでテストされていません) +- ❌: 未実装 + +「レビュー中」と書かれていても、すでにlodashと100%同じ機能を提供している場合があります。 +::: + + diff --git a/docs/ja/reference/compat/array/castArray.md b/docs/ja/compat/reference/array/castArray.md similarity index 100% rename from docs/ja/reference/compat/array/castArray.md rename to docs/ja/compat/reference/array/castArray.md diff --git a/docs/ja/compat/reference/array/chunk.md b/docs/ja/compat/reference/array/chunk.md new file mode 100644 index 000000000..1f4a655aa --- /dev/null +++ b/docs/ja/compat/reference/array/chunk.md @@ -0,0 +1,70 @@ +# chunk(Lodash 互換性) + +::: warning `es-toolkit` の [`chunk`](../../../reference/array/chunk.md) を使用してください + +この `chunk` 関数は `null`、`undefined` の処理、`size` のデフォルト値処理などにより動作が遅くなります。 + +より高速でモダンな実装である `es-toolkit` の [chunk](../../../reference/array/chunk.md) を使用してください。 + +::: + +配列を指定されたサイズの小さな配列に分割します。 + +```typescript +const chunked = chunk(arr, size); +``` + +## 使用法 + +### `chunk(arr, size?)` + +長い配列を同じサイズの複数の小さな配列に分割したい場合は `chunk` を使用します。配列を均等に分割できない場合、最後の配列に残りの要素が含まれます。 + +```typescript +import { chunk } from 'es-toolkit/compat'; + +// 数値配列をサイズ 2 のチャンクに分割します。 +chunk([1, 2, 3, 4], 2); +// 戻り値: [[1, 2], [3, 4]] + +// 文字列配列をサイズ 3 のチャンクに分割します。 +chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); +// 戻り値: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] + +// 均等に分割できない場合 +chunk([1, 2, 3, 4, 5], 2); +// 戻り値: [[1, 2], [3, 4], [5]] +``` + +`null` または `undefined` は空の配列として扱われます。 + +```typescript +import { chunk } from 'es-toolkit/compat'; + +chunk(null, 2); +// 戻り値: [] + +chunk(undefined, 2); +// 戻り値: [] +``` + +サイズが 0 または負の場合、空の配列を返します。 + +```typescript +import { chunk } from 'es-toolkit/compat'; + +chunk([1, 2, 3], 0); +// 戻り値: [] + +chunk([1, 2, 3], -1); +// 戻り値: [] +``` + +#### パラメータ + +- `arr` (`ArrayLike | null | undefined`): 分割する配列。 +- `size` (`number`, オプション): 各小さな配列のサイズ。デフォルト値は `1`。 + +#### 戻り値 + +(`T[][]`): サイズ `size` で分割された二次元配列を返します。 diff --git a/docs/ja/compat/reference/array/compact.md b/docs/ja/compat/reference/array/compact.md new file mode 100644 index 000000000..4db8918f9 --- /dev/null +++ b/docs/ja/compat/reference/array/compact.md @@ -0,0 +1,77 @@ +# compact (Lodash 互換性) + +::: warning `es-toolkit`の[`compact`](../../../reference/array/compact.md)を使用してください + +この `compact` 関数は、`null` や `undefined` の処理、`size` のデフォルト値処理などにより、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [compact](../../../reference/array/compact.md) を使用してください。 + +::: + +配列から偽値と評価される値を削除します。 + +```typescript +const compacted = compact(arr); +``` + +## 使用法 + +### `compact(arr)` + +配列から `false`、`null`、`0`、`""`、`undefined`、`NaN` のような偽値と評価される値を削除したい場合、`compact` を使用してください。 + +```typescript +import { compact } from 'es-toolkit/compat'; + +// 偽値と評価される値を削除 +compact([0, 1, false, 2, '', 3]); +// Returns: [1, 2, 3] + +compact(['a', null, 'b', undefined, 'c', NaN]); +// Returns: ['a', 'b', 'c'] + +// BigInt 0も削除 +compact([0n, 1n, false, 2n]); +// Returns: [1n, 2n] + +// 空配列も処理 +compact([]); +// Returns: [] + +// すべての値が偽値と評価される場合 +compact([false, null, 0, '', undefined, NaN]); +// Returns: [] +``` + +真値と評価される値はそのまま保持されます。 + +```typescript +import { compact } from 'es-toolkit/compat'; + +compact([1, 'hello', true, {}, []]); +// Returns: [1, 'hello', true, {}, []] + +// 0以外の数値 +compact([0, -1, 2, -3]); +// Returns: [-1, 2, -3] +``` + +`null` や `undefined` の配列は空配列として処理されます。 + +```typescript +import { compact } from 'es-toolkit/compat'; + +compact(null); +// Returns: [] + +compact(undefined); +// Returns: [] +``` + +#### パラメータ + +- `arr` (`ArrayLike | null | undefined`): 圧縮する配列です。 + +#### 戻り値 + +(`T[]`): 偽値と評価される値が削除された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/concat.md b/docs/ja/compat/reference/array/concat.md similarity index 100% rename from docs/ja/reference/compat/array/concat.md rename to docs/ja/compat/reference/array/concat.md diff --git a/docs/ja/compat/reference/array/countBy.md b/docs/ja/compat/reference/array/countBy.md new file mode 100644 index 000000000..7da6a3949 --- /dev/null +++ b/docs/ja/compat/reference/array/countBy.md @@ -0,0 +1,88 @@ +# countBy (Lodash 互換性) + +::: warning `es-toolkit`の`countBy`を使用してください + +この `countBy` 関数は、複雑な変換関数処理と型変換により、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [countBy](../../../reference/array/countBy.md) を使用してください。 + +::: + +配列やオブジェクトの要素を条件に従って分類し、各分類の個数を数えます。 + +```typescript +const counts = countBy(collection, iteratee); +``` + +## 使用法 + +### `countBy(collection, iteratee?)` + +配列やオブジェクトの各要素をある基準でグループ化し、各グループに何個の要素があるかを数えたい場合、`countBy` を使用してください。反復関数が返す値がキーになり、そのキーに該当する要素の個数が値になります。 + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// 数値を小数点以下切り捨てでグループ化 +countBy([6.1, 4.2, 6.3], Math.floor); +// Returns: { '4': 1, '6': 2 } + +// 文字列を長さでグループ化 +countBy(['one', 'two', 'three'], 'length'); +// Returns: { '3': 2, '5': 1 } + +// ユーザーを年齢代でグループ化 +const users = [ + { name: 'Alice', age: 25 }, + { name: 'Bob', age: 35 }, + { name: 'Charlie', age: 25 }, +]; +countBy(users, user => Math.floor(user.age / 10) * 10); +// Returns: { '20': 2, '30': 1 } +``` + +オブジェクトも処理できます。 + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// オブジェクトの値を型で分類 +const obj = { a: 1, b: 'string', c: 2, d: 'text' }; +countBy(obj, value => typeof value); +// Returns: { 'number': 2, 'string': 2 } +``` + +反復関数なしで使用すると、値そのものでグループ化されます。 + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// 値そのものでグループ化 +countBy([1, 2, 1, 3, 2, 1]); +// Returns: { '1': 3, '2': 2, '3': 1 } + +// 真偽値でグループ化 +countBy([true, false, true, true]); +// Returns: { 'true': 3, 'false': 1 } +``` + +`null` や `undefined` のコレクションは空のオブジェクトを返します。 + +```typescript +import { countBy } from 'es-toolkit/compat'; + +countBy(null); +// Returns: {} + +countBy(undefined); +// Returns: {} +``` + +#### パラメータ + +- `collection` (`ArrayLike | object | null | undefined`): 処理する配列またはオブジェクトです。 +- `iteratee` (`ValueIteratee`, 選択): 各要素をグループ化する基準を決定する関数です。関数、プロパティ名、または部分オブジェクトを使用できます。 + +#### 戻り値 + +(`Record`): 各グループのキーとそのグループの要素数を持つオブジェクトを返します。 diff --git a/docs/ja/compat/reference/array/difference.md b/docs/ja/compat/reference/array/difference.md new file mode 100644 index 000000000..deafea7a3 --- /dev/null +++ b/docs/ja/compat/reference/array/difference.md @@ -0,0 +1,94 @@ +# difference (Lodash 互換性) + +::: warning `es-toolkit`の`difference`を使用してください + +この `difference` 関数は、`null` や `undefined` の処理、複数の配列引数処理により、複雑に動作します。 + +代わりに、より高速で現代的な `es-toolkit` の [difference](../../../reference/array/difference.md) を使用してください。 + +::: + +最初の配列から他の配列の値を除いた差集合を求めます。 + +```typescript +const result = difference(arr, ...values); +``` + +## 使用法 + +### `difference(arr, ...values)` + +最初の配列から残りの配列に含まれる値をすべて削除したい場合、`difference` を使用してください。順序は最初の配列の順序を保持します。 + +```typescript +import { difference } from 'es-toolkit/compat'; + +// 基本的な使用法 +const array1 = [1, 2, 3, 4, 5]; +const array2 = [2, 4]; +const array3 = [5, 6]; +difference(array1, array2, array3); +// Returns: [1, 3] + +// 文字列配列 +difference(['a', 'b', 'c'], ['b'], ['c', 'd']); +// Returns: ['a'] + +// 重複する値の処理 +difference([1, 2, 2, 3], [2]); +// Returns: [1, 3] +``` + +空配列や空の差集合も処理します。 + +```typescript +import { difference } from 'es-toolkit/compat'; + +// 空配列との差集合 +difference([1, 2, 3], []); +// Returns: [1, 2, 3] + +// すべての値が除外される場合 +difference([1, 2, 3], [1, 2, 3]); +// Returns: [] + +// 重複する値がない場合 +difference([1, 2], [3, 4]); +// Returns: [1, 2] +``` + +`null` や `undefined` の配列は空配列として処理されます。 + +```typescript +import { difference } from 'es-toolkit/compat'; + +difference(null, [1, 2]); +// Returns: [] + +difference(undefined, [1, 2]); +// Returns: [] + +difference([1, 2, 3], null, undefined); +// Returns: [1, 2, 3] (nullとundefinedは無視されます) +``` + +配列風オブジェクトもサポートします。 + +```typescript +import { difference } from 'es-toolkit/compat'; + +// 配列風オブジェクト +const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; +const arrayLike2 = { 0: 2, 1: 4, length: 2 }; +difference(arrayLike1, arrayLike2); +// Returns: [1, 3] +``` + +#### パラメータ + +- `arr` (`ArrayLike | null | undefined`): 差集合を求める基準配列です。 +- `values` (`...ArrayLike[]`): 除外する値を含む配列です。 + +#### 戻り値 + +(`T[]`): 最初の配列から他の配列の値を除いた新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/differenceBy.md b/docs/ja/compat/reference/array/differenceBy.md new file mode 100644 index 000000000..0bf4afa05 --- /dev/null +++ b/docs/ja/compat/reference/array/differenceBy.md @@ -0,0 +1,88 @@ +# differenceBy (Lodash 互換性) + +::: warning `es-toolkit`の`differenceBy`を使用してください + +この `differenceBy` 関数は、複雑な引数処理と反復子変換により、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [differenceBy](../../../reference/array/differenceBy.md) を使用してください。 + +::: + +反復関数で変換した値を基準に、最初の配列から他の配列の要素を除いた差集合を求めます。 + +```typescript +const result = differenceBy(array, ...values, iteratee); +``` + +## 使用法 + +### `differenceBy(array, ...values, iteratee)` + +最初の配列の各要素と除外する配列の要素を反復関数で変換した後、同じ値になる要素を削除したい場合、`differenceBy` を使用してください。オブジェクト配列で特定のプロパティ値や変換された値を基準に比較する際に便利です。 + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// 小数点以下切り捨てで比較 +differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); +// Returns: [1.2] (Math.floor(2.1) === Math.floor(2.3)のため2.1を除外) + +// 文字列の長さで比較 +differenceBy(['one', 'two', 'three'], ['four', 'eight'], 'length'); +// Returns: ['one', 'two'] (threeとeightは長さが同じためthreeを除外) + +// オブジェクトのプロパティで比較 +const users1 = [ + { id: 1, name: 'Alice' }, + { id: 2, name: 'Bob' }, +]; +const users2 = [{ id: 1, name: 'Different Alice' }]; +differenceBy(users1, users2, 'id'); +// Returns: [{ id: 2, name: 'Bob' }] (idが1のオブジェクトを除外) +``` + +複数の配列を一度に除外できます。 + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// 複数の配列から除外 +differenceBy([2.1, 1.2, 3.5], [2.3], [1.4], [3.2], Math.floor); +// Returns: [] (すべての要素が除外されます) + +// 文字列配列を長さで比較 +differenceBy(['a', 'bb', 'ccc'], ['x'], ['yy'], ['zzz'], 'length'); +// Returns: [] (長さ1、2、3がすべて除外されます) +``` + +反復関数がない場合、通常の `difference` のように動作します。 + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// 反復関数なしで使用 +differenceBy([1, 2, 3], [2, 4]); +// Returns: [1, 3] +``` + +`null` や `undefined` の配列は空配列として処理されます。 + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +differenceBy(null, [1, 2], Math.floor); +// Returns: [] + +differenceBy(undefined, [1, 2], x => x); +// Returns: [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 差集合を求める基準配列です。 +- `values` (`...ArrayLike[]`): 除外する値を含む配列です。 +- `iteratee` (`ValueIteratee`): 各要素を比較する値に変換する関数です。関数、プロパティ名、または部分オブジェクトを使用できます。 + +#### 戻り値 + +(`T[]`): 反復関数で変換した値を基準に除外された要素を除いた新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/differenceWith.md b/docs/ja/compat/reference/array/differenceWith.md new file mode 100644 index 000000000..dc1fa991e --- /dev/null +++ b/docs/ja/compat/reference/array/differenceWith.md @@ -0,0 +1,79 @@ +# differenceWith (Lodash 互換性) + +::: warning `es-toolkit`の`differenceWith`を使用してください + +この `differenceWith` 関数は、`null` や `undefined` の処理、複数の配列処理、`ArrayLike` 型の処理などにより、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [differenceWith](../../../reference/array/differenceWith.md) を使用してください。 + +::: + +比較関数を使用して、最初の配列から他の配列に含まれる要素を削除します。 + +```typescript +const result = differenceWith(array, ...values, comparator); +``` + +## 使用法 + +### `differenceWith(array, ...values, comparator)` + +各要素を比較関数で比較して差を求めたい場合、`differenceWith` を使用してください。最後の引数が比較関数になります。 + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +// オブジェクトをidで比較します。 +const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; +const others = [{ id: 2 }]; +const comparator = (a, b) => a.id === b.id; + +differenceWith(objects, others, comparator); +// Returns: [{ id: 1 }, { id: 3 }] + +// 複数の配列を一度に除外します。 +const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]; +const values1 = [{ id: 2 }]; +const values2 = [{ id: 3 }]; + +differenceWith(array, values1, values2, comparator); +// Returns: [{ id: 1 }, { id: 4 }] +``` + +比較関数を提供しない場合、通常の `difference` のように動作します。 + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +// 比較関数なしで使用すると通常の比較を行います。 +differenceWith([1, 2, 3], [2], [3]); +// Returns: [1] +``` + +複雑な比較ロジックも使用できます。 + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +const users = [ + { name: 'alice', age: 25 }, + { name: 'bob', age: 30 }, + { name: 'charlie', age: 35 }, +]; +const excludeUsers = [{ name: 'bob', age: 25 }]; // 異なる年齢 + +// 名前のみで比較します。 +const compareByName = (a, b) => a.name === b.name; +differenceWith(users, excludeUsers, compareByName); +// Returns: [{ name: 'alice', age: 25 }, { name: 'charlie', age: 35 }] +// bobが除外されます(年齢が違っても名前が同じため) +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 差を求める基準配列です。 +- `...values` (`Array>` + `(a: T, b: T) => boolean`): 除外する要素を含む配列と最後に比較関数です。 + +#### 戻り値 + +(`T[]`): 比較関数を使用して最初の配列から残りの配列の要素を削除した新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/drop.md b/docs/ja/compat/reference/array/drop.md new file mode 100644 index 000000000..d55a67402 --- /dev/null +++ b/docs/ja/compat/reference/array/drop.md @@ -0,0 +1,97 @@ +# drop (Lodash 互換性) + +::: warning `es-toolkit` の `drop` を使用してください + +この `drop` 関数は、`null` や `undefined` の処理、`toInteger` 変換などにより複雑に動作します。 + +代わりに、より高速で現代的な `es-toolkit` の [`drop`](../../../reference/array/drop.md) を使用してください。 + +::: + +配列の先頭から指定された個数の要素を削除します。 + +```typescript +const result = drop(array, n); +``` + +## 使用法 + +### `drop(array, n?)` + +配列の先頭からいくつかの要素を削除し、残りを取得したい場合に `drop` を使用します。デフォルトでは、最初の要素を1つ削除します。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 基本的な使用法(最初の要素を削除) +drop([1, 2, 3, 4, 5]); +// 戻り値: [2, 3, 4, 5] + +// 最初の2つの要素を削除 +drop([1, 2, 3, 4, 5], 2); +// 戻り値: [3, 4, 5] + +// 最初の3つの要素を削除 +drop(['a', 'b', 'c', 'd'], 3); +// 戻り値: ['d'] +``` + +0または負の数を指定すると、元の配列をそのまま返します。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 0個削除 +drop([1, 2, 3], 0); +// 戻り値: [1, 2, 3] + +// 負の数を指定 +drop([1, 2, 3], -1); +// 戻り値: [1, 2, 3] +``` + +配列より大きい数を指定すると、空の配列を返します。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 配列のサイズより大きい数を指定 +drop([1, 2, 3], 5); +// 戻り値: [] + +// 空の配列から削除 +drop([], 1); +// 戻り値: [] +``` + +`null` または `undefined` の配列は空の配列として処理されます。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +drop(null, 1); +// 戻り値: [] + +drop(undefined, 2); +// 戻り値: [] +``` + +配列風オブジェクトもサポートされています。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 配列風オブジェクト +const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; +drop(arrayLike, 1); +// 戻り値: ['b', 'c'] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 要素を削除する配列です。 +- `n` (`number`, オプション): 削除する要素の個数です。デフォルトは `1` です。 + +#### 戻り値 + +(`T[]`): 先頭から指定された個数の要素が削除された新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/dropRight.md b/docs/ja/compat/reference/array/dropRight.md new file mode 100644 index 000000000..7c46cb8e2 --- /dev/null +++ b/docs/ja/compat/reference/array/dropRight.md @@ -0,0 +1,55 @@ +# dropRight (Lodash 互換性) + +::: warning `es-toolkit` の `dropRight` を使用してください + +この `dropRight` 関数は、`null` や `undefined` の処理、`guard` パラメータ処理、`toInteger` 変換などにより遅く動作します。 + +代わりに、より高速で現代的な `es-toolkit` の [`dropRight`](../../../reference/array/dropRight.md) を使用してください。 + +::: + +配列の末尾から指定された個数の要素を削除した新しい配列を返します。 + +```typescript +const result = dropRight(array, itemsCount); +``` + +## 使用法 + +### `dropRight(array, itemsCount)` + +配列の末尾から特定の個数の要素を削除し、残りの要素で新しい配列を作成したい場合に `dropRight` を使用します。 + +```typescript +import { dropRight } from 'es-toolkit/compat'; + +// 数値配列から末尾の2つの要素を削除します。 +dropRight([1, 2, 3, 4, 5], 2); +// 戻り値: [1, 2, 3] + +// 文字列配列から末尾の1つの要素を削除します。 +dropRight(['a', 'b', 'c'], 1); +// 戻り値: ['a', 'b'] + +// 削除する個数を指定しない場合、デフォルト値1が使用されます。 +dropRight([1, 2, 3]); +// 戻り値: [1, 2] +``` + +`null` または `undefined` は空の配列として処理されます。 + +```typescript +import { dropRight } from 'es-toolkit/compat'; + +dropRight(null, 2); // [] +dropRight(undefined, 2); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 要素を削除する配列です。 +- `itemsCount` (`number`, オプション): 配列の末尾から削除する要素の個数です。デフォルトは `1` です。 + +#### 戻り値 + +(`T[]`): 末尾から `itemsCount` 個の要素が削除された新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/dropRightWhile.md b/docs/ja/compat/reference/array/dropRightWhile.md new file mode 100644 index 000000000..3d205a80e --- /dev/null +++ b/docs/ja/compat/reference/array/dropRightWhile.md @@ -0,0 +1,65 @@ +# dropRightWhile (Lodash 互換性) + +::: warning `es-toolkit` の `dropRightWhile` を使用してください + +この `dropRightWhile` 関数は、`null` や `undefined` の処理、`ArrayLike` 型の処理、様々な条件関数形式のサポートなどにより遅く動作します。 + +代わりに、より高速で現代的な `es-toolkit` の [`dropRightWhile`](../../../reference/array/dropRightWhile.md) を使用してください。 + +::: + +条件関数に基づいて配列の末尾から要素を削除します。 + +```typescript +const result = dropRightWhile(array, predicate); +``` + +## 使用法 + +### `dropRightWhile(array, predicate)` + +配列の末尾から特定の条件を満たす要素を連続して削除したい場合に `dropRightWhile` を使用します。条件関数が `false` を返すと削除を中断します。 + +```typescript +import { dropRightWhile } from 'es-toolkit/compat'; + +// 関数を条件として使用します。 +const users = [ + { user: 'barney', active: true }, + { user: 'fred', active: false }, + { user: 'pebbles', active: false }, +]; + +dropRightWhile(users, user => !user.active); +// 戻り値: [{ user: 'barney', active: true }] + +// オブジェクトパターンでマッチングします。 +dropRightWhile(users, { user: 'pebbles', active: false }); +// 戻り値: [{ user: 'barney', active: true }, { user: 'fred', active: false }] + +// 配列形式でプロパティと値を指定します。 +dropRightWhile(users, ['active', false]); +// 戻り値: [{ user: 'barney', active: true }] + +// プロパティ名で条件を確認します。 +dropRightWhile(users, 'active'); +// 戻り値: [{ user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }] +``` + +`null` または `undefined` は空の配列として処理されます。 + +```typescript +import { dropRightWhile } from 'es-toolkit/compat'; + +dropRightWhile(null, x => x > 0); // [] +dropRightWhile(undefined, x => x > 0); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 要素を削除する配列です。 +- `predicate` (`ListIteratee`, オプション): 各要素に適用する条件関数です。関数、オブジェクトパターン、配列パターン、またはプロパティ名を受け取ることができます。 + +#### 戻り値 + +(`T[]`): 条件を満たさない最初の要素からの新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/dropWhile.md b/docs/ja/compat/reference/array/dropWhile.md new file mode 100644 index 000000000..5050d70cd --- /dev/null +++ b/docs/ja/compat/reference/array/dropWhile.md @@ -0,0 +1,67 @@ +# dropWhile (Lodash 互換性) + +::: warning `es-toolkit` の `dropWhile` を使用してください + +この `dropWhile` 関数は、`null` や `undefined` の処理、`ArrayLike` 型の処理、様々な条件関数形式のサポートなどにより遅く動作します。 + +代わりに、より高速で現代的な `es-toolkit` の [`dropWhile`](../../../reference/array/dropWhile.md) を使用してください。 + +::: + +条件関数に基づいて配列の先頭から要素を削除します。 + +```typescript +const result = dropWhile(array, predicate); +``` + +## 使用法 + +### `dropWhile(array, predicate)` + +配列の先頭から特定の条件を満たす要素を連続して削除したい場合に `dropWhile` を使用します。条件関数が `false` を返すと削除を中断します。 + +```typescript +import { dropWhile } from 'es-toolkit/compat'; + +// 関数を条件として使用します。 +dropWhile([1, 2, 3, 4, 5], n => n < 3); +// 戻り値: [3, 4, 5] + +// オブジェクトパターンでマッチングします。 +const users = [ + { name: 'alice', active: false }, + { name: 'bob', active: false }, + { name: 'charlie', active: true }, +]; + +dropWhile(users, { active: false }); +// 戻り値: [{ name: 'charlie', active: true }] + +// 配列形式でプロパティと値を指定します。 +dropWhile(users, ['active', false]); +// 戻り値: [{ name: 'charlie', active: true }] + +// プロパティ名で条件を確認します。 +const items = [{ visible: false }, { visible: false }, { visible: true }]; + +dropWhile(items, 'visible'); +// 戻り値: [{ visible: false }, { visible: false }, { visible: true }] +``` + +`null` または `undefined` は空の配列として処理されます。 + +```typescript +import { dropWhile } from 'es-toolkit/compat'; + +dropWhile(null, x => x > 0); // [] +dropWhile(undefined, x => x > 0); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 要素を削除する配列です。 +- `predicate` (`ListIteratee`, オプション): 各要素に適用する条件関数です。関数、オブジェクトパターン、配列パターン、またはプロパティ名を受け取ることができます。デフォルトは `identity` です。 + +#### 戻り値 + +(`T[]`): 条件を満たさない最初の要素からの新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/each.md b/docs/ja/compat/reference/array/each.md similarity index 100% rename from docs/ja/reference/compat/array/each.md rename to docs/ja/compat/reference/array/each.md diff --git a/docs/ja/compat/reference/array/eachRight.md b/docs/ja/compat/reference/array/eachRight.md new file mode 100644 index 000000000..0a049674d --- /dev/null +++ b/docs/ja/compat/reference/array/eachRight.md @@ -0,0 +1,58 @@ +# eachRight (Lodash 互換性) + +::: warning `es-toolkit` の `forEachRight` を使用してください + +この `eachRight` 関数は、`null` や `undefined` の処理、`ArrayLike` 型の処理、様々な条件関数形式のサポートなどにより遅く動作します。 + +代わりに、より高速で現代的な `es-toolkit` の [`forEachRight`](../../../reference/array/forEachRight.md) を使用してください。 + +::: + +配列またはオブジェクトの各要素に対して右から左へ反復操作を実行します。 + +```typescript +const result = eachRight(collection, iteratee); +``` + +## 使用法 + +### `eachRight(collection, iteratee)` + +配列、オブジェクト、文字列の各要素を右から左へ順回しながら与えられた関数を実行します。配列の場合は最後のインデックスから逆順に、オブジェクトの場合は列挙可能なプロパティを逆順に順回します。 + +```typescript +import { eachRight } from 'es-toolkit/compat'; + +// 配列を逆順に順回 +eachRight([1, 2, 3], (value, index) => console.log(value, index)); +// ログ: 3 2, 2 1, 1 0 + +// オブジェクトを逆順に順回 +eachRight({ a: 1, b: 2 }, (value, key) => console.log(key, value)); +// ログ: 'b' 2, 'a' 1 + +// 文字列を逆順に順回 +eachRight('hello', (char, index) => console.log(char, index)); +// ログ: 'o' 4, 'l' 3, 'l' 2, 'e' 1, 'h' 0 +``` + +関数が `false` を返すと順回を中断します。 + +```typescript +import { eachRight } from 'es-toolkit/compat'; + +eachRight([1, 2, 3, 4], value => { + console.log(value); + return value !== 2; // 2で中断 +}); +// ログ: 4, 3, 2 +``` + +#### パラメータ + +- `collection` (`ArrayLike | Record | string | null | undefined`): 順回するコレクションです。 +- `iteratee` (`(item: any, index: any, collection: any) => unknown`, オプション): 各要素に対して実行する関数です。デフォルトは `identity` 関数です。 + +#### 戻り値 + +(`ArrayLike | Record | string | null | undefined`): 元のコレクションを返します。 diff --git a/docs/ja/reference/compat/array/every.md b/docs/ja/compat/reference/array/every.md similarity index 100% rename from docs/ja/reference/compat/array/every.md rename to docs/ja/compat/reference/array/every.md diff --git a/docs/ja/compat/reference/array/fill.md b/docs/ja/compat/reference/array/fill.md new file mode 100644 index 000000000..a5787b77f --- /dev/null +++ b/docs/ja/compat/reference/array/fill.md @@ -0,0 +1,82 @@ +# fill (Lodash 互換性) + +::: warning `es-toolkit` の `fill` を使用してください + +この `fill` 関数は、`null` や `undefined` の処理、配列風オブジェクトのサポートなどにより複雑に動作します。 + +代わりに、より高速で現代的な `es-toolkit` の [`fill`](../../../reference/array/fill.md) を使用してください。 + +::: + +配列の要素を指定された値で埋めます。 + +```typescript +const result = fill(array, value, start, end); +``` + +## 使用法 + +### `fill(array, value, start?, end?)` + +配列の特定の範囲または全体を同じ値で埋めたい場合に `fill` を使用します。元の配列を直接変更します。 + +```typescript +import { fill } from 'es-toolkit/compat'; + +// 配列全体を埋める +const arr1 = [1, 2, 3]; +fill(arr1, 'a'); +// 戻り値: ['a', 'a', 'a'] + +// 特定の範囲を埋める +const arr2 = [1, 2, 3, 4, 5]; +fill(arr2, '*', 1, 4); +// 戻り値: [1, '*', '*', '*', 5] + +// 負のインデックスを使用 +const arr3 = [1, 2, 3, 4, 5]; +fill(arr3, 'x', -3, -1); +// 戻り値: [1, 2, 'x', 'x', 5] +``` + +配列風オブジェクトもサポートされています。 + +```typescript +import { fill } from 'es-toolkit/compat'; + +const arrayLike = { 0: 1, 1: 2, 2: 3, length: 3 }; +fill(arrayLike, 'a', 1, 2); +// 戻り値: { 0: 1, 1: 'a', 2: 3, length: 3 } +``` + +`null` または `undefined` の配列は空の配列として処理されます。 + +```typescript +import { fill } from 'es-toolkit/compat'; + +fill(null, 'a'); +// 戻り値: [] + +fill(undefined, 'a'); +// 戻り値: [] +``` + +文字列は読み取り専用なのでそのまま返します。 + +```typescript +import { fill } from 'es-toolkit/compat'; + +fill('abc', 'x'); +// 戻り値: 'abc' (変更されません) +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 埋める配列です。 +- `value` (`U`): 配列を埋める値です。 +- `start` (`number`, オプション): 開始位置です。デフォルトは `0` です。 +- `end` (`number`, オプション): 終了位置です(含まれません)。デフォルトは `array.length` です。 + +#### 戻り値 + +(`ArrayLike`): 値で埋められた配列を返します。 diff --git a/docs/ja/reference/compat/array/filter.md b/docs/ja/compat/reference/array/filter.md similarity index 100% rename from docs/ja/reference/compat/array/filter.md rename to docs/ja/compat/reference/array/filter.md diff --git a/docs/ja/reference/compat/array/find.md b/docs/ja/compat/reference/array/find.md similarity index 100% rename from docs/ja/reference/compat/array/find.md rename to docs/ja/compat/reference/array/find.md diff --git a/docs/ja/reference/compat/array/findIndex.md b/docs/ja/compat/reference/array/findIndex.md similarity index 100% rename from docs/ja/reference/compat/array/findIndex.md rename to docs/ja/compat/reference/array/findIndex.md diff --git a/docs/ja/reference/compat/array/findLast.md b/docs/ja/compat/reference/array/findLast.md similarity index 100% rename from docs/ja/reference/compat/array/findLast.md rename to docs/ja/compat/reference/array/findLast.md diff --git a/docs/ja/reference/compat/array/findLastIndex.md b/docs/ja/compat/reference/array/findLastIndex.md similarity index 100% rename from docs/ja/reference/compat/array/findLastIndex.md rename to docs/ja/compat/reference/array/findLastIndex.md diff --git a/docs/ja/compat/reference/array/first.md b/docs/ja/compat/reference/array/first.md new file mode 100644 index 000000000..912d40293 --- /dev/null +++ b/docs/ja/compat/reference/array/first.md @@ -0,0 +1,78 @@ +# first (Lodash 互換性) + +::: warning `es-toolkit`の`head`を使用してください + +この`first`関数は、`null`や`undefined`の処理と配列のようなオブジェクトの変換により、動作が遅くなります。`es-toolkit`の`head`関数は、これらの追加処理なしで、より高速かつシンプルに動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[head](../../../reference/array/head.md)を使用してください。 + +::: + +配列の最初の要素を返します。 + +```typescript +const firstElement = first(array); +``` + +## 使用法 + +### `first(array)` + +配列の最初の要素を取得したい場合は`first`を使用してください。配列が空であるか、`null`、`undefined`の場合は`undefined`を返します。 + +```typescript +import { first } from 'es-toolkit/compat'; + +// 通常の配列から最初の要素を取得 +first([1, 2, 3]); +// Returns: 1 + +// 文字列配列から最初の要素を取得 +first(['a', 'b', 'c']); +// Returns: 'a' + +// 空の配列 +first([]); +// Returns: undefined +``` + +`null`または`undefined`は`undefined`を返します。 + +```typescript +import { first } from 'es-toolkit/compat'; + +first(null); // undefined +first(undefined); // undefined +``` + +配列のようなオブジェクトでも使用できます。 + +```typescript +import { first } from 'es-toolkit/compat'; + +const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; +first(arrayLike); +// Returns: 'a' + +// 文字列も配列のように処理されます +first('hello'); +// Returns: 'h' +``` + +型が保証されたタプルでは、正確な型を返します。 + +```typescript +import { first } from 'es-toolkit/compat'; + +const tuple = [1, 'two', true] as const; +first(tuple); +// Returns: 1 (型は1と推論されます) +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 最初の要素を取得する配列です。 + +#### 戻り値 + +(`T | undefined`): 配列の最初の要素を返します。配列が空または無効な場合は`undefined`を返します。 diff --git a/docs/ja/compat/reference/array/flatMap.md b/docs/ja/compat/reference/array/flatMap.md new file mode 100644 index 000000000..ee6ace74e --- /dev/null +++ b/docs/ja/compat/reference/array/flatMap.md @@ -0,0 +1,77 @@ +# flatMap (Lodash 互換性) + +::: warning `es-toolkit`の`flatMap`を使用してください + +この`flatMap`関数は、`null`や`undefined`の処理、`ArrayLike`型の処理、様々な条件関数形式のサポートなどにより、動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[flatMap](../../../reference/array/flatMap.md)を使用してください。 + +::: + +各要素に関数を適用した後、結果を平坦化します。 + +```typescript +const result = flatMap(collection, iteratee); +``` + +## 使用法 + +### `flatMap(collection, iteratee)` + +コレクションの各要素にイテレータ関数を適用した後、1段階平坦化した配列を返します。配列、オブジェクト、文字列をサポートし、様々な形式のイテレータを使用できます。 + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +// 配列に関数を適用 +function duplicate(n) { + return [n, n]; +} +flatMap([1, 2], duplicate); +// 結果: [1, 1, 2, 2] + +// オブジェクトに関数を適用 +const obj = { a: 1, b: 2 }; +flatMap(obj, (value, key) => [key, value]); +// 結果: ['a', 1, 'b', 2] + +// 文字列プロパティでマッピング +const users = [ + { user: 'barney', hobbies: ['hiking', 'coding'] }, + { user: 'fred', hobbies: ['reading'] }, +]; +flatMap(users, 'hobbies'); +// 結果: ['hiking', 'coding', 'reading'] +``` + +イテレータなしで使用すると、値を1段階平坦化します。 + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +const obj = { a: [1, 2], b: [3, 4] }; +flatMap(obj); +// 結果: [1, 2, 3, 4] +``` + +部分オブジェクトで条件マッピングも可能です。 + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +const users = [ + { user: 'barney', age: 36, active: true }, + { user: 'fred', age: 40, active: false }, +]; +flatMap(users, { active: false }); +// 結果: [false, true] (activeがfalseの要素のマッチング結果) +``` + +#### パラメータ + +- `collection` (`object | null | undefined`): 反復処理するコレクションです。配列、オブジェクト、文字列が可能です。 +- `iteratee` (`ListIterator | ObjectIterator | string | object`, オプション): 各要素に適用するイテレータです。関数、プロパティ名、または部分オブジェクトが可能です。 + +#### 戻り値 + +(`any[]`): マッピング後1段階平坦化された新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/flatMapDeep.md b/docs/ja/compat/reference/array/flatMapDeep.md new file mode 100644 index 000000000..1bd43e23d --- /dev/null +++ b/docs/ja/compat/reference/array/flatMapDeep.md @@ -0,0 +1,77 @@ +# flatMapDeep (Lodash 互換性) + +::: warning `es-toolkit`の[`flatMapDeep`](../../../reference/array/flatMapDeep.md)を使用してください + +この`flatMapDeep`関数は、複雑なコレクション型の処理と深い平坦化ロジックにより、動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[flatMapDeep](../../../reference/array/flatMapDeep.md)を使用してください。 + +::: + +各要素に関数を適用した後、結果を再帰的に平坦化します。 + +```typescript +const result = flatMapDeep(collection, iteratee); +``` + +## 使用法 + +### `flatMapDeep(collection, iteratee)` + +コレクションの各要素にイテレータ関数を適用した後、無限の深さまで平坦化した配列を返します。ネストされた配列構造がすべて平坦化されて1次元配列になります。 + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +// 配列に関数を適用して深く平坦化 +function duplicate(n) { + return [[[n, n]]]; +} +flatMapDeep([1, 2], duplicate); +// 結果: [1, 1, 2, 2] + +// オブジェクトに関数を適用して深く平坦化 +const obj = { a: 1, b: 2 }; +flatMapDeep(obj, (value, key) => [[[key, value]]]); +// 結果: ['a', 1, 'b', 2] + +// 文字列プロパティでマッピングして深く平坦化 +const users = [ + { user: 'barney', hobbies: [['hiking', 'coding']] }, + { user: 'fred', hobbies: [['reading']] }, +]; +flatMapDeep(users, 'hobbies'); +// 結果: ['hiking', 'coding', 'reading'] +``` + +イテレータなしで使用すると、値を再帰的に平坦化します。 + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +const obj = { a: [[1, 2]], b: [[[3]]] }; +flatMapDeep(obj); +// 結果: [1, 2, 3] +``` + +部分オブジェクトで条件マッピングも可能です。 + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +const users = [ + { user: 'barney', active: [true, false] }, + { user: 'fred', active: [false] }, +]; +flatMapDeep(users, { active: [false] }); +// 結果: [true, true] (active配列に[false]が含まれる要素のマッチング結果) +``` + +#### パラメータ + +- `collection` (`object | null | undefined`): 反復処理するコレクションです。配列、オブジェクト、文字列が可能です。 +- `iteratee` (`ListIterator | ObjectIterator | string | object`, オプション): 各要素に適用するイテレータです。関数、プロパティ名、または部分オブジェクトが可能です。 + +#### 戻り値 + +(`any[]`): マッピング後再帰的に平坦化された新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/flatMapDepth.md b/docs/ja/compat/reference/array/flatMapDepth.md new file mode 100644 index 000000000..4c13e15a6 --- /dev/null +++ b/docs/ja/compat/reference/array/flatMapDepth.md @@ -0,0 +1,79 @@ +# flatMapDepth (Lodash 互換性) + +::: warning `es-toolkit`の[flatMap](../../../reference/array/flatMap.md)を使用してください + +この`flatMapDepth`関数は、Lodashとの互換性のために様々な形式のイテレータをサポートし、`null`や`undefined`の処理などにより複雑に実装されています。メインライブラリの`flatMap`関数はシンプルな関数イテレータのみをサポートするため、より高速に動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[flatMap](../../../reference/array/flatMap.md)を使用してください。 + +::: + +配列の各要素をイテレータ関数で変換した後、指定された深さまで平坦化します。 + +```typescript +const result = flatMapDepth(collection, iteratee, depth); +``` + +## 使用法 + +### `flatMapDepth(collection, iteratee, depth)` + +配列またはオブジェクトの各要素を与えられた関数で変換した後、結果を指定された深さまで平坦化して新しい配列として返します。ネストされた配列構造を望む深さまでのみ平坦化したいときに便利です。 + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +// 配列を変換して深さ2まで平坦化 +flatMapDepth([1, 2], n => [[n, n]], 2); +// => [1, 1, 2, 2] + +// 深さ1に制限すると完全に平坦化されません +flatMapDepth([1, 2], n => [[n, n]], 1); +// => [[1, 1], [2, 2]] + +// オブジェクトから値を抽出して平坦化 +const users = [ + { user: 'barney', hobbies: [['hiking'], ['coding']] }, + { user: 'fred', hobbies: [['reading']] }, +]; +flatMapDepth(users, 'hobbies', 2); +// => ['hiking', 'coding', 'reading'] +``` + +この関数は様々な形式のイテレータをサポートします。 + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +// 関数を使用した変換 +flatMapDepth([1, 2, 3], n => [[n, n]], 2); + +// プロパティ名で値を抽出 +const objects = [{ items: [['a'], ['b']] }, { items: [['c']] }]; +flatMapDepth(objects, 'items', 2); +// => ['a', 'b', 'c'] + +// オブジェクトの部分一致 +const users = [{ active: [[true], [false]] }, { active: [[false]] }]; +flatMapDepth(users, { active: [[false]] }, 2); +// => [true, true] +``` + +`null`または`undefined`は空の配列として処理されます。 + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +flatMapDepth(null, n => [n], 1); // => [] +flatMapDepth(undefined, n => [n], 1); // => [] +``` + +#### パラメータ + +- `collection` (`ArrayLike | Record | Record | object | null | undefined`): 反復処理する配列またはオブジェクトです。 +- `iteratee` (`((value: T, index: number, collection: any) => any) | string | object`, オプション): 各要素に対して実行する変換関数またはプロパティ名です。デフォルトは`identity`です。 +- `depth` (`number`, オプション): 平坦化する最大深さです。デフォルトは`1`です。 + +#### 戻り値 + +(`T[]`): イテレータで変換された後、指定された深さまで平坦化された新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/flatten.md b/docs/ja/compat/reference/array/flatten.md new file mode 100644 index 000000000..334affeee --- /dev/null +++ b/docs/ja/compat/reference/array/flatten.md @@ -0,0 +1,69 @@ +# flatten (Lodash 互換性) + +::: warning `es-toolkit`の`flatten`を使用してください + +この`flatten`関数は、`null`や`undefined`の処理、`ArrayLike`型の処理、様々な条件関数形式のサポートなどにより、動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[flatten](../../../reference/array/flatten.md)を使用してください。 + +::: + +配列を1段階平坦化します。 + +```typescript +const result = flatten(array, depth); +``` + +## 使用法 + +### `flatten(value, depth)` + +ネストされた配列を指定された深さだけ平坦化します。デフォルトでは1段階のみ平坦化し、ArgumentsオブジェクトやSymbol.isConcatSpreadableを持つオブジェクトもサポートします。 + +```typescript +import { flatten } from 'es-toolkit/compat'; + +// 基本的な平坦化(1段階) +flatten([1, [2, [3, [4]], 5]]); +// 結果: [1, 2, [3, [4]], 5] + +// 深さを指定 +flatten([1, [2, [3, [4]], 5]], 2); +// 結果: [1, 2, 3, [4], 5] + +// Argumentsオブジェクトのサポート +function example() { + return flatten(arguments); +} +example(1, [2, 3], [[4]]); +// 結果: [1, 2, 3, [4]] +``` + +空の配列やnull、undefinedは空の配列を返します。 + +```typescript +import { flatten } from 'es-toolkit/compat'; + +flatten(null); // [] +flatten(undefined); // [] +flatten([]); // [] +``` + +Symbol.isConcatSpreadableを持つオブジェクトも配列のように平坦化されます。 + +```typescript +import { flatten } from 'es-toolkit/compat'; + +const spreadable = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true }; +flatten([1, spreadable, 3]); +// 結果: [1, 'a', 'b', 3] +``` + +#### パラメータ + +- `value` (`ArrayLike | null | undefined`): 平坦化する配列です。 +- `depth` (`number`, オプション): 平坦化する最大深さです。デフォルトは`1`です。 + +#### 戻り値 + +(`T[]`): 平坦化された新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/flattenDeep.md b/docs/ja/compat/reference/array/flattenDeep.md new file mode 100644 index 000000000..52f4ede73 --- /dev/null +++ b/docs/ja/compat/reference/array/flattenDeep.md @@ -0,0 +1,64 @@ +# flattenDeep (Lodash 互換性) + +::: warning `es-toolkit`の`flattenDeep`を使用してください + +この`flattenDeep`関数は、`null`や`undefined`の処理、`ArrayLike`型の処理、様々な条件関数形式のサポートなどにより、動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[flattenDeep](../../../reference/array/flattenDeep.md)を使用してください。 + +::: + +配列を完全に平坦化します。 + +```typescript +const result = flattenDeep(array); +``` + +## 使用法 + +### `flattenDeep(value)` + +ネストされた配列をすべての深さで再帰的に平坦化します。すべてのネストレベルが削除され、完全に平坦化された1次元配列を返します。 + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +// 深くネストされた配列を完全に平坦化 +flattenDeep([1, [2, [3, [4]], 5]]); +// 結果: [1, 2, 3, 4, 5] + +// 複雑なネスト構造も完全に平坦化 +flattenDeep([1, [2, [3, [[[[4]]]]], 5]]); +// 結果: [1, 2, 3, 4, 5] + +// 混合された型もサポート +flattenDeep(['a', ['b', ['c', [['d']]]]]); +// 結果: ['a', 'b', 'c', 'd'] +``` + +空の配列やnull、undefinedは空の配列を返します。 + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +flattenDeep(null); // [] +flattenDeep(undefined); // [] +flattenDeep([]); // [] +``` + +すでに平坦化された配列はそのままコピーされます。 + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +flattenDeep([1, 2, 3, 4, 5]); +// 結果: [1, 2, 3, 4, 5] +``` + +#### パラメータ + +- `value` (`ListOfRecursiveArraysOrValues | null | undefined`): 完全に平坦化する配列です。 + +#### 戻り値 + +(`Array`): すべてのネストが削除された完全に平坦化された新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/flattenDepth.md b/docs/ja/compat/reference/array/flattenDepth.md new file mode 100644 index 000000000..bdef86f3a --- /dev/null +++ b/docs/ja/compat/reference/array/flattenDepth.md @@ -0,0 +1,55 @@ +# flattenDepth (Lodash 互換性) + +::: warning `es-toolkit`の`flatten`を使用してください + +この`flattenDepth`関数は、`null`や`undefined`の処理などにより、動作が遅くなります。`es-toolkit`の`flatten`関数は、これらの追加処理なしで、より高速かつシンプルに動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[flatten](../../../reference/array/flatten.md)を使用してください。 + +::: + +配列を指定した深さまで平坦化します。 + +```typescript +const flattened = flattenDepth(array, depth); +``` + +## 使用法 + +### `flattenDepth(array, depth)` + +ネストされた配列を望む深さまで平坦化したい場合は`flattenDepth`を使用してください。深さを指定すると、その深さまでのみネストされた配列を平坦化します。 + +```typescript +import { flattenDepth } from 'es-toolkit/compat'; + +// 深さ1まで平坦化します +flattenDepth([1, [2, [3, [4]], 5]], 1); +// Returns: [1, 2, [3, [4]], 5] + +// 深さ2まで平坦化します +flattenDepth([1, [2, [3, [4]], 5]], 2); +// Returns: [1, 2, 3, [4], 5] + +// 深さを指定しない場合、デフォルト値1で平坦化します +flattenDepth([1, [2, [3, [4]], 5]]); +// Returns: [1, 2, [3, [4]], 5] +``` + +`null`または`undefined`は空の配列として処理されます。 + +```typescript +import { flattenDepth } from 'es-toolkit/compat'; + +flattenDepth(null, 2); // [] +flattenDepth(undefined, 2); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 平坦化する配列です。 +- `depth` (`number`, オプション): 平坦化する最大深さです。デフォルトは`1`です。 + +#### 戻り値 + +(`T[]`): 指定した深さまで平坦化された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/forEach.md b/docs/ja/compat/reference/array/forEach.md similarity index 100% rename from docs/ja/reference/compat/array/forEach.md rename to docs/ja/compat/reference/array/forEach.md diff --git a/docs/ja/compat/reference/array/forEachRight.md b/docs/ja/compat/reference/array/forEachRight.md new file mode 100644 index 000000000..c6d6baeff --- /dev/null +++ b/docs/ja/compat/reference/array/forEachRight.md @@ -0,0 +1,75 @@ +# forEachRight (Lodash 互換性) + +::: warning `es-toolkit`の`forEachRight`を使用してください + +この`forEachRight`関数は、`null`や`undefined`の処理、`ArrayLike`タイプの処理、さまざまな条件関数形式のサポートなどにより、動作が遅くなります。 + +代わりに、より高速でモダンな`es-toolkit`の[forEachRight](../../../reference/array/forEachRight.md)を使用してください。 + +::: + +配列またはオブジェクトの要素を右から左に走査し、各要素に対して関数を実行します。 + +```typescript +forEachRight(collection, callback); +``` + +## 使用法 + +### `forEachRight(collection, callback)` + +配列、オブジェクト、文字列を右から左の順序で走査し、各要素に対してコールバック関数を実行します。コールバックが`false`を返すと走査を中断します。 + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +// 配列を逆順で走査します +forEachRight([1, 2, 3], (value, index) => { + console.log(value, index); +}); +// 出力: 3 2, 2 1, 1 0 + +// 文字列を逆順で走査します +forEachRight('abc', (char, index) => { + console.log(char, index); +}); +// 出力: 'c' 2, 'b' 1, 'a' 0 + +// オブジェクトを逆順で走査します +forEachRight({ a: 1, b: 2, c: 3 }, (value, key) => { + console.log(value, key); +}); +// 出力: 3 'c', 2 'b', 1 'a' +``` + +`null`または`undefined`はそのまま返します。 + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +forEachRight(null, value => console.log(value)); // null +forEachRight(undefined, value => console.log(value)); // undefined +``` + +コールバックが`false`を返すと走査を中断します。 + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +forEachRight([1, 2, 3, 4], value => { + console.log(value); + if (value === 2) { + return false; // 走査を中断 + } +}); +// 出力: 4, 3, 2 +``` + +#### パラメータ + +- `collection` (`ArrayLike | Record | string | null | undefined`): 走査するコレクションです。配列、オブジェクト、文字列、またはnull/undefinedを指定できます。 +- `callback` (`(item: any, index: any, arr: any) => unknown`, 選択): 各要素に対して実行する関数です。`false`を返すと走査を中断します。デフォルトは`identity`関数です。 + +#### 戻り値 + +(`ArrayLike | Record | string | null | undefined`): 元のコレクションをそのまま返します。 diff --git a/docs/ja/compat/reference/array/groupBy.md b/docs/ja/compat/reference/array/groupBy.md new file mode 100644 index 000000000..88b8b370c --- /dev/null +++ b/docs/ja/compat/reference/array/groupBy.md @@ -0,0 +1,79 @@ +# groupBy (Lodash 互換性) + +::: warning `es-toolkit`の[groupBy](../../../reference/array/groupBy.md)を使用してください + +この`groupBy`関数は、`null`や`undefined`の処理、オブジェクトのサポート、複雑な型処理などにより、動作が遅くなります。 + +代わりに、より高速でモダンな`es-toolkit`の[groupBy](../../../reference/array/groupBy.md)を使用してください。 + +::: + +配列またはオブジェクトの要素を与えられた条件に従ってグループ化します。 + +```typescript +const grouped = groupBy(collection, iteratee); +``` + +## 使用法 + +### `groupBy(collection, iteratee)` + +配列またはオブジェクトの各要素を与えられた条件関数に従ってグループ化し、グループ別に分類されたオブジェクトを返します。条件は関数、プロパティ名、部分オブジェクトなど、さまざまな形式で提供できます。 + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +// 関数でグループ化 +const array = [6.1, 4.2, 6.3]; +const result = groupBy(array, Math.floor); +// resultは{ '4': [4.2], '6': [6.1, 6.3] } + +// プロパティ名でグループ化 +const users = [ + { name: 'john', age: 30 }, + { name: 'jane', age: 25 }, + { name: 'bob', age: 30 }, +]; +const byAge = groupBy(users, 'age'); +// byAgeは{ '25': [{ name: 'jane', age: 25 }], '30': [{ name: 'john', age: 30 }, { name: 'bob', age: 30 }] } + +// オブジェクトからグループ化 +const obj = { a: 6.1, b: 4.2, c: 6.3 }; +const groupedObj = groupBy(obj, Math.floor); +// groupedObjは{ '4': [4.2], '6': [6.1, 6.3] } +``` + +`null`または`undefined`は空のオブジェクトとして扱われます。 + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +groupBy(null, x => x); // {} +groupBy(undefined, x => x); // {} +``` + +部分オブジェクトやプロパティ-値ペアでもグループ化できます。 + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +const products = [ + { category: 'fruit', name: 'apple' }, + { category: 'fruit', name: 'banana' }, + { category: 'vegetable', name: 'carrot' }, +]; + +// 部分オブジェクトでグループ化 +const byCategory = groupBy(products, { category: 'fruit' }); +// プロパティ-値ペアでグループ化 +const byName = groupBy(products, ['name', 'apple']); +``` + +#### パラメータ + +- `collection` (`ArrayLike | Record | null | undefined`): グループ化する配列またはオブジェクトです。 +- `iteratee` (`Function | PropertyKey | Array | Object`, 選択): グループ化する条件です。関数、プロパティ名、プロパティ-値ペア、または部分オブジェクトを指定できます。デフォルトは`identity`関数です。 + +#### 戻り値 + +(`Record`): 各キーがグループの条件値で、値がそのグループに属する要素の配列であるオブジェクトを返します。 diff --git a/docs/ja/compat/reference/array/head.md b/docs/ja/compat/reference/array/head.md new file mode 100644 index 000000000..fb1079114 --- /dev/null +++ b/docs/ja/compat/reference/array/head.md @@ -0,0 +1,61 @@ +# head (Lodash 互換性) + +::: warning `es-toolkit`の[head](../../../reference/array/head.md)を使用してください + +この`head`関数は、`ArrayLike`オブジェクトの処理と配列変換プロセスにより、動作が遅くなります。 + +代わりに、より高速でモダンな`es-toolkit`の[head](../../../reference/array/head.md)を使用してください。 + +::: + +配列の最初の要素を返します。 + +```typescript +const firstElement = head(array); +``` + +## 使用法 + +### `head(array)` + +配列または配列のようなオブジェクトの最初の要素を返します。配列が空または無効な場合は`undefined`を返します。 + +```typescript +import { head } from 'es-toolkit/compat'; + +// 数値配列の最初の要素 +const numbers = [1, 2, 3, 4]; +const first = head(numbers); +// firstは1 + +// 文字列配列の最初の要素 +const strings = ['a', 'b', 'c']; +const firstChar = head(strings); +// firstCharは'a' + +// 配列のようなオブジェクト +const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; +const firstItem = head(arrayLike); +// firstItemは'x' +``` + +空の配列または無効な入力は`undefined`を返します。 + +```typescript +import { head } from 'es-toolkit/compat'; + +const emptyArray: number[] = []; +const noElement = head(emptyArray); +// noElementはundefined + +head(null); // undefined +head(undefined); // undefined +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 最初の要素を取得する配列または配列のようなオブジェクトです。 + +#### 戻り値 + +(`T | undefined`): 配列の最初の要素を返し、配列が空または無効な場合は`undefined`を返します。 diff --git a/docs/ja/reference/compat/array/includes.md b/docs/ja/compat/reference/array/includes.md similarity index 100% rename from docs/ja/reference/compat/array/includes.md rename to docs/ja/compat/reference/array/includes.md diff --git a/docs/ja/reference/compat/array/indexOf.md b/docs/ja/compat/reference/array/indexOf.md similarity index 100% rename from docs/ja/reference/compat/array/indexOf.md rename to docs/ja/compat/reference/array/indexOf.md diff --git a/docs/ja/compat/reference/array/initial.md b/docs/ja/compat/reference/array/initial.md new file mode 100644 index 000000000..2eeaf9e5a --- /dev/null +++ b/docs/ja/compat/reference/array/initial.md @@ -0,0 +1,65 @@ +# initial (Lodash 互換性) + +::: warning `es-toolkit`の[initial](../../../reference/array/initial.md)を使用してください + +この`initial`関数は、`ArrayLike`オブジェクトの処理と配列変換プロセスにより、動作が遅くなります。 + +代わりに、より高速でモダンな`es-toolkit`の[initial](../../../reference/array/initial.md)を使用してください。 + +::: + +配列から最後の要素を除くすべての要素を新しい配列として返します。 + +```typescript +const result = initial(array); +``` + +## 使用法 + +### `initial(array)` + +配列または配列のようなオブジェクトから最後の要素を除くすべての要素を含む新しい配列を返します。配列が空または要素が1つだけの場合は空の配列を返します。 + +```typescript +import { initial } from 'es-toolkit/compat'; + +// 数値配列から最後の要素を除外 +const numbers = [1, 2, 3, 4]; +const result = initial(numbers); +// resultは[1, 2, 3] + +// 文字列配列から最後の要素を除外 +const strings = ['a', 'b', 'c', 'd']; +const withoutLast = initial(strings); +// withoutLastは['a', 'b', 'c'] + +// 配列のようなオブジェクト +const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; +const items = initial(arrayLike); +// itemsは['x', 'y'] +``` + +空の配列または無効な入力は空の配列を返します。 + +```typescript +import { initial } from 'es-toolkit/compat'; + +const emptyArray: number[] = []; +const result = initial(emptyArray); +// resultは[] + +const singleItem = [42]; +const onlyOne = initial(singleItem); +// onlyOneは[] + +initial(null); // [] +initial(undefined); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 最後の要素を除外する配列または配列のようなオブジェクトです。 + +#### 戻り値 + +(`T[]`): 最後の要素を除外した新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/intersection.md b/docs/ja/compat/reference/array/intersection.md new file mode 100644 index 000000000..eaacfb857 --- /dev/null +++ b/docs/ja/compat/reference/array/intersection.md @@ -0,0 +1,80 @@ +# intersection (Lodash 互換性) + +::: warning `es-toolkit`の[intersection](../../../reference/array/intersection.md)を使用してください + +この`intersection`関数は、`null`や`undefined`の処理、複数配列のサポート、重複除去プロセスにより、動作が遅くなります。 + +代わりに、より高速でモダンな`es-toolkit`の[intersection](../../../reference/array/intersection.md)を使用してください。 + +::: + +複数の配列の共通部分を求めます。 + +```typescript +const result = intersection(...arrays); +``` + +## 使用法 + +### `intersection(...arrays)` + +複数の配列で共通に存在する要素を見つけて新しい配列として返します。結果は重複が除去され、最初の配列の順序を維持します。 + +```typescript +import { intersection } from 'es-toolkit/compat'; + +// 2つの配列の共通部分 +const array1 = [1, 2, 3, 4]; +const array2 = [2, 3, 5, 6]; +const result = intersection(array1, array2); +// resultは[2, 3] + +// 3つの配列の共通部分 +const array3 = [3, 4, 7, 8]; +const multiResult = intersection(array1, array2, array3); +// multiResultは[3] + +// 文字列配列 +const strings1 = ['a', 'b', 'c']; +const strings2 = ['b', 'c', 'd']; +const stringResult = intersection(strings1, strings2); +// stringResultは['b', 'c'] + +// 配列のようなオブジェクト +const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; +const arrayLike2 = { 0: 2, 1: 3, 2: 4, length: 3 }; +const likeResult = intersection(arrayLike1, arrayLike2); +// likeResultは[2, 3] +``` + +`null`または`undefined`配列は空の配列として扱われます。 + +```typescript +import { intersection } from 'es-toolkit/compat'; + +const array1 = [1, 2, 3]; +const result1 = intersection(array1, null); +// result1は[] + +const result2 = intersection(null, undefined); +// result2は[] +``` + +重複した要素は結果から除去されます。 + +```typescript +import { intersection } from 'es-toolkit/compat'; + +const array1 = [1, 1, 2, 3]; +const array2 = [1, 2, 2, 4]; +const result = intersection(array1, array2); +// resultは[1, 2](重複除去されます) +``` + +#### パラメータ + +- `...arrays` (`Array | null | undefined>`): 共通部分を求める配列です。配列のようなオブジェクトやnull/undefinedも許可されます。 + +#### 戻り値 + +(`T[]`): すべての配列で共通に存在する要素の新しい配列を返します。重複は除去され、最初の配列の順序に従います。 diff --git a/docs/ja/compat/reference/array/intersectionBy.md b/docs/ja/compat/reference/array/intersectionBy.md new file mode 100644 index 000000000..29b6f11f3 --- /dev/null +++ b/docs/ja/compat/reference/array/intersectionBy.md @@ -0,0 +1,93 @@ +# intersectionBy (Lodash 互換性) + +::: warning `es-toolkit`の[intersectionBy](../../../reference/array/intersectionBy.md)を使用してください + +この`intersectionBy`関数は、複雑な条件処理、複数配列のサポート、プロパティパスの解析などにより、動作が遅くなります。 + +代わりに、より高速でモダンな`es-toolkit`の[intersectionBy](../../../reference/array/intersectionBy.md)を使用してください。 + +::: + +与えられた条件関数を使用して複数の配列の共通部分を求めます。 + +```typescript +const result = intersectionBy(...arrays, iteratee); +``` + +## 使用法 + +### `intersectionBy(...arrays, iteratee)` + +複数の配列で、各要素を与えられた条件関数で変換した値を基準に共通部分を求めます。条件は関数、プロパティ名、部分オブジェクトなど、さまざまな形式で提供できます。 + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +// 関数で共通部分を求める +const array1 = [2.1, 1.2]; +const array2 = [2.3, 3.4]; +const result = intersectionBy(array1, array2, Math.floor); +// resultは[2.1](Math.floor基準で2が共通) + +// プロパティで共通部分を求める +const users1 = [ + { id: 1, name: 'john' }, + { id: 2, name: 'jane' }, +]; +const users2 = [ + { id: 2, name: 'jane' }, + { id: 3, name: 'bob' }, +]; +const byId = intersectionBy(users1, users2, 'id'); +// byIdは[{ id: 2, name: 'jane' }] + +// 3つの配列の共通部分 +const array3 = [2.5, 4.1]; +const multiResult = intersectionBy(array1, array2, array3, Math.floor); +// multiResultは[2.1] + +// 配列のようなオブジェクト +const arrayLike1 = { 0: { x: 1 }, 1: { x: 2 }, length: 2 }; +const arrayLike2 = { 0: { x: 2 }, 1: { x: 3 }, length: 2 }; +const byProperty = intersectionBy(arrayLike1, arrayLike2, 'x'); +// byPropertyは[{ x: 2 }] +``` + +`null`または`undefined`配列は空の配列として扱われます。 + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +const array1 = [{ x: 1 }, { x: 2 }]; +const result = intersectionBy(array1, null, 'x'); +// resultは[] +``` + +部分オブジェクトやプロパティ-値ペアでも条件を指定できます。 + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +const products1 = [ + { category: 'fruit', name: 'apple' }, + { category: 'vegetable', name: 'carrot' }, +]; +const products2 = [ + { category: 'fruit', name: 'banana' }, + { category: 'meat', name: 'beef' }, +]; + +// 部分オブジェクトで条件を指定 +const byCategory = intersectionBy(products1, products2, { category: 'fruit' }); +// プロパティ-値ペアで条件を指定 +const byCategoryPair = intersectionBy(products1, products2, ['category', 'fruit']); +``` + +#### パラメータ + +- `...arrays` (`Array | null | undefined>`): 共通部分を求める配列です。 +- `iteratee` (`Function | PropertyKey | Array | Object`): 各要素を変換する条件です。関数、プロパティ名、プロパティ-値ペア、または部分オブジェクトを指定できます。 + +#### 戻り値 + +(`T[]`): 変換された値を基準にすべての配列で共通に存在する要素の新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/intersectionWith.md b/docs/ja/compat/reference/array/intersectionWith.md new file mode 100644 index 000000000..99e9c5b3e --- /dev/null +++ b/docs/ja/compat/reference/array/intersectionWith.md @@ -0,0 +1,64 @@ +# intersectionWith (Lodash 互換性) + +::: warning `es-toolkit`の[intersectionWith](../../../reference/array/intersectionWith.md)を使用してください + +この`intersectionWith`関数は、`null`や`undefined`の処理、さまざまなオーバーロードのサポートなどにより、動作が遅くなります。 + +代わりに、より高速でモダンな`es-toolkit`の[intersectionWith](../../../reference/array/intersectionWith.md)を使用してください。 + +::: + +カスタム比較関数を使用して、すべての配列に含まれる共通要素の配列を作成します。 + +```typescript +const result = intersectionWith(array, ...otherArrays, comparator); +``` + +## 使用法 + +### `intersectionWith(array, ...otherArrays, comparator)` + +カスタム比較関数を使用して、最初の配列と残りの配列の共通部分を求めます。比較関数で各要素が等しいかを判断し、すべての配列に含まれる要素のみを返します。 + +```typescript +import { intersectionWith } from 'es-toolkit/compat'; + +const objects = [ + { id: 1, name: 'john' }, + { id: 2, name: 'jane' }, +]; +const others = [ + { id: 1, name: 'john' }, + { id: 3, name: 'joe' }, +]; + +intersectionWith(objects, others, (a, b) => a.id === b.id); +// => [{ id: 1, name: 'john' }] + +// 複数の配列と比較することもできます +const array1 = [{ x: 1 }, { x: 2 }]; +const array2 = [{ x: 1 }, { x: 3 }]; +const array3 = [{ x: 1 }, { x: 4 }]; + +intersectionWith(array1, array2, array3, (a, b) => a.x === b.x); +// => [{ x: 1 }] +``` + +`null`または`undefined`は空の配列として扱われます。 + +```typescript +import { intersectionWith } from 'es-toolkit/compat'; + +intersectionWith(null, [1, 2], (a, b) => a === b); // [] +intersectionWith([1, 2], undefined, (a, b) => a === b); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 比較する最初の配列です。 +- `...otherArrays` (`Array | ((a: T, b: T | U) => boolean)>`): 比較する他の配列と、最後の要素として比較関数です。 +- `comparator` (`(a: T, b: T | U) => boolean`): 2つの要素が等しいかを判断する関数です。 + +#### 戻り値 + +(`T[]`): すべての配列で共通に見つかった要素の新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/invokeMap.md b/docs/ja/compat/reference/array/invokeMap.md similarity index 100% rename from docs/ja/reference/compat/array/invokeMap.md rename to docs/ja/compat/reference/array/invokeMap.md diff --git a/docs/ja/reference/compat/array/join.md b/docs/ja/compat/reference/array/join.md similarity index 100% rename from docs/ja/reference/compat/array/join.md rename to docs/ja/compat/reference/array/join.md diff --git a/docs/ja/compat/reference/array/keyBy.md b/docs/ja/compat/reference/array/keyBy.md new file mode 100644 index 000000000..d94b08a8e --- /dev/null +++ b/docs/ja/compat/reference/array/keyBy.md @@ -0,0 +1,64 @@ +# keyBy (Lodash 互換性) + +::: warning `es-toolkit` の [keyBy](../../../reference/array/keyBy.md) を使用してください + +この `keyBy` 関数は、`null` や `undefined` の処理、さまざまなパラメータ型の処理などにより動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [keyBy](../../../reference/array/keyBy.md) を使用してください。 + +::: + +コレクションの要素を指定されたキーに基づいてオブジェクトに構成します。 + +```typescript +const result = keyBy(collection, iteratee); +``` + +## 使用法 + +### `keyBy(collection, iteratee)` + +配列またはオブジェクトの各要素を、指定されたキー生成関数またはプロパティ名を使用してオブジェクトに構成します。同じキーを持つ要素が複数ある場合は、最後の要素が使用されます。 + +```typescript +import { keyBy } from 'es-toolkit/compat'; + +// プロパティ名でキーを生成する +const array = [ + { dir: 'left', code: 97 }, + { dir: 'right', code: 100 }, +]; + +keyBy(array, 'dir'); +// => { left: { dir: 'left', code: 97 }, right: { dir: 'right', code: 100 } } + +// 関数でキーを生成する +keyBy(array, o => String.fromCharCode(o.code)); +// => { a: { dir: 'left', code: 97 }, d: { dir: 'right', code: 100 } } + +// オブジェクトでも使用可能 +const obj = { + a: { id: 1, name: 'john' }, + b: { id: 2, name: 'jane' }, +}; +keyBy(obj, 'name'); +// => { john: { id: 1, name: 'john' }, jane: { id: 2, name: 'jane' } } +``` + +`null` または `undefined` は空のオブジェクトとして扱われます。 + +```typescript +import { keyBy } from 'es-toolkit/compat'; + +keyBy(null, 'id'); // {} +keyBy(undefined, 'id'); // {} +``` + +#### パラメータ + +- `collection` (`ArrayLike | null | undefined`): キーで構成する配列またはオブジェクトです。 +- `iteratee` (`ValueIterateeCustom`, オプション): キーを生成する関数またはプロパティ名です。省略すると、要素自体がキーとして使用されます。 + +#### 戻り値 + +(`Record`): 各要素が生成されたキーにマッピングされた新しいオブジェクトを返します。 diff --git a/docs/ja/compat/reference/array/last.md b/docs/ja/compat/reference/array/last.md new file mode 100644 index 000000000..a1361df64 --- /dev/null +++ b/docs/ja/compat/reference/array/last.md @@ -0,0 +1,79 @@ +# last (Lodash互換性) + +::: warning `es-toolkit`の[last](../../../reference/array/last.md)を使用してください + +この`last`関数は`null`や`undefined`の処理により複雑に動作します。 + +代わりに、より高速でモダンな`es-toolkit`の[last](../../../reference/array/last.md)を使用してください。 + +::: + +配列の最後の要素を返します。 + +```typescript +const lastElement = last(array); +``` + +## 使用法 + +### `last(array)` + +配列の最後の要素を取得したいときに`last`を使用してください。配列が空の場合は`undefined`を返します。 + +```typescript +import { last } from 'es-toolkit/compat'; + +// 数値配列の最後の要素 +last([1, 2, 3, 4, 5]); +// Returns: 5 + +// 文字列配列の最後の要素 +last(['a', 'b', 'c']); +// Returns: 'c' + +// オブジェクト配列の最後の要素 +const users = [{ name: 'Alice' }, { name: 'Bob' }]; +last(users); +// Returns: { name: 'Bob' } +``` + +空の配列や`null`、`undefined`は`undefined`を返します。 + +```typescript +import { last } from 'es-toolkit/compat'; + +// 空の配列 +last([]); +// Returns: undefined + +// null配列 +last(null); +// Returns: undefined + +// undefined配列 +last(undefined); +// Returns: undefined +``` + +配列風オブジェクトもサポートしています。 + +```typescript +import { last } from 'es-toolkit/compat'; + +// 配列風オブジェクト +const arrayLike = { 0: 'first', 1: 'second', length: 2 }; +last(arrayLike); +// Returns: 'second' + +// 文字列も配列風オブジェクト +last('hello'); +// Returns: 'o' +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 最後の要素を取得する配列です。 + +#### 戻り値 + +(`T | undefined`): 配列の最後の要素を返し、配列が空または`null`、`undefined`の場合は`undefined`を返します。 diff --git a/docs/ja/reference/compat/array/lastIndexOf.md b/docs/ja/compat/reference/array/lastIndexOf.md similarity index 100% rename from docs/ja/reference/compat/array/lastIndexOf.md rename to docs/ja/compat/reference/array/lastIndexOf.md diff --git a/docs/ja/reference/compat/array/map.md b/docs/ja/compat/reference/array/map.md similarity index 100% rename from docs/ja/reference/compat/array/map.md rename to docs/ja/compat/reference/array/map.md diff --git a/docs/ja/reference/compat/array/nth.md b/docs/ja/compat/reference/array/nth.md similarity index 100% rename from docs/ja/reference/compat/array/nth.md rename to docs/ja/compat/reference/array/nth.md diff --git a/docs/ja/compat/reference/array/orderBy.md b/docs/ja/compat/reference/array/orderBy.md new file mode 100644 index 000000000..59dad02a2 --- /dev/null +++ b/docs/ja/compat/reference/array/orderBy.md @@ -0,0 +1,82 @@ +# orderBy (Lodash 互換性) + +::: warning `es-toolkit` の [orderBy](../../../reference/array/orderBy.md) を使用してください + +この `orderBy` 関数は、`null` や `undefined` の処理、複雑なパス探索、様々なソート条件の処理により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [orderBy](../../../reference/array/orderBy.md) を使用してください。 + +::: + +複数の条件でコレクションの要素をソートします。 + +```typescript +const result = orderBy(collection, criteria, orders); +``` + +## 使用法 + +### `orderBy(collection, criteria, orders)` + +指定された条件とソート順に従って、配列またはオブジェクトの要素をソートします。複数の条件を使用でき、各条件に対して昇順 (`'asc'`) または降順 (`'desc'`) のソートを指定できます。 + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +const users = [ + { name: 'fred', age: 48 }, + { name: 'barney', age: 34 }, + { name: 'fred', age: 40 }, + { name: 'barney', age: 36 }, +]; + +// 名前昇順、年齢降順でソート +orderBy(users, ['name', 'age'], ['asc', 'desc']); +// => [ +// { name: 'barney', age: 36 }, +// { name: 'barney', age: 34 }, +// { name: 'fred', age: 48 }, +// { name: 'fred', age: 40 } +// ] + +// 関数でソート条件を指定 +orderBy(users, [user => user.name, user => user.age], ['asc', 'desc']); +// => 上記と同じ結果 + +// 単一の条件でソート +orderBy(users, 'age', 'desc'); +// => [{ name: 'fred', age: 48 }, { name: 'fred', age: 40 }, ...] +``` + +オブジェクトの場合、値をソートします。 + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +const obj = { + a: { name: 'fred', age: 48 }, + b: { name: 'barney', age: 34 }, +}; + +orderBy(obj, 'age', 'desc'); +// => [{ name: 'fred', age: 48 }, { name: 'barney', age: 34 }] +``` + +`null` または `undefined` は空の配列として扱われます。 + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +orderBy(null, 'name'); // [] +orderBy(undefined, 'age'); // [] +``` + +#### パラメータ + +- `collection` (`ArrayLike | object | null | undefined`): ソートする配列またはオブジェクトです。 +- `criteria` (`Criterion | Array>`, オプション): ソート条件です。プロパティ名、プロパティパス、関数などを使用できます。デフォルトは `[null]` です。 +- `orders` (`unknown | unknown[]`, オプション): 各条件のソート順です。`'asc'`(昇順)、`'desc'`(降順)、`true`(昇順)、`false`(降順)を使用できます。デフォルトは `[]` です。 + +#### 戻り値 + +(`T[]`): 新しくソートされた配列を返します。 diff --git a/docs/ja/compat/reference/array/partition.md b/docs/ja/compat/reference/array/partition.md new file mode 100644 index 000000000..f2cfecaf0 --- /dev/null +++ b/docs/ja/compat/reference/array/partition.md @@ -0,0 +1,89 @@ +# partition (Lodash 互換性) + +::: warning `es-toolkit` の [partition](../../../reference/array/partition.md) を使用してください + +この `partition` 関数は、`null` や `undefined` の処理、様々な条件タイプにより動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [partition](../../../reference/array/partition.md) を使用してください。 + +::: + +条件に基づいてコレクションの要素を2つのグループに分けます。 + +```typescript +const [truthy, falsy] = partition(collection, predicate); +``` + +## 使用法 + +### `partition(collection, predicate)` + +与えられた条件関数に基づいて、配列またはオブジェクトの要素を2つのグループに分けます。最初のグループには条件が真である要素が含まれ、2番目のグループには条件が偽である要素が含まれます。 + +```typescript +import { partition } from 'es-toolkit/compat'; + +// 数値配列を偶数と奇数に分ける +partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); +// => [[2, 4, 6], [1, 3, 5]] + +// プロパティ名で条件を指定 +const users = [ + { name: 'john', active: true }, + { name: 'jane', active: false }, + { name: 'bob', active: true }, +]; + +partition(users, 'active'); +// => [ +// [{ name: 'john', active: true }, { name: 'bob', active: true }], +// [{ name: 'jane', active: false }] +// ] + +// オブジェクト条件でフィルタリング +partition(users, { active: true }); +// => [ +// [{ name: 'john', active: true }, { name: 'bob', active: true }], +// [{ name: 'jane', active: false }] +// ] + +// 配列条件でフィルタリング +partition(users, ['name', 'john']); +// => [ +// [{ name: 'john', active: true }], +// [{ name: 'jane', active: false }, { name: 'bob', active: true }] +// ] +``` + +オブジェクトの場合、値を分割します。 + +```typescript +import { partition } from 'es-toolkit/compat'; + +const obj = { + a: { score: 90 }, + b: { score: 40 }, + c: { score: 80 }, +}; + +partition(obj, item => item.score >= 80); +// => [[{ score: 90 }, { score: 80 }], [{ score: 40 }]] +``` + +`null` または `undefined` は空の配列として扱われます。 + +```typescript +import { partition } from 'es-toolkit/compat'; + +partition(null, x => x > 0); // [[], []] +partition(undefined, 'active'); // [[], []] +``` + +#### パラメータ + +- `collection` (`ArrayLike | T | null | undefined`): 分割する配列またはオブジェクトです。 +- `predicate` (`((value: T) => unknown) | Partial | [PropertyKey, any] | PropertyKey`, オプション): 各要素をテストする条件です。関数、部分オブジェクト、プロパティ-値配列、またはプロパティ名を使用できます。デフォルトは `identity` です。 + +#### 戻り値 + +(`[T[], T[]]`): 条件を満たす要素の配列と満たさない要素の配列を含む配列を返します。 diff --git a/docs/ja/compat/reference/array/pull.md b/docs/ja/compat/reference/array/pull.md new file mode 100644 index 000000000..119cc5e7a --- /dev/null +++ b/docs/ja/compat/reference/array/pull.md @@ -0,0 +1,44 @@ +# pull (Lodash 互換性) + +::: warning `es-toolkit` の [pull](../../../reference/array/pull.md) を使用してください + +この `pull` 関数は Lodash 互換性のための関数であり、より複雑な型処理とオーバーロードにより動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [pull](../../../reference/array/pull.md) を使用してください。 + +::: + +配列から指定された値をすべて削除します。 + +```typescript +const result = pull(array, ...valuesToRemove); +``` + +## 使用法 + +### `pull(array, ...valuesToRemove)` + +配列から指定された値をすべて削除し、元の配列を変更します。配列をコピーせずに元の配列を直接変更することでメモリを節約できます。 + +```typescript +import { pull } from 'es-toolkit/compat'; + +// 数値配列から特定の値を削除 +const numbers = [1, 2, 3, 2, 4, 2, 5]; +pull(numbers, 2, 3); +console.log(numbers); // [1, 4, 5] + +// 文字列配列から特定の値を削除 +const fruits = ['apple', 'banana', 'apple', 'cherry']; +pull(fruits, 'apple'); +console.log(fruits); // ['banana', 'cherry'] +``` + +#### パラメータ + +- `array` (`T[]`): 変更する配列です。 +- `...valuesToRemove` (`T[]`): 配列から削除する値です。 + +#### 戻り値 + +(`T[]`): 変更された元の配列を返します。 diff --git a/docs/ja/reference/compat/array/pullAll.md b/docs/ja/compat/reference/array/pullAll.md similarity index 100% rename from docs/ja/reference/compat/array/pullAll.md rename to docs/ja/compat/reference/array/pullAll.md diff --git a/docs/ja/reference/compat/array/pullAllBy.md b/docs/ja/compat/reference/array/pullAllBy.md similarity index 100% rename from docs/ja/reference/compat/array/pullAllBy.md rename to docs/ja/compat/reference/array/pullAllBy.md diff --git a/docs/ja/reference/compat/array/pullAllWith.md b/docs/ja/compat/reference/array/pullAllWith.md similarity index 100% rename from docs/ja/reference/compat/array/pullAllWith.md rename to docs/ja/compat/reference/array/pullAllWith.md diff --git a/docs/ja/compat/reference/array/pullAt.md b/docs/ja/compat/reference/array/pullAt.md new file mode 100644 index 000000000..ae338d8a2 --- /dev/null +++ b/docs/ja/compat/reference/array/pullAt.md @@ -0,0 +1,57 @@ +# pullAt (Lodash 互換性) + +::: warning `es-toolkit` の [pullAt](../../../reference/array/pullAt.md) を使用してください + +この `pullAt` 関数は、複雑な型処理とオーバーロードにより動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [pullAt](../../../reference/array/pullAt.md) を使用してください。 + +::: + +指定されたインデックスにある要素を配列から削除し、削除された要素を返します。 + +```typescript +const removed = pullAt(array, ...indexes); +``` + +## 使用法 + +### `pullAt(array, ...indexes)` + +指定されたインデックスにある要素を配列から削除し、削除された要素の配列を返します。元の配列は変更されます。 + +```typescript +import { pullAt } from 'es-toolkit/compat'; + +// 個別のインデックスで削除 +const array = [1, 2, 3, 4, 5]; +const removed = pullAt(array, 1, 3); +console.log(array); // [1, 3, 5] +console.log(removed); // [2, 4] + +// インデックスの配列で削除 +const colors = ['red', 'green', 'blue', 'yellow']; +const removedColors = pullAt(colors, [0, 2]); +console.log(colors); // ['green', 'yellow'] +console.log(removedColors); // ['red', 'blue'] +``` + +存在しないインデックスは `undefined` として扱われます。 + +```typescript +import { pullAt } from 'es-toolkit/compat'; + +const numbers = [10, 20, 30]; +const removed = pullAt(numbers, 1, 5); +console.log(numbers); // [10, 30] +console.log(removed); // [20, undefined] +``` + +#### パラメータ + +- `array` (`ArrayLike`): 変更する配列です。 +- `...indexes` (`Array`): 削除する要素のインデックスです。個別の数値または数値の配列として渡すことができます。 + +#### 戻り値 + +(`ArrayLike`): 削除された要素の配列を返します。 diff --git a/docs/ja/reference/compat/array/reduce.md b/docs/ja/compat/reference/array/reduce.md similarity index 100% rename from docs/ja/reference/compat/array/reduce.md rename to docs/ja/compat/reference/array/reduce.md diff --git a/docs/ja/reference/compat/array/reduceRight.md b/docs/ja/compat/reference/array/reduceRight.md similarity index 100% rename from docs/ja/reference/compat/array/reduceRight.md rename to docs/ja/compat/reference/array/reduceRight.md diff --git a/docs/ja/reference/compat/array/reject.md b/docs/ja/compat/reference/array/reject.md similarity index 100% rename from docs/ja/reference/compat/array/reject.md rename to docs/ja/compat/reference/array/reject.md diff --git a/docs/ja/compat/reference/array/remove.md b/docs/ja/compat/reference/array/remove.md new file mode 100644 index 000000000..8d54ff117 --- /dev/null +++ b/docs/ja/compat/reference/array/remove.md @@ -0,0 +1,70 @@ +# remove (Lodash 互換性) + +::: warning `es-toolkit`の`remove`を使用してください + +この`remove`関数は、Lodashとの互換性のために様々な形式の述語をサポートするため、複雑に実装されています。メインライブラリの`remove`関数はシンプルな関数述語のみをサポートするため、より高速に動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[remove](../../../reference/array/remove.md)を使用してください。 + +::: + +配列から条件に一致する要素を削除し、削除された要素を配列として返します。 + +```typescript +const removedElements = remove(array, predicate); +``` + +## 使用法 + +### `remove(array, predicate)` + +配列を反復処理し、与えられた条件に一致する要素を元の配列から削除し、削除された要素を新しい配列として返します。元の配列が直接変更されることに注意してください。 + +```typescript +import { remove } from 'es-toolkit/compat'; + +// 関数を使用した条件で削除 +const numbers = [1, 2, 3, 4, 5]; +const evens = remove(numbers, n => n % 2 === 0); +console.log(numbers); // => [1, 3, 5] +console.log(evens); // => [2, 4] + +// 部分オブジェクトのマッチングで削除 +const objects = [{ a: 1 }, { a: 2 }, { a: 3 }]; +const removed = remove(objects, { a: 1 }); +console.log(objects); // => [{ a: 2 }, { a: 3 }] +console.log(removed); // => [{ a: 1 }] + +// プロパティ-値ペアで削除 +const items = [{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }]; +const cherries = remove(items, ['name', 'cherry']); +console.log(items); // => [{ name: 'apple' }, { name: 'banana' }] +console.log(cherries); // => [{ name: 'cherry' }] +``` + +この関数は様々な形式の述語をサポートします。 + +```typescript +import { remove } from 'es-toolkit/compat'; + +// 関数を使用した条件 +remove(users, user => user.active === false); + +// 部分オブジェクトのマッチング +remove(users, { status: 'inactive' }); + +// プロパティ-値配列 +remove(users, ['type', 'guest']); + +// プロパティ名で真値を確認 +remove(users, 'isDeleted'); +``` + +#### パラメータ + +- `array` (`ArrayLike`): 変更する配列です。 +- `predicate` (`((value: T, index: number, array: ArrayLike) => boolean) | Partial | [keyof T, unknown] | keyof T`, オプション): 各要素に対して実行する条件です。デフォルトは`identity`です。 + +#### 戻り値 + +(`T[]`): 条件に一致して削除された要素で構成された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/reverse.md b/docs/ja/compat/reference/array/reverse.md similarity index 100% rename from docs/ja/reference/compat/array/reverse.md rename to docs/ja/compat/reference/array/reverse.md diff --git a/docs/ja/compat/reference/array/sample.md b/docs/ja/compat/reference/array/sample.md new file mode 100644 index 000000000..87d880516 --- /dev/null +++ b/docs/ja/compat/reference/array/sample.md @@ -0,0 +1,54 @@ +# sample(Lodash 互換性) + +::: warning `es-toolkit` の [sample](../../../reference/array/sample.md) を使用してください + +この `sample` 関数は、`null` や `undefined` の処理、オブジェクト値の処理などにより、遅く動作します。 + +より高速でモダンな `es-toolkit` の [sample](../../../reference/array/sample.md) を使用してください。 + +::: + +配列またはオブジェクトからランダムな要素を1つ取得します。 + +```typescript +const randomItem = sample(collection); +``` + +## 使用法 + +### `sample(collection)` + +配列またはオブジェクトからランダムな要素を1つ選択する場合は `sample` を使用します。配列ではランダムな要素を返し、オブジェクトではランダムな値を返します。 + +```typescript +import { sample } from 'es-toolkit/compat'; + +// 配列からランダムな要素を取得 +sample([1, 2, 3, 4, 5]); +// 1から5の中からランダムな数値を1つ返します + +// オブジェクトからランダムな値を取得 +sample({ a: 1, b: 2, c: 3 }); +// 1、2、3の中からランダムな値を1つ返します + +// 文字列も処理します +sample('hello'); +// 'h'、'e'、'l'、'l'、'o'の中からランダムな文字を1つ返します +``` + +`null` や `undefined` は `undefined` を返します。 + +```typescript +import { sample } from 'es-toolkit/compat'; + +sample(null); // undefined +sample(undefined); // undefined +``` + +#### パラメータ + +- `collection` (`ArrayLike | Record | null | undefined`): サンプリングする配列またはオブジェクト。 + +#### 戻り値 + +(`T | string | undefined`): 配列またはオブジェクトからランダムに選択された要素を返します。コレクションが空であるか `null`、`undefined` の場合は `undefined` を返します。 diff --git a/docs/ja/compat/reference/array/sampleSize.md b/docs/ja/compat/reference/array/sampleSize.md new file mode 100644 index 000000000..4dcebd0f7 --- /dev/null +++ b/docs/ja/compat/reference/array/sampleSize.md @@ -0,0 +1,54 @@ +# sampleSize(Lodash 互換性) + +::: warning `es-toolkit` の [sampleSize](../../../reference/array/sampleSize.md) を使用してください + +この `sampleSize` 関数は、`null` や `undefined` の処理、オブジェクトのサポート、デフォルト値の処理などにより、遅く動作します。 + +より高速でモダンな `es-toolkit` の [sampleSize](../../../reference/array/sampleSize.md) を使用してください。 + +::: + +配列またはオブジェクトから指定された数だけランダムに要素を選択します。 + +```typescript +const sampled = sampleSize(collection, size); +``` + +## 使用法 + +### `sampleSize(collection, size?)` + +配列またはオブジェクトからランダムに要素を選択する場合は `sampleSize` を使用します。Floyd アルゴリズムを使用して重複なく効率的にサンプリングします。 + +```typescript +import { sampleSize } from 'es-toolkit/compat'; + +// 配列から3個の要素をランダムに選択します。 +sampleSize([1, 2, 3, 4, 5], 3); +// 戻り値:[2, 4, 5](実際の結果は異なる場合があります) + +// オブジェクトから2個の値をランダムに選択します。 +sampleSize({ a: 1, b: 2, c: 3, d: 4 }, 2); +// 戻り値:[2, 4](実際の結果は異なる場合があります) +``` + +`null` や `undefined` は空の配列として処理します。 + +```typescript +import { sampleSize } from 'es-toolkit/compat'; + +sampleSize(null, 2); +// 戻り値:[] + +sampleSize(undefined, 2); +// 戻り値:[] +``` + +#### パラメータ + +- `collection` (`Record | Record | T | null | undefined`): サンプリングする配列またはオブジェクト。 +- `size` (`number`、オプション): 選択する要素の個数。デフォルトは `1` です。 + +#### 戻り値 + +(`T[]`):ランダムに選択された要素で構成される新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/shuffle.md b/docs/ja/compat/reference/array/shuffle.md new file mode 100644 index 000000000..1342cc3d5 --- /dev/null +++ b/docs/ja/compat/reference/array/shuffle.md @@ -0,0 +1,60 @@ +# shuffle(Lodash 互換性) + +::: warning `es-toolkit` の `shuffle` を使用してください + +この `shuffle` 関数は、Lodash との互換性のために追加の処理が含まれており、遅く動作します。 + +より高速でモダンな `es-toolkit` の [shuffle](../../../reference/array/shuffle.md) を使用してください。 + +::: + +配列またはオブジェクトの要素をランダムにシャッフルして新しい配列を返します。 + +```typescript +const result = shuffle(collection); +``` + +## 使用法 + +### `shuffle(collection)` + +Fisher-Yates アルゴリズムを使用して配列またはオブジェクトの要素をランダムにシャッフルし、新しい配列を返します。元は変更されません。 + +```typescript +import { shuffle } from 'es-toolkit/compat'; + +// 数値配列をシャッフル +const numbers = [1, 2, 3, 4, 5]; +const shuffled1 = shuffle(numbers); +// 戻り値:例えば [3, 1, 5, 2, 4](毎回異なる順序) + +// 文字列配列をシャッフル +const fruits = ['apple', 'banana', 'cherry', 'date']; +const shuffled2 = shuffle(fruits); +// 戻り値:例えば ['cherry', 'apple', 'date', 'banana'] + +// オブジェクトの値をシャッフル +const obj = { a: 1, b: 2, c: 3, d: 4 }; +const shuffled3 = shuffle(obj); +// 戻り値:例えば [3, 1, 4, 2](オブジェクトの値がランダムにシャッフルされる) +``` + +`null` や `undefined` は空の配列として処理します。 + +```typescript +import { shuffle } from 'es-toolkit/compat'; + +shuffle(null); +// 戻り値:[] + +shuffle(undefined); +// 戻り値:[] +``` + +#### パラメータ + +- `collection` (`ArrayLike | T | null | undefined`): シャッフルする配列またはオブジェクト。 + +#### 戻り値 + +(`T[]`):要素がランダムにシャッフルされた新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/size.md b/docs/ja/compat/reference/array/size.md similarity index 100% rename from docs/ja/reference/compat/array/size.md rename to docs/ja/compat/reference/array/size.md diff --git a/docs/ja/reference/compat/array/slice.md b/docs/ja/compat/reference/array/slice.md similarity index 100% rename from docs/ja/reference/compat/array/slice.md rename to docs/ja/compat/reference/array/slice.md diff --git a/docs/ja/reference/compat/array/some.md b/docs/ja/compat/reference/array/some.md similarity index 100% rename from docs/ja/reference/compat/array/some.md rename to docs/ja/compat/reference/array/some.md diff --git a/docs/ja/reference/compat/array/sortBy.md b/docs/ja/compat/reference/array/sortBy.md similarity index 100% rename from docs/ja/reference/compat/array/sortBy.md rename to docs/ja/compat/reference/array/sortBy.md diff --git a/docs/ja/reference/compat/array/sortedIndex.md b/docs/ja/compat/reference/array/sortedIndex.md similarity index 100% rename from docs/ja/reference/compat/array/sortedIndex.md rename to docs/ja/compat/reference/array/sortedIndex.md diff --git a/docs/ja/reference/compat/array/sortedIndexBy.md b/docs/ja/compat/reference/array/sortedIndexBy.md similarity index 100% rename from docs/ja/reference/compat/array/sortedIndexBy.md rename to docs/ja/compat/reference/array/sortedIndexBy.md diff --git a/docs/ja/reference/compat/array/sortedIndexOf.md b/docs/ja/compat/reference/array/sortedIndexOf.md similarity index 100% rename from docs/ja/reference/compat/array/sortedIndexOf.md rename to docs/ja/compat/reference/array/sortedIndexOf.md diff --git a/docs/ja/reference/compat/array/sortedLastIndex.md b/docs/ja/compat/reference/array/sortedLastIndex.md similarity index 100% rename from docs/ja/reference/compat/array/sortedLastIndex.md rename to docs/ja/compat/reference/array/sortedLastIndex.md diff --git a/docs/ja/reference/compat/array/sortedLastIndexBy.md b/docs/ja/compat/reference/array/sortedLastIndexBy.md similarity index 100% rename from docs/ja/reference/compat/array/sortedLastIndexBy.md rename to docs/ja/compat/reference/array/sortedLastIndexBy.md diff --git a/docs/ja/reference/compat/array/sortedLastIndexOf.md b/docs/ja/compat/reference/array/sortedLastIndexOf.md similarity index 100% rename from docs/ja/reference/compat/array/sortedLastIndexOf.md rename to docs/ja/compat/reference/array/sortedLastIndexOf.md diff --git a/docs/ja/compat/reference/array/tail.md b/docs/ja/compat/reference/array/tail.md new file mode 100644 index 000000000..71ede54b1 --- /dev/null +++ b/docs/ja/compat/reference/array/tail.md @@ -0,0 +1,58 @@ +# tail (Lodash 互換性) + +::: warning `es-toolkit`の[tail](../../../reference/array/tail.md)を使用してください + +この`tail`関数は、`null`や`undefined`の処理などにより遅く動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[tail](../../../reference/array/tail.md)を使用してください。 + +::: + +配列の最初の要素を除いた残りの要素を返します。 + +```typescript +const result = tail(array); +``` + +## 使用法 + +### `tail(array)` + +配列の最初の要素を除いたすべての要素を含む新しい配列を作成したい場合は`tail`を使用してください。入力配列が空または要素が1つだけの場合は空の配列を返します。 + +```typescript +import { tail } from 'es-toolkit/compat'; + +// 数値配列から最初の要素を削除します。 +tail([1, 2, 3]); +// Returns: [2, 3] + +// 文字列配列から最初の要素を削除します。 +tail(['a', 'b', 'c']); +// Returns: ['b', 'c'] + +// 要素が1つだけの配列です。 +tail([1]); +// Returns: [] + +// 空の配列です。 +tail([]); +// Returns: [] +``` + +`null`や`undefined`は空の配列として扱われます。 + +```typescript +import { tail } from 'es-toolkit/compat'; + +tail(null); // [] +tail(undefined); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 最初の要素を削除する配列です。 + +#### 戻り値 + +(`T[]`): 最初の要素を除いた残りの要素を含む新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/take.md b/docs/ja/compat/reference/array/take.md new file mode 100644 index 000000000..40862dcaf --- /dev/null +++ b/docs/ja/compat/reference/array/take.md @@ -0,0 +1,56 @@ +# take (Lodash 互換性) + +::: warning `es-toolkit`の[take](../../../reference/array/take.md)を使用してください + +この`take`関数は、Lodashとの互換性のための追加処理が含まれているため遅く動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[take](../../../reference/array/take.md)を使用してください。 + +::: + +配列の先頭から指定された個数の要素を取得して新しい配列を作成します。 + +```typescript +const result = take([1, 2, 3, 4, 5], 3); +// resultは[1, 2, 3]になります。 +``` + +## 使用法 + +### `take(array, count)` + +配列の先頭から指定された個数の要素を取得して新しい配列を返します。`count`が配列の長さより大きい場合は、配列全体を返します。 + +```typescript +import { take } from 'es-toolkit/compat'; + +// 基本的な使用法 +const numbers = [1, 2, 3, 4, 5]; +const result1 = take(numbers, 3); +// Returns: [1, 2, 3] + +// 配列の長さより大きい個数を要求 +const result2 = take(numbers, 10); +// Returns: [1, 2, 3, 4, 5] (配列全体) + +// 0個を要求 +const result3 = take(numbers, 0); +// Returns: [] + +// 空の配列を処理 +const result4 = take([], 3); +// Returns: [] + +// 負の数を処理 +const result5 = take(numbers, -1); +// Returns: [] +``` + +#### パラメータ + +- `array` (`T[]`): 要素を取得する配列です。 +- `count` (`number`): 取得する要素の個数です。デフォルト値は1です。 + +#### 戻り値 + +(`T[]`): 先頭から指定された個数の要素を含む新しい配列です。 diff --git a/docs/ja/compat/reference/array/takeRight.md b/docs/ja/compat/reference/array/takeRight.md new file mode 100644 index 000000000..52ea71d85 --- /dev/null +++ b/docs/ja/compat/reference/array/takeRight.md @@ -0,0 +1,63 @@ +# takeRight (Lodash 互換性) + +::: warning `es-toolkit`の[takeRight](../../../reference/array/takeRight.md)を使用してください + +この`takeRight`関数は、`null`や`undefined`の処理などにより遅く動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[takeRight](../../../reference/array/takeRight.md)を使用してください。 + +::: + +配列の末尾から指定された個数の要素を取得します。 + +```typescript +const result = takeRight(array, count); +``` + +## 使用法 + +### `takeRight(array, count)` + +配列の末尾から指定された個数の要素を取得して新しい配列を作成したい場合は`takeRight`を使用してください。要求された個数が配列の長さより大きい場合は、配列全体を返します。 + +```typescript +import { takeRight } from 'es-toolkit/compat'; + +// 数値配列から末尾の2個の要素を取得します。 +takeRight([1, 2, 3, 4, 5], 2); +// Returns: [4, 5] + +// 文字列配列から末尾の3個の要素を取得します。 +takeRight(['a', 'b', 'c'], 2); +// Returns: ['b', 'c'] + +// 要求された個数が配列の長さより大きい場合 +takeRight([1, 2, 3], 5); +// Returns: [1, 2, 3] + +// 0個を要求 +takeRight([1, 2, 3], 0); +// Returns: [] + +// 負の数を要求 +takeRight([1, 2, 3], -1); +// Returns: [] +``` + +`null`や`undefined`は空の配列として扱われます。 + +```typescript +import { takeRight } from 'es-toolkit/compat'; + +takeRight(null, 2); // [] +takeRight(undefined, 2); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 要素を取得する配列です。 +- `count` (`number`, オプション): 取得する要素の個数です。デフォルト値は`1`です。 + +#### 戻り値 + +(`T[]`): 末尾から指定された個数の要素を含む新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/takeRightWhile.md b/docs/ja/compat/reference/array/takeRightWhile.md new file mode 100644 index 000000000..a2f8831c4 --- /dev/null +++ b/docs/ja/compat/reference/array/takeRightWhile.md @@ -0,0 +1,71 @@ +# takeRightWhile (Lodash 互換性) + +::: warning `es-toolkit`の[takeRightWhile](../../../reference/array/takeRightWhile.md)を使用してください + +この`takeRightWhile`関数は、`null`や`undefined`の処理などにより遅く動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[takeRightWhile](../../../reference/array/takeRightWhile.md)を使用してください。 + +::: + +条件を満たす間、配列の末尾から要素を取得します。 + +```typescript +const result = takeRightWhile(array, predicate); +``` + +## 使用法 + +### `takeRightWhile(array, predicate)` + +配列の末尾から開始して条件を満たす間、要素を取得して新しい配列を作成したい場合は`takeRightWhile`を使用してください。条件が偽と評価されると停止します。 + +```typescript +import { takeRightWhile } from 'es-toolkit/compat'; + +// 関数条件を使用 +const numbers = [1, 2, 3, 4, 5]; +takeRightWhile(numbers, x => x > 3); +// Returns: [4, 5] + +// オブジェクトプロパティ条件を使用 +const users = [ + { user: 'barney', active: true }, + { user: 'fred', active: false }, + { user: 'pebbles', active: false }, +]; + +takeRightWhile(users, o => !o.active); +// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] + +// 部分オブジェクトで条件マッチング +takeRightWhile(users, { active: false }); +// Returns: [{ user: 'pebbles', active: false }] + +// プロパティ-値配列で条件マッチング +takeRightWhile(users, ['active', false]); +// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] + +// プロパティ名で真と評価される値を確認 +const items = [{ active: false }, { active: true }, { active: true }]; +takeRightWhile(items, 'active'); +// Returns: [{ active: true }, { active: true }] +``` + +`null`や`undefined`は空の配列として扱われます。 + +```typescript +import { takeRightWhile } from 'es-toolkit/compat'; + +takeRightWhile(null, x => x > 0); // [] +takeRightWhile(undefined, x => x > 0); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 処理する配列です。 +- `predicate` (`ListIteratee`, オプション): 各要素に対して実行する条件です。関数、部分オブジェクト、プロパティ-値配列、プロパティ名を使用できます。デフォルトは恒等関数です。 + +#### 戻り値 + +(`T[]`): 条件を満たす間、配列の末尾から取得した要素の新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/takeWhile.md b/docs/ja/compat/reference/array/takeWhile.md new file mode 100644 index 000000000..55e96b6c1 --- /dev/null +++ b/docs/ja/compat/reference/array/takeWhile.md @@ -0,0 +1,71 @@ +# takeWhile (Lodash 互換性) + +::: warning `es-toolkit`の[takeWhile](../../../reference/array/takeWhile.md)を使用してください + +この`takeWhile`関数は、`null`や`undefined`の処理などにより遅く動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[takeWhile](../../../reference/array/takeWhile.md)を使用してください。 + +::: + +条件を満たす間、配列の先頭から要素を取得します。 + +```typescript +const result = takeWhile(array, predicate); +``` + +## 使用法 + +### `takeWhile(array, predicate)` + +配列の開始から条件を満たす間、要素を取得して新しい配列を作成したい場合は`takeWhile`を使用してください。条件が偽と評価されると停止します。 + +```typescript +import { takeWhile } from 'es-toolkit/compat'; + +// 関数条件を使用 +const numbers = [1, 2, 3, 4, 5]; +takeWhile(numbers, x => x < 3); +// Returns: [1, 2] + +// オブジェクトプロパティ条件を使用 +const users = [ + { user: 'barney', active: false }, + { user: 'fred', active: false }, + { user: 'pebbles', active: true }, +]; + +takeWhile(users, o => !o.active); +// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] + +// 部分オブジェクトで条件マッチング +takeWhile(users, { active: false }); +// Returns: [{ user: 'barney', active: false }] + +// プロパティ-値配列で条件マッチング +takeWhile(users, ['active', false]); +// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] + +// プロパティ名で真と評価される値を確認 +const items = [{ active: true }, { active: true }, { active: false }]; +takeWhile(items, 'active'); +// Returns: [{ active: true }, { active: true }] +``` + +`null`や`undefined`は空の配列として扱われます。 + +```typescript +import { takeWhile } from 'es-toolkit/compat'; + +takeWhile(null, x => x > 0); // [] +takeWhile(undefined, x => x > 0); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 処理する配列です。 +- `predicate` (`ListIteratee`, オプション): 各要素に対して実行する条件です。関数、部分オブジェクト、プロパティ-値配列、プロパティ名を使用できます。デフォルトは恒等関数です。 + +#### 戻り値 + +(`T[]`): 条件を満たす間、配列の先頭から取得した要素の新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/union.md b/docs/ja/compat/reference/array/union.md new file mode 100644 index 000000000..7f00e0da5 --- /dev/null +++ b/docs/ja/compat/reference/array/union.md @@ -0,0 +1,62 @@ +# union (Lodash互換) + +::: warning `es-toolkit`の[union](../../../reference/array/union.md)を使用してください + +この`union`関数は複雑な配列処理により動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[union](../../../reference/array/union.md)を使用してください。 + +::: + +複数の配列からユニークな値のみを集めて新しい配列を作成します。 + +```typescript +const result = union(...arrays); +``` + +## 使用法 + +### `union(...arrays)` + +複数の配列をマージして重複を削除し、ユニークな値のみを含む新しい配列を作成したい場合は`union`を使用してください。各値が最初に出現する順序を保持します。 + +```typescript +import { union } from 'es-toolkit/compat'; + +// 数値配列をマージ +union([2], [1, 2]); +// 戻り値: [2, 1] + +// 複数の配列をマージ +union([2], [1, 2], [2, 3]); +// 戻り値: [2, 1, 3] + +// ネストした配列は平坦化されません +union([1, 3, 2], [1, [5]], [2, [4]]); +// 戻り値: [1, 3, 2, [5], [4]] + +// 配列でない値は無視されます +union([0], 3, { '0': 1 }, null, [2, 1]); +// 戻り値: [0, 2, 1] + +// 配列のようなオブジェクトも処理されます +union([0], { 0: 'a', length: 1 }, [2, 1]); +// 戻り値: [0, 'a', 2, 1] +``` + +`null`または`undefined`は無視されます。 + +```typescript +import { union } from 'es-toolkit/compat'; + +union([1, 2], null, undefined, [3, 4]); +// 戻り値: [1, 2, 3, 4] +``` + +#### パラメータ + +- `...arrays` (`Array | null | undefined>`): マージする配列。配列でない値は無視されます。 + +#### 戻り値 + +(`T[]`): すべての配列のユニークな値を含む新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/unionBy.md b/docs/ja/compat/reference/array/unionBy.md new file mode 100644 index 000000000..66e035cce --- /dev/null +++ b/docs/ja/compat/reference/array/unionBy.md @@ -0,0 +1,66 @@ +# unionBy (Lodash互換) + +::: warning `es-toolkit`の[unionBy](../../../reference/array/unionBy.md)を使用してください + +この`unionBy`関数は複雑な処理により動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[unionBy](../../../reference/array/unionBy.md)を使用してください。 + +::: + +複数の配列をマージし、指定された基準に基づいてユニークな値のみを残します。 + +```typescript +const result = unionBy(...arrays, iteratee); +``` + +## 使用法 + +### `unionBy(...arrays, iteratee)` + +複数の配列をマージし、与えられた基準関数に基づいて重複を削除してユニークな値のみを含む新しい配列を作成したい場合は`unionBy`を使用してください。各値が最初に出現する順序を保持します。 + +```typescript +import { unionBy } from 'es-toolkit/compat'; + +// 小数を切り捨てて比較 +unionBy([2.1], [1.2, 2.3], Math.floor); +// 戻り値: [2.1, 1.2] + +// オブジェクトのプロパティで比較 +unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); +// 戻り値: [{ x: 1 }, { x: 2 }] + +// 関数で比較 +unionBy( + [{ id: 1, name: 'a' }], + [ + { id: 2, name: 'b' }, + { id: 1, name: 'c' }, + ], + item => item.id +); +// 戻り値: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }] + +// 部分オブジェクトで比較 +unionBy([{ x: 1, y: 1 }], [{ x: 1, y: 2 }], { x: 1 }); +// 戻り値: [{ x: 1, y: 1 }] +``` + +`null`または`undefined`配列は無視されます。 + +```typescript +import { unionBy } from 'es-toolkit/compat'; + +unionBy([1, 2], null, undefined, [3, 4], x => x); +// 戻り値: [1, 2, 3, 4] +``` + +#### パラメータ + +- `...arrays` (`Array | null | undefined>`): マージする配列。 +- `iteratee` (`ValueIteratee`): ユニーク性を決定する基準。関数、プロパティ名、部分オブジェクト、またはプロパティ-値配列を使用できます。 + +#### 戻り値 + +(`T[]`): 指定された基準に基づいて重複を削除したユニークな値を含む新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/unionWith.md b/docs/ja/compat/reference/array/unionWith.md new file mode 100644 index 000000000..f2698c9aa --- /dev/null +++ b/docs/ja/compat/reference/array/unionWith.md @@ -0,0 +1,64 @@ +# unionWith (Lodash互換) + +::: warning `es-toolkit`の[unionWith](../../../reference/array/unionWith.md)を使用してください + +この`unionWith`関数は複雑な処理により動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[unionWith](../../../reference/array/unionWith.md)を使用してください。 + +::: + +複数の配列をマージし、比較関数を使用してユニークな値のみを残します。 + +```typescript +const result = unionWith(...arrays, comparator); +``` + +## 使用法 + +### `unionWith(...arrays, comparator)` + +複数の配列をマージし、カスタム比較関数を使用して重複を削除し、ユニークな値のみを含む新しい配列を作成したい場合は`unionWith`を使用してください。各値が最初に出現する順序を保持します。 + +```typescript +import { unionWith } from 'es-toolkit/compat'; + +// カスタム比較関数を使用 +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, +]; +const others = [ + { x: 1, y: 1 }, + { x: 1, y: 2 }, +]; + +unionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); +// 戻り値: [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 1, y: 1 }] + +// 単純な等価比較 +unionWith([1, 2], [2, 3], (a, b) => a === b); +// 戻り値: [1, 2, 3] + +// 文字列の長さで比較 +unionWith(['ab', 'cd'], ['ef', 'gh', 'ab'], (a, b) => a.length === b.length); +// 戻り値: ['ab'] +``` + +`null`または`undefined`配列は無視されます。 + +```typescript +import { unionWith } from 'es-toolkit/compat'; + +unionWith([1, 2], null, undefined, [3, 4], (a, b) => a === b); +// 戻り値: [1, 2, 3, 4] +``` + +#### パラメータ + +- `...arrays` (`Array | null | undefined>`): マージする配列。 +- `comparator` (`(a: T, b: T) => boolean`): 2つの値が等しいかどうかを判断する比較関数。 + +#### 戻り値 + +(`T[]`): 比較関数を使用して重複を削除したユニークな値を含む新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/uniq.md b/docs/ja/compat/reference/array/uniq.md new file mode 100644 index 000000000..23b7c4bec --- /dev/null +++ b/docs/ja/compat/reference/array/uniq.md @@ -0,0 +1,51 @@ +# uniq (Lodash互換) + +::: warning `es-toolkit`の[uniq](../../../reference/array/uniq.md)を使用してください + +この`uniq`関数はLodash互換性のための追加処理により動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[uniq](../../../reference/array/uniq.md)を使用してください。 + +::: + +配列から重複する要素を削除してユニークな要素のみを残した新しい配列を作成します。 + +```typescript +const result = uniq([1, 2, 2, 3, 3, 4]); +// resultは[1, 2, 3, 4]になります。 +``` + +## 使用法 + +### `uniq(array)` + +配列から重複する要素を削除してユニークな要素のみを含む新しい配列を返します。最初に出現する要素のみが保持され、順序は保たれます。 + +```typescript +import { uniq } from 'es-toolkit/compat'; + +// 数値配列から重複を削除 +const numbers = [1, 2, 2, 3, 3, 4, 1]; +const result1 = uniq(numbers); +// 戻り値: [1, 2, 3, 4] + +// 文字列配列から重複を削除 +const strings = ['a', 'b', 'b', 'c', 'a']; +const result2 = uniq(strings); +// 戻り値: ['a', 'b', 'c'] + +// オブジェクト配列から重複を削除(参照値比較) +const obj1 = { id: 1 }; +const obj2 = { id: 2 }; +const objects = [obj1, obj2, obj1]; +const result3 = uniq(objects); +// 戻り値: [{ id: 1 }, { id: 2 }] +``` + +#### パラメータ + +- `array` (`T[]`): 処理する配列。 + +#### 戻り値 + +(`T[]`): 重複が削除された新しい配列。 diff --git a/docs/ja/compat/reference/array/uniqBy.md b/docs/ja/compat/reference/array/uniqBy.md new file mode 100644 index 000000000..59c72a1c4 --- /dev/null +++ b/docs/ja/compat/reference/array/uniqBy.md @@ -0,0 +1,55 @@ +# uniqBy (Lodash互換) + +::: warning `es-toolkit`の[uniqBy](../../../reference/array/uniqBy.md)を使用してください + +この`uniqBy`関数は`null`または`undefined`の処理、複雑な引数タイプ処理などにより動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[uniqBy](../../../reference/array/uniqBy.md)を使用してください。 + +::: + +配列で変換関数が返す値に基づいて重複を削除し、ユニークな要素で構成される新しい配列を作成します。 + +```typescript +const result = uniqBy(array, iteratee); +``` + +## 使用法 + +### `uniqBy(array, iteratee)` + +配列の各要素に変換関数を適用し、変換結果が同じ要素の中で最初の要素のみを保持します。オブジェクト配列で特定のプロパティを基準に重複を削除したり、数値配列で特定の計算結果を基準に重複を削除するときに便利です。 + +```typescript +import { uniqBy } from 'es-toolkit/compat'; + +// 数値配列でMath.floor結果により重複を削除 +uniqBy([2.1, 1.2, 2.3], Math.floor); +// 戻り値: [2.1, 1.2] + +// オブジェクト配列でプロパティにより重複を削除 +uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); +// 戻り値: [{ x: 1 }, { x: 2 }] + +// 関数で重複を削除 +uniqBy([{ name: 'John' }, { name: 'Jane' }, { name: 'John' }], obj => obj.name); +// 戻り値: [{ name: 'John' }, { name: 'Jane' }] +``` + +`null`または`undefined`は空配列として扱われます。 + +```typescript +import { uniqBy } from 'es-toolkit/compat'; + +uniqBy(null, Math.floor); // [] +uniqBy(undefined, 'x'); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 重複を削除する配列。 +- `iteratee` (`ValueIteratee`): 各要素に適用する変換関数。関数、プロパティ名、部分オブジェクトなどを使用できます。 + +#### 戻り値 + +(`T[]`): 変換関数の結果を基準に重複が削除された新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/uniqWith.md b/docs/ja/compat/reference/array/uniqWith.md new file mode 100644 index 000000000..e1aad566b --- /dev/null +++ b/docs/ja/compat/reference/array/uniqWith.md @@ -0,0 +1,60 @@ +# uniqWith (Lodash互換) + +::: warning `es-toolkit`の[uniqWith](../../../reference/array/uniqWith.md)を使用してください + +この`uniqWith`関数は`null`または`undefined`の処理、複雑な引数タイプ処理などにより動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[uniqWith](../../../reference/array/uniqWith.md)を使用してください。 + +::: + +配列で比較関数を使用して重複を削除し、ユニークな要素で構成される新しい配列を作成します。 + +```typescript +const result = uniqWith(array, comparator); +``` + +## 使用法 + +### `uniqWith(array, comparator)` + +配列の各要素を比較関数で比較して重複を削除します。比較関数が`true`を返すと2つの要素が同じと判断され、最初に出現する要素のみが保持されます。比較関数を提供しない場合、デフォルトで浅い等価比較を使用します。 + +```typescript +import { uniqWith } from 'es-toolkit/compat'; + +// 比較関数なしで使用(浅い等価比較) +uniqWith([1, 2, 2, 3]); +// 戻り値: [1, 2, 3] + +// カスタム比較関数で奇数/偶数基準により重複を削除 +uniqWith([1, 2, 3, 4], (a, b) => a % 2 === b % 2); +// 戻り値: [1, 2] + +// オブジェクト配列でプロパティ基準により重複を削除 +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 1, y: 2 }, +]; +uniqWith(objects, (a, b) => a.x === b.x && a.y === b.y); +// 戻り値: [{ x: 1, y: 2 }, { x: 2, y: 1 }] +``` + +`null`または`undefined`は空配列として扱われます。 + +```typescript +import { uniqWith } from 'es-toolkit/compat'; + +uniqWith(null); // [] +uniqWith(undefined); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 重複を削除する配列。 +- `comparator` (`(a: T, b: T) => boolean`, 選択): 2つの要素が等しいか比較する関数。`true`を返すと同じと判断されます。デフォルトは浅い等価比較です。 + +#### 戻り値 + +(`T[]`): 比較関数の結果を基準に重複が削除された新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/unzip.md b/docs/ja/compat/reference/array/unzip.md new file mode 100644 index 000000000..8113c6690 --- /dev/null +++ b/docs/ja/compat/reference/array/unzip.md @@ -0,0 +1,68 @@ +# unzip (Lodash互換) + +::: warning `es-toolkit`の[unzip](../../../reference/array/unzip.md)を使用してください + +この`unzip`関数は`null`または`undefined`の処理、配列でない値のフィルタリングなどにより動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[unzip](../../../reference/array/unzip.md)を使用してください。 + +::: + +グループ化された配列の同じ位置にある要素を集めて新しい配列を作成します。 + +```typescript +const result = unzip(array); +``` + +## 使用法 + +### `unzip(array)` + +ネストした配列の同じインデックスにある要素を集めて新しい配列として返します。`zip`関数の逆の操作を実行します。行列を転置したり構造化データを再編成するときに便利です。 + +```typescript +import { unzip } from 'es-toolkit/compat'; + +// 文字列、ブール値、数値が混在した配列をアンジップ +const zipped = [ + ['a', true, 1], + ['b', false, 2], +]; +const result = unzip(zipped); +// 戻り値: [['a', 'b'], [true, false], [1, 2]] + +// 数値配列をアンジップ +const numbers = [ + [1, 4], + [2, 5], + [3, 6], +]; +unzip(numbers); +// 戻り値: [[1, 2, 3], [4, 5, 6]] + +// 長さが異なる配列も処理 +const uneven = [ + ['a', 1], + ['b', 2, true], +]; +unzip(uneven); +// 戻り値: [['a', 'b'], [1, 2], [undefined, true]] +``` + +`null`、`undefined`、または空配列は空配列として扱われます。 + +```typescript +import { unzip } from 'es-toolkit/compat'; + +unzip(null); // [] +unzip(undefined); // [] +unzip([]); // [] +``` + +#### パラメータ + +- `array` (`T[][] | ArrayLike> | null | undefined`): アンジップするネストした配列。各内部配列の同じ位置の要素が集められます。 + +#### 戻り値 + +(`T[][]`): 同じ位置の要素が集められた新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/unzipWith.md b/docs/ja/compat/reference/array/unzipWith.md new file mode 100644 index 000000000..372f38a83 --- /dev/null +++ b/docs/ja/compat/reference/array/unzipWith.md @@ -0,0 +1,84 @@ +# unzipWith (Lodash互換) + +::: warning `es-toolkit`の`unzipWith`を使用してください + +この`unzipWith`関数は`null`または`undefined`の処理、`ArrayLike`タイプ処理、さまざまな条件関数形式のサポートなどにより動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[unzipWith](../../../reference/array/unzipWith.md)を使用してください。 + +::: + +グループ化された配列の同じ位置にある要素を集めて変換関数を適用した新しい配列を作成します。 + +```typescript +const result = unzipWith(array, iteratee); +``` + +## 使用法 + +### `unzipWith(array, iteratee)` + +ネストした配列の同じインデックスにある要素を集めて変換関数を適用します。`unzip`関数と似ていますが、各グループに変換関数を適用できます。変換関数を提供しない場合、デフォルトの`unzip`操作を実行します。 + +```typescript +import { unzipWith } from 'es-toolkit/compat'; + +// 同じ位置の要素を足す +unzipWith( + [ + [1, 10, 100], + [2, 20, 200], + ], + (a, b) => a + b +); +// 戻り値: [3, 30, 300] + +// 変換関数なしで使用(デフォルトunzip操作) +unzipWith([ + [1, 4], + [2, 5], + [3, 6], +]); +// 戻り値: [[1, 2, 3], [4, 5, 6]] + +// 文字列連結 +unzipWith( + [ + ['a', 'x'], + ['b', 'y'], + ['c', 'z'], + ], + (a, b) => a + b +); +// 戻り値: ['abc', 'xyz'] + +// 最大値を探す +unzipWith( + [ + [1, 10], + [2, 20], + [3, 5], + ], + Math.max +); +// 戻り値: [3, 20] +``` + +`null`、`undefined`、または空配列は空配列として扱われます。 + +```typescript +import { unzipWith } from 'es-toolkit/compat'; + +unzipWith(null, (a, b) => a + b); // [] +unzipWith(undefined, (a, b) => a + b); // [] +unzipWith([], (a, b) => a + b); // [] +``` + +#### パラメータ + +- `array` (`ArrayLike> | null | undefined`): アンジップするネストした配列。 +- `iteratee` (`(...values: T[]) => R`, 選択): 各グループの要素に適用する変換関数。提供しない場合、デフォルトの`unzip`操作を実行します。 + +#### 戻り値 + +(`R[]`または`T[][]`): 変換関数がある場合は変換された結果の配列を、ない場合はアンジップされた配列を返します。 diff --git a/docs/ja/compat/reference/array/without.md b/docs/ja/compat/reference/array/without.md new file mode 100644 index 000000000..cc1fbbf0e --- /dev/null +++ b/docs/ja/compat/reference/array/without.md @@ -0,0 +1,49 @@ +# without (Lodash互換) + +::: warning `es-toolkit`の[without](../../../reference/array/without.md)を使用してください + +この`without`関数はLodash互換性のための追加処理により動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[without](../../../reference/array/without.md)を使用してください。 + +::: + +配列から指定された値を除外した新しい配列を作成します。 + +```typescript +const result = without([1, 2, 3, 4, 5], 2, 4); +// resultは[1, 3, 5]になります。 +``` + +## 使用法 + +### `without(array, ...values)` + +配列から指定された値を削除した新しい配列を返します。元の配列は変更されません。 + +```typescript +import { without } from 'es-toolkit/compat'; + +// 数値配列から複数の値を削除 +const numbers = [1, 2, 3, 4, 5, 2, 4]; +const result1 = without(numbers, 2, 4); +// 戻り値: [1, 3, 5] + +// 文字列配列から値を削除 +const fruits = ['apple', 'banana', 'cherry', 'banana']; +const result2 = without(fruits, 'banana'); +// 戻り値: ['apple', 'cherry'] + +// 空配列を処理 +const result3 = without([], 1, 2, 3); +// 戻り値: [] +``` + +#### パラメータ + +- `array` (`T[]`): 処理する元の配列。 +- `...values` (`T[]`): 削除する値。 + +#### 戻り値 + +(`T[]`): 指定された値を削除した新しい配列。 diff --git a/docs/ja/compat/reference/array/xor.md b/docs/ja/compat/reference/array/xor.md new file mode 100644 index 000000000..3c7a3e6b1 --- /dev/null +++ b/docs/ja/compat/reference/array/xor.md @@ -0,0 +1,61 @@ +# xor (Lodash互換) + +::: warning `es-toolkit`の[xor](../../../reference/array/xor.md)を使用してください + +この`xor`関数は`null`または`undefined`の処理、複雑な重複計算ロジックなどにより動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[xor](../../../reference/array/xor.md)を使用してください。 + +::: + +複数の配列で正確に1つの配列にのみ存在する要素で構成される新しい配列を作成します。 + +```typescript +const result = xor(...arrays); +``` + +## 使用法 + +### `xor(...arrays)` + +複数の配列の対称差集合を計算します。つまり、与えられた配列の中で正確に1つの配列にのみ存在する要素を返します。2つ以上の配列を比較する際に重複しないユニークな要素を見つけたい場合に便利です。 + +```typescript +import { xor } from 'es-toolkit/compat'; + +// 2つの配列の対称差集合 +xor([1, 2, 3, 4], [3, 4, 5, 6]); +// 戻り値: [1, 2, 5, 6] + +// 3つの配列の対称差集合 +xor([1, 2], [2, 3], [4, 5]); +// 戻り値: [1, 3, 4, 5] + +// 文字列配列 +xor(['a', 'b'], ['b', 'c']); +// 戻り値: ['a', 'c'] + +// 1つの配列のみを提供 +xor([1, 2, 3]); +// 戻り値: [1, 2, 3] +``` + +`null`、`undefined`、または空配列は無視され、有効な配列のみが処理されます。 + +```typescript +import { xor } from 'es-toolkit/compat'; + +xor([1, 2], null, [2, 3]); +// 戻り値: [1, 3] + +xor([], [1, 2], [2, 3]); +// 戻り値: [1, 3] +``` + +#### パラメータ + +- `...arrays` (`Array | null | undefined>`): 対称差集合を計算する配列。`null`または`undefined`は無視されます。 + +#### 戻り値 + +(`T[]`): 正確に1つの配列にのみ存在する要素で構成される新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/xorBy.md b/docs/ja/compat/reference/array/xorBy.md new file mode 100644 index 000000000..4d32fd9c8 --- /dev/null +++ b/docs/ja/compat/reference/array/xorBy.md @@ -0,0 +1,63 @@ +# xorBy (Lodash互換) + +::: warning `es-toolkit`の[xorBy](../../../reference/array/xorBy.md)を使用してください + +この`xorBy`関数は`null`または`undefined`の処理、複雑な重複計算ロジックなどにより動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[xorBy](../../../reference/array/xorBy.md)を使用してください。 + +::: + +複数の配列で変換関数を基準に正確に1つの配列にのみ存在する要素で構成される新しい配列を作成します。 + +```typescript +const result = xorBy(...arrays, iteratee); +``` + +## 使用法 + +### `xorBy(...arrays, iteratee)` + +複数の配列の対称差集合を変換関数を基準に計算します。各要素に変換関数を適用した結果が正確に1つの配列にのみ存在する要素を返します。オブジェクト配列で特定のプロパティを基準に比較したり、数値配列で特定の計算結果を基準に比較するときに便利です。 + +```typescript +import { xorBy } from 'es-toolkit/compat'; + +// Math.floor結果により対称差集合を計算 +xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); +// 戻り値: [1.2, 4.3] + +// オブジェクトのプロパティにより対称差集合を計算 +xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); +// 戻り値: [{ x: 2 }] + +// 関数で対称差集合を計算 +const users1 = [{ name: 'John', age: 30 }]; +const users2 = [ + { name: 'Jane', age: 25 }, + { name: 'John', age: 30 }, +]; +xorBy(users1, users2, user => user.name); +// 戻り値: [{ name: 'Jane', age: 25 }] + +// 3つの配列の対称差集合 +xorBy([1.2, 2.3], [3.4, 4.5], [5.6, 6.7], Math.floor); +// 戻り値: [1.2, 2.3, 3.4, 4.5, 5.6, 6.7] +``` + +`null`または`undefined`は無視されます。 + +```typescript +import { xorBy } from 'es-toolkit/compat'; + +xorBy([2.1, 1.2], null, [4.3, 2.4], Math.floor); +// 戻り値: [1.2, 4.3] +``` + +#### パラメータ + +- `...arrays` (`Array | null | undefined | ValueIteratee>`): 対称差集合を計算する配列と最後の変換関数。関数、プロパティ名、部分オブジェクトなどを使用できます。 + +#### 戻り値 + +(`T[]`): 変換関数の結果を基準に正確に1つの配列にのみ存在する要素で構成される新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/xorWith.md b/docs/ja/compat/reference/array/xorWith.md new file mode 100644 index 000000000..56b7280bf --- /dev/null +++ b/docs/ja/compat/reference/array/xorWith.md @@ -0,0 +1,66 @@ +# xorWith (Lodash互換) + +::: warning `es-toolkit`の[xorWith](../../../reference/array/xorWith.md)を使用してください + +この`xorWith`関数は`null`または`undefined`の処理、複雑な重複計算ロジックなどにより動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[xorWith](../../../reference/array/xorWith.md)を使用してください。 + +::: + +複数の配列で比較関数を使用して正確に1つの配列にのみ存在する要素で構成される新しい配列を作成します。 + +```typescript +const result = xorWith(...arrays, comparator); +``` + +## 使用法 + +### `xorWith(...arrays, comparator)` + +複数の配列の対称差集合を比較関数を使用して計算します。比較関数が`true`を返すと2つの要素が同じと判断され、正確に1つの配列にのみ存在する要素を返します。複雑なオブジェクトやカスタム比較ロジックが必要な場合に便利です。 + +```typescript +import { xorWith } from 'es-toolkit/compat'; + +// 単純な数値比較 +xorWith([1, 2], [2, 3], (a, b) => a === b); +// 戻り値: [1, 3] + +// オブジェクトのプロパティを比較 +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, +]; +const others = [ + { x: 1, y: 1 }, + { x: 1, y: 2 }, +]; +xorWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); +// 戻り値: [{ x: 2, y: 1 }, { x: 1, y: 1 }] + +// 3つの配列の対称差集合 +xorWith([1], [2], [3], (a, b) => a === b); +// 戻り値: [1, 2, 3] + +// 文字列の長さで比較 +xorWith(['hello'], ['world', 'hi'], (a, b) => a.length === b.length); +// 戻り値: ['hi'] +``` + +比較関数を提供しない場合、デフォルトで浅い等価比較を使用します。 + +```typescript +import { xorWith } from 'es-toolkit/compat'; + +xorWith([1, 2], [2, 3]); +// 戻り値: [1, 3] +``` + +#### パラメータ + +- `...arrays` (`Array | null | undefined | ((a: T, b: T) => boolean)>`): 対称差集合を計算する配列と最後の比較関数。比較関数は2つの要素が等しい場合に`true`を返す必要があります。 + +#### 戻り値 + +(`T[]`): 比較関数の結果を基準に正確に1つの配列にのみ存在する要素で構成される新しい配列を返します。 diff --git a/docs/ja/compat/reference/array/zip.md b/docs/ja/compat/reference/array/zip.md new file mode 100644 index 000000000..89ac859d2 --- /dev/null +++ b/docs/ja/compat/reference/array/zip.md @@ -0,0 +1,48 @@ +# zip (Lodash互換) + +::: warning `es-toolkit`の[zip](../../../reference/array/zip.md)を使用してください + +この`zip`関数はLodash互換性のための追加処理により動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[zip](../../../reference/array/zip.md)を使用してください。 + +::: + +複数の配列を1つのタプルの配列に結合します。 + +```typescript +const result = zip([1, 2], ['a', 'b']); +// resultは[[1, 'a'], [2, 'b']]になります。 +``` + +## 使用法 + +### `zip(...arrs)` + +複数の配列を受け取り、各インデックスの要素を1つのタプルにまとめて新しい配列を作成します。入力配列の長さが異なる場合、結果の配列の長さは最も長い入力配列の長さとなり、欠落した要素は`undefined`で埋められます。 + +```typescript +import { zip } from 'es-toolkit/compat'; + +const arr1 = [1, 2, 3]; +const arr2 = ['a', 'b', 'c']; +const result = zip(arr1, arr2); +// 戻り値: [[1, 'a'], [2, 'b'], [3, 'c']] + +// 長さが異なる配列 +const arr3 = [true, false]; +const result2 = zip(arr1, arr2, arr3); +// 戻り値: [[1, 'a', true], [2, 'b', false], [3, 'c', undefined]] + +// 空配列が含まれる場合 +zip([1, 2], [], ['a', 'b']); +// 戻り値: [[1, undefined, 'a'], [2, undefined, 'b']] +``` + +#### パラメータ + +- `...arrs` (`any[][]`): 結合する配列。 + +#### 戻り値 + +(`any[][]`): 入力配列の各インデックスの要素を含むタプルの新しい配列。 diff --git a/docs/ja/compat/reference/array/zipObject.md b/docs/ja/compat/reference/array/zipObject.md new file mode 100644 index 000000000..fe702b914 --- /dev/null +++ b/docs/ja/compat/reference/array/zipObject.md @@ -0,0 +1,50 @@ +# zipObject (Lodash互換) + +::: warning `es-toolkit`の[zipObject](../../../reference/array/zipObject.md)を使用してください + +この`zipObject`関数はLodash互換性のための追加処理により動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[zipObject](../../../reference/array/zipObject.md)を使用してください。 + +::: + +2つの配列を使用してオブジェクトを作成します。最初の配列はプロパティ名として、2番目の配列は対応する値として使用されます。 + +```typescript +const result = zipObject(keys, values); +``` + +## 使用法 + +### `zipObject(keys, values)` + +キー配列と値配列から1つのオブジェクトを作成したい場合は`zipObject`を使用してください。最初の配列の要素をプロパティ名として、2番目の配列の要素を対応する値として使用してオブジェクトを作成します。APIレスポンスの処理やデータの変換時に特に便利です。 + +```typescript +import { zipObject } from 'es-toolkit/compat'; + +// 基本的な使用法 +const keys = ['a', 'b', 'c']; +const values = [1, 2, 3]; +const result = zipObject(keys, values); +// 戻り値: { a: 1, b: 2, c: 3 } + +// 長さが異なる配列 +const keys2 = ['x', 'y', 'z']; +const values2 = [10, 20]; +const result2 = zipObject(keys2, values2); +// 戻り値: { x: 10, y: 20, z: undefined } + +// 空配列が提供された場合 +const result3 = zipObject([], []); +// 戻り値: {} +``` + +#### パラメータ + +- `keys` (`PropertyKey[]`): プロパティ名として使用する配列。 +- `values` (`T[]`): プロパティ値として使用する配列。 + +#### 戻り値 + +(`Record`): 作成されたオブジェクト。 diff --git a/docs/ja/reference/compat/array/zipObjectDeep.md b/docs/ja/compat/reference/array/zipObjectDeep.md similarity index 100% rename from docs/ja/reference/compat/array/zipObjectDeep.md rename to docs/ja/compat/reference/array/zipObjectDeep.md diff --git a/docs/ja/compat/reference/array/zipWith.md b/docs/ja/compat/reference/array/zipWith.md new file mode 100644 index 000000000..108dd66dd --- /dev/null +++ b/docs/ja/compat/reference/array/zipWith.md @@ -0,0 +1,47 @@ +# zipWith (Lodash互換) + +::: warning `es-toolkit`の[zipWith](../../../reference/array/zipWith.md)を使用してください + +この`zipWith`関数はLodash互換性のための追加処理により動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[zipWith](../../../reference/array/zipWith.md)を使用してください。 + +::: + +複数の配列の要素を結合関数を使用して新しい配列に結合します。 + +```typescript +const result = zipWith([1, 2], [3, 4], (a, b) => a + b); +// resultは[4, 6]になります。 +``` + +## 使用法 + +### `zipWith(...arrs, iteratee)` + +複数の配列を受け取り、各インデックスの要素を提供された関数で結合して新しい配列を作成します。配列の長さが異なる場合、最も長い配列の長さまで処理し、欠落した値には`undefined`が渡されます。 + +```typescript +import { zipWith } from 'es-toolkit/compat'; + +// 2つの配列の要素を足す +const result1 = zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b); +// 戻り値: [5, 7, 9] + +// 3つの配列の要素を結合 +const result2 = zipWith([1, 2], [3, 4], [5, 6], (a, b, c) => a + b + c); +// 戻り値: [9, 12] + +// 長さが異なる配列 +const result3 = zipWith([1, 2, 3], [4, 5], (a, b) => (a || 0) + (b || 0)); +// 戻り値: [5, 7, 3] +``` + +#### パラメータ + +- `...arrs` (`any[][]`): 結合する配列。 +- `iteratee` (`Function`): 各インデックスの要素を結合する関数。 + +#### 戻り値 + +(`any[]`): 結合関数を適用した結果からなる新しい配列。 diff --git a/docs/ja/compat/reference/function/after.md b/docs/ja/compat/reference/function/after.md new file mode 100644 index 000000000..4b8877750 --- /dev/null +++ b/docs/ja/compat/reference/function/after.md @@ -0,0 +1,75 @@ +# after (Lodash 互換性) + +::: warning `es-toolkit` の [`after`](../../../reference/function/after.md) を使用してください + +この `after` 関数は、複雑な型検証と整数変換処理により動作が遅くなります。 + +代わりに、より高速でモダンな `es-toolkit` の [after](../../../reference/function/after.md) を使用してください。 + +::: + +指定された回数呼び出された後にのみ実行される関数を作成します。 + +```typescript +const restrictedFunction = after(n, func); +``` + +## 使用法 + +### `after(n, func)` + +関数が特定の回数呼び出された後にのみ実行されるように制限したい場合は、`after` を使用してください。複数の非同期操作が完了した後にコールバックを実行したり、初期化段階を経た後に関数を有効化する際に便利です。 + +```typescript +import { after } from 'es-toolkit/compat'; + +// 基本的な使用法 +const logAfterThree = after(3, () => { + console.log('3回目の呼び出しから実行されます!'); +}); + +logAfterThree(); // 実行されない +logAfterThree(); // 実行されない +logAfterThree(); // "3回目の呼び出しから実行されます!" が出力される +logAfterThree(); // "3回目の呼び出しから実行されます!" が出力される (実行が続く) +``` + +複数の非同期操作がすべて完了した後に特定のコールバックを実行する際にも使用できます。 + +```typescript +import { after } from 'es-toolkit/compat'; + +const tasks = ['task1', 'task2', 'task3']; +const allTasksComplete = after(tasks.length, () => { + console.log('すべてのタスクが完了しました!'); +}); + +// 各タスクが完了するたびに呼び出される +tasks.forEach(task => { + performAsyncTask(task, () => { + console.log(`${task} 完了`); + allTasksComplete(); // 3回目の呼び出しで "すべてのタスクが完了しました!" が出力される + }); +}); +``` + +0または負の数を渡すと、最初の呼び出しからすぐに実行されます。 + +```typescript +import { after } from 'es-toolkit/compat'; + +const immediate = after(0, () => console.log('すぐに実行')); +immediate(); // "すぐに実行" + +const negative = after(-1, () => console.log('すぐに実行')); +negative(); // "すぐに実行" +``` + +#### パラメータ + +- `n` (`number`): 関数が実行される前に必要な呼び出し回数です。 +- `func` (`TFunc`): 制限する関数です。 + +#### 戻り値 + +(`TFunc`): n回目の呼び出しから元の関数を実行する新しい制限された関数を返します。 diff --git a/docs/ja/compat/reference/function/ary.md b/docs/ja/compat/reference/function/ary.md new file mode 100644 index 000000000..a3b9fe38c --- /dev/null +++ b/docs/ja/compat/reference/function/ary.md @@ -0,0 +1,90 @@ +# ary (Lodash 互換性) + +::: warning `es-toolkit` の [`ary`](../../../reference/function/ary.md) を使用してください + +この `ary` 関数は、複雑なパラメータ検証により動作が遅くなります。 + +代わりに、より高速でモダンな `es-toolkit` の [ary](../../../reference/function/ary.md) を使用してください。 + +::: + +関数が受け取ることができる引数の数を制限する関数を作成します。 + +```typescript +const cappedFunction = ary(func, n); +``` + +## 使用法 + +### `ary(func, n)` + +関数が受け取る引数の数を制限したい場合は、`ary` を使用してください。あまりにも多くの引数を受け取る関数を安全に使用したり、コールバック関数で不要な引数を無視する際に便利です。 + +```typescript +import { ary } from 'es-toolkit/compat'; + +// 基本的な使用法 +function greet(name, age, city) { + return `こんにちは、${name}さん! ${age}歳、${city}からいらっしゃいました。`; +} + +const limitedGreet = ary(greet, 2); +console.log(limitedGreet('田中', 30, '東京', '追加引数')); +// "こんにちは、田中さん! 30歳、undefinedからいらっしゃいました。" +// 3番目の引数以降は無視される +``` + +配列メソッドと一緒に使用する際、コールバック関数に不要な引数が渡されないようにできます。 + +```typescript +import { ary } from 'es-toolkit/compat'; + +// parseIntは第2引数(基数)を受け取るが、mapのコールバックは3つの引数を渡す +const numbers = ['1', '2', '3', '4', '5']; + +// 誤った使用法 - parseIntがインデックスを基数として受け取る +console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] + +// aryを使用して最初の引数のみ渡す +console.log(numbers.map(ary(parseInt, 1))); // [1, 2, 3, 4, 5] +``` + +関数が希望するパラメータ引数の数だけを受け取るように制限できます。 + +```typescript +import { ary } from 'es-toolkit/compat'; + +function sum(...args) { + return args.reduce((total, num) => total + num, 0); +} + +const sum0 = ary(sum, 0); +const sum1 = ary(sum, 1); +const sum2 = ary(sum, 2); +const sum3 = ary(sum, 3); + +console.log(sum0(1, 2, 3, 4, 5)); // 0 (引数なし) +console.log(sum1(1, 2, 3, 4, 5)); // 1 (最初の引数のみ) +console.log(sum2(1, 2, 3, 4, 5)); // 3 (最初の2つの引数のみ) +console.log(sum3(1, 2, 3, 4, 5)); // 6 (最初の3つの引数のみ) +``` + +負の数や `NaN` を渡すと、0として扱われ、すべての引数が無視されます。 + +```typescript +import { ary } from 'es-toolkit/compat'; + +const func = (a, b, c) => [a, b, c]; + +console.log(ary(func, -1)(1, 2, 3)); // [] (負数は0として扱われる) +console.log(ary(func, NaN)(1, 2, 3)); // [] (NaNは0として扱われる) +``` + +#### パラメータ + +- `func` (`Function`): 引数の数を制限する関数です。 +- `n` (`number`, オプション): 許可する最大引数数です。省略した場合、関数の `length` プロパティを使用します。 + +#### 戻り値 + +(`Function`): 最大 `n` 個の引数のみを受け取る新しい関数を返します。 diff --git a/docs/ja/compat/reference/function/attempt.md b/docs/ja/compat/reference/function/attempt.md new file mode 100644 index 000000000..33c3e43af --- /dev/null +++ b/docs/ja/compat/reference/function/attempt.md @@ -0,0 +1,66 @@ +# attempt (Lodash 互換性) + +::: warning `es-toolkit` の [`attempt`](../../../reference/util/attempt.md) 関数または try-catch ブロックを使用してください + +この `attempt` 関数は、エラーと戻り値を区別せずに返すため、使用時に混乱する可能性があります。 + +代わりに、より直接的で明確な [`attempt`](../../../reference/util/attempt.md) 関数または try-catch ブロックを使用してください。 + +::: + +関数を実行し、エラーが発生した場合にエラーオブジェクトを返す関数です。 + +```typescript +const result = attempt(func, ...args); +``` + +## 使用法 + +### `attempt(func, ...args)` + +関数を安全に実行したい場合は `attempt` を使用してください。エラーが発生する可能性のある関数を実行する際に、プログラムがクラッシュするのを防ぎ、エラーを戻り値として処理するのに便利です。 + +```typescript +import { attempt } from 'es-toolkit/compat'; + +// 基本的な使用法 - 成功する場合 +const result = attempt((x, y) => x + y, 2, 3); +console.log(result); // 5 + +// エラーが発生する場合 +const errorResult = attempt(() => { + throw new Error('何かがうまくいきませんでした'); +}); +console.log(errorResult); // Error: 何かがうまくいきませんでした +``` + +try-catch ブロックの使用との違いは次のとおりです。 + +```typescript +// attempt を使用 +import { attempt } from 'es-toolkit/compat'; + +const result = attempt(riskyFunction, arg1, arg2); +if (result instanceof Error) { + console.log('エラーが発生しました:', result.message); +} else { + console.log('結果:', result); +} + +// try-catch を使用 (より直接的) +try { + const result = riskyFunction(arg1, arg2); + console.log('結果:', result); +} catch (error) { + console.log('エラーが発生しました:', error.message); +} +``` + +#### パラメータ + +- `func` (`Function`): 実行する関数です。 +- `args` (`...any[]`): 関数に渡す引数です。 + +#### 戻り値 + +(`ReturnType | Error`): 関数が成功した場合は戻り値を、エラーが発生した場合は Error オブジェクトを返します。 diff --git a/docs/ja/compat/reference/function/before.md b/docs/ja/compat/reference/function/before.md new file mode 100644 index 000000000..83dd8b5b8 --- /dev/null +++ b/docs/ja/compat/reference/function/before.md @@ -0,0 +1,186 @@ +# before (Lodash 互換性) + +::: warning `es-toolkit` の [`before`](../../../reference/function/before.md) を使用してください + +この `before` 関数は、複雑な型検証と整数変換処理により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [before](../../../reference/function/before.md) を使用してください。 + +::: + +指定された回数まで元の関数を実行し、その後は最後の結果を返す関数を作成します。 + +```typescript +const limitedFunction = before(n, func); +``` + +## 使用法 + +### `before(n, func)` + +関数を特定の回数まで実行するように制限したい場合は `before` を使用してください。関数呼び出し回数を制限したり、初期設定段階でのみ関数を実行したい場合に便利です。 + +```typescript +import { before } from 'es-toolkit/compat'; + +// 基本的な使い方 +let count = 0; +const beforeThree = before(3, () => ++count); + +console.log(beforeThree()); // 1 (最初の呼び出し) +console.log(beforeThree()); // 2 (2回目の呼び出し) +console.log(beforeThree()); // 2 (3回目以降は最後の結果を返す) +console.log(beforeThree()); // 2 (引き続き最後の結果を返す) +``` + +クロージャを使用した代替案: + +```typescript +// before を使用 +const beforeThree = before(3, myFunction); + +// クロージャを使用(よりシンプルで高速) +function createBefore(limit, callback) { + let callCount = 0; + let lastResult; + + return function (...args) { + if (callCount < limit - 1) { + lastResult = callback.apply(this, args); + callCount++; + } + return lastResult; + }; +} + +const beforeThreeAlternative = createBefore(3, myFunction); +``` + +初期化関数として活用: + +```typescript +import { before } from 'es-toolkit/compat'; + +class Database { + constructor() { + this.isInitialized = false; + + // 初期化は一度だけ実行 + this.initialize = before(2, () => { + console.log('データベースを初期化中...'); + this.setupConnection(); + this.isInitialized = true; + return '初期化完了'; + }); + } + + setupConnection() { + // 実際の接続設定ロジック + } + + query(sql) { + const initResult = this.initialize(); + console.log(initResult); // 最初の呼び出し: "初期化完了"、以降:同じ結果 + + // クエリ実行ロジック + return `クエリを実行: ${sql}`; + } +} + +const db = new Database(); +db.query('SELECT * FROM users'); // 初期化実行 +db.query('SELECT * FROM products'); // 初期化は実行されない +``` + +API 呼び出しの制限: + +```typescript +import { before } from 'es-toolkit/compat'; + +// API 呼び出しを最大5回まで許可 +const limitedApiCall = before(6, endpoint => { + console.log(`API 呼び出し: ${endpoint}`); + return fetch(endpoint).then(res => res.json()); +}); + +// 最初の5回は実際の API 呼び出し +limitedApiCall('/api/data1'); // 実際の呼び出し +limitedApiCall('/api/data2'); // 実際の呼び出し +limitedApiCall('/api/data3'); // 実際の呼び出し +limitedApiCall('/api/data4'); // 実際の呼び出し +limitedApiCall('/api/data5'); // 実際の呼び出し +limitedApiCall('/api/data6'); // 最後の結果を返す(API 呼び出しなし) +``` + +イベントリスナーの制限: + +```typescript +import { before } from 'es-toolkit/compat'; + +// クリックイベントを3回まで処理 +const limitedClickHandler = before(4, event => { + console.log('クリック処理:', event.target.id); + return `処理完了: ${Date.now()}`; +}); + +document.getElementById('button').addEventListener('click', limitedClickHandler); +// 最初の3回のクリックのみ処理され、その後は最後の結果を返す +``` + +パラメータと戻り値の処理: + +```typescript +import { before } from 'es-toolkit/compat'; + +const limitedCalculator = before(3, (operation, a, b) => { + const result = operation === 'add' ? a + b : a - b; + console.log(`計算: ${a} ${operation} ${b} = ${result}`); + return result; +}); + +console.log(limitedCalculator('add', 5, 3)); // "計算: 5 add 3 = 8"、返す: 8 +console.log(limitedCalculator('subtract', 10, 4)); // "計算: 10 subtract 4 = 6"、返す: 6 +console.log(limitedCalculator('multiply', 7, 2)); // 計算しない、返す: 6(最後の結果) +``` + +0または1を渡すと関数が実行されません: + +```typescript +import { before } from 'es-toolkit/compat'; + +const neverCalled = before(0, () => { + console.log('この関数は実行されません'); + return '結果'; +}); + +const onceOnly = before(1, () => { + console.log('この関数も実行されません'); + return '結果'; +}); + +console.log(neverCalled()); // undefined +console.log(onceOnly()); // undefined +``` + +リソースクリーンアップの最適化: + +```typescript +import { before } from 'es-toolkit/compat'; + +// 関数参照が自動的にクリーンアップされてメモリリークを防止 +const limitedProcessor = before(2, data => { + // 複雑なデータ処理 + return processComplexData(data); +}); + +// 2回目の呼び出し後、元の関数参照が削除される(ガベージコレクション) +``` + +#### パラメータ + +- `n` (`number`): 関数を実行する最大回数。n-1回まで実行され、n回目以降は最後の結果を返します。 +- `func` (`Function`): 制限する関数。 + +#### 戻り値 + +(`Function`): 指定された回数まで元の関数を実行し、その後は最後の結果を返す新しい関数を返します。 diff --git a/docs/ja/reference/compat/function/bind.md b/docs/ja/compat/reference/function/bind.md similarity index 100% rename from docs/ja/reference/compat/function/bind.md rename to docs/ja/compat/reference/function/bind.md diff --git a/docs/ja/reference/compat/function/bindKey.md b/docs/ja/compat/reference/function/bindKey.md similarity index 100% rename from docs/ja/reference/compat/function/bindKey.md rename to docs/ja/compat/reference/function/bindKey.md diff --git a/docs/ja/compat/reference/function/curry.md b/docs/ja/compat/reference/function/curry.md new file mode 100644 index 000000000..de1c0b327 --- /dev/null +++ b/docs/ja/compat/reference/function/curry.md @@ -0,0 +1,222 @@ +# curry (Lodash 互換性) + +::: warning `es-toolkit` の `curry` または手動クロージャを使用してください +この `curry` 関数は、複雑なプレースホルダー処理、引数個数検証、引数合成ロジックにより、動作が遅くなります。 + +プレースホルダーが必要ない場合は、より高速な `es-toolkit` の [`curry`](../../../reference/function/curry.md) またはシンプルなクロージャを使用してください。 +::: + +関数をカリー化して、引数を一つずつ受け取るか、複数個を一度に受け取ることができる関数を作成します。 + +```typescript +const curriedFunction = curry(func, arity); +``` + +## 使用法 + +### `curry(func, arity)` + +部分適用を容易にするために関数をカリー化したい場合に `curry` を使用します。引数を段階的に提供する場合や、プレースホルダーを使用して特定の位置の引数を後で提供する場合に便利です。 + +```typescript +import { curry } from 'es-toolkit/compat'; + +// 基本的な使用法 +function add(a, b, c) { + return a + b + c; +} + +const curriedAdd = curry(add); + +// さまざまな方法で呼び出し可能 +console.log(curriedAdd(1)(2)(3)); // 6 +console.log(curriedAdd(1, 2)(3)); // 6 +console.log(curriedAdd(1)(2, 3)); // 6 +console.log(curriedAdd(1, 2, 3)); // 6 +``` + +メインライブラリの curry との比較: + +```typescript +// compat バージョン (柔軟、ただし遅い) +import { curry } from 'es-toolkit/compat'; +const curriedCompat = curry(add); +curriedCompat(1, 2)(3); // サポート +curriedCompat(1)(curry.placeholder, 3)(2); // プレースホルダーサポート + +// メインライブラリバージョン (より速い、ただし一度に一つずつのみ) +import { curry } from 'es-toolkit'; +const curriedMain = curry(add); +curriedMain(1)(2)(3); // サポート +curriedMain(1, 2)(3); // サポートされていない +``` + +プレースホルダー機能の使用: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function greet(greeting, name, punctuation) { + return `${greeting}, ${name}${punctuation}`; +} + +const curriedGreet = curry(greet); + +// プレースホルダーで中間引数をスキップ +const greetWithExclamation = curriedGreet(curry.placeholder, curry.placeholder, '!'); +console.log(greetWithExclamation('Hello', 'John')); // "Hello, John!" + +const sayHello = curriedGreet('Hello'); +console.log(sayHello(curry.placeholder, '~')('Jane')); // "Hello, Jane~" +``` + +関数型プログラミングでの活用: + +```typescript +import { curry } from 'es-toolkit/compat'; + +// マッピング関数を作成 +const map = curry((fn, array) => array.map(fn)); +const filter = curry((predicate, array) => array.filter(predicate)); + +const numbers = [1, 2, 3, 4, 5]; + +// 再利用可能な関数を生成 +const double = x => x * 2; +const isEven = x => x % 2 === 0; + +const mapDouble = map(double); +const filterEven = filter(isEven); + +console.log(mapDouble(numbers)); // [2, 4, 6, 8, 10] +console.log(filterEven(numbers)); // [2, 4] + +// 関数合成 +const processNumbers = nums => mapDouble(filterEven(nums)); +console.log(processNumbers(numbers)); // [4, 8] +``` + +API クライアントの構成: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function apiRequest(method, baseUrl, endpoint, options) { + return fetch(`${baseUrl}${endpoint}`, { + method, + ...options, + }); +} + +const curriedApiRequest = curry(apiRequest); + +// デフォルト設定で特化した関数を生成 +const apiGet = curriedApiRequest('GET', 'https://api.example.com'); +const apiPost = curriedApiRequest('POST', 'https://api.example.com'); + +// 認証ヘッダーを含む +const authenticatedPost = apiPost(curry.placeholder, { + headers: { Authorization: 'Bearer token123' }, +}); + +// 使用 +apiGet('/users'); // GET https://api.example.com/users +authenticatedPost('/users'); // POST with auth headers +``` + +数学演算関数: + +```typescript +import { curry } from 'es-toolkit/compat'; + +const calculate = curry((operation, a, b) => { + switch (operation) { + case '+': + return a + b; + case '-': + return a - b; + case '*': + return a * b; + case '/': + return a / b; + default: + throw new Error('サポートされていない演算'); + } +}); + +// 特化した演算関数 +const add = calculate('+'); +const subtract = calculate('-'); +const multiply = calculate('*'); + +console.log(add(5, 3)); // 8 +console.log(subtract(10)(4)); // 6 +console.log(multiply(3, 4)); // 12 + +// プレースホルダーで第二オペランドを固定 +const addFive = calculate('+', curry.placeholder, 5); +console.log(addFive(10)); // 15 +``` + +引数個数の指定: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function variableArgsFunction(a, b, c, ...rest) { + return [a, b, c, rest]; +} + +// 引数個数を 3 に制限 +const curriedFixed = curry(variableArgsFunction, 3); + +console.log(curriedFixed(1)(2)(3)); // [1, 2, 3, []] +console.log(curriedFixed(1, 2)(3)); // [1, 2, 3, []] + +// 引数個数なしで使用 (デフォルト値: function.length) +const curriedDefault = curry(variableArgsFunction); // arity = 3 +``` + +シンプルなカリー化の代替: + +```typescript +// curry を使用 +const curriedAdd = curry((a, b, c) => a + b + c); + +// 手動クロージャ (より速い) +const manualCurry = a => b => c => a + b + c; + +// どちらも同じ結果 +console.log(curriedAdd(1)(2)(3)); // 6 +console.log(manualCurry(1)(2)(3)); // 6 +``` + +コンストラクタ関数もサポート: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function Person(name, age, city) { + this.name = name; + this.age = age; + this.city = city; +} + +const CurriedPerson = curry(Person); +const SeoulPerson = CurriedPerson(curry.placeholder, curry.placeholder, 'Seoul'); + +const person1 = new SeoulPerson('John', 30); +const person2 = new SeoulPerson('Jane', 25); + +console.log(person1.city); // "Seoul" +console.log(person2.city); // "Seoul" +``` + +#### パラメータ + +- `func` (`Function`): カリー化する関数。 +- `arity` (`number`, オプション): 関数の引数個数。省略すると `func.length` が使用されます。 + +#### 戻り値 + +(`Function & { placeholder: symbol }`): カリー化された関数を返します。`placeholder` プロパティで引数の位置を制御できます。 diff --git a/docs/ja/compat/reference/function/curryRight.md b/docs/ja/compat/reference/function/curryRight.md new file mode 100644 index 000000000..2d3f255c2 --- /dev/null +++ b/docs/ja/compat/reference/function/curryRight.md @@ -0,0 +1,242 @@ +# curryRight (Lodash 互換性) + +::: warning `es-toolkit` の [`curryRight`](../../../reference/function/curryRight.md) または手動クロージャを使用してください + +この `curryRight` 関数は、複雑なプレースホルダー処理、引数数の検証、引数合成ロジックにより動作が遅くなります。 + +プレースホルダーが不要な場合は、より高速な `es-toolkit` の [`curryRight`](../../../reference/function/curryRight.md) またはシンプルなクロージャを使用してください。 + +::: + +関数を右からカリー化し、最後の引数から1つずつまたは複数ずつ受け取ることができる関数を作成します。 + +```typescript +const curriedFunction = curryRight(func, arity); +``` + +## 使用法 + +### `curryRight(func, arity)` + +関数を右からカリー化し、最後の引数から部分適用したい場合は `curryRight` を使用します。通常の `curry` とは異なり、最後の引数から先に処理します。 + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 基本的な使用法 +function subtract(a, b, c) { + return a - b - c; +} + +const curriedSubtract = curryRight(subtract); + +// 右から(最後の引数から)カリー化 +console.log(curriedSubtract(1)(2)(5)); // 5 - 2 - 1 = 2 +console.log(curriedSubtract(1, 2)(5)); // 5 - 2 - 1 = 2 +console.log(curriedSubtract(1)(2, 5)); // 2 - 5 - 1 = -4 +console.log(curriedSubtract(1, 2, 5)); // 1 - 2 - 5 = -6 +``` + +`curry` と `curryRight` の違い: + +```typescript +import { curry, curryRight } from 'es-toolkit/compat'; + +function divide(a, b, c) { + return a / b / c; +} + +// 通常の curry(左から) +const leftCurried = curry(divide); +console.log(leftCurried(12)(3)(2)); // ((12 / 3) / 2) = 2 + +// curryRight(右から) +const rightCurried = curryRight(divide); +console.log(rightCurried(2)(3)(12)); // ((12 / 3) / 2) = 2 +// 最後に渡した 12 が最初の引数(a)になる +``` + +メインライブラリとの比較: + +```typescript +// compat バージョン(柔軟だが遅い) +import { curryRight } from 'es-toolkit/compat'; +const curriedCompat = curryRight(subtract); +curriedCompat(1, 2)(3); // サポート +curriedCompat(1)(curryRight.placeholder, 3)(2); // プレースホルダーサポート + +// メインライブラリバージョン(より高速だが一度に1つのみ) +import { curryRight } from 'es-toolkit'; +const curriedMain = curryRight(subtract); +curriedMain(1)(2)(3); // サポート +curriedMain(1, 2)(3); // サポートされていない +``` + +プレースホルダー機能の使用: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function formatMessage(name, action, time) { + return `${name}さんが${action}を${time}に行いました`; +} + +const curriedFormat = curryRight(formatMessage); + +// プレースホルダーで特定の位置をスキップ +const todayAction = curriedFormat('今日'); +const todayLoginAction = todayAction(curryRight.placeholder, 'ログイン'); + +console.log(todayLoginAction('田中')); +// "田中さんがログインを今日に行いました" + +// 時間を先に固定 +const morningFormat = curriedFormat('朝9時'); +console.log(morningFormat('コメント作成', '佐藤')); +// "佐藤さんがコメント作成を朝9時に行いました" +``` + +配列処理での活用: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 配列の末尾から特定の数だけ取得 +function takeFromEnd(array, count, separator = ', ') { + return array.slice(-count).join(separator); +} + +const curriedTake = curryRight(takeFromEnd); + +// カンマ区切りの関数を作成 +const takeWithComma = curriedTake(', '); + +// 最後の3つを取得 +const takeLast3 = takeWithComma(3); + +const fruits = ['りんご', 'バナナ', 'オレンジ', 'ぶどう', 'キウイ']; +console.log(takeLast3(fruits)); // "オレンジ, ぶどう, キウイ" + +// 異なる区切り文字を使用 +const takeWithDash = curriedTake(' - '); +console.log(takeWithDash(2, fruits)); // "ぶどう - キウイ" +``` + +関数合成での活用: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// ログ出力関数 +function logWithPrefix(message, level, timestamp) { + return `[${timestamp}] ${level}: ${message}`; +} + +const curriedLog = curryRight(logWithPrefix); + +// 現在時刻で固定 +const currentTimeLog = curriedLog(new Date().toISOString()); + +// レベル別のロガーを作成 +const errorLog = currentTimeLog('ERROR'); +const infoLog = currentTimeLog('INFO'); +const debugLog = currentTimeLog('DEBUG'); + +// 使用 +console.log(errorLog('データベース接続失敗')); +console.log(infoLog('サーバー起動')); +console.log(debugLog('ユーザーリクエスト処理中')); +``` + +関数型プログラミングパイプライン: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// データ変換関数 +const mapWith = curryRight((array, fn) => array.map(fn)); +const filterWith = curryRight((array, predicate) => array.filter(predicate)); +const reduceWith = curryRight((array, reducer, initial) => array.reduce(reducer, initial)); + +const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + +// 変換関数を定義 +const double = x => x * 2; +const isEven = x => x % 2 === 0; +const sum = (acc, val) => acc + val; + +// パイプラインを構成(右から優先) +const processNumbers = nums => { + return reduceWith(filterWith(mapWith(nums, double), isEven), sum, 0); +}; + +console.log(processNumbers(numbers)); // すべての数を2倍にして偶数のみフィルタリングして合計 +``` + +API リクエストビルダー: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function makeRequest(url, method, headers, body) { + return fetch(url, { method, headers, body }); +} + +const curriedRequest = curryRight(makeRequest); + +// body から設定 +const withJsonBody = curriedRequest(JSON.stringify({ data: 'test' })); + +// headers を追加 +const withHeaders = withJsonBody({ + 'Content-Type': 'application/json', + Authorization: 'Bearer token123', +}); + +// POST メソッドを設定 +const postRequest = withHeaders('POST'); + +// 最終的な使用 +postRequest('/api/data') + .then(response => response.json()) + .then(data => console.log(data)); +``` + +手動カリー化の代替: + +```typescript +// curryRight を使用 +const curriedSubtract = curryRight((a, b, c) => a - b - c); + +// 手動クロージャ(より高速、右から) +const manualCurryRight = c => b => a => a - b - c; + +// 両方とも同じ結果 +console.log(curriedSubtract(1)(2)(5)); // 2 +console.log(manualCurryRight(1)(2)(5)); // 2 +``` + +引数数の指定: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function variableArgsFunction(a, b, c, ...rest) { + return { a, b, c, rest }; +} + +// 引数数を3に制限(rest は無視) +const curriedFixed = curryRight(variableArgsFunction, 3); + +// 右から c, b, a の順序で受け取る +console.log(curriedFixed(3)(2)(1)); // { a: 1, b: 2, c: 3, rest: [] } +``` + +#### パラメータ + +- `func` (`Function`): 右からカリー化する関数です。 +- `arity` (`number`, オプション): 関数の引数数です。省略すると `func.length` が使用されます。 + +#### 戻り値 + +(`Function & { placeholder: symbol }`): 右からカリー化された関数を返します。`placeholder` プロパティで引数の位置を制御できます。 diff --git a/docs/ja/compat/reference/function/debounce.md b/docs/ja/compat/reference/function/debounce.md new file mode 100644 index 000000000..96f5f68c5 --- /dev/null +++ b/docs/ja/compat/reference/function/debounce.md @@ -0,0 +1,264 @@ +# debounce (Lodash 互換) + +::: warning `es-toolkit` の [`debounce`](../../../reference/function/debounce.md) を使用してください + +この `debounce` 関数は、複雑な `maxWait` 処理と Lodash 互換のオプション構造によるオーバーヘッドがあります。 + +代わりに、より高速で現代的な `es-toolkit` の [`debounce`](../../../reference/function/debounce.md) を使用してください。 + +::: + +関数呼び出しを遅延させ、最後の呼び出しから指定された時間が経過した後にのみ実行されるデバウンス関数を作成します。 + +```typescript +const debouncedFunction = debounce(func, wait, options); +``` + +## 使用法 + +### `debounce(func, wait, options)` + +関数呼び出しを遅延させたい場合は `debounce` を使用してください。検索入力、スクロールイベント、ボタンクリックなどでの過度な呼び出しを防ぐのに便利です。 + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// 基本的な使用法 +const searchFunction = debounce(query => { + console.log('検索:', query); +}, 300); + +// 300ms 以内に再度呼び出されなければ実行される +searchFunction('React'); // 実行されない +searchFunction('Vue'); // 実行されない +searchFunction('Angular'); // 300ms 後に "検索: Angular" と出力 +``` + +メインライブラリの debounce との比較: + +```typescript +// compat バージョン(Lodash 互換、maxWait などの追加オプション) +import { debounce } from 'es-toolkit/compat'; +const debouncedCompat = debounce(func, 300, { + leading: true, + trailing: false, + maxWait: 1000 +}); + +// メインライブラリバージョン(より高速でシンプル) +import { debounce } from 'es-toolkit'; +const debouncedMain = debounce(func, 300, { + edges: ['leading'] // leading/trailing の代わりに edges を使用 +}); +``` + +leading と trailing オプション: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const func = () => console.log('実行されました'); + +// leading: true - 最初の呼び出し時に即座に実行 +const leadingDebounce = debounce(func, 1000, { leading: true }); +leadingDebounce(); // 即座に "実行されました" と出力 +leadingDebounce(); // 1秒待機 +// 1秒後に追加の実行なし + +// trailing: true(デフォルト) - 最後の呼び出し後の遅延時間後に実行 +const trailingDebounce = debounce(func, 1000, { trailing: true }); +trailingDebounce(); // 1秒待機 +trailingDebounce(); // 1秒待機(前のタイマーをキャンセル) +// 1秒後に "実行されました" と出力 + +// 両方とも true - 開始時と終了時に実行 +const bothDebounce = debounce(func, 1000, { + leading: true, + trailing: true, +}); +bothDebounce(); // 即座に "実行されました" と出力 +bothDebounce(); // 1秒待機 +// 1秒後に "実行されました" と出力(trailing) +``` + +maxWait オプション: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// 最大2秒ごとには必ず実行 +const debouncedWithMaxWait = debounce(() => console.log('保存されました'), 500, { maxWait: 2000 }); + +// 高速に連続呼び出しされても、最大2秒ごとに実行される +setInterval(() => { + debouncedWithMaxWait(); +}, 100); // 100ms ごとに呼び出されるが、2秒ごとに "保存されました" と出力 +``` + +実際の検索例: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +class SearchComponent { + constructor() { + this.searchInput = document.getElementById('search'); + + // ユーザー入力を 300ms デバウンス + this.debouncedSearch = debounce(this.performSearch.bind(this), 300, { + leading: false, // 入力開始時に即座に検索しない + trailing: true, // 入力停止後に検索 + }); + + this.searchInput.addEventListener('input', e => { + this.debouncedSearch(e.target.value); + }); + } + + performSearch(query) { + if (query.length < 2) return; + + console.log('API 呼び出し:', query); + // fetch(`/api/search?q=${query}`)... + } +} +``` + +スクロールイベントの最適化: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// スクロールイベントを 100ms デバウンスするが、最大 500ms ごとには実行 +const optimizedScrollHandler = debounce( + () => { + const scrollTop = window.pageYOffset; + console.log('スクロール位置:', scrollTop); + + // ヘッダーの非表示/表示ロジック + if (scrollTop > 100) { + document.header.classList.add('hidden'); + } else { + document.header.classList.remove('hidden'); + } + }, + 100, + { maxWait: 500 } +); + +window.addEventListener('scroll', optimizedScrollHandler); +``` + +API 呼び出しの制限: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +class AutoSave { + constructor() { + // 500ms デバウンス、最大5秒ごとには保存 + this.debouncedSave = debounce(this.saveToServer.bind(this), 500, { maxWait: 5000 }); + } + + onTextChange(content) { + this.pendingContent = content; + this.debouncedSave(); + } + + saveToServer() { + if (!this.pendingContent) return; + + console.log('サーバーに保存:', this.pendingContent); + // fetch('/api/save', { ... }) + + this.pendingContent = null; + } +} +``` + +cancel と flush メソッド: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const debouncedFunc = debounce(() => { + console.log('実行されました'); +}, 1000); + +debouncedFunc(); // 1秒待機中 + +// 待機中の実行をキャンセル +debouncedFunc.cancel(); + +// または即座に実行 +debouncedFunc(); // 1秒待機開始 +debouncedFunc.flush(); // 即座に "実行されました" と出力し、タイマーをキャンセル +``` + +ボタンクリックの重複防止: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const handleSubmit = debounce( + async formData => { + console.log('フォーム送信中...'); + try { + const response = await fetch('/api/submit', { + method: 'POST', + body: formData, + }); + console.log('送信完了'); + } catch (error) { + console.error('送信失敗:', error); + } + }, + 1000, + { leading: true, trailing: false } // 最初のクリックのみ処理 +); + +document.getElementById('submit-btn').addEventListener('click', e => { + const formData = new FormData(e.target.form); + handleSubmit(formData); +}); +``` + +リサイズイベント処理: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const handleResize = debounce( + () => { + const width = window.innerWidth; + const height = window.innerHeight; + + console.log('ウィンドウサイズ変更:', { width, height }); + + // レイアウトの再計算 + recalculateLayout(); + }, + 250, + { leading: false, trailing: true } +); + +window.addEventListener('resize', handleResize); + +// ページ終了時にクリーンアップ +window.addEventListener('beforeunload', () => { + handleResize.cancel(); +}); +``` + +#### パラメータ + +- `func` (`Function`): デバウンスする関数です。 +- `wait` (`number`, オプション): 遅延するミリ秒数です。デフォルトは `0` です。 +- `options` (`DebounceSettings`, オプション): オプションオブジェクトです。 + - `leading` (`boolean`): `true` の場合、遅延開始時点で関数を実行します。デフォルトは `false` です。 + - `trailing` (`boolean`): `true` の場合、遅延終了時点で関数を実行します。デフォルトは `true` です。 + - `maxWait` (`number`): 関数実行が遅延できる最大時間です。デフォルトは `Infinity` です。 + +#### 戻り値 + +(`DebouncedFunc`): デバウンスされた関数を返します。`cancel()` と `flush()` メソッドが含まれています。 diff --git a/docs/ja/reference/compat/function/defer.md b/docs/ja/compat/reference/function/defer.md similarity index 100% rename from docs/ja/reference/compat/function/defer.md rename to docs/ja/compat/reference/function/defer.md diff --git a/docs/ja/reference/compat/function/delay.md b/docs/ja/compat/reference/function/delay.md similarity index 100% rename from docs/ja/reference/compat/function/delay.md rename to docs/ja/compat/reference/function/delay.md diff --git a/docs/ja/reference/compat/function/flip.md b/docs/ja/compat/reference/function/flip.md similarity index 100% rename from docs/ja/reference/compat/function/flip.md rename to docs/ja/compat/reference/function/flip.md diff --git a/docs/ja/compat/reference/function/flow.md b/docs/ja/compat/reference/function/flow.md new file mode 100644 index 000000000..30e77ebe5 --- /dev/null +++ b/docs/ja/compat/reference/function/flow.md @@ -0,0 +1,87 @@ +# flow (Lodash 互換性) + +::: warning `es-toolkit` の `flow` を使用してください +この `flow` 関数は Lodash 互換性のために配列のフラット化処理が追加されており、複雑です。 + +代わりに、より高速で現代的な `es-toolkit` の [flow](../../../reference/function/flow.md) を使用してください。 +::: + +与えられた関数を左から右へ順次実行する新しい関数を作成します。 + +```typescript +const combinedFunc = flow(...functions); +``` + +## 使用法 + +### `flow(...functions)` + +複数の関数を左から右へ順次実行する1つの合成関数を作成したい場合は `flow` を使用してください。データ変換パイプラインを作成する際に便利です。 + +```typescript +import { flow } from 'es-toolkit/compat'; + +// 基本的な使い方 +function add(x, y) { + return x + y; +} + +function square(n) { + return n * n; +} + +function double(n) { + return n * 2; +} + +// 左から右へ実行: double(square(add(x, y))) +const calculate = flow(add, square, double); +console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 + +// 配列で関数を渡す +const calculate2 = flow([add, square], double); +console.log(calculate2(2, 3)); // 50 + +// 現代的な代替案(推奨) +const modernCalculate = (x, y) => double(square(add(x, y))); +console.log(modernCalculate(1, 2)); // 18 + +// パイプ演算子を使用(将来の JavaScript) +const pipeCalculate = (x, y) => add(x, y) |> square |> double; + +// またはチェーンパターン +class Calculator { + constructor(value) { + this.value = value; + } + + add(n) { + this.value += n; + return this; + } + + square() { + this.value *= this.value; + return this; + } + + double() { + this.value *= 2; + return this; + } + + valueOf() { + return this.value; + } +} + +const chainedResult = new Calculator(3).square().double().valueOf(); // 18 +``` + +#### パラメータ + +- `...functions` (`Array`): 左から右へ実行する関数です。配列で渡すこともできます。 + +#### 戻り値 + +(`Function`): すべての関数を左から右へ順次実行する新しい合成関数を返します。 diff --git a/docs/ja/compat/reference/function/flowRight.md b/docs/ja/compat/reference/function/flowRight.md new file mode 100644 index 000000000..de0af5fc2 --- /dev/null +++ b/docs/ja/compat/reference/function/flowRight.md @@ -0,0 +1,65 @@ +# flowRight (Lodash 互換性) + +::: warning `es-toolkit` の `flowRight` を使用してください +この `flowRight` 関数は Lodash 互換性のために配列のフラット化処理が追加されており、複雑です。 + +代わりに、より高速で現代的な `es-toolkit` の [flowRight](../../../reference/function/flowRight.md) を使用してください。 +::: + +与えられた関数を右から左へ順次実行する新しい関数を作成します。 + +```typescript +const combinedFunc = flowRight(...functions); +``` + +## 使用法 + +### `flowRight(...functions)` + +複数の関数を右から左へ順次実行する1つの合成関数を作成したい場合は `flowRight` を使用してください。データ変換パイプラインを作成する際に便利です。 + +```typescript +import { flowRight } from 'es-toolkit/compat'; + +// 基本的な使い方 +function add(x, y) { + return x + y; +} + +function square(n) { + return n * n; +} + +function double(n) { + return n * 2; +} + +// 右から左へ実行: double(square(add(x, y))) +const calculate = flowRight(double, square, add); +console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 + +// 配列で関数を渡す +const calculate2 = flowRight([double, square], add); +console.log(calculate2(2, 3)); // 50 + +// 現代的な代替案(推奨) +const modernCalculate = (x, y) => double(square(add(x, y))); +console.log(modernCalculate(1, 2)); // 18 + +// または関数チェーンを使用 +const chainedCalculate = (x, y) => [x, y] + .reduce((acc, val, idx) => idx === 0 ? val : acc + val) + .valueOf() + |> (n => n * n) + |> (n => n * 2); +``` + +一般的に `flow` と反対の順序で動作します。合成関数と似た方式で動作するため直感的です。 + +#### パラメータ + +- `...functions` (`Array`): 右から左へ実行する関数です。配列で渡すこともできます。 + +#### 戻り値 + +(`Function`): すべての関数を右から左へ順次実行する新しい合成関数を返します。 diff --git a/docs/ja/compat/reference/function/identity.md b/docs/ja/compat/reference/function/identity.md new file mode 100644 index 000000000..2f3478d4e --- /dev/null +++ b/docs/ja/compat/reference/function/identity.md @@ -0,0 +1,62 @@ +# identity (Lodash 互換性) + +::: warning `es-toolkit` の `identity` を使用してください +この `identity` 関数は `es-toolkit` のメインライブラリにも同じ機能の関数があります。単に入力値をそのまま返す機能です。 + +代わりに、より高速で現代的な `es-toolkit` の [identity](../../../reference/function/identity.md) を使用してください。 +::: + +受け取った値をそのまま返します。 + +```typescript +const result = identity(value); +``` + +## 使用法 + +### `identity(value)` + +受け取った値をそのまま返したい場合は `identity` を使用してください。主にデフォルト値やプレースホルダー関数として使用され、関数型プログラミングでよく使われます。 + +```typescript +import { identity } from 'es-toolkit/compat'; + +// 基本的な使い方 +console.log(identity(5)); // 5 +console.log(identity('hello')); // 'hello' +console.log(identity({ key: 'value' })); // { key: 'value' } + +// 配列の map と一緒に使用(値のコピー) +const numbers = [1, 2, 3, 4, 5]; +const copied = numbers.map(identity); +console.log(copied); // [1, 2, 3, 4, 5] + +// フィルタリングでデフォルト値として使用 +const values = [1, 0, '', 'hello', null, undefined, false, true]; +const filtered = values.filter(identity); // 真と評価される値だけを残す +console.log(filtered); // [1, 'hello', true] + +// デフォルトの変換関数として使用 +function processData(data, transform = identity) { + return transform(data); +} + +console.log(processData('hello')); // 'hello' +console.log(processData('hello', x => x.toUpperCase())); // 'HELLO' +``` + +ほとんどの場合、より簡単なアロー関数 `x => x` で置き換えることができます: + +```typescript +// identity の代わりにアロー関数を使用(推奨) +const copied = numbers.map(x => x); +const filtered = values.filter(x => x); +``` + +#### パラメータ + +- `value` (`T`): 返す値です。 + +#### 戻り値 + +(`T`): 受け取った値をそのまま返します。 diff --git a/docs/ja/compat/reference/function/memoize.md b/docs/ja/compat/reference/function/memoize.md new file mode 100644 index 000000000..8b47af5ae --- /dev/null +++ b/docs/ja/compat/reference/function/memoize.md @@ -0,0 +1,66 @@ +# memoize (Lodash 互換性) + +::: warning `es-toolkit` の `memoize` を使用してください +この `memoize` 関数は `resolver` 関数の `null` チェック、`MapCache` インターフェースの複雑な型処理、そして Lodash 互換性のための追加のオーバーヘッドにより遅く動作します。 + +代わりに、より高速で現代的な `es-toolkit` の [memoize](../../../reference/function/memoize.md) を使用してください。 +::: + +関数の結果をキャッシュして、同じ引数で呼び出されたときにパフォーマンスを向上させます。 + +```typescript +const memoizedFunc = memoize(func, resolver); +``` + +## 使用法 + +### `memoize(func, resolver)` + +関数の結果をメモ化して、同じ引数で呼び出されたときに以前の結果を再利用したい場合は `memoize` を使用してください。コストのかかる計算や API 呼び出しに便利です。 + +```typescript +import { memoize } from 'es-toolkit/compat'; + +// 基本的な使い方 +function expensiveCalculation(n) { + console.log('計算中...', n); + return n * n; +} + +const memoizedCalc = memoize(expensiveCalculation); + +console.log(memoizedCalc(5)); // '計算中... 5', 25 +console.log(memoizedCalc(5)); // 25 (キャッシュされた結果、計算しない) +console.log(memoizedCalc(10)); // '計算中... 10', 100 + +// カスタムリゾルバーを使用 +function fetchUserData(userId, includeProfile) { + console.log('ユーザーデータを取得中...', userId, includeProfile); + return { id: userId, profile: includeProfile ? 'プロフィールデータ' : null }; +} + +// すべての引数を考慮したキャッシュキーを生成 +const memoizedFetch = memoize(fetchUserData, (userId, includeProfile) => { + return `${userId}_${includeProfile}`; +}); + +memoizedFetch(1, true); // 'ユーザーデータを取得中... 1 true' +memoizedFetch(1, true); // キャッシュされた結果を使用 +memoizedFetch(1, false); // 'ユーザーデータを取得中... 1 false' (異なるキャッシュキー) + +// キャッシュへのアクセスと変更 +console.log(memoizedCalc.cache.get(5)); // 25 +memoizedCalc.cache.set(7, 49); // 手動でキャッシュを設定 +console.log(memoizedCalc(7)); // 49 (計算せずにキャッシュされた値を使用) +``` + +ほとんどの場合、基本的なハッシュマップを使用しますが、必要に応じてカスタムキャッシュ実装を使用することもできます。 + +#### パラメータ + +- `func` (`Function`): メモ化する関数です。 +- `resolver` (`Function`, オプション): キャッシュキーを決定する関数です。提供されない場合は最初の引数をキーとして使用します。 + +#### 戻り値 + +(`Function & { cache: MapCache }`): メモ化された関数を返します。返された関数には `cache` プロパティがあり、キャッシュに直接アクセスできます。 diff --git a/docs/ja/reference/compat/function/negate.md b/docs/ja/compat/reference/function/negate.md similarity index 100% rename from docs/ja/reference/compat/function/negate.md rename to docs/ja/compat/reference/function/negate.md diff --git a/docs/ja/compat/reference/function/noop.md b/docs/ja/compat/reference/function/noop.md new file mode 100644 index 000000000..dbd88859f --- /dev/null +++ b/docs/ja/compat/reference/function/noop.md @@ -0,0 +1,60 @@ +# noop (Lodash 互換性) + +::: warning `es-toolkit` の `noop` を使用してください + +`es-toolkit` にも同じ動作をする [noop](../../../reference/function/noop.md) 関数があります。 + +::: + +何もしない空の関数です。 + +```typescript +noop(); +``` + +## 使用法 + +### `noop(...args)` + +何もしないプレースホルダー関数が必要な場合は `noop` を使用してください。デフォルト値やコールバック関数としてよく使われます。 + +```typescript +import { noop } from 'es-toolkit/compat'; + +// 基本的な使用法 +noop(); // 何もしない +noop(1, 2, 3); // 引数を受け取るが何もしない + +// デフォルトのコールバックとして使用 +function processData(data, callback = noop) { + // データ処理 + console.log('データ処理中...', data); + + // コールバック呼び出し(提供されていなければ noop) + callback(data); +} + +processData('テスト'); // コールバックが提供されていなくてもエラーなく動作 + +// 現代的な代替案(推奨) +function modernProcessData(data, callback = () => {}) { + console.log('データ処理中...', data); + callback(data); +} + +// またはオプショナルなコールバックを使用 +function processDataOptional(data, callback) { + console.log('データ処理中...', data); + callback?.(data); // コールバックが提供された場合のみ呼び出し +} +``` + +デフォルト値やプレースホルダーが必要な状況で便利ですが、現代の JavaScript ではオプショナルチェイニング(`?.`)やデフォルトパラメータを使用する方が一般的です。 + +#### パラメータ + +- `...args` (`any[]`): どんな引数でも受け取れますが、すべて無視されます。 + +#### 戻り値 + +(`void`): 何も返しません。 diff --git a/docs/ja/reference/compat/function/nthArg.md b/docs/ja/compat/reference/function/nthArg.md similarity index 100% rename from docs/ja/reference/compat/function/nthArg.md rename to docs/ja/compat/reference/function/nthArg.md diff --git a/docs/ja/compat/reference/function/once.md b/docs/ja/compat/reference/function/once.md new file mode 100644 index 000000000..67c0890c2 --- /dev/null +++ b/docs/ja/compat/reference/function/once.md @@ -0,0 +1,56 @@ +# once (Lodash 互換性) + +::: warning `es-toolkit` の `once` を使用してください + +この `once` 関数は、`es-toolkit` のメインライブラリ [once](../../../reference/function/once.md) 関数と同じ機能を持っています。 + +::: + +関数が1回だけ呼び出されるように制限します。 + +```typescript +const limitedFunc = once(func); +``` + +## 使用法 + +### `once(func)` + +関数を1回だけ呼び出すように制限したい場合は `once` を使用してください。最初の呼び出し後は結果がキャッシュされ、同じ値を返します。 + +```typescript +import { once } from 'es-toolkit/compat'; + +// 基本的な使用法 +let count = 0; +const increment = once(() => { + count++; + console.log('カウンター増加:', count); + return count; +}); + +increment(); // 'カウンター増加: 1' を出力、1 を返す +increment(); // 何も出力しない、1 を返す +increment(); // 何も出力しない、1 を返す + +// 実用的な例 - 初期化関数 +const initialize = once(() => { + console.log('アプリケーション初期化中...'); + // コストのかかる初期化操作 + return '初期化完了'; +}); + +// 複数回呼び出しても、初期化は1回だけ実行される +initialize(); // 'アプリケーション初期化中...' を出力 +initialize(); // 何も出力しない +``` + +コストのかかる初期化操作やセットアップ関数を作成する際に便利です。例えば、データベース接続、APIトークンの初期化などに使用できます。 + +#### パラメータ + +- `func` (`Function`): 1回だけ呼び出すように制限する関数です。 + +#### 戻り値 + +(`Function`): 1回だけ呼び出される新しい関数を返します。2回目の呼び出し以降は、最初の呼び出しの結果を返します。 diff --git a/docs/ja/reference/compat/function/overArgs.md b/docs/ja/compat/reference/function/overArgs.md similarity index 100% rename from docs/ja/reference/compat/function/overArgs.md rename to docs/ja/compat/reference/function/overArgs.md diff --git a/docs/ja/compat/reference/function/partial.md b/docs/ja/compat/reference/function/partial.md new file mode 100644 index 000000000..d72eb3fa6 --- /dev/null +++ b/docs/ja/compat/reference/function/partial.md @@ -0,0 +1,59 @@ +# partial (Lodash 互換性) + +::: warning `es-toolkit` の `partial` を使用してください + +この `partial` 関数は多くのオーバーロードとユニオン型処理により非効率的です。また、ほとんどの場合、より簡単なアロー関数で代替できます。 + +代わりに、より高速で現代的な `es-toolkit` の [`partial`](../../../reference/function/partial.md) を使用してください。 + +::: + +関数の引数を事前に埋めて部分適用された関数を作成します。 + +```typescript +const partialFunc = partial(func, ...args); +``` + +## 使用法 + +### `partial(func, ...args)` + +関数の引数を事前に埋めて部分適用された関数を作成したい場合は `partial` を使用してください。主に引数の順序が重要な関数で最初の引数を固定する際に便利です。 + +```typescript +import { partial } from 'es-toolkit/compat'; + +// 基本的な使用法 +function greet(greeting, name, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// 最初の引数を事前設定 +const sayHello = partial(greet, 'Hello'); +sayHello('Alice', '!'); // 'Hello Alice!' + +// 複数の引数を事前設定 +const greetAlice = partial(greet, 'Hello', 'Alice'); +greetAlice('!'); // 'Hello Alice!' + +// placeholder を使用して引数の順序を調整 +const greetWithExclamation = partial(greet, partial.placeholder, 'Alice', '!'); +greetWithExclamation('Hi'); // 'Hi Alice!' +``` + +ほとんどの場合、アロー関数で代替できます: + +```typescript +// partial の代わりにアロー関数を使用(推奨) +const sayHello = (name, punctuation) => greet('Hello', name, punctuation); +const greetAlice = punctuation => greet('Hello', 'Alice', punctuation); +``` + +#### パラメータ + +- `func` (`Function`): 部分適用する関数です。 +- `...args` (`any[]`): 事前に埋める引数です。`partial.placeholder` を使用して引数の順序を調整できます。 + +#### 戻り値 + +(`Function`): 引数が事前に埋められた新しい関数を返します。 diff --git a/docs/ja/compat/reference/function/partialRight.md b/docs/ja/compat/reference/function/partialRight.md new file mode 100644 index 000000000..471ba733c --- /dev/null +++ b/docs/ja/compat/reference/function/partialRight.md @@ -0,0 +1,59 @@ +# partialRight (Lodash 互換性) + +::: warning `es-toolkit` の `partialRight` を使用してください + +この `partialRight` 関数は多くのオーバーロードとユニオン型処理により非効率的です。また、ほとんどの場合、より簡単なアロー関数で代替できます。 + +代わりに、より高速で現代的な `es-toolkit` の [`partialRight`](../../../reference/function/partialRight.md) を使用してください。 + +::: + +関数の右側から引数を事前に埋めて部分適用された関数を作成します。 + +```typescript +const partialFunc = partialRight(func, ...args); +``` + +## 使用法 + +### `partialRight(func, ...args)` + +関数の右側から引数を事前に埋めて部分適用された関数を作成したい場合は `partialRight` を使用してください。主に引数の順序が重要な関数で最後の引数を固定する際に便利です。 + +```typescript +import { partialRight } from 'es-toolkit/compat'; + +// 基本的な使用法 +function greet(greeting, name, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// 最後の引数を事前設定 +const greetWithExclamation = partialRight(greet, '!'); +greetWithExclamation('Hello', 'Alice'); // 'Hello Alice!' + +// 複数の引数を事前設定 +const sayHiToAlice = partialRight(greet, 'Alice', '!'); +sayHiToAlice('Hi'); // 'Hi Alice!' + +// placeholder を使用して引数の順序を調整 +const greetAliceWithCustom = partialRight(greet, 'Alice', partialRight.placeholder); +greetAliceWithCustom('Hello', '?'); // 'Hello Alice?' +``` + +ほとんどの場合、アロー関数で代替できます: + +```typescript +// partialRight の代わりにアロー関数を使用(推奨) +const greetWithExclamation = (greeting, name) => greet(greeting, name, '!'); +const sayHiToAlice = greeting => greet(greeting, 'Alice', '!'); +``` + +#### パラメータ + +- `func` (`Function`): 部分適用する関数です。 +- `...args` (`any[]`): 事前に埋める引数です。`partialRight.placeholder` を使用して引数の順序を調整できます。 + +#### 戻り値 + +(`Function`): 右側から引数が事前に埋められた新しい関数を返します。 diff --git a/docs/ja/reference/compat/function/rearg.md b/docs/ja/compat/reference/function/rearg.md similarity index 100% rename from docs/ja/reference/compat/function/rearg.md rename to docs/ja/compat/reference/function/rearg.md diff --git a/docs/ja/compat/reference/function/rest.md b/docs/ja/compat/reference/function/rest.md new file mode 100644 index 000000000..be8f3d2d8 --- /dev/null +++ b/docs/ja/compat/reference/function/rest.md @@ -0,0 +1,54 @@ +# rest (Lodash 互換性) + +::: warning `es-toolkit` の `rest` を使用してください + +この `rest` 関数は、デフォルト値処理やインデックス検証などの追加ロジックにより、パフォーマンスが低下する可能性があります。 + +代わりに、より高速で現代的な `es-toolkit` の [rest](../../../reference/function/rest.md) を使用してください。 + +::: + +指定されたインデックスから残りの引数を配列にグループ化する関数を作成します。 + +```typescript +const restFunc = rest(func, start); +``` + +## 使用法 + +### `rest(func, start)` + +指定されたインデックスから残りの引数を配列にグループ化して関数の引数を変換したい場合は、`rest` を使用してください。可変長引数を受け取る関数を作成するのに便利です。 + +```typescript +import { rest } from 'es-toolkit/compat'; + +// 基本的な使用法 - 最後の引数を配列にグループ化 +function logMessage(level, message, ...details) { + console.log(`[${level}] ${message}`, details); +} + +const restLogger = rest(logMessage, 2); +restLogger('ERROR', 'エラーが発生しました', '詳細情報 1', '詳細情報 2'); +// 内部的に logMessage('ERROR', 'エラーが発生しました', [['詳細情報 1', '詳細情報 2']]) として呼び出されます + +// 別のインデックスの例 +function process(action, target, ...args) { + return { action, target, args }; +} + +const restProcess = rest(process, 1); +restProcess('update', 'user', 'name', 'John', 'age', 25); +// { action: 'update', target: ['user', 'name', 'John', 'age', 25], args: [] } +``` + +関数の最後の引数を配列として受け取りたい場合に使用します。現代の JavaScript では、残余パラメータ構文(`...args`)を使用するのがより一般的です。 + +#### パラメータ + +- `func` (`Function`): 変換する関数です。 +- `start` (`number`, オプション): 配列へのグループ化を開始するインデックスです。デフォルト値は `func.length - 1` です。 + +#### 戻り値 + +(`Function`): 指定されたインデックスから残りの引数を配列にグループ化する新しい関数を返します。 diff --git a/docs/ja/reference/compat/function/spread.md b/docs/ja/compat/reference/function/spread.md similarity index 100% rename from docs/ja/reference/compat/function/spread.md rename to docs/ja/compat/reference/function/spread.md diff --git a/docs/ja/compat/reference/function/throttle.md b/docs/ja/compat/reference/function/throttle.md new file mode 100644 index 000000000..b15490e84 --- /dev/null +++ b/docs/ja/compat/reference/function/throttle.md @@ -0,0 +1,52 @@ +# throttle (Lodash 互換性) + +::: warning `es-toolkit` の `throttle` を使用してください + +この `throttle` 関数は、Lodash 互換性のために内部的に debounce 関数を使用しているため、少し複雑になっています。また、デフォルト値やオプションの処理もより複雑です。 + +代わりに、より高速で現代的な `es-toolkit` の [throttle](../../../reference/function/throttle.md) を使用してください。 + +::: + +関数呼び出しを指定された時間間隔で最大1回実行されるように制限します。 + +```typescript +const throttledFunc = throttle(func, wait, options); +``` + +## 使用法 + +### `throttle(func, wait, options)` + +関数呼び出しを指定された時間間隔で最大1回実行されるように制限したい場合は、`throttle` を使用してください。イベントハンドラーや API 呼び出しの頻度を制限するのに便利です。 + +```typescript +import { throttle } from 'es-toolkit/compat'; + +// 基本的な使用法 - 1秒に最大1回実行 +const throttledLog = throttle(() => { + console.log('イベント発生!'); +}, 1000); + +// オプションを使用した例 +const throttledScroll = throttle(handleScroll, 100, { + leading: true, // 最初にすぐ実行 + trailing: false, // 最後に実行しない +}); + +window.addEventListener('scroll', throttledScroll); +``` + +スクロールイベントやリサイズイベントのように速く発生するイベントを処理する際、パフォーマンスのために必須です。 + +#### パラメータ + +- `func` (`Function`): スロットリングする関数です。 +- `wait` (`number`, オプション): ミリ秒単位の待機時間です。デフォルト値は `0` です。 +- `options` (`ThrottleSettings`, オプション): スロットリングオプションです。 + - `leading` (`boolean`): 最初の呼び出しですぐに実行するかどうかです。デフォルト値は `true` です。 + - `trailing` (`boolean`): 最後の呼び出し後に実行するかどうかです。デフォルト値は `true` です。 + +#### 戻り値 + +(`DebouncedFunc`): スロットリングされた関数を返します。`cancel()` メソッドで待機中の実行をキャンセルできます。 diff --git a/docs/ja/compat/reference/function/unary.md b/docs/ja/compat/reference/function/unary.md new file mode 100644 index 000000000..871c4410f --- /dev/null +++ b/docs/ja/compat/reference/function/unary.md @@ -0,0 +1,46 @@ +# unary (Lodash 互換性) + +::: warning `es-toolkit` の `ary` を使用してください + +この `unary` 関数は `ary` 関数の特殊なケースとして実装されています。より多くの制御が必要な場合は、`es-toolkit` の [ary](../../../reference/function/ary.md) を直接使用する方が効率的です。 + +代わりに、より高速で現代的な `es-toolkit` の [ary](../../../reference/function/ary.md) を使用してください。 + +::: + +関数が最大1つの引数のみを受け取るように制限します。 + +```typescript +const limitedFunc = unary(func); +``` + +## 使用法 + +### `unary(func)` + +関数が最大1つの引数のみを受け取るように制限したい場合は、`unary` を使用してください。追加で渡される引数はすべて無視されます。 + +```typescript +import { unary } from 'es-toolkit/compat'; + +function greet(name, greeting, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// 最初の引数のみを受け取る関数に変換 +const greetOne = unary(greet); +greetOne('Alice', 'Hello', '!'); // greet('Alice') と同じように動作 + +// 配列の map 関数と一緒に使用すると便利 +const numbers = ['1', '2', '3']; +numbers.map(parseInt); // [1, NaN, NaN] - 予期しない結果 +numbers.map(unary(parseInt)); // [1, 2, 3] - 正しい結果 +``` + +#### パラメータ + +- `func` (`(...args: any[]) => any`): 引数を制限する関数です。 + +#### 戻り値 + +(`(...args: any[]) => any`): 最大1つの引数のみを受け取る新しい関数を返します。 diff --git a/docs/ja/reference/compat/function/wrap.md b/docs/ja/compat/reference/function/wrap.md similarity index 100% rename from docs/ja/reference/compat/function/wrap.md rename to docs/ja/compat/reference/function/wrap.md diff --git a/docs/ja/reference/compat/math/add.md b/docs/ja/compat/reference/math/add.md similarity index 100% rename from docs/ja/reference/compat/math/add.md rename to docs/ja/compat/reference/math/add.md diff --git a/docs/ja/reference/compat/math/ceil.md b/docs/ja/compat/reference/math/ceil.md similarity index 100% rename from docs/ja/reference/compat/math/ceil.md rename to docs/ja/compat/reference/math/ceil.md diff --git a/docs/ja/compat/reference/math/clamp.md b/docs/ja/compat/reference/math/clamp.md new file mode 100644 index 000000000..deef4610c --- /dev/null +++ b/docs/ja/compat/reference/math/clamp.md @@ -0,0 +1,82 @@ +# clamp (Lodash 互換性) + +::: warning `es-toolkit`の[clamp](../../../reference/math/clamp.md)を使用してください + +この `clamp` 関数はNaN検証と処理により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [clamp](../../../reference/math/clamp.md) を使用してください。 + +::: + +数値を指定された範囲内に制限します。 + +```typescript +const clamped = clamp(number, lower, upper); +``` + +## 使用法 + +### `clamp(number, lower, upper)` + +数値を指定された最小値と最大値の間に制限したい場合は `clamp` を使用してください。 + +```typescript +import { clamp } from 'es-toolkit/compat'; + +// 基本的な使用法 +clamp(3, 2, 4); +// Returns: 3 (範囲内にある) + +clamp(0, 5, 10); +// Returns: 5 (最小値で制限) + +clamp(15, 5, 10); +// Returns: 10 (最大値で制限) + +// 負の数も処理 +clamp(-5, -10, -1); +// Returns: -5 + +clamp(-15, -10, -1); +// Returns: -10 (最小値で制限) +``` + +### `clamp(number, upper)` + +1つの引数のみを提供すると、その値を最大値として使用します。 + +```typescript +import { clamp } from 'es-toolkit/compat'; + +// 最大値のみ指定 +clamp(5, 3); +// Returns: 3 (最大値で制限) + +clamp(2, 3); +// Returns: 2 (範囲内にある) + +clamp(1, 5); +// Returns: 1 +``` + +NaN値は0として処理されます。 + +```typescript +import { clamp } from 'es-toolkit/compat'; + +clamp(5, NaN, 10); +// Returns: 5 (NaNが0として処理され、範囲は0〜10) + +clamp(5, 2, NaN); +// Returns: 2 (NaNが0として処理され、範囲は0〜2) +``` + +#### パラメータ + +- `number` (`number`): 制限する数値です。 +- `lower` (`number`): 最小値です。2番目のパラメータのみがある場合は最大値になります。 +- `upper` (`number`, オプション): 最大値です。 + +#### 戻り値 + +(`number`): 指定された範囲内に制限された数値を返します。 diff --git a/docs/ja/reference/compat/math/divide.md b/docs/ja/compat/reference/math/divide.md similarity index 100% rename from docs/ja/reference/compat/math/divide.md rename to docs/ja/compat/reference/math/divide.md diff --git a/docs/ja/reference/compat/math/floor.md b/docs/ja/compat/reference/math/floor.md similarity index 100% rename from docs/ja/reference/compat/math/floor.md rename to docs/ja/compat/reference/math/floor.md diff --git a/docs/ja/compat/reference/math/inRange.md b/docs/ja/compat/reference/math/inRange.md new file mode 100644 index 000000000..99a5b2caf --- /dev/null +++ b/docs/ja/compat/reference/math/inRange.md @@ -0,0 +1,101 @@ +# inRange (Lodash 互換性) + +::: warning `es-toolkit`の[inRange](../../../reference/math/inRange.md)を使用してください + +この `inRange` 関数は複雑な型変換とnull/undefined処理により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [inRange](../../../reference/math/inRange.md) を使用してください。 + +::: + +数値が指定された範囲内にあるかを確認します。 + +```typescript +const result = inRange(value, minimum, maximum); +``` + +## 使用法 + +### `inRange(value, minimum, maximum?)` + +数値が特定の範囲内にあるかを確認したい場合は `inRange` を使用してください。最小値は含まれ、最大値は含まれません。 + +```typescript +import { inRange } from 'es-toolkit/compat'; + +// 基本的な使用法 +inRange(3, 2, 4); +// Returns: true (2 ≤ 3 < 4) + +inRange(1, 2, 5); +// Returns: false (1 < 2) + +inRange(5, 2, 5); +// Returns: false (5は含まれない) + +// 範囲境界値 +inRange(2, 2, 4); +// Returns: true (最小値は含まれる) + +inRange(4, 2, 4); +// Returns: false (最大値は含まれない) +``` + +### `inRange(value, maximum)` + +2つの引数のみを提供すると、0からmaximumまでの範囲として処理されます。 + +```typescript +import { inRange } from 'es-toolkit/compat'; + +inRange(3, 5); +// Returns: true (0 ≤ 3 < 5) + +inRange(-1, 5); +// Returns: false (-1 < 0) + +inRange(0, 5); +// Returns: true (0 ≤ 0 < 5) + +inRange(5, 5); +// Returns: false (5は含まれない) +``` + +最小値が最大値より大きい場合は自動的に交換されます。 + +```typescript +import { inRange } from 'es-toolkit/compat'; + +inRange(3, 5, 2); +// Returns: true (範囲が2〜5に変更され、2 ≤ 3 < 5) + +inRange(1, 5, 2); +// Returns: false (1 < 2) +``` + +不正な値は適切に変換されます。 + +```typescript +import { inRange } from 'es-toolkit/compat'; + +// 文字列数値変換 +inRange(3, '2', '4'); +// Returns: true + +// falsy値は0として処理 +inRange(1, null, 5); +// Returns: true (nullが0として処理され、0〜5の範囲) + +inRange(3, false, 5); +// Returns: true (falseが0として処理) +``` + +#### パラメータ + +- `value` (`number`): 範囲内にあるかを確認する数値です。 +- `minimum` (`number`): 範囲の最小値です(含まれる)。`maximum`がない場合、この値が最大値になります。 +- `maximum` (`number`, オプション): 範囲の最大値です(含まれない)。 + +#### 戻り値 + +(`boolean`): 値が指定された範囲内にある場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/math/max.md b/docs/ja/compat/reference/math/max.md similarity index 100% rename from docs/ja/reference/compat/math/max.md rename to docs/ja/compat/reference/math/max.md diff --git a/docs/ja/compat/reference/math/maxBy.md b/docs/ja/compat/reference/math/maxBy.md new file mode 100644 index 000000000..453ff0acd --- /dev/null +++ b/docs/ja/compat/reference/math/maxBy.md @@ -0,0 +1,114 @@ +# maxBy (Lodash 互換性) + +::: warning es-toolkitの[maxBy](../../../reference/array/maxBy.md)を使用してください + +この `maxBy` 関数はiteratee関数処理と型変換により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [maxBy](../../../reference/array/maxBy.md) を使用してください。 + +::: + +条件に合う値の中から最大値要素を見つけます。 + +```typescript +const maxItem = maxBy(array, iteratee); +``` + +## 使用法 + +### `maxBy(array, iteratee)` + +配列から関数で計算した値が最も大きい要素を見つけます。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +// オブジェクト配列から特定のプロパティが最大の要素 +const people = [ + { name: '홍길동', age: 25 }, + { name: '김철수', age: 30 }, + { name: '이영희', age: 35 }, +]; + +maxBy(people, person => person.age); +// Returns: { name: '이영희', age: 35 } + +// プロパティ名でも可能 +maxBy(people, 'age'); +// Returns: { name: '이영희', age: 35 } +``` + +関数で値を変換して最大値を見つけます。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +maxBy(items, x => x.a); +// Returns: { a: 3 } + +const numbers = [-1, -2, -3]; +maxBy(numbers, x => Math.abs(x)); +// Returns: -3 (絶対値が最も大きい要素) +``` + +配列要素でアクセスします。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const arrays = [ + [1, 2], + [3, 4], + [0, 5], +]; +maxBy(arrays, 0); // 最初の要素が最大の配列 +// Returns: [3, 4] + +maxBy(arrays, 1); // 2番目の要素が最大の配列 +// Returns: [0, 5] +``` + +オブジェクトの特定プロパティと値が一致する場合を見つけます。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const users = [ + { name: '홍길동', age: 25, active: true }, + { name: '김철수', age: 30, active: false }, + { name: '이영희', age: 35, active: true }, +]; + +// activeがtrueの要素の中から最初のもの +maxBy(users, ['active', true]); +// Returns: { name: '홍길동', age: 25, active: true } + +// オブジェクトで条件指定 +maxBy(users, { active: true }); +// Returns: { name: '홍길동', age: 25, active: true } +``` + +空の配列はundefinedを返します。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +maxBy([], x => x.a); +// Returns: undefined + +maxBy(null); +// Returns: undefined + +maxBy(undefined); +// Returns: undefined +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 検索する配列です。 +- `iteratee` (`ValueIteratee`, オプション): 各要素に適用する関数、プロパティ名、または条件です。 + +#### 戻り値 + +(`T | undefined`): 条件に合う値が最も大きい要素を返します。空の配列の場合は `undefined` を返します。 diff --git a/docs/ja/compat/reference/math/mean.md b/docs/ja/compat/reference/math/mean.md new file mode 100644 index 000000000..a178d99a8 --- /dev/null +++ b/docs/ja/compat/reference/math/mean.md @@ -0,0 +1,76 @@ +# mean (Lodash 互換性) + +::: warning es-toolkitの[mean](../../../reference/math/mean.md)を使用してください + +この `mean` 関数は型変換とnull/undefined処理により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [mean](../../../reference/math/mean.md) を使用してください。 + +::: + +配列の平均値を計算します。 + +```typescript +const average = mean(array); +``` + +## 使用法 + +### `mean(array)` + +数値配列の平均値を計算します。 + +```typescript +import { mean } from 'es-toolkit/compat'; + +// 数値配列 +mean([1, 2, 3, 4, 5]); +// Returns: 3 + +mean([10, 20, 30]); +// Returns: 20 + +mean([1.5, 2.5, 3.5]); +// Returns: 2.5 +``` + +空の配列はNaNを返します。 + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean([]); +// Returns: NaN + +mean(null); +// Returns: NaN + +mean(undefined); +// Returns: NaN +``` + +無効な値は0として扱われ、計算に含まれます。 + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean([1, undefined, 2, null, 3]); +// Returns: 1.2 (1 + 2 + 3) / 5 = 1.2 +``` + +文字列は連結されます。 + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean(['1', '2', '3']); +// Returns: 41 (123 / 3 = 41) +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 平均を計算する数値が含まれる配列です。 + +#### 戻り値 + +(`number`): 配列の平均値を返します。空の配列の場合は `NaN` を返します。 diff --git a/docs/ja/compat/reference/math/meanBy.md b/docs/ja/compat/reference/math/meanBy.md new file mode 100644 index 000000000..5dc5b4af8 --- /dev/null +++ b/docs/ja/compat/reference/math/meanBy.md @@ -0,0 +1,103 @@ +# meanBy (Lodash 互換性) + +::: warning es-toolkitの[meanBy](../../../reference/math/meanBy.md)を使用してください + +この `meanBy` 関数はiteratee関数処理と型変換により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [meanBy](../../../reference/math/meanBy.md) を使用してください。 + +::: + +条件に合う値の平均を計算します。 + +```typescript +const average = meanBy(array, iteratee); +``` + +## 使用法 + +### `meanBy(array, iteratee)` + +配列の各要素に関数を適用した結果の平均を計算します。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +// オブジェクト配列から特定プロパティの平均 +const people = [ + { name: '홍길동', age: 25 }, + { name: '김철수', age: 30 }, + { name: '이영희', age: 35 }, +]; + +meanBy(people, person => person.age); +// Returns: 30 + +// プロパティ名でも可能 +meanBy(people, 'age'); +// Returns: 30 +``` + +関数で値を変換して平均を計算します。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const numbers = [1.5, 2.7, 3.2, 4.8]; +meanBy(numbers, x => Math.floor(x)); +// Returns: 2.5 (1 + 2 + 3 + 4) / 4 + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +meanBy(items, x => x.a); +// Returns: 2 +``` + +配列要素でアクセスします。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const arrays = [[2], [3], [1]]; +meanBy(arrays, 0); // 最初の要素の平均 +// Returns: 2 +``` + +オブジェクトの特定プロパティと値が一致する場合のみ計算します。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const users = [ + { name: '홍길동', age: 25, active: true }, + { name: '김철수', age: 30, active: false }, + { name: '이영희', age: 35, active: true }, +]; + +// activeがtrueの人のみ +meanBy(users, { active: true }); +// Returns: 0.6666666 (active が true の人の割合) +``` + +空の配列はNaNを返します。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +meanBy([], x => x.a); +// Returns: NaN + +meanBy(null); +// Returns: NaN + +meanBy(undefined); +// Returns: NaN +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 処理する配列です。 +- `iteratee` (`ValueIteratee`, オプション): 各要素に適用する関数、プロパティ名、または条件です。 + +#### 戻り値 + +(`number`): 条件に合う値の平均を返します。空の配列の場合は `NaN` を返します。 diff --git a/docs/ja/reference/compat/math/min.md b/docs/ja/compat/reference/math/min.md similarity index 100% rename from docs/ja/reference/compat/math/min.md rename to docs/ja/compat/reference/math/min.md diff --git a/docs/ja/compat/reference/math/minBy.md b/docs/ja/compat/reference/math/minBy.md new file mode 100644 index 000000000..cdb65713b --- /dev/null +++ b/docs/ja/compat/reference/math/minBy.md @@ -0,0 +1,114 @@ +# minBy (Lodash 互換性) + +::: warning es-toolkitの[minBy](../../../reference/array/minBy.md)を使用してください + +この `minBy` 関数はiteratee関数処理と型変換により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [minBy](../../../reference/array/minBy.md) を使用してください。 + +::: + +条件に合致する値の中で最小値要素を見つけます。 + +```typescript +const minItem = minBy(array, iteratee); +``` + +## 使用法 + +### `minBy(array, iteratee)` + +配列から関数で計算した値が最小の要素を見つけます。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +// オブジェクト配列から特定のプロパティが最小の要素 +const people = [ + { name: 'ホンギルドン', age: 25 }, + { name: 'キムチョルス', age: 30 }, + { name: 'イヨンヒ', age: 35 }, +]; + +minBy(people, person => person.age); +// Returns: { name: 'ホンギルドン', age: 25 } + +// プロパティ名でも可能 +minBy(people, 'age'); +// Returns: { name: 'ホンギルドン', age: 25 } +``` + +関数で値を変換して最小値を見つけます。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +minBy(items, x => x.a); +// Returns: { a: 1 } + +const numbers = [-1, -2, -3]; +minBy(numbers, x => Math.abs(x)); +// Returns: -1 (絶対値が最小の要素) +``` + +配列要素でアクセスします。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const arrays = [ + [1, 2], + [3, 4], + [0, 5], +]; +minBy(arrays, 0); // 最初の要素が最小の配列 +// Returns: [0, 5] + +minBy(arrays, 1); // 2番目の要素が最小の配列 +// Returns: [1, 2] +``` + +オブジェクトの特定プロパティと値が一致する場合を見つけます。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const users = [ + { name: 'ホンギルドン', age: 25, active: true }, + { name: 'キムチョルス', age: 30, active: false }, + { name: 'イヨンヒ', age: 35, active: true }, +]; + +// activeがtrueの要素の中で最初ではないものを見つける +minBy(users, ['active', true]); +// Returns: { name: 'キムチョルス', age: 30, active: false } + +// オブジェクトで条件を指定 +minBy(users, { active: true }); +// Returns: { name: 'キムチョルス', age: 30, active: false } +``` + +空の配列はundefinedを返します。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +minBy([], x => x.a); +// Returns: undefined + +minBy(null); +// Returns: undefined + +minBy(undefined); +// Returns: undefined +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 検索する配列です。 +- `iteratee` (`ValueIteratee`, オプション): 各要素に適用する関数、プロパティ名、または条件です。 + +#### 戻り値 + +(`T | undefined`): 条件に合致する値が最小の要素を返します。空の配列の場合は `undefined` を返します。 diff --git a/docs/ja/reference/compat/math/multiply.md b/docs/ja/compat/reference/math/multiply.md similarity index 100% rename from docs/ja/reference/compat/math/multiply.md rename to docs/ja/compat/reference/math/multiply.md diff --git a/docs/ja/reference/compat/math/parseInt.md b/docs/ja/compat/reference/math/parseInt.md similarity index 100% rename from docs/ja/reference/compat/math/parseInt.md rename to docs/ja/compat/reference/math/parseInt.md diff --git a/docs/ja/reference/compat/math/random.md b/docs/ja/compat/reference/math/random.md similarity index 100% rename from docs/ja/reference/compat/math/random.md rename to docs/ja/compat/reference/math/random.md diff --git a/docs/ja/compat/reference/math/range.md b/docs/ja/compat/reference/math/range.md new file mode 100644 index 000000000..32a6a4aa3 --- /dev/null +++ b/docs/ja/compat/reference/math/range.md @@ -0,0 +1,99 @@ +# range (Lodash 互換性) + +::: warning es-toolkitの[range](../../../reference/math/range.md)を使用してください + +この `range` 関数は複雑な引数処理と型変換により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [range](../../../reference/math/range.md) を使用してください。 + +::: + +数値範囲の配列を作成します。 + +```typescript +const numbers = range(start, end, step); +``` + +## 使用法 + +### `range(end)` + +0からendまで1ずつ増加する配列を作成します。 + +```typescript +import { range } from 'es-toolkit/compat'; + +range(4); +// Returns: [0, 1, 2, 3] + +range(0); +// Returns: [] + +range(-4); +// Returns: [0, -1, -2, -3] +``` + +### `range(start, end)` + +startからendまで1ずつ増加する配列を作成します。 + +```typescript +import { range } from 'es-toolkit/compat'; + +range(1, 5); +// Returns: [1, 2, 3, 4] + +range(5, 1); +// Returns: [5, 4, 3, 2] (自動的に-1ずつ減少) + +range(-2, 3); +// Returns: [-2, -1, 0, 1, 2] +``` + +### `range(start, end, step)` + +startからendまでstepずつ増加する配列を作成します。 + +```typescript +import { range } from 'es-toolkit/compat'; + +range(0, 20, 5); +// Returns: [0, 5, 10, 15] + +range(0, -4, -1); +// Returns: [0, -1, -2, -3] + +range(1, 4, 0); +// Returns: [1, 1, 1] +``` + +小数のstepも可能です。 + +```typescript +import { range } from 'es-toolkit/compat'; + +range(0, 1, 0.2); +// Returns: [0, 0.2, 0.4, 0.6, 0.8] + +range(1, 0, -0.25); +// Returns: [1, 0.75, 0.5, 0.25] +``` + +iterateeとして使用する場合はguardオブジェクトで処理されます。 + +```typescript +import { range } from 'es-toolkit/compat'; + +[1, 2, 3].map(range); +// Returns: [[0], [0, 1], [0, 1, 2]] +``` + +#### パラメータ + +- `start` (`number`): 範囲の開始値です(含まれます)。`end`がない場合、この値がendになります。 +- `end` (`number`, オプション): 範囲の終了値です(含まれません)。 +- `step` (`number`, オプション): 増加幅です。デフォルトは1または-1です。 + +#### 戻り値 + +(`number[]`): 指定された範囲の数値配列を返します。 diff --git a/docs/ja/compat/reference/math/rangeRight.md b/docs/ja/compat/reference/math/rangeRight.md new file mode 100644 index 000000000..1db217bc1 --- /dev/null +++ b/docs/ja/compat/reference/math/rangeRight.md @@ -0,0 +1,99 @@ +# rangeRight (Lodash 互換性) + +::: warning es-toolkitの[rangeRight](../../../reference/math/rangeRight.md)を使用してください + +この `rangeRight` 関数は複雑な引数処理と型変換により動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [rangeRight](../../../reference/math/rangeRight.md) を使用してください。 + +::: + +数値範囲の配列を逆順で作成します。 + +```typescript +const numbers = rangeRight(start, end, step); +``` + +## 使用法 + +### `rangeRight(end)` + +0からendまで1ずつ増加させた後、逆順で配列を作成します。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(4); +// Returns: [3, 2, 1, 0] + +rangeRight(0); +// Returns: [] + +rangeRight(-4); +// Returns: [-3, -2, -1, 0] +``` + +### `rangeRight(start, end)` + +startからendまで1ずつ増加させた後、逆順で配列を作成します。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(1, 5); +// Returns: [4, 3, 2, 1] + +rangeRight(5, 1); +// Returns: [2, 3, 4, 5] (自動的に-1ずつ減少してから逆順) + +rangeRight(-2, 3); +// Returns: [2, 1, 0, -1, -2] +``` + +### `rangeRight(start, end, step)` + +startからendまでstepずつ増加させた後、逆順で配列を作成します。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(0, 8, 2); +// Returns: [6, 4, 2, 0] + +rangeRight(0, -4, -1); +// Returns: [-3, -2, -1, 0] + +rangeRight(1, 4, 0); +// Returns: [1, 1, 1] +``` + +小数のstepも可能です。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(0, 1, 0.2); +// Returns: [0.8, 0.6, 0.4, 0.2, 0] + +rangeRight(1, 0, -0.25); +// Returns: [0.25, 0.5, 0.75, 1] +``` + +iterateeとして使用する場合はguardオブジェクトで処理されます。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +[1, 2, 3].map(rangeRight); +// Returns: [[0], [1, 0], [2, 1, 0]] +``` + +#### パラメータ + +- `start` (`number`): 範囲の開始値です(含まれます)。`end`がない場合、この値がendになります。 +- `end` (`number`, オプション): 範囲の終了値です(含まれません)。 +- `step` (`number`, オプション): 増加幅です。デフォルトは1または-1です。 + +#### 戻り値 + +(`number[]`): 指定された範囲の数値配列を逆順で返します。 diff --git a/docs/ja/reference/compat/math/round.md b/docs/ja/compat/reference/math/round.md similarity index 100% rename from docs/ja/reference/compat/math/round.md rename to docs/ja/compat/reference/math/round.md diff --git a/docs/ja/reference/compat/math/subtract.md b/docs/ja/compat/reference/math/subtract.md similarity index 100% rename from docs/ja/reference/compat/math/subtract.md rename to docs/ja/compat/reference/math/subtract.md diff --git a/docs/ja/compat/reference/math/sum.md b/docs/ja/compat/reference/math/sum.md new file mode 100644 index 000000000..14a9227cb --- /dev/null +++ b/docs/ja/compat/reference/math/sum.md @@ -0,0 +1,73 @@ +# sum (Lodash 互換性) + +::: warning es-toolkitの[sum](../../../reference/math/sum.md)を使用してください + +この`sum`関数は型変換とnull/undefined処理により動作が遅いです。 + +代わりにより高速で現代的な`es-toolkit`の[sum](../../../reference/math/sum.md)を使用してください。 + +::: + +配列のすべての値を足します。 + +```typescript +const total = sum(array); +``` + +## 使用法 + +### `sum(array)` + +配列内のすべての数値を足して合計を求めます。 + +```typescript +import { sum } from 'es-toolkit/compat'; + +// 数値配列 +sum([1, 2, 3]); +// Returns: 6 + +sum([1.5, 2.5, 3]); +// Returns: 7 + +// 空配列 +sum([]); +// Returns: 0 +``` + +BigIntと文字列も処理します。 + +```typescript +import { sum } from 'es-toolkit/compat'; + +// BigInt配列 +sum([1n, 2n, 3n]); +// Returns: 6n + +// 文字列配列(連結される) +sum(['1', '2']); +// Returns: '12' +``` + +無効な値は無視します。 + +```typescript +import { sum } from 'es-toolkit/compat'; + +sum([1, undefined, 2]); +// Returns: 3 (undefinedを無視) + +sum(null); +// Returns: 0 + +sum(undefined); +// Returns: 0 +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 足す値が含まれる配列です。 + +#### 戻り値 + +(`number`): すべての値を足した合計を返します。 diff --git a/docs/ja/compat/reference/math/sumBy.md b/docs/ja/compat/reference/math/sumBy.md new file mode 100644 index 000000000..5e2ac19f2 --- /dev/null +++ b/docs/ja/compat/reference/math/sumBy.md @@ -0,0 +1,103 @@ +# sumBy (Lodash 互換性) + +::: warning es-toolkitの[sumBy](../../../reference/math/sumBy.md)を使用してください + +この`sumBy`関数はiteratee関数処理と型変換により動作が遅いです。 + +代わりにより高速で現代的な`es-toolkit`の[sumBy](../../../reference/math/sumBy.md)を使用してください。 + +::: + +条件に合う値を足します。 + +```typescript +const total = sumBy(array, iteratee); +``` + +## 使用法 + +### `sumBy(array, iteratee)` + +配列の各要素に関数を適用した結果を足します。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +// 数値配列 +sumBy([1, 2, 3], value => value); +// Returns: 6 + +sumBy([1.5, 2.5, 3.5], value => Math.floor(value)); +// Returns: 6 (1 + 2 + 3) + +// 空配列 +sumBy([], value => value); +// Returns: 0 +``` + +### `sumBy(array)` + +関数を渡さない場合、配列の値をそのまま足します。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +sumBy([1, 2, 3]); +// Returns: 6 + +sumBy([1n, 2n, 3n]); +// Returns: 6n +``` + +オブジェクト配列から特定のプロパティを足します。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +const people = [ + { name: '田中太郎', age: 25 }, + { name: '佐藤次郎', age: 30 }, + { name: '鈴木花子', age: 35 }, +]; + +sumBy(people, person => person.age); +// Returns: 90 + +// プロパティ名でも可能 +sumBy(people, 'age'); +// Returns: 90 +``` + +文字列も連結します。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +const items = [{ a: '1' }, { a: '2' }]; +sumBy(items, obj => obj.a); +// Returns: '12' +``` + +無効な値は無視します。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +sumBy([1, undefined, 2], value => value); +// Returns: 3 (undefinedを無視) + +sumBy(null); +// Returns: 0 + +sumBy(undefined); +// Returns: 0 +``` + +#### パラメータ + +- `array` (`ArrayLike | null | undefined`): 処理する配列です。 +- `iteratee` (`((value: T) => number) | string`, オプション): 各要素に適用する関数またはプロパティ名です。 + +#### 戻り値 + +(`number`): 条件に合う値を足した合計を返します。 diff --git a/docs/ja/reference/compat/object/assign.md b/docs/ja/compat/reference/object/assign.md similarity index 100% rename from docs/ja/reference/compat/object/assign.md rename to docs/ja/compat/reference/object/assign.md diff --git a/docs/ja/reference/compat/object/assignIn.md b/docs/ja/compat/reference/object/assignIn.md similarity index 100% rename from docs/ja/reference/compat/object/assignIn.md rename to docs/ja/compat/reference/object/assignIn.md diff --git a/docs/ja/reference/compat/object/assignInWith.md b/docs/ja/compat/reference/object/assignInWith.md similarity index 100% rename from docs/ja/reference/compat/object/assignInWith.md rename to docs/ja/compat/reference/object/assignInWith.md diff --git a/docs/ja/reference/compat/object/assignWith.md b/docs/ja/compat/reference/object/assignWith.md similarity index 100% rename from docs/ja/reference/compat/object/assignWith.md rename to docs/ja/compat/reference/object/assignWith.md diff --git a/docs/ja/reference/compat/object/at.md b/docs/ja/compat/reference/object/at.md similarity index 100% rename from docs/ja/reference/compat/object/at.md rename to docs/ja/compat/reference/object/at.md diff --git a/docs/ja/compat/reference/object/clone.md b/docs/ja/compat/reference/object/clone.md new file mode 100644 index 000000000..43163cd9a --- /dev/null +++ b/docs/ja/compat/reference/object/clone.md @@ -0,0 +1,89 @@ +# clone (Lodash 互換性) + +::: warning `es-toolkit`の`clone`を使用してください + +この `clone` 関数は、特殊なオブジェクトタイプを処理する複雑なロジックにより相対的に遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [clone](../../../reference/object/clone.md) を使用してください。 + +::: + +オブジェクトの浅いコピーを作成します。 + +```typescript +const cloned = clone(value); +``` + +## 使用法 + +### `clone(value)` + +値の浅いコピーを作成したい場合は、`clone`を使用してください。さまざまなタイプのオブジェクトと原始値をコピーできます。 + +```typescript +import { clone } from 'es-toolkit/compat'; + +// 原始値のコピー +const num = 42; +const clonedNum = clone(num); +// Returns: 42 (同じ値) + +// 配列のコピー +const arr = [1, 2, 3]; +const clonedArr = clone(arr); +// Returns: [1, 2, 3] (新しい配列インスタンス) + +// オブジェクトのコピー +const obj = { a: 1, b: 'hello' }; +const clonedObj = clone(obj); +// Returns: { a: 1, b: 'hello' } (新しいオブジェクトインスタンス) + +// Dateオブジェクトのコピー +const date = new Date('2023-01-01'); +const clonedDate = clone(date); +// Returns: new Date('2023-01-01') (新しいDateインスタンス) + +// 正規表現のコピー +const regex = /hello/gi; +regex.lastIndex = 3; +const clonedRegex = clone(regex); +// Returns: /hello/gi with lastIndex = 3 + +// Mapのコピー +const map = new Map([ + ['a', 1], + ['b', 2], +]); +const clonedMap = clone(map); +// Returns: new Map([['a', 1], ['b', 2]]) + +// Setのコピー +const set = new Set([1, 2, 3]); +const clonedSet = clone(set); +// Returns: new Set([1, 2, 3]) +``` + +ネストされたオブジェクトは浅いコピーのみが行われます。 + +```typescript +import { clone } from 'es-toolkit/compat'; + +const nested = { + a: 1, + b: { + c: 2, + }, +}; +const clonedNested = clone(nested); + +console.log(clonedNested !== nested); // true (異なるオブジェクト) +console.log(clonedNested.b === nested.b); // true (ネストされたオブジェクトは同じ参照) +``` + +#### パラメータ + +- `value` (`T`): コピーする値です。 + +#### 戻り値 + +(`T`): コピーされた値を返します。 diff --git a/docs/ja/compat/reference/object/cloneDeep.md b/docs/ja/compat/reference/object/cloneDeep.md new file mode 100644 index 000000000..19128c31a --- /dev/null +++ b/docs/ja/compat/reference/object/cloneDeep.md @@ -0,0 +1,88 @@ +# cloneDeep (Lodash 互換性) + +::: warning `es-toolkit`の`cloneDeep`を使用してください + +この `cloneDeep` 関数は、特殊なオブジェクトタイプを処理する複雑なロジックにより相対的に遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [cloneDeep](../../../reference/object/cloneDeep.md) を使用してください。 + +::: + +オブジェクトの深いコピーを作成します。 + +```typescript +const cloned = cloneDeep(value); +``` + +## 使用法 + +### `cloneDeep(value)` + +値の深いコピーを作成したい場合は、`cloneDeep`を使用してください。ネストされたオブジェクトと配列を完全に新しいインスタンスとしてコピーします。 + +```typescript +import { cloneDeep } from 'es-toolkit/compat'; + +// 原始値のコピー +const num = 42; +const clonedNum = cloneDeep(num); +// Returns: 42 (同じ値) + +// 配列の深いコピー +const arr = [1, [2, 3], { a: 4 }]; +const clonedArr = cloneDeep(arr); +clonedArr[1][0] = 99; +console.log(arr[1][0]); // 2 (元の値は変更されない) +console.log(clonedArr[1][0]); // 99 + +// オブジェクトの深いコピー +const obj = { + a: 1, + b: { + c: 2, + d: { + e: 3, + }, + }, +}; +const clonedObj = cloneDeep(obj); +clonedObj.b.d.e = 99; +console.log(obj.b.d.e); // 3 (元の値は変更されない) +console.log(clonedObj.b.d.e); // 99 + +// Dateオブジェクトの深いコピー +const date = new Date('2023-01-01'); +const clonedDate = cloneDeep(date); +// Returns: new Date('2023-01-01') (新しいDateインスタンス) + +// 複雑なネスト構造 +const complex = { + arr: [1, { nested: true }], + map: new Map([['key', { value: 1 }]]), + set: new Set([{ item: 1 }]), + date: new Date(), +}; +const clonedComplex = cloneDeep(complex); +// すべてのネストされたオブジェクトが完全に新しいインスタンスとしてコピーされる +``` + +循環参照も正しく処理されます。 + +```typescript +import { cloneDeep } from 'es-toolkit/compat'; + +const obj = { a: 1 }; +obj.self = obj; // 循環参照 + +const cloned = cloneDeep(obj); +console.log(cloned !== obj); // true +console.log(cloned.self === cloned); // true (循環参照が保持される) +``` + +#### パラメータ + +- `value` (`T`): 深くコピーする値です。 + +#### 戻り値 + +(`T`): 深くコピーされた値を返します。 diff --git a/docs/ja/reference/compat/object/cloneDeepWith.md b/docs/ja/compat/reference/object/cloneDeepWith.md similarity index 100% rename from docs/ja/reference/compat/object/cloneDeepWith.md rename to docs/ja/compat/reference/object/cloneDeepWith.md diff --git a/docs/ja/reference/compat/object/cloneWith.md b/docs/ja/compat/reference/object/cloneWith.md similarity index 100% rename from docs/ja/reference/compat/object/cloneWith.md rename to docs/ja/compat/reference/object/cloneWith.md diff --git a/docs/ja/reference/compat/object/create.md b/docs/ja/compat/reference/object/create.md similarity index 100% rename from docs/ja/reference/compat/object/create.md rename to docs/ja/compat/reference/object/create.md diff --git a/docs/ja/reference/compat/object/defaults.md b/docs/ja/compat/reference/object/defaults.md similarity index 100% rename from docs/ja/reference/compat/object/defaults.md rename to docs/ja/compat/reference/object/defaults.md diff --git a/docs/ja/reference/compat/object/defaultsDeep.md b/docs/ja/compat/reference/object/defaultsDeep.md similarity index 100% rename from docs/ja/reference/compat/object/defaultsDeep.md rename to docs/ja/compat/reference/object/defaultsDeep.md diff --git a/docs/ja/reference/compat/object/extend.md b/docs/ja/compat/reference/object/extend.md similarity index 100% rename from docs/ja/reference/compat/object/extend.md rename to docs/ja/compat/reference/object/extend.md diff --git a/docs/ja/reference/compat/object/extendWith.md b/docs/ja/compat/reference/object/extendWith.md similarity index 100% rename from docs/ja/reference/compat/object/extendWith.md rename to docs/ja/compat/reference/object/extendWith.md diff --git a/docs/ja/compat/reference/object/findKey.md b/docs/ja/compat/reference/object/findKey.md new file mode 100644 index 000000000..3d5d009bf --- /dev/null +++ b/docs/ja/compat/reference/object/findKey.md @@ -0,0 +1,61 @@ +# findKey (Lodash 互換性) + +::: warning `es-toolkit`の`findKey`を使用してください + +この`findKey`関数は、さまざまな条件タイプの処理と互換性ロジックにより、複雑に動作します。 + +代わりに、より高速で現代的な`es-toolkit`の[findKey](../../../reference/object/findKey.md)を使用してください。 + +::: + +条件に一致する最初の要素のキーを検索します。 + +```typescript +const key = findKey(obj, predicate); +``` + +## 使用法 + +### `findKey(obj, predicate)` + +オブジェクト内で条件に一致する最初の要素のキーを検索するには`findKey`を使用してください。関数、オブジェクト、配列、文字列など、さまざまな形式の条件を使用できます。 + +```typescript +import { findKey } from 'es-toolkit/compat'; + +// 関数条件でキーを検索 +const users = { + alice: { age: 25, active: true }, + bob: { age: 30, active: false }, + charlie: { age: 35, active: true }, +}; + +findKey(users, user => user.age > 30); +// 戻り値: 'charlie' + +// オブジェクト条件でキーを検索 +findKey(users, { active: false }); +// 戻り値: 'bob' + +// プロパティパスでキーを検索 +findKey(users, 'active'); +// 戻り値: 'alice' +``` + +条件に一致する要素がない場合は`undefined`を返します。 + +```typescript +import { findKey } from 'es-toolkit/compat'; + +findKey({ a: 1, b: 2 }, value => value > 5); +// 戻り値: undefined +``` + +#### パラメータ + +- `obj` (`T | null | undefined`): 検索するオブジェクトです。 +- `predicate` (`ObjectIteratee`, オプション): 各要素に適用する条件です。関数、オブジェクト、配列、文字列を指定できます。 + +#### 戻り値 + +(`string | undefined`): 条件に一致する最初の要素のキーを返します。一致するものがない場合は`undefined`を返します。 diff --git a/docs/ja/reference/compat/object/findLastKey.md b/docs/ja/compat/reference/object/findLastKey.md similarity index 100% rename from docs/ja/reference/compat/object/findLastKey.md rename to docs/ja/compat/reference/object/findLastKey.md diff --git a/docs/ja/reference/compat/object/forIn.md b/docs/ja/compat/reference/object/forIn.md similarity index 100% rename from docs/ja/reference/compat/object/forIn.md rename to docs/ja/compat/reference/object/forIn.md diff --git a/docs/ja/reference/compat/object/forInRight.md b/docs/ja/compat/reference/object/forInRight.md similarity index 100% rename from docs/ja/reference/compat/object/forInRight.md rename to docs/ja/compat/reference/object/forInRight.md diff --git a/docs/ja/reference/compat/object/forOwn.md b/docs/ja/compat/reference/object/forOwn.md similarity index 100% rename from docs/ja/reference/compat/object/forOwn.md rename to docs/ja/compat/reference/object/forOwn.md diff --git a/docs/ja/reference/compat/object/forOwnRight.md b/docs/ja/compat/reference/object/forOwnRight.md similarity index 100% rename from docs/ja/reference/compat/object/forOwnRight.md rename to docs/ja/compat/reference/object/forOwnRight.md diff --git a/docs/ja/reference/compat/object/fromPairs.md b/docs/ja/compat/reference/object/fromPairs.md similarity index 100% rename from docs/ja/reference/compat/object/fromPairs.md rename to docs/ja/compat/reference/object/fromPairs.md diff --git a/docs/ja/reference/compat/object/functions.md b/docs/ja/compat/reference/object/functions.md similarity index 100% rename from docs/ja/reference/compat/object/functions.md rename to docs/ja/compat/reference/object/functions.md diff --git a/docs/ja/reference/compat/object/functionsIn.md b/docs/ja/compat/reference/object/functionsIn.md similarity index 100% rename from docs/ja/reference/compat/object/functionsIn.md rename to docs/ja/compat/reference/object/functionsIn.md diff --git a/docs/ja/reference/compat/object/get.md b/docs/ja/compat/reference/object/get.md similarity index 100% rename from docs/ja/reference/compat/object/get.md rename to docs/ja/compat/reference/object/get.md diff --git a/docs/ja/reference/compat/object/has.md b/docs/ja/compat/reference/object/has.md similarity index 100% rename from docs/ja/reference/compat/object/has.md rename to docs/ja/compat/reference/object/has.md diff --git a/docs/ja/reference/compat/object/hasIn.md b/docs/ja/compat/reference/object/hasIn.md similarity index 100% rename from docs/ja/reference/compat/object/hasIn.md rename to docs/ja/compat/reference/object/hasIn.md diff --git a/docs/ja/compat/reference/object/invert.md b/docs/ja/compat/reference/object/invert.md new file mode 100644 index 000000000..20733f373 --- /dev/null +++ b/docs/ja/compat/reference/object/invert.md @@ -0,0 +1,60 @@ +# invert (Lodash 互換性) + +::: warning `es-toolkit`の`invert`を使用してください + +この`invert`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[`invert`](../../../reference/object/invert.md)を使用してください。 + +::: + +オブジェクトのキーと値を入れ替えます。 + +```typescript +const inverted = invert(object); +``` + +## 使用法 + +### `invert(object)` + +オブジェクトのキーと値を入れ替えたい場合は`invert`を使用してください。元のオブジェクトのキーは新しいオブジェクトの値になり、元のオブジェクトの値は新しいオブジェクトのキーになります。 + +```typescript +import { invert } from 'es-toolkit/compat'; + +// 基本的なキー・値の入れ替え +const object = { a: 1, b: 2, c: 3 }; +invert(object); +// => { '1': 'a', '2': 'b', '3': 'c' } + +// 文字列値の入れ替え +const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' }; +invert(colors); +// => { '#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue' } + +// 混合キーと値のタイプ +const mixed = { a: 1, 2: 'b', c: 3, 4: 'd' }; +invert(mixed); +// => { '1': 'a', 'b': '2', '3': 'c', 'd': '4' } +``` + +重複した値がある場合、最後のキーが使用されます。 + +```typescript +import { invert } from 'es-toolkit/compat'; + +// 重複した値がある場合 +const object = { a: 1, b: 1, c: 2 }; +invert(object); +// => { '1': 'b', '2': 'c' } +// 'a'は上書きされて失われます +``` + +#### パラメータ + +- `object` (`object`): 入れ替えるオブジェクトです。 + +#### 戻り値 + +(`Record`): キーと値が入れ替わった新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/invertBy.md b/docs/ja/compat/reference/object/invertBy.md similarity index 100% rename from docs/ja/reference/compat/object/invertBy.md rename to docs/ja/compat/reference/object/invertBy.md diff --git a/docs/ja/reference/compat/object/keys.md b/docs/ja/compat/reference/object/keys.md similarity index 100% rename from docs/ja/reference/compat/object/keys.md rename to docs/ja/compat/reference/object/keys.md diff --git a/docs/ja/reference/compat/object/keysIn.md b/docs/ja/compat/reference/object/keysIn.md similarity index 100% rename from docs/ja/reference/compat/object/keysIn.md rename to docs/ja/compat/reference/object/keysIn.md diff --git a/docs/ja/compat/reference/object/mapKeys.md b/docs/ja/compat/reference/object/mapKeys.md new file mode 100644 index 000000000..172fc5082 --- /dev/null +++ b/docs/ja/compat/reference/object/mapKeys.md @@ -0,0 +1,63 @@ +# mapKeys (Lodash 互換性) + +::: warning `es-toolkit`の`mapKeys`を使用してください + +この `mapKeys` 関数は、`null`や`undefined`の処理、`iteratee`変換過程により相対的に遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[`mapKeys`](../../../reference/object/mapKeys.md)を使用してください。 + +::: + +値をそのままにしてキーを変換し、新しいオブジェクトを作成します。 + +```typescript +const result = mapKeys(obj, iteratee); +``` + +## 使用法 + +### `mapKeys(object, iteratee)` + +`iteratee`関数を使用してオブジェクト内の各キーを変換し、新しいオブジェクトを作成します。値は変更されず、キーのみが変更されます。オブジェクトのキーを変換または正規化する際に便利です。 + +```typescript +import { mapKeys } from 'es-toolkit/compat'; + +// キーに接頭辞を追加 +const obj = { a: 1, b: 2, c: 3 }; +const result = mapKeys(obj, (value, key) => 'prefix_' + key); +// 結果: { prefix_a: 1, prefix_b: 2, prefix_c: 3 } + +// キーを大文字に変換 +const data = { name: 'John', age: 30 }; +const uppercased = mapKeys(data, (value, key) => key.toUpperCase()); +// 結果: { NAME: 'John', AGE: 30 } + +// 配列のインデックスをキーに変換 +const arr = ['apple', 'banana', 'orange']; +const indexed = mapKeys(arr, (value, index) => `item_${index}`); +// 結果: { item_0: 'apple', item_1: 'banana', item_2: 'orange' } + +// キーと値を組み合わせて新しいキーを生成 +const scores = { math: 90, science: 85, english: 92 }; +const detailed = mapKeys(scores, (value, key) => `${key}_score_${value}`); +// 結果: { math_score_90: 90, science_score_85: 85, english_score_92: 92 } +``` + +`null`または`undefined`は空のオブジェクトとして処理されます。 + +```typescript +import { mapKeys } from 'es-toolkit/compat'; + +mapKeys(null, iteratee); // {} +mapKeys(undefined, iteratee); // {} +``` + +#### パラメータ + +- `object` (`ArrayLike | T | null | undefined`): キーを変換するオブジェクトまたは配列です。 +- `iteratee` (`ListIteratee | ObjectIteratee`, オプション): 各キーを変換する関数です。デフォルトは`identity`関数です。 + +#### 戻り値 + +(`Record | Record`): 変換されたキーを持つ新しいオブジェクトを返します。 diff --git a/docs/ja/compat/reference/object/mapValues.md b/docs/ja/compat/reference/object/mapValues.md new file mode 100644 index 000000000..46b0bd979 --- /dev/null +++ b/docs/ja/compat/reference/object/mapValues.md @@ -0,0 +1,71 @@ +# mapValues (Lodash 互換性) + +::: warning `es-toolkit`の`mapValues`を使用してください + +この `mapValues` 関数は、`null`や`undefined`の処理、`iteratee`変換過程により相対的に遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[`mapValues`](../../../reference/object/mapValues.md)を使用してください。 + +::: + +キーをそのままにして値を変換し、新しいオブジェクトを作成します。 + +```typescript +const result = mapValues(obj, iteratee); +``` + +## 使用法 + +### `mapValues(object, iteratee)` + +`iteratee`関数を使用してオブジェクト内の各値を変換し、新しいオブジェクトを作成します。キーは変更されず、値のみが変更されます。文字列、配列、オブジェクトすべてを処理できます。データを変換または計算する際に便利です。 + +```typescript +import { mapValues } from 'es-toolkit/compat'; + +// オブジェクトの値を変換 +const obj = { a: 1, b: 2, c: 3 }; +const doubled = mapValues(obj, value => value * 2); +// 結果: { a: 2, b: 4, c: 6 } + +// 文字列を大文字に変換 +const names = { first: 'john', last: 'doe' }; +const uppercased = mapValues(names, value => value.toUpperCase()); +// 結果: { first: 'JOHN', last: 'DOE' } + +// 文字列の各文字を変換 +const str = 'abc'; +const charMap = mapValues(str, char => char.toUpperCase()); +// 結果: { '0': 'A', '1': 'B', '2': 'C' } + +// 配列をオブジェクトに変換 +const arr = [10, 20, 30]; +const arrMap = mapValues(arr, (value, index) => value + index); +// 結果: { '0': 10, '1': 21, '2': 32 } + +// プロパティパスで値を抽出 +const users = { + user1: { profile: { name: 'Alice' } }, + user2: { profile: { name: 'Bob' } }, +}; +const userNames = mapValues(users, 'profile.name'); +// 結果: { user1: 'Alice', user2: 'Bob' } +``` + +`null`または`undefined`は空のオブジェクトとして処理されます。 + +```typescript +import { mapValues } from 'es-toolkit/compat'; + +mapValues(null, iteratee); // {} +mapValues(undefined, iteratee); // {} +``` + +#### パラメータ + +- `object` (`string | T[] | T | null | undefined`): 値を変換するオブジェクト、配列、または文字列です。 +- `iteratee` (`ValueIteratee`, オプション): 各値を変換する関数、プロパティパス、またはマッチングオブジェクトです。デフォルトは`identity`関数です。 + +#### 戻り値 + +(`Record | { [P in keyof T]: U } | Record | Record | Partial`): 変換された値を持つ新しいオブジェクトを返します。 diff --git a/docs/ja/compat/reference/object/merge.md b/docs/ja/compat/reference/object/merge.md new file mode 100644 index 000000000..2915f1434 --- /dev/null +++ b/docs/ja/compat/reference/object/merge.md @@ -0,0 +1,82 @@ +# merge (Lodash 互換性) + +::: warning `es-toolkit`の`merge`を使用してください + +この `merge` 関数は、内部的に複雑な `mergeWith` 関数を呼び出すため相対的に遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[`merge`](../../../reference/object/merge.md)を使用してください。 + +::: + +複数のオブジェクトを深くマージして1つのオブジェクトにします。 + +```typescript +const result = merge(target, ...sources); +``` + +## 使用法 + +### `merge(object, ...sources)` + +ターゲットオブジェクトに1つ以上のソースオブジェクトを深くマージします。ネストされたオブジェクトと配列は再帰的にマージされます。ソースオブジェクトのプロパティが`undefined`の場合、ターゲットオブジェクトの既存の値は上書きされません。オブジェクト設定のマージやデフォルト値の適用に便利です。 + +```typescript +import { merge } from 'es-toolkit/compat'; + +// 基本的なオブジェクトのマージ +const target = { a: 1, b: { x: 1, y: 2 } }; +const source = { b: { y: 3, z: 4 }, c: 5 }; +const result = merge(target, source); +// 結果: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } + +// 配列のマージ +const obj1 = { arr: [1, 2] }; +const obj2 = { arr: [3, 4] }; +const merged = merge(obj1, obj2); +// 結果: { arr: [3, 4] } (配列は置き換えられる) + +// 複数のオブジェクトをマージ +const base = { a: 1 }; +const ext1 = { b: 2 }; +const ext2 = { c: 3 }; +const ext3 = { d: 4 }; +const combined = merge(base, ext1, ext2, ext3); +// 結果: { a: 1, b: 2, c: 3, d: 4 } + +// ネストされたオブジェクトのマージ +const config = { + api: { url: 'https://api.example.com', timeout: 5000 }, + features: { auth: true }, +}; +const overrides = { + api: { timeout: 10000, retries: 3 }, + features: { analytics: true }, +}; +const finalConfig = merge(config, overrides); +// 結果: { +// api: { url: 'https://api.example.com', timeout: 10000, retries: 3 }, +// features: { auth: true, analytics: true } +// } +``` + +ターゲットオブジェクトは変更されるため、元を保持したい場合は空のオブジェクトを使用してください。 + +```typescript +import { merge } from 'es-toolkit/compat'; + +const original = { a: 1, b: { x: 1 } }; +const source = { b: { y: 2 } }; + +// 元を保持 +const result = merge({}, original, source); +// original は変更されない +``` + +#### パラメータ + +- `object` (`any`): マージ先となるターゲットオブジェクトです。このオブジェクトは変更されます。 +- `...sources` (`any[]`): マージするソースオブジェクトです。 + +#### 戻り値 + +(`any`): マージされたターゲットオブジェクトを返します。 diff --git a/docs/ja/compat/reference/object/mergeWith.md b/docs/ja/compat/reference/object/mergeWith.md new file mode 100644 index 000000000..2aec630e0 --- /dev/null +++ b/docs/ja/compat/reference/object/mergeWith.md @@ -0,0 +1,94 @@ +# mergeWith (Lodash 互換性) + +::: warning `es-toolkit`の`mergeWith`を使用してください + +この `mergeWith` 関数は、複雑な型チェック、循環参照処理、特殊オブジェクト処理により相対的に遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[`mergeWith`](../../../reference/object/mergeWith.md)を使用してください。 + +::: + +カスタマイザー関数でマージ方法を制御しながら、複数のオブジェクトを深くマージします。 + +```typescript +const result = mergeWith(target, ...sources, customizer); +``` + +## 使用法 + +### `mergeWith(object, ...sources, customizer)` + +ターゲットオブジェクトに1つ以上のソースオブジェクトを深くマージしますが、カスタマイザー関数でマージ方法を制御します。カスタマイザー関数が`undefined`を返す場合、デフォルトのマージロジックが使用されます。配列の連結や特別なマージルールが必要な場合に便利です。 + +```typescript +import { mergeWith } from 'es-toolkit/compat'; + +// 数値を加算 +const obj1 = { a: 1, b: 2 }; +const obj2 = { b: 3, c: 4 }; +const result = mergeWith(obj1, obj2, (objValue, srcValue) => { + if (typeof objValue === 'number' && typeof srcValue === 'number') { + return objValue + srcValue; + } +}); +// 結果: { a: 1, b: 5, c: 4 } + +// 配列を連結 +const arr1 = { items: [1, 2] }; +const arr2 = { items: [3, 4] }; +const merged = mergeWith(arr1, arr2, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return objValue.concat(srcValue); + } +}); +// 結果: { items: [1, 2, 3, 4] } + +// 文字列を連結 +const str1 = { message: 'Hello' }; +const str2 = { message: 'World' }; +const combined = mergeWith(str1, str2, (objValue, srcValue, key) => { + if (key === 'message' && typeof objValue === 'string') { + return objValue + ' ' + srcValue; + } +}); +// 結果: { message: 'Hello World' } + +// 複数のソースオブジェクトとカスタマイザー +const base = { scores: [80] }; +const quiz1 = { scores: [90] }; +const quiz2 = { scores: [85] }; +const final = mergeWith(base, quiz1, quiz2, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return objValue.concat(srcValue); + } +}); +// 結果: { scores: [80, 90, 85] } +``` + +カスタマイザー関数は様々なパラメータを受け取ります。 + +```typescript +import { mergeWith } from 'es-toolkit/compat'; + +const customizer = (objValue, srcValue, key, object, source, stack) => { + console.log('マージ中:', key, objValue, '->', srcValue); + + // 特定のキーに対してのみカスタマイズ + if (key === 'specialField') { + return `${objValue}_${srcValue}`; + } + + // undefinedを返すとデフォルトのマージロジックを使用 + return undefined; +}; +``` + +#### パラメータ + +- `object` (`any`): マージ先となるターゲットオブジェクトです。このオブジェクトは変更されます。 +- `...sources` (`any[]`): マージするソースオブジェクトです。 +- `customizer` (`MergeWithCustomizer`): 値の割り当てをカスタマイズする関数です。形式: `(objValue, srcValue, key, object, source, stack) => any`。 + +#### 戻り値 + +(`any`): マージされたターゲットオブジェクトを返します。 diff --git a/docs/ja/compat/reference/object/omit.md b/docs/ja/compat/reference/object/omit.md new file mode 100644 index 000000000..33544cf99 --- /dev/null +++ b/docs/ja/compat/reference/object/omit.md @@ -0,0 +1,82 @@ +# omit (Lodash 互換性) + +::: warning `es-toolkit`の`omit`を使用してください + +この `omit` 関数は、深いコピーと `unset` 関数の呼び出しにより相対的に遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[`omit`](../../../reference/object/omit.md)を使用してください。 + +::: + +オブジェクトから指定されたキーを除外した新しいオブジェクトを作成します。 + +```typescript +const result = omit(obj, ...keys); +``` + +## 使用法 + +### `omit(object, ...paths)` + +オブジェクトから指定されたキーを除外した新しいオブジェクトを作成します。深いキーパスをサポートし、配列を使用して一度に複数のキーを指定することもできます。オブジェクトから機密情報を削除したり、必要なプロパティのみを選択する際に便利です。 + +```typescript +import { omit } from 'es-toolkit/compat'; + +// 基本的なキーの削除 +const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }; +const publicUser = omit(user, 'password', 'email'); +// 結果: { id: 1, name: 'John' } + +// 配列で複数のキーを削除 +const data = { a: 1, b: 2, c: 3, d: 4 }; +const filtered = omit(data, ['a', 'c']); +// 結果: { b: 2, d: 4 } + +// 深いキーパスの削除 +const nested = { + user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, + admin: true, +}; +const result = omit(nested, 'user.profile.age', 'admin'); +// 結果: { user: { profile: { name: 'John' }, settings: { theme: 'dark' } } } + +// ネストされた配列とキーの組み合わせ +const complex = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; +const simplified = omit(complex, 'a', ['b', 'c'], 'd.f'); +// 結果: { d: { e: 4 } } +``` + +配列、文字列、キーパスを自由に組み合わせることができます。 + +```typescript +import { omit } from 'es-toolkit/compat'; + +const config = { + api: { url: 'https://api.example.com', key: 'secret', timeout: 5000 }, + ui: { theme: 'dark', language: 'en' }, + debug: true, +}; + +// 複数の方法でキーを指定 +const cleaned = omit(config, 'api.key', ['debug'], 'ui.language'); +// 結果: { api: { url: 'https://api.example.com', timeout: 5000 }, ui: { theme: 'dark' } } +``` + +`null`または`undefined`は空のオブジェクトとして処理されます。 + +```typescript +import { omit } from 'es-toolkit/compat'; + +omit(null, 'key'); // {} +omit(undefined, 'key'); // {} +``` + +#### パラメータ + +- `object` (`T | null | undefined`): キーを削除する元のオブジェクトです。 +- `...paths` (`Array>`): 削除するキーです。単一のキー、キーの配列、または深いキーパスを指定できます。 + +#### 戻り値 + +(`Partial`): 指定されたキーが削除された新しいオブジェクトを返します。 diff --git a/docs/ja/compat/reference/object/omitBy.md b/docs/ja/compat/reference/object/omitBy.md new file mode 100644 index 000000000..6ffc9451a --- /dev/null +++ b/docs/ja/compat/reference/object/omitBy.md @@ -0,0 +1,76 @@ +# omitBy (Lodash 互換性) + +::: warning `es-toolkit`の`omitBy`を使用してください + +この `omitBy` 関数は、配列様オブジェクトのチェック、`iteratee`変換、キー変換過程により相対的に遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[`omitBy`](../../../reference/object/omitBy.md)を使用してください。 + +::: + +述語関数がtrueを返すプロパティを除外した新しいオブジェクトを作成します。 + +```typescript +const result = omitBy(obj, predicate); +``` + +## 使用法 + +### `omitBy(object, predicate)` + +オブジェクトの各プロパティに対して述語関数を実行し、述語がtrueを返すプロパティを除外した新しいオブジェクトを作成します。条件に基づいてプロパティを動的にフィルタリングする際に便利です。 + +```typescript +import { omitBy } from 'es-toolkit/compat'; + +// 特定の型の値を削除 +const data = { a: 1, b: 'remove', c: 3, d: 'keep' }; +const numbers = omitBy(data, value => typeof value === 'string'); +// 結果: { a: 1, c: 3 } + +// 条件に基づいてプロパティを削除 +const user = { id: 1, name: 'John', age: 0, active: false, email: '' }; +const validData = omitBy(user, value => !value); +// 結果: { id: 1, name: 'John' } (偽値を削除) + +// キー名でフィルタリング +const settings = { userSetting: true, adminSetting: false, debugMode: true }; +const userOnly = omitBy(settings, (value, key) => key.startsWith('admin')); +// 結果: { userSetting: true, debugMode: true } + +// 数値プロパティのみ削除 +const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; +const noNumbers = omitBy(mixed, value => typeof value === 'number'); +// 結果: { str: 'hello', bool: true, obj: {} } + +// 配列でも使用可能 +const arr = [1, 2, 3, 4, 5]; +const filtered = omitBy(arr, value => value % 2 === 0); +// 結果: { '0': 1, '2': 3, '4': 5 } (偶数インデックスの奇数値) + +// 値、キー、元のオブジェクトをすべて活用 +const scores = { math: 90, science: 75, english: 85, art: 60 }; +const passingGrades = omitBy(scores, (value, key, obj) => { + console.log(`${key}: ${value} (平均: ${Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length})`); + return value < 80; +}); +// 結果: { math: 90, english: 85 } +``` + +`null`または`undefined`は空のオブジェクトとして処理されます。 + +```typescript +import { omitBy } from 'es-toolkit/compat'; + +omitBy(null, () => true); // {} +omitBy(undefined, () => true); // {} +``` + +#### パラメータ + +- `object` (`Record | Record | object | null | undefined`): フィルタリングする元のオブジェクトです。 +- `predicate` (`ValueKeyIteratee | ValueKeyIteratee`, オプション): 各プロパティに対して実行する述語関数です。これがtrueを返すプロパティは削除されます。デフォルトは`identity`関数です。 + +#### 戻り値 + +(`Record | Record | Partial`): 条件に合致しないプロパティで構成された新しいオブジェクトを返します。 diff --git a/docs/ja/compat/reference/object/pick.md b/docs/ja/compat/reference/object/pick.md new file mode 100644 index 000000000..ba0ebbdc9 --- /dev/null +++ b/docs/ja/compat/reference/object/pick.md @@ -0,0 +1,73 @@ +# pick (Lodash 互換性) + +::: warning `es-toolkit`の`pick`を使用してください + +この `pick` 関数は、複雑なパス処理、`get`/`set`関数の呼び出し、`null`/`undefined`の処理により相対的に遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[`pick`](../../../reference/object/pick.md)を使用してください。 + +::: + +オブジェクトから指定したプロパティのみを選択して新しいオブジェクトを作成します。 + +```typescript +const result = pick(obj, ...keys); +``` + +## 使用法 + +### `pick(object, ...props)` + +オブジェクトから必要なプロパティのみを選んで新しいオブジェクトを作りたい場合は`pick`を使用してください。配列で複数のキーを一度に渡すか、個別の引数として1つずつ渡すことができます。深いキーパスもサポートしているため、ネストされたプロパティも選択できます。 + +```typescript +import { pick } from 'es-toolkit/compat'; + +// 基本的な使用法 +const obj = { a: 1, b: 2, c: 3, d: 4 }; +const result = pick(obj, ['a', 'c']); +// 結果: { a: 1, c: 3 } + +// 個別の引数として渡す +const result2 = pick(obj, 'a', 'c'); +// 結果: { a: 1, c: 3 } + +// 深いパスを選択 +const nested = { + user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, + admin: true, +}; +const userInfo = pick(nested, 'user.profile.name', 'admin'); +// 結果: { user: { profile: { name: 'John' } }, admin: true } + +// 配列と個別のキーを混在 +const mixed = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; +const selected = pick(mixed, ['a', 'b'], 'c', 'd.e'); +// 結果: { a: 1, b: 2, c: 3, d: { e: 4 } } + +// ドット表記キーと実際のドット付きキーを区別 +const ambiguous = { + 'a.b': 1, // 実際のキー 'a.b' + a: { b: 2, c: 3 }, // ネストされたオブジェクト +}; +const dotKey = pick(ambiguous, 'a.b'); +// 結果: { 'a.b': 1 } (実際のキーが優先) +``` + +`null`または`undefined`は空のオブジェクトとして処理されます。 + +```typescript +import { pick } from 'es-toolkit/compat'; + +pick(null, ['a', 'b']); // {} +pick(undefined, ['a', 'b']); // {} +``` + +#### パラメータ + +- `object` (`T | null | undefined`): プロパティを選択するオブジェクトです。 +- `...props` (`Array>`): 選択するプロパティのキーです。単一のキー、キーの配列、または深いキーパスを指定できます。 + +#### 戻り値 + +(`Pick | Partial`): 指定されたプロパティのみを含む新しいオブジェクトを返します。 diff --git a/docs/ja/compat/reference/object/pickBy.md b/docs/ja/compat/reference/object/pickBy.md new file mode 100644 index 000000000..60512396f --- /dev/null +++ b/docs/ja/compat/reference/object/pickBy.md @@ -0,0 +1,86 @@ +# pickBy (Lodash 互換性) + +::: warning `es-toolkit`の`pickBy`を使用してください + +この `pickBy` 関数は、配列様オブジェクトのチェック、`iteratee`変換、キー変換過程により相対的に遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[`pickBy`](../../../reference/object/pickBy.md)を使用してください。 + +::: + +述語関数がtrueを返すプロパティのみを選択して新しいオブジェクトを作成します。 + +```typescript +const result = pickBy(obj, predicate); +``` + +## 使用法 + +### `pickBy(object, predicate)` + +オブジェクトの各プロパティに対して述語関数を実行し、述語がtrueを返すプロパティのみを含む新しいオブジェクトを作成します。条件に基づいてプロパティを動的に選択する際に便利です。 + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +// 特定の型の値のみを選択 +const data = { a: 1, b: 'keep', c: 3, d: 'select' }; +const strings = pickBy(data, value => typeof value === 'string'); +// 結果: { b: 'keep', d: 'select' } + +// 条件に基づいてプロパティを選択 +const user = { id: 1, name: 'John', age: 0, active: true, email: '' }; +const validData = pickBy(user, value => Boolean(value)); +// 結果: { id: 1, name: 'John', active: true } (真値のみ) + +// キー名でフィルタリング +const settings = { userSetting: true, adminSetting: false, debugMode: true }; +const userOnly = pickBy(settings, (value, key) => key.startsWith('user')); +// 結果: { userSetting: true } + +// 数値プロパティのみを選択 +const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; +const numbersOnly = pickBy(mixed, value => typeof value === 'number'); +// 結果: { num1: 42, num2: 0 } + +// 配列でも使用可能 +const arr = [1, 2, 3, 4, 5]; +const evens = pickBy(arr, value => value % 2 === 0); +// 結果: { '1': 2, '3': 4 } (偶数のインデックスと値) + +// 値、キー、元のオブジェクトをすべて活用 +const scores = { math: 90, science: 75, english: 85, art: 60 }; +const highScores = pickBy(scores, (value, key, obj) => { + const average = Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length; + return value > average; +}); +// 結果: { math: 90, english: 85 } +``` + +述語関数なしで呼び出すと、真値のみが選択されます。 + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +const data = { a: 1, b: '', c: 0, d: 'hello', e: null, f: true }; +const truthyValues = pickBy(data); +// 結果: { a: 1, d: 'hello', f: true } +``` + +`null`または`undefined`は空のオブジェクトとして処理されます。 + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +pickBy(null, () => true); // {} +pickBy(undefined, () => true); // {} +``` + +#### パラメータ + +- `object` (`Record | Record | object | null | undefined`): フィルタリングする元のオブジェクトです。 +- `predicate` (`ValueKeyIterateeTypeGuard | ValueKeyIteratee | ValueKeyIteratee`, オプション): 各プロパティに対して実行する述語関数です。これがtrueを返すプロパティが選択されます。デフォルトは`identity`関数です。 + +#### 戻り値 + +(`Record | Record | Partial`): 条件に合致するプロパティで構成された新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/property.md b/docs/ja/compat/reference/object/property.md similarity index 100% rename from docs/ja/reference/compat/object/property.md rename to docs/ja/compat/reference/object/property.md diff --git a/docs/ja/reference/compat/object/propertyOf.md b/docs/ja/compat/reference/object/propertyOf.md similarity index 100% rename from docs/ja/reference/compat/object/propertyOf.md rename to docs/ja/compat/reference/object/propertyOf.md diff --git a/docs/ja/reference/compat/object/result.md b/docs/ja/compat/reference/object/result.md similarity index 100% rename from docs/ja/reference/compat/object/result.md rename to docs/ja/compat/reference/object/result.md diff --git a/docs/ja/reference/compat/object/set.md b/docs/ja/compat/reference/object/set.md similarity index 100% rename from docs/ja/reference/compat/object/set.md rename to docs/ja/compat/reference/object/set.md diff --git a/docs/ja/reference/compat/object/setWith.md b/docs/ja/compat/reference/object/setWith.md similarity index 100% rename from docs/ja/reference/compat/object/setWith.md rename to docs/ja/compat/reference/object/setWith.md diff --git a/docs/ja/reference/compat/object/toDefaulted.md b/docs/ja/compat/reference/object/toDefaulted.md similarity index 100% rename from docs/ja/reference/compat/object/toDefaulted.md rename to docs/ja/compat/reference/object/toDefaulted.md diff --git a/docs/ja/reference/compat/object/toPairs.md b/docs/ja/compat/reference/object/toPairs.md similarity index 100% rename from docs/ja/reference/compat/object/toPairs.md rename to docs/ja/compat/reference/object/toPairs.md diff --git a/docs/ja/reference/compat/object/toPairsIn.md b/docs/ja/compat/reference/object/toPairsIn.md similarity index 100% rename from docs/ja/reference/compat/object/toPairsIn.md rename to docs/ja/compat/reference/object/toPairsIn.md diff --git a/docs/ja/reference/compat/object/transform.md b/docs/ja/compat/reference/object/transform.md similarity index 100% rename from docs/ja/reference/compat/object/transform.md rename to docs/ja/compat/reference/object/transform.md diff --git a/docs/ja/reference/compat/object/unset.md b/docs/ja/compat/reference/object/unset.md similarity index 100% rename from docs/ja/reference/compat/object/unset.md rename to docs/ja/compat/reference/object/unset.md diff --git a/docs/ja/reference/compat/object/update.md b/docs/ja/compat/reference/object/update.md similarity index 100% rename from docs/ja/reference/compat/object/update.md rename to docs/ja/compat/reference/object/update.md diff --git a/docs/ja/reference/compat/object/updateWith.md b/docs/ja/compat/reference/object/updateWith.md similarity index 100% rename from docs/ja/reference/compat/object/updateWith.md rename to docs/ja/compat/reference/object/updateWith.md diff --git a/docs/ja/reference/compat/object/values.md b/docs/ja/compat/reference/object/values.md similarity index 100% rename from docs/ja/reference/compat/object/values.md rename to docs/ja/compat/reference/object/values.md diff --git a/docs/ja/reference/compat/object/valuesIn.md b/docs/ja/compat/reference/object/valuesIn.md similarity index 100% rename from docs/ja/reference/compat/object/valuesIn.md rename to docs/ja/compat/reference/object/valuesIn.md diff --git a/docs/ja/reference/compat/predicate/conforms.md b/docs/ja/compat/reference/predicate/conforms.md similarity index 100% rename from docs/ja/reference/compat/predicate/conforms.md rename to docs/ja/compat/reference/predicate/conforms.md diff --git a/docs/ja/reference/compat/predicate/conformsTo.md b/docs/ja/compat/reference/predicate/conformsTo.md similarity index 100% rename from docs/ja/reference/compat/predicate/conformsTo.md rename to docs/ja/compat/reference/predicate/conformsTo.md diff --git a/docs/ja/reference/compat/predicate/isArguments.md b/docs/ja/compat/reference/predicate/isArguments.md similarity index 100% rename from docs/ja/reference/compat/predicate/isArguments.md rename to docs/ja/compat/reference/predicate/isArguments.md diff --git a/docs/ja/reference/compat/predicate/isArray.md b/docs/ja/compat/reference/predicate/isArray.md similarity index 100% rename from docs/ja/reference/compat/predicate/isArray.md rename to docs/ja/compat/reference/predicate/isArray.md diff --git a/docs/ja/compat/reference/predicate/isArrayBuffer.md b/docs/ja/compat/reference/predicate/isArrayBuffer.md new file mode 100644 index 000000000..1bc6e4c61 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isArrayBuffer.md @@ -0,0 +1,44 @@ +# isArrayBuffer (Lodash互換性) + +::: warning es-toolkitの[isArrayBuffer](../../../reference/predicate/isArrayBuffer.md)を使用してください +この`isArrayBuffer`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より速く現代的な`es-toolkit`の[isArrayBuffer](../../../reference/predicate/isArrayBuffer.md)を使用してください。 +::: + +値がArrayBufferかどうかを確認します。 + +```typescript +const result = isArrayBuffer(value); +``` + +## 使用法 + +### `isArrayBuffer(value)` + +値がArrayBufferかどうかを型安全に確認したい場合は`isArrayBuffer`を使用してください。TypeScriptでタイプガードとしても動作します。 + +```typescript +import { isArrayBuffer } from 'es-toolkit/compat'; + +// ArrayBufferの確認 +const buffer = new ArrayBuffer(16); +isArrayBuffer(buffer); // true + +// 他の型はfalse +isArrayBuffer(new Array()); // false +isArrayBuffer(new Map()); // false +isArrayBuffer({}); // false +isArrayBuffer('hello'); // false +isArrayBuffer(123); // false +isArrayBuffer(null); // false +isArrayBuffer(undefined); // false +``` + +#### パラメータ + +- `value` (`unknown`): ArrayBufferかどうかを確認する値です。 + +#### 戻り値 + +(`value is ArrayBuffer`): 値がArrayBufferの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isArrayLike.md b/docs/ja/compat/reference/predicate/isArrayLike.md similarity index 100% rename from docs/ja/reference/compat/predicate/isArrayLike.md rename to docs/ja/compat/reference/predicate/isArrayLike.md diff --git a/docs/ja/reference/compat/predicate/isArrayLikeObject.md b/docs/ja/compat/reference/predicate/isArrayLikeObject.md similarity index 100% rename from docs/ja/reference/compat/predicate/isArrayLikeObject.md rename to docs/ja/compat/reference/predicate/isArrayLikeObject.md diff --git a/docs/ja/reference/compat/predicate/isBoolean.md b/docs/ja/compat/reference/predicate/isBoolean.md similarity index 100% rename from docs/ja/reference/compat/predicate/isBoolean.md rename to docs/ja/compat/reference/predicate/isBoolean.md diff --git a/docs/ja/compat/reference/predicate/isBuffer.md b/docs/ja/compat/reference/predicate/isBuffer.md new file mode 100644 index 000000000..34e27e0a0 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isBuffer.md @@ -0,0 +1,43 @@ +# isBuffer (Lodash互換性) + +::: warning es-toolkitの[isBuffer](../../../reference/predicate/isBuffer.md)を使用してください +この`isBuffer`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より速く現代的な`es-toolkit`の[isBuffer](../../../reference/predicate/isBuffer.md)を使用してください。 +::: + +値がBufferインスタンスかどうかを確認します。 + +```typescript +const result = isBuffer(value); +``` + +## 使用法 + +### `isBuffer(value)` + +値がBufferインスタンスかどうかを型安全に確認したい場合は`isBuffer`を使用してください。Node.js環境でBufferオブジェクトを扱う際に便利です。TypeScriptでタイプガードとしても動作します。 + +```typescript +import { isBuffer } from 'es-toolkit/compat'; + +// Bufferインスタンスの確認 +const buffer = Buffer.from('hello'); +isBuffer(buffer); // true + +// 他の型はfalse +isBuffer('hello'); // false +isBuffer([1, 2, 3]); // false +isBuffer(new Uint8Array([1, 2, 3])); // false +isBuffer({}); // false +isBuffer(null); // false +isBuffer(undefined); // false +``` + +#### パラメータ + +- `value` (`unknown`): Bufferインスタンスかどうかを確認する値です。 + +#### 戻り値 + +(`boolean`): 値がBufferインスタンスの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/compat/reference/predicate/isDate.md b/docs/ja/compat/reference/predicate/isDate.md new file mode 100644 index 000000000..79a1a6df2 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isDate.md @@ -0,0 +1,46 @@ +# isDate (Lodash互換性) + +::: warning es-toolkitの[isDate](../../../reference/predicate/isDate.md)を使用してください +この`isDate`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より速く現代的な`es-toolkit`の[isDate](../../../reference/predicate/isDate.md)を使用してください。 +::: + +値がDateオブジェクトかどうかを確認します。 + +```typescript +const result = isDate(value); +``` + +## 使用法 + +### `isDate(value)` + +値がDateオブジェクトかどうかを型安全に確認したい場合は`isDate`を使用してください。TypeScriptでタイプガードとしても動作します。 + +```typescript +import { isDate } from 'es-toolkit/compat'; + +// Dateオブジェクトの確認 +const date = new Date(); +isDate(date); // true + +// 無効なDateもDateオブジェクトとして認識します +const invalidDate = new Date('invalid'); +isDate(invalidDate); // true + +// 他の型はfalse +isDate('2024-01-01'); // false +isDate(1640995200000); // false +isDate({}); // false +isDate(null); // false +isDate(undefined); // false +``` + +#### パラメータ + +- `value` (`unknown`): Dateオブジェクトかどうかを確認する値です。 + +#### 戻り値 + +(`value is Date`): 値がDateオブジェクトの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isElement.md b/docs/ja/compat/reference/predicate/isElement.md similarity index 100% rename from docs/ja/reference/compat/predicate/isElement.md rename to docs/ja/compat/reference/predicate/isElement.md diff --git a/docs/ja/reference/compat/predicate/isEmpty.md b/docs/ja/compat/reference/predicate/isEmpty.md similarity index 100% rename from docs/ja/reference/compat/predicate/isEmpty.md rename to docs/ja/compat/reference/predicate/isEmpty.md diff --git a/docs/ja/compat/reference/predicate/isEqual.md b/docs/ja/compat/reference/predicate/isEqual.md new file mode 100644 index 000000000..af848ff56 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isEqual.md @@ -0,0 +1,82 @@ +# isEqual (Lodash互換性) + +::: warning `es-toolkit`の[isEqual](../../../reference/predicate/isEqual.md)を使用してください +この`isEqual`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より速く現代的な`es-toolkit`の[isEqual](../../../reference/predicate/isEqual.md)を使用してください。 +::: + +二つの値が同じかどうかを深く比較して確認します。 + +```typescript +const result = isEqual(value1, value2); +``` + +## 使用法 + +### `isEqual(a, b)` + +二つの値が同じかどうかを深く比較して確認したい場合は`isEqual`を使用してください。Date、RegExp、オブジェクト、配列などの複雑な型も内容まで比較します。 + +```typescript +import { isEqual } from 'es-toolkit/compat'; + +// 基本型の比較 +isEqual(1, 1); // true +isEqual('hello', 'hello'); // true +isEqual(true, true); // true + +// オブジェクトの深い比較 +isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true +isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true +isEqual({ a: 1 }, { a: 1, b: undefined }); // false + +// 配列の深い比較 +isEqual([1, 2, 3], [1, 2, 3]); // true +isEqual([1, [2, 3]], [1, [2, 3]]); // true + +// Dateオブジェクトの比較 +isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true +isEqual(new Date('2020-01-01'), new Date('2020-01-02')); // false + +// RegExpオブジェクトの比較 +isEqual(/abc/g, /abc/g); // true +isEqual(/abc/g, /abc/i); // false +``` + +ネストされたオブジェクトや配列も再帰的に比較します。 + +```typescript +import { isEqual } from 'es-toolkit/compat'; + +const obj1 = { + user: { + name: 'John', + details: { + age: 30, + hobbies: ['reading', 'gaming'], + }, + }, +}; + +const obj2 = { + user: { + name: 'John', + details: { + age: 30, + hobbies: ['reading', 'gaming'], + }, + }, +}; + +isEqual(obj1, obj2); // true +``` + +#### パラメータ + +- `a` (`unknown`): 比較する最初の値です。 +- `b` (`unknown`): 比較する2番目の値です。 + +#### 戻り値 + +(`boolean`): 二つの値が同じ場合は`true`、異なる場合は`false`を返します。 diff --git a/docs/ja/compat/reference/predicate/isEqualWith.md b/docs/ja/compat/reference/predicate/isEqualWith.md new file mode 100644 index 000000000..0fb839346 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isEqualWith.md @@ -0,0 +1,92 @@ +# isEqualWith (Lodash互換性) + +::: warning es-toolkitの[isEqualWith](../../../reference/predicate/isEqualWith.md)を使用してください +この`isEqualWith`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より速く現代的な`es-toolkit`の[isEqualWith](../../../reference/predicate/isEqualWith.md)を使用してください。 +::: + +カスタム比較関数を使用して二つの値が同じかどうかを確認します。 + +```typescript +const result = isEqualWith(a, b, customizer); +``` + +## 使用法 + +### `isEqualWith(a, b, areValuesEqual?)` + +カスタム比較関数を使用して二つの値を深く比較します。カスタム関数がboolean値を返す場合はその結果を使用し、`undefined`を返す場合はデフォルトの等価性比較を使用します。 + +カスタム比較関数はオブジェクト、配列、Map、Setなどの複雑な構造の内部の値を比較する際にも使用され、深い比較を保証します。 + +```typescript +import { isEqualWith } from 'es-toolkit/compat'; + +// 大文字小文字を無視した文字列比較 +const customizer = (a: any, b: any) => { + if (typeof a === 'string' && typeof b === 'string') { + return a.toLowerCase() === b.toLowerCase(); + } +}; + +isEqualWith('Hello', 'hello', customizer); // true +isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true + +// 数値の絶対値で比較 +const absCustomizer = (a: any, b: any) => { + if (typeof a === 'number' && typeof b === 'number') { + return Math.abs(a) === Math.abs(b); + } +}; + +isEqualWith([-1, 2], [1, -2], absCustomizer); // true + +// 複雑なオブジェクトの比較 +const obj1 = { + name: 'JOHN', + details: { age: 30, city: 'NYC' }, +}; +const obj2 = { + name: 'john', + details: { age: 30, city: 'nyc' }, +}; + +isEqualWith(obj1, obj2, customizer); // true +``` + +MapとSetに対しては特別な処理を行います。 + +```typescript +import { isEqualWith } from 'es-toolkit/compat'; + +const customizer = (a: any, b: any) => { + if (typeof a === 'string' && typeof b === 'string') { + return a.toLowerCase() === b.toLowerCase(); + } +}; + +const map1 = new Map([['KEY', 'value']]); +const map2 = new Map([['key', 'value']]); +isEqualWith(map1, map2, customizer); // true + +const set1 = new Set(['HELLO']); +const set2 = new Set(['hello']); +isEqualWith(set1, set2, customizer); // true +``` + +#### パラメータ + +- `a` (`any`): 比較する最初の値です。 +- `b` (`any`): 比較する2番目の値です。 +- `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): カスタム比較関数です。 + - `x`: 最初のオブジェクト`a`からの値 + - `y`: 2番目のオブジェクト`b`からの値 + - `property`: `x`と`y`を取得する際に使用したプロパティキー + - `xParent`: 最初の値`x`の親オブジェクト + - `yParent`: 2番目の値`y`の親オブジェクト + - `stack`: 循環参照を処理する内部スタック (Map) + +#### 戻り値 + +(`boolean`): カスタム関数によって二つの値が同じ場合は`true`、異なる場合は`false`を返します。 diff --git a/docs/ja/compat/reference/predicate/isError.md b/docs/ja/compat/reference/predicate/isError.md new file mode 100644 index 000000000..82ed44494 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isError.md @@ -0,0 +1,47 @@ +# isError (Lodash互換性) + +::: warning es-toolkitの[isError](../../../reference/predicate/isError.md)を使用してください +この`isError`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より速く現代的な`es-toolkit`の[isError](../../../reference/predicate/isError.md)を使用してください。 +::: + +値がErrorオブジェクトかどうかを確認します。 + +```typescript +const result = isError(value); +``` + +## 使用法 + +### `isError(value)` + +値がErrorオブジェクトかどうかを型安全に確認したい場合は`isError`を使用してください。TypeScriptでタイプガードとしても動作します。 + +```typescript +import { isError } from 'es-toolkit/compat'; + +// Errorオブジェクトの確認 +isError(new Error()); // true +isError(new TypeError('Type error')); // true +isError(new ReferenceError('Reference error')); // true + +// Errorを継承したカスタムエラー +class CustomError extends Error {} +isError(new CustomError()); // true + +// 他の型はfalse +isError('Error'); // false +isError({ name: 'Error', message: 'Something went wrong' }); // false +isError({}); // false +isError(null); // false +isError(undefined); // false +``` + +#### パラメータ + +- `value` (`unknown`): Errorオブジェクトかどうかを確認する値です。 + +#### 戻り値 + +(`value is Error`): 値がErrorオブジェクトの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isFinite.md b/docs/ja/compat/reference/predicate/isFinite.md similarity index 100% rename from docs/ja/reference/compat/predicate/isFinite.md rename to docs/ja/compat/reference/predicate/isFinite.md diff --git a/docs/ja/compat/reference/predicate/isFunction.md b/docs/ja/compat/reference/predicate/isFunction.md new file mode 100644 index 000000000..a8ce391ef --- /dev/null +++ b/docs/ja/compat/reference/predicate/isFunction.md @@ -0,0 +1,52 @@ +# isFunction (Lodash互換性) + +::: warning es-toolkitの[isFunction](../../../reference/predicate/isFunction.md)を使用してください +この`isFunction`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より速く現代的な`es-toolkit`の[isFunction](../../../reference/predicate/isFunction.md)を使用してください。 +::: + +値が関数かどうかを確認します。 + +```typescript +const result = isFunction(value); +``` + +## 使用法 + +### `isFunction(value)` + +値が関数かどうかを型安全に確認したい場合は`isFunction`を使用してください。TypeScriptでタイプガードとしても動作します。 + +```typescript +import { isFunction } from 'es-toolkit/compat'; + +// 通常の関数 +isFunction(function () {}); // true +isFunction(() => {}); // true + +// 内蔵関数とコンストラクタ +isFunction(Array.prototype.slice); // true +isFunction(Proxy); // true +isFunction(Int8Array); // true + +// 非同期関数とジェネレータ関数 +isFunction(async function () {}); // true +isFunction(function* () {}); // true + +// 他の型はfalse +isFunction('function'); // false +isFunction({}); // false +isFunction([]); // false +isFunction(null); // false +isFunction(undefined); // false +isFunction(123); // false +``` + +#### パラメータ + +- `value` (`unknown`): 関数かどうかを確認する値です。 + +#### 戻り値 + +(`value is (...args: any[]) => any`): 値が関数の場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isInteger.md b/docs/ja/compat/reference/predicate/isInteger.md similarity index 100% rename from docs/ja/reference/compat/predicate/isInteger.md rename to docs/ja/compat/reference/predicate/isInteger.md diff --git a/docs/ja/compat/reference/predicate/isLength.md b/docs/ja/compat/reference/predicate/isLength.md new file mode 100644 index 000000000..1413fdbb7 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isLength.md @@ -0,0 +1,63 @@ +# isLength (Lodash互換性) + +::: warning es-toolkitの[isLength](../../../reference/predicate/isLength.md)を使用してください +この`isLength`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より速く現代的な`es-toolkit`の[isLength](../../../reference/predicate/isLength.md)を使用してください。 +::: + +値が有効な長さかどうかを確認します。 + +```typescript +const result = isLength(value); +``` + +## 使用法 + +### `isLength(value)` + +値が有効な長さかどうかを確認したい場合は`isLength`を使用してください。有効な長さは数値型で、非負の整数であり、JavaScriptの最大安全整数(`Number.MAX_SAFE_INTEGER`)以下である必要があります。TypeScriptでタイプガードとしても動作します。 + +```typescript +import { isLength } from 'es-toolkit/compat'; + +// 有効な長さ +isLength(0); // true +isLength(42); // true +isLength(100); // true +isLength(Number.MAX_SAFE_INTEGER); // true + +// 無効な長さ +isLength(-1); // false (負数) +isLength(1.5); // false (整数ではない) +isLength(Number.MAX_SAFE_INTEGER + 1); // false (安全範囲超過) +isLength('3'); // false (文字列) +isLength(null); // false +isLength(undefined); // false +isLength({}); // false +isLength([]); // false +``` + +配列や文字列のlengthプロパティが有効かどうかを確認する際に便利です。 + +```typescript +import { isLength } from 'es-toolkit/compat'; + +function validateArrayLength(arr: any[]) { + if (isLength(arr.length)) { + console.log(`配列の長さ${arr.length}は有効です`); + return true; + } + return false; +} + +validateArrayLength([1, 2, 3]); // "配列の長さ3は有効です" +``` + +#### パラメータ + +- `value` (`any`): 有効な長さかどうかを確認する値です。 + +#### 戻り値 + +(`boolean`): 値が有効な長さの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/compat/reference/predicate/isMap.md b/docs/ja/compat/reference/predicate/isMap.md new file mode 100644 index 000000000..bd1f1a0c4 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isMap.md @@ -0,0 +1,63 @@ +# isMap (Lodash互換性) + +::: warning es-toolkitの[isMap](../../../reference/predicate/isMap.md)を使用してください + +この`isMap`関数はLodash互換性のための複雑な処理により動作が遅くなります。 + +代わりに、より速く現代的な`es-toolkit`の[isMap](../../../reference/predicate/isMap.md)を使用してください。 + +::: + +値がMapかどうかを確認します。 + +```typescript +const result = isMap(value); +``` + +## 使用法 + +### `isMap(value)` + +値がMapかどうかを型安全に確認したい場合は`isMap`を使用してください。TypeScriptでタイプガードとしても動作します。 + +```typescript +import { isMap } from 'es-toolkit/compat'; + +// Mapの確認 +const map = new Map(); +isMap(map); // true + +// 他の型はfalse +isMap(new Set()); // false +isMap(new WeakMap()); // false +isMap({}); // false +isMap([]); // false +isMap('map'); // false +isMap(123); // false +isMap(null); // false +isMap(undefined); // false +``` + +Mapと似た他のコレクションとも区別します。 + +```typescript +import { isMap } from 'es-toolkit/compat'; + +// Map vs Set vs WeakMap +isMap(new Map([['key', 'value']])); // true +isMap(new Set(['value'])); // false +isMap(new WeakMap()); // false + +// Map vs 通常のオブジェクト +isMap({}); // false +isMap({ key: 'value' }); // false +isMap(Object.create(null)); // false +``` + +#### パラメータ + +- `value` (`unknown`): Mapかどうかを確認する値です。 + +#### 戻り値 + +(`value is Map`): 値がMapの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isMatch.md b/docs/ja/compat/reference/predicate/isMatch.md similarity index 100% rename from docs/ja/reference/compat/predicate/isMatch.md rename to docs/ja/compat/reference/predicate/isMatch.md diff --git a/docs/ja/reference/compat/predicate/isMatchWith.md b/docs/ja/compat/reference/predicate/isMatchWith.md similarity index 100% rename from docs/ja/reference/compat/predicate/isMatchWith.md rename to docs/ja/compat/reference/predicate/isMatchWith.md diff --git a/docs/ja/reference/compat/predicate/isNaN.md b/docs/ja/compat/reference/predicate/isNaN.md similarity index 100% rename from docs/ja/reference/compat/predicate/isNaN.md rename to docs/ja/compat/reference/predicate/isNaN.md diff --git a/docs/ja/reference/compat/predicate/isNative.md b/docs/ja/compat/reference/predicate/isNative.md similarity index 100% rename from docs/ja/reference/compat/predicate/isNative.md rename to docs/ja/compat/reference/predicate/isNative.md diff --git a/docs/ja/compat/reference/predicate/isNil.md b/docs/ja/compat/reference/predicate/isNil.md new file mode 100644 index 000000000..590a47c74 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isNil.md @@ -0,0 +1,62 @@ +# isNil (Lodash 互換性) + +::: warning es-toolkitの [isNil](../../../reference/predicate/isNil.md)を使用してください + +この `isNil` 関数はLodash互換性のための複雑な処理により遅く動作します。 + +代わりにより高速で現代的な `es-toolkit` の [isNil](../../../reference/predicate/isNil.md) を使用してください。 + +::: + +値が `null` または `undefined` かどうかを確認します。 + +```typescript +const result = isNil(value); +``` + +## 使用法 + +### `isNil(x)` + +値が `null` または `undefined` かどうかを型安全に確認したい場合に `isNil` を使用してください。TypeScript で型ガードとしても動作します。 + +```typescript +import { isNil } from 'es-toolkit/compat'; + +// nullとundefinedはtrue +isNil(null); // true +isNil(undefined); // true + +// その他すべての値はfalse +isNil(0); // false +isNil(''); // false +isNil(false); // false +isNil([]); // false +isNil({}); // false +isNil('hello'); // false +isNil(42); // false +``` + +falsy として評価されるが `null` や `undefined` でない値と区別します。 + +```typescript +import { isNil } from 'es-toolkit/compat'; + +// falsyとして評価されるがnull/undefinedでない値 +isNil(0); // false +isNil(''); // false +isNil(false); // false +isNil(NaN); // false + +// nullとundefinedのみtrue +isNil(null); // true +isNil(undefined); // true +``` + +#### パラメータ + +- `x` (`any`): `null` または `undefined` かどうかを確認する値です。 + +#### 戻り値 + +(`x is null | undefined`): 値が `null` または `undefined` の場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/compat/reference/predicate/isNull.md b/docs/ja/compat/reference/predicate/isNull.md new file mode 100644 index 000000000..3003cd0f1 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isNull.md @@ -0,0 +1,68 @@ +# isNull (Lodash 互換性) + +::: warning es-toolkitの [isNull](../../../reference/predicate/isNull.md)を使用してください + +この `isNull` 関数はLodash互換性のための関数ですが、メインライブラリと同じ実装です。 + +代わりにより高速で現代的な `es-toolkit` の [isNull](../../../reference/predicate/isNull.md) を使用してください。 + +::: + +値が `null` かどうかを確認します。 + +```typescript +const result = isNull(value); +``` + +## 使用法 + +### `isNull(value)` + +値が正確に `null` かどうかを型安全に確認したい場合に `isNull` を使用してください。TypeScript で型ガードとしても動作します。 + +```typescript +import { isNull } from 'es-toolkit/compat'; + +// nullのみtrue +isNull(null); // true + +// undefinedもfalse +isNull(undefined); // false + +// その他すべての値もfalse +isNull(0); // false +isNull(''); // false +isNull(false); // false +isNull([]); // false +isNull({}); // false +isNull('null'); // false +isNull(NaN); // false +``` + +`null` と `undefined` を区別して確認することができます。 + +```typescript +import { isNull } from 'es-toolkit/compat'; + +function handleValue(value: string | null | undefined) { + if (isNull(value)) { + console.log('値が明示的にnullです'); + } else if (value === undefined) { + console.log('値がundefinedです'); + } else { + console.log(`値があります: ${value}`); + } +} + +handleValue(null); // "値が明示的にnullです" +handleValue(undefined); // "値がundefinedです" +handleValue('hello'); // "値があります: hello" +``` + +#### パラメータ + +- `value` (`any`): `null` かどうかを確認する値です。 + +#### 戻り値 + +(`value is null`): 値が `null` の場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/predicate/isNumber.md b/docs/ja/compat/reference/predicate/isNumber.md similarity index 100% rename from docs/ja/reference/compat/predicate/isNumber.md rename to docs/ja/compat/reference/predicate/isNumber.md diff --git a/docs/ja/reference/compat/predicate/isObject.md b/docs/ja/compat/reference/predicate/isObject.md similarity index 100% rename from docs/ja/reference/compat/predicate/isObject.md rename to docs/ja/compat/reference/predicate/isObject.md diff --git a/docs/ja/reference/compat/predicate/isObjectLike.md b/docs/ja/compat/reference/predicate/isObjectLike.md similarity index 100% rename from docs/ja/reference/compat/predicate/isObjectLike.md rename to docs/ja/compat/reference/predicate/isObjectLike.md diff --git a/docs/ja/compat/reference/predicate/isPlainObject.md b/docs/ja/compat/reference/predicate/isPlainObject.md new file mode 100644 index 000000000..e75938956 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isPlainObject.md @@ -0,0 +1,85 @@ +# isPlainObject (Lodash 互換性) + +::: warning es-toolkitの [isPlainObject](../../../reference/predicate/isPlainObject.md)を使用してください + +この `isPlainObject` 関数はLodash互換性のための複雑な処理により遅く動作します。 + +代わりにより高速で現代的な `es-toolkit` の [isPlainObject](../../../reference/predicate/isPlainObject.md) を使用してください。 + +::: + +値がプレーンオブジェクトかどうかを確認します。 + +```typescript +const result = isPlainObject(object); +``` + +## 使用法 + +### `isPlainObject(object)` + +値がプレーンオブジェクトかどうかを確認したい場合に `isPlainObject` を使用してください。プレーンオブジェクトは `{}` リテラル、`new Object()`、または `Object.create(null)` で生成されたオブジェクトです。TypeScript で型ガードとしても動作します。 + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +// プレーンオブジェクト +isPlainObject({}); // true +isPlainObject(new Object()); // true +isPlainObject(Object.create(null)); // true +isPlainObject({ name: 'John', age: 30 }); // true + +// プレーンオブジェクトでない値 +isPlainObject([]); // false (配列) +isPlainObject(new Date()); // false (Date インスタンス) +isPlainObject(new Map()); // false (Map インスタンス) +isPlainObject(new Set()); // false (Set インスタンス) +isPlainObject(/regex/); // false (正規表現) +isPlainObject(function () {}); // false (関数) +isPlainObject(null); // false +isPlainObject(undefined); // false +isPlainObject('object'); // false (文字列) +isPlainObject(42); // false (数値) +``` + +クラスインスタンスとプレーンオブジェクトを区別します。 + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +class Person { + name: string; + constructor(name: string) { + this.name = name; + } +} + +const person = new Person('John'); +const plainObj = { name: 'John' }; + +isPlainObject(person); // false (クラスインスタンス) +isPlainObject(plainObj); // true (プレーンオブジェクト) +``` + +カスタム `Symbol.toStringTag` プロパティも正しく処理します。 + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +// 書き込み可能な Symbol.toStringTag +const obj1 = {}; +obj1[Symbol.toStringTag] = 'CustomObject'; +isPlainObject(obj1); // true + +// 読み取り専用 Symbol.toStringTag(内蔵オブジェクト) +const date = new Date(); +isPlainObject(date); // false +``` + +#### パラメータ + +- `object` (`any`): プレーンオブジェクトかどうかを確認する値です。 + +#### 戻り値 + +(`boolean`): 値がプレーンオブジェクトの場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/compat/reference/predicate/isRegExp.md b/docs/ja/compat/reference/predicate/isRegExp.md new file mode 100644 index 000000000..116b289e9 --- /dev/null +++ b/docs/ja/compat/reference/predicate/isRegExp.md @@ -0,0 +1,82 @@ +# isRegExp (Lodash 互換性) + +::: warning es-toolkitの [isRegExp](../../../reference/predicate/isRegExp.md)を使用してください + +この `isRegExp` 関数はLodash互換性のための関数ですが、単純な型確認です。 + +代わりにより高速で現代的な `es-toolkit` の [isRegExp](../../../reference/predicate/isRegExp.md) を使用してください。 + +::: + +値が正規表現かどうかを確認します。 + +```typescript +const result = isRegExp(value); +``` + +## 使用法 + +### `isRegExp(value)` + +値が正規表現かどうかを型安全に確認したい場合に `isRegExp` を使用してください。TypeScript で型ガードとしても動作します。 + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// 正規表現 +isRegExp(/abc/); // true +isRegExp(new RegExp('abc')); // true +isRegExp(/[a-z]+/g); // true +isRegExp(/pattern/gi); // true + +// その他の型はfalse +isRegExp('/abc/'); // false (文字列) +isRegExp('pattern'); // false (文字列) +isRegExp({}); // false (オブジェクト) +isRegExp([]); // false (配列) +isRegExp(null); // false +isRegExp(undefined); // false +isRegExp(123); // false (数値) +``` + +正規表現文字列と実際の正規表現オブジェクトを区別します。 + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// 正規表現 vs 正規表現文字列 +isRegExp(/test/); // true +isRegExp('/test/'); // false +isRegExp('\\d+'); // false +isRegExp('/\\d+/g'); // false + +// 様々な正規表現フラグ +isRegExp(/test/i); // true (大文字小文字無視) +isRegExp(/test/g); // true (グローバル検索) +isRegExp(/test/m); // true (複数行) +isRegExp(/test/gim); // true (すべてのフラグの組み合わせ) +``` + +動的に生成された正規表現も認識します。 + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// RegExp コンストラクタで作成した正規表現 +const dynamicRegex = new RegExp('\\d{3}-\\d{4}', 'g'); +isRegExp(dynamicRegex); // true + +// 文字列を通じて生成した正規表現 +const pattern = 'hello'; +const flags = 'gi'; +const regex = new RegExp(pattern, flags); +isRegExp(regex); // true +``` + +#### パラメータ + +- `value` (`any`): 正規表現かどうかを確認する値です。 + +#### 戻り値 + +(`value is RegExp`): 値が正規表現の場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/predicate/isSafeInteger.md b/docs/ja/compat/reference/predicate/isSafeInteger.md similarity index 100% rename from docs/ja/reference/compat/predicate/isSafeInteger.md rename to docs/ja/compat/reference/predicate/isSafeInteger.md diff --git a/docs/ja/compat/reference/predicate/isSet.md b/docs/ja/compat/reference/predicate/isSet.md new file mode 100644 index 000000000..f4002324b --- /dev/null +++ b/docs/ja/compat/reference/predicate/isSet.md @@ -0,0 +1,67 @@ +# isSet (Lodash 互換性) + +::: warning `es-toolkit`の [isSet](../../../reference/predicate/isSet.md)を使用してください + +この `isSet` 関数はLodash互換性のための関数ですが、メインライブラリと同じ実装です。 + +代わりにより高速で現代的な `es-toolkit` の [isSet](../../../reference/predicate/isSet.md) を使用してください。 + +::: + +値がSetかどうかを確認します。 + +```typescript +const result = isSet(value); +``` + +## 使用法 + +### `isSet(value)` + +値がSetかどうかを型安全に確認したい場合に `isSet` を使用してください。TypeScript で型ガードとしても動作します。 + +```typescript +import { isSet } from 'es-toolkit/compat'; + +// Set確認 +const set = new Set(); +isSet(set); // true + +// その他の型はfalse +isSet(new Map()); // false +isSet(new WeakSet()); // false +isSet([]); // false +isSet({}); // false +isSet('set'); // false +isSet(123); // false +isSet(null); // false +isSet(undefined); // false +``` + +Setと似た他のコレクションとも区別します。 + +```typescript +import { isSet } from 'es-toolkit/compat'; + +// Set vs Map vs WeakSet +isSet(new Set([1, 2, 3])); // true +isSet(new Map([['key', 'value']])); // false +isSet(new WeakSet()); // false + +// Set vs 配列 +isSet(new Set([1, 2, 3])); // true +isSet([1, 2, 3]); // false + +// Set vs 一般オブジェクト +isSet(new Set()); // true +isSet({}); // false +isSet(Object.create(null)); // false +``` + +#### パラメータ + +- `value` (`unknown`): Setかどうかを確認する値です。 + +#### 戻り値 + +(`value is Set`): 値がSetの場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/predicate/isString.md b/docs/ja/compat/reference/predicate/isString.md similarity index 100% rename from docs/ja/reference/compat/predicate/isString.md rename to docs/ja/compat/reference/predicate/isString.md diff --git a/docs/ja/reference/compat/predicate/isSymbol.md b/docs/ja/compat/reference/predicate/isSymbol.md similarity index 100% rename from docs/ja/reference/compat/predicate/isSymbol.md rename to docs/ja/compat/reference/predicate/isSymbol.md diff --git a/docs/ja/reference/compat/predicate/isTypedArray.md b/docs/ja/compat/reference/predicate/isTypedArray.md similarity index 100% rename from docs/ja/reference/compat/predicate/isTypedArray.md rename to docs/ja/compat/reference/predicate/isTypedArray.md diff --git a/docs/ja/compat/reference/predicate/isUndefined.md b/docs/ja/compat/reference/predicate/isUndefined.md new file mode 100644 index 000000000..35fcfbaca --- /dev/null +++ b/docs/ja/compat/reference/predicate/isUndefined.md @@ -0,0 +1,92 @@ +# isUndefined (Lodash 互換性) + +::: warning es-toolkitの [isUndefined](../../../reference/predicate/isUndefined.md)を使用してください + +この `isUndefined` 関数はLodash互換性のための複雑な処理により遅く動作します。 + +代わりにより高速で現代的な `es-toolkit` の [isUndefined](../../../reference/predicate/isUndefined.md) を使用してください。 + +::: + +値が `undefined` かどうかを確認します。 + +```typescript +const result = isUndefined(value); +``` + +## 使用法 + +### `isUndefined(x)` + +値が正確に `undefined` かどうかを型安全に確認したい場合に `isUndefined` を使用してください。TypeScript で型ガードとしても動作します。 + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +// undefinedのみtrue +isUndefined(undefined); // true + +// nullもfalse +isUndefined(null); // false + +// その他すべての値もfalse +isUndefined(0); // false +isUndefined(''); // false +isUndefined(false); // false +isUndefined([]); // false +isUndefined({}); // false +isUndefined('undefined'); // false +isUndefined(NaN); // false +``` + +`undefined` と `null` を区別して確認することができます。 + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +function handleValue(value: string | null | undefined) { + if (isUndefined(value)) { + console.log('値がundefinedです'); + } else if (value === null) { + console.log('値が明示的にnullです'); + } else { + console.log(`値があります: ${value}`); + } +} + +handleValue(undefined); // "値がundefinedです" +handleValue(null); // "値が明示的にnullです" +handleValue('hello'); // "値があります: hello" +``` + +宣言されていない変数や初期化されていないプロパティを確認する際に便利です。 + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +const obj: { name?: string; age?: number } = { name: 'John' }; + +if (isUndefined(obj.age)) { + console.log('年齢が設定されていません'); + obj.age = 25; // デフォルト値を設定 +} + +// 関数パラメータのデフォルト値処理 +function greet(name: string, title?: string) { + if (isUndefined(title)) { + title = 'さん'; + } + console.log(`こんにちは、${name}${title}!`); +} + +greet('田中'); // "こんにちは、田中さん!" +greet('田中', '先生'); // "こんにちは、田中先生!" +``` + +#### パラメータ + +- `x` (`any`): `undefined` かどうかを確認する値です。 + +#### 戻り値 + +(`x is undefined`): 値が `undefined` の場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/predicate/isWeakMap.md b/docs/ja/compat/reference/predicate/isWeakMap.md similarity index 100% rename from docs/ja/reference/compat/predicate/isWeakMap.md rename to docs/ja/compat/reference/predicate/isWeakMap.md diff --git a/docs/ja/reference/compat/predicate/isWeakSet.md b/docs/ja/compat/reference/predicate/isWeakSet.md similarity index 100% rename from docs/ja/reference/compat/predicate/isWeakSet.md rename to docs/ja/compat/reference/predicate/isWeakSet.md diff --git a/docs/ja/reference/compat/predicate/matches.md b/docs/ja/compat/reference/predicate/matches.md similarity index 100% rename from docs/ja/reference/compat/predicate/matches.md rename to docs/ja/compat/reference/predicate/matches.md diff --git a/docs/ja/reference/compat/predicate/matchesProperty.md b/docs/ja/compat/reference/predicate/matchesProperty.md similarity index 100% rename from docs/ja/reference/compat/predicate/matchesProperty.md rename to docs/ja/compat/reference/predicate/matchesProperty.md diff --git a/docs/ja/compat/reference/string/camelCase.md b/docs/ja/compat/reference/string/camelCase.md new file mode 100644 index 000000000..00dbbe895 --- /dev/null +++ b/docs/ja/compat/reference/string/camelCase.md @@ -0,0 +1,48 @@ +# camelCase (Lodash 互換性) + +::: warning `es-toolkit` の `camelCase` を使用してください + +この `camelCase` 関数は、文字列以外の入力値の処理と短縮アポストロフィの除去などにより、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [camelCase](../../../reference/string/camelCase.md) を使用してください。 + +::: + +文字列をキャメルケースに変換します。 + +```typescript +const result = camelCase(str); +``` + +## 使用法 + +### `camelCase(str)` + +文字列をキャメルケースに変換します。キャメルケースは、最初の単語を小文字で始め、後続の単語の最初の文字を大文字にして、スペースなしで連結する命名規則です。 + +```typescript +import { camelCase } from 'es-toolkit/compat'; + +camelCase('camelCase'); // 'camelCase' +camelCase('some whitespace'); // 'someWhitespace' +camelCase('hyphen-text'); // 'hyphenText' +camelCase('HTTPRequest'); // 'httpRequest' +``` + +文字列以外の値も文字列に変換して処理します。 + +```typescript +import { camelCase } from 'es-toolkit/compat'; + +camelCase(123); // '123' +camelCase(null); // '' +camelCase(undefined); // '' +``` + +#### パラメータ + +- `str` (`string | object`,オプション): キャメルケースに変換する値です。 + +#### 戻り値 + +(`string`): キャメルケースに変換された文字列を返します。 diff --git a/docs/ja/compat/reference/string/capitalize.md b/docs/ja/compat/reference/string/capitalize.md new file mode 100644 index 000000000..1fa5f1965 --- /dev/null +++ b/docs/ja/compat/reference/string/capitalize.md @@ -0,0 +1,48 @@ +# capitalize (Lodash 互換性) + +::: warning `es-toolkit` の `capitalize` を使用してください + +この `capitalize` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [capitalize](../../../reference/string/capitalize.md) を使用してください。 + +::: + +文字列の最初の文字を大文字に、残りの文字を小文字に変換します。 + +```typescript +const result = capitalize(str); +``` + +## 使用法 + +### `capitalize(str)` + +文字列の最初の文字を大文字に、残りの文字を小文字に変換します。単語の第一印象を良くしたり、タイトル形式にする際に便利です。 + +```typescript +import { capitalize } from 'es-toolkit/compat'; + +capitalize('fred'); // 'Fred' +capitalize('FRED'); // 'Fred' +capitalize('fRED'); // 'Fred' +``` + +空文字列や文字列以外の値も処理できます。 + +```typescript +import { capitalize } from 'es-toolkit/compat'; + +capitalize(''); // '' +capitalize(123); // '123' +capitalize(null); // '' +capitalize(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`,オプション): 最初の文字を大文字に変換する文字列です。 + +#### 戻り値 + +(`string`): 最初の文字が大文字で残りが小文字の文字列を返します。 diff --git a/docs/ja/compat/reference/string/deburr.md b/docs/ja/compat/reference/string/deburr.md new file mode 100644 index 000000000..fe40ed041 --- /dev/null +++ b/docs/ja/compat/reference/string/deburr.md @@ -0,0 +1,47 @@ +# deburr (Lodash 互換性) + +::: warning `es-toolkit` の `deburr` を使用してください + +この `deburr` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [deburr](../../../reference/string/deburr.md) を使用してください。 + +::: + +文字列内の特殊文字と発音区別記号をASCII文字に変換します。 + +```typescript +const result = deburr(str); +``` + +## 使用法 + +### `deburr(str)` + +文字列内の特殊文字と発音区別記号をASCII文字に変換します。多言語テキストを検索やソートに使いやすくする際に便利です。 + +```typescript +import { deburr } from 'es-toolkit/compat'; + +deburr('Æthelred'); // 'Aethelred' +deburr('München'); // 'Munchen' +deburr('Crème brûlée'); // 'Creme brulee' +``` + +文字列以外の値も文字列に変換して処理します。 + +```typescript +import { deburr } from 'es-toolkit/compat'; + +deburr(123); // '123' +deburr(null); // '' +deburr(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`,オプション): 特殊文字を削除する文字列です。 + +#### 戻り値 + +(`string`): 特殊文字と発音区別記号がASCII文字に変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/endsWith.md b/docs/ja/compat/reference/string/endsWith.md similarity index 100% rename from docs/ja/reference/compat/string/endsWith.md rename to docs/ja/compat/reference/string/endsWith.md diff --git a/docs/ja/compat/reference/string/escape.md b/docs/ja/compat/reference/string/escape.md new file mode 100644 index 000000000..3383a2a31 --- /dev/null +++ b/docs/ja/compat/reference/string/escape.md @@ -0,0 +1,48 @@ +# escape (Lodash 互換性) + +::: warning `es-toolkit` の `escape` を使用してください + +この `escape` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [escape](../../../reference/string/escape.md) を使用してください。 + +::: + +文字列内のHTML特殊文字をHTMLエンティティに変換します。 + +```typescript +const result = escape(str); +``` + +## 使用法 + +### `escape(str)` + +文字列内の `&`、`<`、`>`、`"`、`'` 文字を対応するHTMLエンティティに変換します。HTML文書にテキストを安全に挿入する際にXSS攻撃を防ぐのに便利です。 + +```typescript +import { escape } from 'es-toolkit/compat'; + +escape('This is a
element.'); // 'This is a <div> element.' +escape('This is a "quote"'); // 'This is a "quote"' +escape("This is a 'quote'"); // 'This is a 'quote'' +escape('This is a & symbol'); // 'This is a & symbol' +``` + +文字列以外の値も文字列に変換して処理します。 + +```typescript +import { escape } from 'es-toolkit/compat'; + +escape(123); // '123' +escape(null); // '' +escape(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`,オプション): HTML特殊文字をエスケープする文字列です。 + +#### 戻り値 + +(`string`): HTML特殊文字がエンティティに変換された文字列を返します。 diff --git a/docs/ja/compat/reference/string/escapeRegExp.md b/docs/ja/compat/reference/string/escapeRegExp.md new file mode 100644 index 000000000..8dbedc500 --- /dev/null +++ b/docs/ja/compat/reference/string/escapeRegExp.md @@ -0,0 +1,49 @@ +# escapeRegExp (Lodash 互換性) + +::: warning `es-toolkit` の `escapeRegExp` を使用してください + +この `escapeRegExp` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [escapeRegExp](../../../reference/string/escapeRegExp.md) を使用してください。 + +::: + +文字列内の正規表現特殊文字をエスケープします。 + +```typescript +const result = escapeRegExp(str); +``` + +## 使用法 + +### `escapeRegExp(str)` + +文字列内の正規表現特殊文字 `^`、`$`、`\`、`.`、`*`、`+`、`?`、`(`、`)`、`[`、`]`、`{`、`}`、`|` をエスケープします。動的に正規表現を生成する際に文字列を文字通り処理したい場合に便利です。 + +```typescript +import { escapeRegExp } from 'es-toolkit/compat'; + +escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); +// '\\[es-toolkit\\]\\(https://es-toolkit\\.dev/\\)' + +escapeRegExp('$^{}.+*?()[]|\\'); +// '\\$\\^\\{\\}\\.\\+\\*\\?\\(\\)\\[\\]\\|\\\\' +``` + +文字列以外の値も文字列に変換して処理します。 + +```typescript +import { escapeRegExp } from 'es-toolkit/compat'; + +escapeRegExp(123); // '123' +escapeRegExp(null); // '' +escapeRegExp(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`,オプション): 正規表現特殊文字をエスケープする文字列です。 + +#### 戻り値 + +(`string`): 正規表現特殊文字がエスケープされた文字列を返します。 diff --git a/docs/ja/compat/reference/string/kebabCase.md b/docs/ja/compat/reference/string/kebabCase.md new file mode 100644 index 000000000..39db909c2 --- /dev/null +++ b/docs/ja/compat/reference/string/kebabCase.md @@ -0,0 +1,48 @@ +# kebabCase (Lodash 互換性) + +::: warning `es-toolkit` の `kebabCase` を使用してください + +この `kebabCase` 関数は、文字列以外の入力値の処理と短縮アポストロフィの除去などにより、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [kebabCase](../../../reference/string/kebabCase.md) を使用してください。 + +::: + +文字列をケバブケースに変換します。 + +```typescript +const result = kebabCase(str); +``` + +## 使用法 + +### `kebabCase(str)` + +文字列をケバブケースに変換します。ケバブケースは、各単語を小文字で書き、ダッシュ(-)文字で連結する命名規則です。URLやCSSクラス名で主に使用されます。 + +```typescript +import { kebabCase } from 'es-toolkit/compat'; + +kebabCase('camelCase'); // 'camel-case' +kebabCase('some whitespace'); // 'some-whitespace' +kebabCase('hyphen-text'); // 'hyphen-text' +kebabCase('HTTPRequest'); // 'http-request' +``` + +文字列以外の値も文字列に変換して処理します。 + +```typescript +import { kebabCase } from 'es-toolkit/compat'; + +kebabCase(123); // '123' +kebabCase(null); // '' +kebabCase(undefined); // '' +``` + +#### パラメータ + +- `str` (`string | object`,オプション): ケバブケースに変換する値です。 + +#### 戻り値 + +(`string`): ケバブケースに変換された文字列を返します。 diff --git a/docs/ja/compat/reference/string/lowerCase.md b/docs/ja/compat/reference/string/lowerCase.md new file mode 100644 index 000000000..f2d780c5d --- /dev/null +++ b/docs/ja/compat/reference/string/lowerCase.md @@ -0,0 +1,48 @@ +# lowerCase (Lodash 互換性) + +::: warning `es-toolkit` の `lowerCase` を使用してください + +この `lowerCase` 関数は、文字列以外の入力値の処理と短縮アポストロフィの除去などにより、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [lowerCase](../../../reference/string/lowerCase.md) を使用してください。 + +::: + +文字列を小文字の単語にスペースで区切って変換します。 + +```typescript +const result = lowerCase(str); +``` + +## 使用法 + +### `lowerCase(str)` + +文字列を小文字の単語にスペースで区切って変換します。各単語は小文字に変換され、スペース文字で連結されます。人間が読みやすいテキスト形式にする際に便利です。 + +```typescript +import { lowerCase } from 'es-toolkit/compat'; + +lowerCase('camelCase'); // 'camel case' +lowerCase('some whitespace'); // 'some whitespace' +lowerCase('hyphen-text'); // 'hyphen text' +lowerCase('HTTPRequest'); // 'http request' +``` + +文字列以外の値も文字列に変換して処理します。 + +```typescript +import { lowerCase } from 'es-toolkit/compat'; + +lowerCase(123); // '123' +lowerCase(null); // '' +lowerCase(undefined); // '' +``` + +#### パラメータ + +- `str` (`string | object`,オプション): 小文字形式に変換する値です。 + +#### 戻り値 + +(`string`): 小文字の単語がスペースで区切られた文字列を返します。 diff --git a/docs/ja/compat/reference/string/lowerFirst.md b/docs/ja/compat/reference/string/lowerFirst.md new file mode 100644 index 000000000..f2dd0663a --- /dev/null +++ b/docs/ja/compat/reference/string/lowerFirst.md @@ -0,0 +1,48 @@ +# lowerFirst (Lodash 互換性) + +::: warning `es-toolkit` の `lowerFirst` を使用してください + +この `lowerFirst` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [lowerFirst](../../../reference/string/lowerFirst.md) を使用してください。 + +::: + +文字列の最初の文字を小文字に変換します。 + +```typescript +const result = lowerFirst(str); +``` + +## 使用法 + +### `lowerFirst(str)` + +文字列の最初の文字を小文字に変換します。残りの文字はそのまま維持されます。camelCase変数名を作成したり、最初の文字だけ小文字にしたい場合に便利です。 + +```typescript +import { lowerFirst } from 'es-toolkit/compat'; + +lowerFirst('fred'); // 'fred' +lowerFirst('Fred'); // 'fred' +lowerFirst('FRED'); // 'fRED' +lowerFirst(''); // '' +``` + +文字列以外の値も文字列に変換して処理します。 + +```typescript +import { lowerFirst } from 'es-toolkit/compat'; + +lowerFirst(123); // '123' +lowerFirst(null); // '' +lowerFirst(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`,オプション): 最初の文字を小文字に変換する文字列です。 + +#### 戻り値 + +(`string`): 最初の文字が小文字に変換された文字列を返します。 diff --git a/docs/ja/compat/reference/string/pad.md b/docs/ja/compat/reference/string/pad.md new file mode 100644 index 000000000..a79960da4 --- /dev/null +++ b/docs/ja/compat/reference/string/pad.md @@ -0,0 +1,60 @@ +# pad (Lodash 互換性) + +::: warning `es-toolkit` の `pad` を使用してください + +この `pad` 関数は、`null` や `undefined` の処理などにより、動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [pad](../../../reference/string/pad.md) を使用してください。 + +::: + +文字列の前後にパディング文字を追加して、指定された長さに合わせます。 + +```typescript +const padded = pad(str, length, chars); +``` + +## 使用法 + +### `pad(str, length, chars)` + +文字列が希望する長さより短い場合に、前後にパディング文字を追加して長さを合わせたい場合は `pad` を使用してください。パディング文字が均等に分割されない場合、追加の文字は右側に配置されます。 + +```typescript +import { pad } from 'es-toolkit/compat'; + +// デフォルトの空白でパディング +pad('abc', 8); +// Returns: ' abc ' + +// 指定した文字でパディング +pad('abc', 8, '_-'); +// Returns: '_-abc_-_' + +// すでに十分な長さならそのまま返す +pad('abc', 3); +// Returns: 'abc' + +// 長さがより短いならそのまま返す +pad('abc', 2); +// Returns: 'abc' +``` + +`null` や `undefined` は空文字列として処理されます。 + +```typescript +import { pad } from 'es-toolkit/compat'; + +pad(null, 5); // ' ' +pad(undefined, 3, '*'); // '***' +``` + +#### パラメータ + +- `str` (`string`,オプション): パディングする文字列です。 +- `length` (`number`,オプション): 目標の長さです。デフォルトは `0` です。 +- `chars` (`string`,オプション): パディングに使用する文字です。デフォルトは空白 `' '` です。 + +#### 戻り値 + +(`string`): 指定された長さまでパディングされた文字列を返します。 diff --git a/docs/ja/reference/compat/string/padEnd.md b/docs/ja/compat/reference/string/padEnd.md similarity index 100% rename from docs/ja/reference/compat/string/padEnd.md rename to docs/ja/compat/reference/string/padEnd.md diff --git a/docs/ja/reference/compat/string/padStart.md b/docs/ja/compat/reference/string/padStart.md similarity index 100% rename from docs/ja/reference/compat/string/padStart.md rename to docs/ja/compat/reference/string/padStart.md diff --git a/docs/ja/reference/compat/string/repeat.md b/docs/ja/compat/reference/string/repeat.md similarity index 100% rename from docs/ja/reference/compat/string/repeat.md rename to docs/ja/compat/reference/string/repeat.md diff --git a/docs/ja/reference/compat/string/replace.md b/docs/ja/compat/reference/string/replace.md similarity index 100% rename from docs/ja/reference/compat/string/replace.md rename to docs/ja/compat/reference/string/replace.md diff --git a/docs/ja/compat/reference/string/snakeCase.md b/docs/ja/compat/reference/string/snakeCase.md new file mode 100644 index 000000000..2d29bdbe6 --- /dev/null +++ b/docs/ja/compat/reference/string/snakeCase.md @@ -0,0 +1,58 @@ +# snakeCase (Lodash 互換性) + +::: warning `es-toolkit` の `snakeCase` を使用してください + +この `snakeCase` 関数は、`null` または `undefined` を処理するための正規化ロジックにより動作が遅くなります。 + +代わりに、より高速で現代的な `es-toolkit` の [snakeCase](../../../reference/string/snakeCase.md) を使用してください。 + +::: + +文字列をスネークケースに変換します。 + +```typescript +const snakeCased = snakeCase(str); +``` + +## 使用法 + +### `snakeCase(str)` + +文字列をスネークケース (snake*case) に変換したい場合は `snakeCase` を使用してください。スネークケースは、各単語を小文字で書き、アンダースコア (*) で連結する命名規則です。 + +```typescript +import { snakeCase } from 'es-toolkit/compat'; + +// キャメルケースの変換 +snakeCase('camelCase'); +// Returns: 'camel_case' + +// 空白で区切られた文字列の変換 +snakeCase('some whitespace'); +// Returns: 'some_whitespace' + +// ハイフンで区切られた文字列の変換 +snakeCase('hyphen-text'); +// Returns: 'hyphen_text' + +// 連続する大文字の処理 +snakeCase('HTTPRequest'); +// Returns: 'http_request' +``` + +`null` または `undefined` は空文字列として扱われます。 + +```typescript +import { snakeCase } from 'es-toolkit/compat'; + +snakeCase(null); // '' +snakeCase(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`, オプション): スネークケースに変換する文字列です。 + +#### 戻り値 + +(`string`): スネークケースに変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/split.md b/docs/ja/compat/reference/string/split.md similarity index 100% rename from docs/ja/reference/compat/string/split.md rename to docs/ja/compat/reference/string/split.md diff --git a/docs/ja/compat/reference/string/startCase.md b/docs/ja/compat/reference/string/startCase.md new file mode 100644 index 000000000..fca867aa4 --- /dev/null +++ b/docs/ja/compat/reference/string/startCase.md @@ -0,0 +1,58 @@ +# startCase (Lodash 互換性) + +::: warning `es-toolkit`の`startCase`を使用してください + +この`startCase`関数は、`null`または`undefined`を処理するための正規化ロジックにより、動作が遅くなります。 + +代わりに、より高速で現代的な`es-toolkit`の[startCase](../../../reference/string/startCase.md)を使用してください。 + +::: + +文字列をスタートケースに変換します。 + +```typescript +const startCased = startCase(str); +``` + +## 使用法 + +### `startCase(str)` + +文字列をスタートケース(Start Case)に変換したい場合は、`startCase`を使用してください。スタートケースは、各単語の最初の文字を大文字にし、スペースで区切る命名規則です。 + +```typescript +import { startCase } from 'es-toolkit/compat'; + +// 通常の文字列を変換 +startCase('hello world'); +// 戻り値: 'Hello World' + +// すでに大文字の単語はそのまま保持 +startCase('HELLO WORLD'); +// 戻り値: 'HELLO WORLD' + +// ハイフンで区切られた文字列を変換 +startCase('hello-world'); +// 戻り値: 'Hello World' + +// アンダースコアで区切られた文字列を変換 +startCase('hello_world'); +// 戻り値: 'Hello World' +``` + +`null`または`undefined`は空文字列として処理されます。 + +```typescript +import { startCase } from 'es-toolkit/compat'; + +startCase(null); // '' +startCase(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`, オプション): スタートケースに変換する文字列です。 + +#### 戻り値 + +(`string`): スタートケースに変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/startsWith.md b/docs/ja/compat/reference/string/startsWith.md similarity index 100% rename from docs/ja/reference/compat/string/startsWith.md rename to docs/ja/compat/reference/string/startsWith.md diff --git a/docs/ja/reference/compat/string/template.md b/docs/ja/compat/reference/string/template.md similarity index 100% rename from docs/ja/reference/compat/string/template.md rename to docs/ja/compat/reference/string/template.md diff --git a/docs/ja/reference/compat/string/toLower.md b/docs/ja/compat/reference/string/toLower.md similarity index 100% rename from docs/ja/reference/compat/string/toLower.md rename to docs/ja/compat/reference/string/toLower.md diff --git a/docs/ja/reference/compat/string/toUpper.md b/docs/ja/compat/reference/string/toUpper.md similarity index 100% rename from docs/ja/reference/compat/string/toUpper.md rename to docs/ja/compat/reference/string/toUpper.md diff --git a/docs/ja/compat/reference/string/trim.md b/docs/ja/compat/reference/string/trim.md new file mode 100644 index 000000000..2b79cbe3a --- /dev/null +++ b/docs/ja/compat/reference/string/trim.md @@ -0,0 +1,55 @@ +# trim (Lodash 互換性) + +::: warning `es-toolkit` の `trim` を使用してください + +この `trim` 関数は、`null` や `undefined` の処理、配列型の `chars` 処理などにより動作が遅くなります。 + +代わりに、より高速でモダンな `es-toolkit` の [trim](../../../reference/string/trim.md) を使用してください。 + +::: + +文字列の先頭と末尾の空白または指定された文字を削除します。 + +```typescript +const trimmed = trim(str, chars); +``` + +## 使用法 + +### `trim(str, chars)` + +文字列の先頭と末尾から空白または特定の文字を削除したい場合は `trim` を使用します。`chars` を指定しない場合は、先頭と末尾の空白のみが削除されます。 + +```typescript +import { trim } from 'es-toolkit/compat'; + +// 先頭と末尾の空白を削除 +trim(' hello '); +// 戻り値: 'hello' + +// 指定された文字を削除 +trim('--hello--', '-'); +// 戻り値: 'hello' + +// 配列で複数の文字を削除 +trim('##hello##', ['#', 'o']); +// 戻り値: 'hell' +``` + +`null` または `undefined` は空文字列として扱われます。 + +```typescript +import { trim } from 'es-toolkit/compat'; + +trim(null); // '' +trim(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`, オプション): トリミングする文字列。 +- `chars` (`string`, オプション): 削除する文字。指定しない場合は空白が削除されます。 + +#### 戻り値 + +(`string`): 先頭と末尾から指定された文字が削除された文字列を返します。 diff --git a/docs/ja/compat/reference/string/trimEnd.md b/docs/ja/compat/reference/string/trimEnd.md new file mode 100644 index 000000000..14477d978 --- /dev/null +++ b/docs/ja/compat/reference/string/trimEnd.md @@ -0,0 +1,55 @@ +# trimEnd (Lodash 互換性) + +::: warning `es-toolkit` の `trimEnd` を使用してください + +この `trimEnd` 関数は、`null` や `undefined` の処理、パラメータの順序変更などにより動作が遅くなります。 + +代わりに、より高速でモダンな `es-toolkit` の [trimEnd](../../../reference/string/trimEnd.md) を使用してください。 + +::: + +文字列の末尾の空白または指定された文字を削除します。 + +```typescript +const trimmed = trimEnd(str, chars); +``` + +## 使用法 + +### `trimEnd(str, chars)` + +文字列の末尾から空白または特定の文字を削除したい場合は `trimEnd` を使用します。`chars` を指定しない場合は、末尾の空白のみが削除されます。 + +```typescript +import { trimEnd } from 'es-toolkit/compat'; + +// 末尾の空白を削除 +trimEnd(' abc '); +// 戻り値: ' abc' + +// 指定された文字を削除 +trimEnd('-_-abc-_-', '_-'); +// 戻り値: '-_-abc' + +// 文字列の末尾にのみ適用 +trimEnd('abc', 'a'); +// 戻り値: 'abc' +``` + +`null` または `undefined` は空文字列として扱われます。 + +```typescript +import { trimEnd } from 'es-toolkit/compat'; + +trimEnd(null); // '' +trimEnd(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`, オプション): 末尾をトリミングする文字列。 +- `chars` (`string`, オプション): 削除する文字。指定しない場合は空白が削除されます。 + +#### 戻り値 + +(`string`): 末尾から指定された文字が削除された文字列を返します。 diff --git a/docs/ja/compat/reference/string/trimStart.md b/docs/ja/compat/reference/string/trimStart.md new file mode 100644 index 000000000..8bef9b3c5 --- /dev/null +++ b/docs/ja/compat/reference/string/trimStart.md @@ -0,0 +1,55 @@ +# trimStart (Lodash 互換性) + +::: warning `es-toolkit` の `trimStart` を使用してください + +この `trimStart` 関数は、`null` や `undefined` の処理、パラメータの順序変更などにより動作が遅くなります。 + +代わりに、より高速でモダンな `es-toolkit` の [trimStart](../../../reference/string/trimStart.md) を使用してください。 + +::: + +文字列の先頭の空白または指定された文字を削除します。 + +```typescript +const trimmed = trimStart(str, chars); +``` + +## 使用法 + +### `trimStart(str, chars)` + +文字列の先頭から空白または特定の文字を削除したい場合は `trimStart` を使用します。`chars` を指定しない場合は、先頭の空白のみが削除されます。 + +```typescript +import { trimStart } from 'es-toolkit/compat'; + +// 先頭の空白を削除 +trimStart(' abc '); +// 戻り値: 'abc ' + +// 指定された文字を削除 +trimStart('-_-abc-_-', '_-'); +// 戻り値: 'abc-_-' + +// 文字列の先頭にのみ適用 +trimStart('abc', 'c'); +// 戻り値: 'abc' +``` + +`null` または `undefined` は空文字列として扱われます。 + +```typescript +import { trimStart } from 'es-toolkit/compat'; + +trimStart(null); // '' +trimStart(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`, オプション): 先頭をトリミングする文字列。 +- `chars` (`string`, オプション): 削除する文字。指定しない場合は空白が削除されます。 + +#### 戻り値 + +(`string`): 先頭から指定された文字が削除された文字列を返します。 diff --git a/docs/ja/reference/compat/string/truncate.md b/docs/ja/compat/reference/string/truncate.md similarity index 100% rename from docs/ja/reference/compat/string/truncate.md rename to docs/ja/compat/reference/string/truncate.md diff --git a/docs/ja/compat/reference/string/unescape.md b/docs/ja/compat/reference/string/unescape.md new file mode 100644 index 000000000..d5274dbbf --- /dev/null +++ b/docs/ja/compat/reference/string/unescape.md @@ -0,0 +1,58 @@ +# unescape (Lodash 互換性) + +::: warning `es-toolkit` の `unescape` を使用してください + +この `unescape` 関数は、`null` や `undefined` の処理のための変換ロジックにより動作が遅くなります。 + +代わりに、より高速でモダンな `es-toolkit` の [unescape](../../../reference/string/unescape.md) を使用してください。 + +::: + +HTML エンティティを元の文字に変換します。 + +```typescript +const unescaped = unescape(str); +``` + +## 使用法 + +### `unescape(str)` + +HTML エンティティ `&`、`<`、`>`、`"`、`'` を元の文字に戻したい場合は `unescape` を使用します。これは `escape` 関数の逆の操作です。 + +```typescript +import { unescape } from 'es-toolkit/compat'; + +// HTML タグをアンエスケープ +unescape('This is a <div> element.'); +// 戻り値: 'This is a
element.' + +// 引用符をアンエスケープ +unescape('This is a "quote"'); +// 戻り値: 'This is a "quote"' + +// アポストロフィをアンエスケープ +unescape('This is a 'quote''); +// 戻り値: 'This is a 'quote'' + +// アンパサンドをアンエスケープ +unescape('This is a & symbol'); +// 戻り値: 'This is a & symbol' +``` + +`null` または `undefined` は空文字列として扱われます。 + +```typescript +import { unescape } from 'es-toolkit/compat'; + +unescape(null); // '' +unescape(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`, オプション): アンエスケープする文字列。 + +#### 戻り値 + +(`string`): HTML エンティティが元の文字に変換された文字列を返します。 diff --git a/docs/ja/compat/reference/string/upperCase.md b/docs/ja/compat/reference/string/upperCase.md new file mode 100644 index 000000000..e4f6906f9 --- /dev/null +++ b/docs/ja/compat/reference/string/upperCase.md @@ -0,0 +1,58 @@ +# upperCase (Lodash 互換性) + +::: warning `es-toolkit` の `upperCase` を使用してください + +この `upperCase` 関数は、`null` や `undefined` の処理のための正規化ロジックにより動作が遅くなります。 + +代わりに、より高速でモダンな `es-toolkit` の [upperCase](../../../reference/string/upperCase.md) を使用してください。 + +::: + +文字列をアッパーケースに変換します。 + +```typescript +const upperCased = upperCase(str); +``` + +## 使用法 + +### `upperCase(str)` + +文字列をアッパーケース (UPPER CASE) に変換したい場合は `upperCase` を使用します。アッパーケースは、各単語を大文字で書き、スペースで接続する命名規則です。 + +```typescript +import { upperCase } from 'es-toolkit/compat'; + +// キャメルケースを変換 +upperCase('camelCase'); +// 戻り値: 'CAMEL CASE' + +// スペース区切りの文字列を変換 +upperCase('some whitespace'); +// 戻り値: 'SOME WHITESPACE' + +// ハイフン区切りの文字列を変換 +upperCase('hyphen-text'); +// 戻り値: 'HYPHEN TEXT' + +// 大文字が連続して現れる場合 +upperCase('HTTPRequest'); +// 戻り値: 'HTTP REQUEST' +``` + +`null` または `undefined` は空文字列として扱われます。 + +```typescript +import { upperCase } from 'es-toolkit/compat'; + +upperCase(null); // '' +upperCase(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`, オプション): アッパーケースに変換する文字列。 + +#### 戻り値 + +(`string`): アッパーケースに変換された文字列を返します。 diff --git a/docs/ja/compat/reference/string/upperFirst.md b/docs/ja/compat/reference/string/upperFirst.md new file mode 100644 index 000000000..b2843d6ac --- /dev/null +++ b/docs/ja/compat/reference/string/upperFirst.md @@ -0,0 +1,54 @@ +# upperFirst (Lodash 互換性) + +::: warning `es-toolkit` の `upperFirst` を使用してください + +この `upperFirst` 関数は、`null` や `undefined` の処理のための変換ロジックにより動作が遅くなります。 + +代わりに、より高速でモダンな `es-toolkit` の [upperFirst](../../../reference/string/upperFirst.md) を使用してください。 + +::: + +文字列の最初の文字を大文字に変換します。 + +```typescript +const upperCased = upperFirst(str); +``` + +## 使用法 + +### `upperFirst(str)` + +文字列の最初の文字のみを大文字にしたい場合は `upperFirst` を使用します。残りの文字はそのまま保持されます。 + +```typescript +import { upperFirst } from 'es-toolkit/compat'; + +// 小文字で始まる文字列 +upperFirst('fred'); +// 戻り値: 'Fred' + +// すでに大文字で始まる文字列 +upperFirst('Fred'); +// 戻り値: 'Fred' + +// すべて大文字の文字列 +upperFirst('FRED'); +// 戻り値: 'FRED' +``` + +`null` または `undefined` は空文字列として扱われます。 + +```typescript +import { upperFirst } from 'es-toolkit/compat'; + +upperFirst(null); // '' +upperFirst(undefined); // '' +``` + +#### パラメータ + +- `str` (`string`, オプション): 最初の文字を大文字に変換する文字列。 + +#### 戻り値 + +(`string`): 最初の文字が大文字に変換された文字列を返します。 diff --git a/docs/ja/compat/reference/string/words.md b/docs/ja/compat/reference/string/words.md new file mode 100644 index 000000000..267b3e3a5 --- /dev/null +++ b/docs/ja/compat/reference/string/words.md @@ -0,0 +1,69 @@ +# words (Lodash 互換性) + +::: warning `es-toolkit` の `words` を使用してください + +この `words` 関数は、`null` や `undefined` の処理、複雑な Unicode サポートなどにより動作が遅くなります。 + +代わりに、より高速でモダンな `es-toolkit` の [words](../../../reference/string/words.md) を使用してください。 + +::: + +文字列を単語の配列に分割します。 + +```typescript +const wordArray = words(str, pattern); +``` + +## 使用法 + +### `words(str, pattern)` + +文字列を単語単位で分割したい場合は `words` を使用します。デフォルトでは、英字、数字、絵文字などを認識して単語を抽出します。 + +```typescript +import { words } from 'es-toolkit/compat'; + +// 基本的な単語抽出 +words('fred, barney, & pebbles'); +// 戻り値: ['fred', 'barney', 'pebbles'] + +// キャメルケースから単語を抽出 +words('camelCaseWord'); +// 戻り値: ['camel', 'Case', 'Word'] + +// 数字を含む文字列 +words('hello123world'); +// 戻り値: ['hello', '123', 'world'] +``` + +カスタムパターンを使用して単語を抽出することもできます。 + +```typescript +import { words } from 'es-toolkit/compat'; + +// 正規表現を使用した単語抽出 +words('hello world', /\w+/g); +// 戻り値: ['hello', 'world'] + +// 文字列パターンを使用 +words('one-two-three', '-'); +// 戻り値: ['-'] +``` + +`null` または `undefined` は空の配列として扱われます。 + +```typescript +import { words } from 'es-toolkit/compat'; + +words(null); // [] +words(undefined); // [] +``` + +#### パラメータ + +- `str` (`string`, オプション): 単語に分割する文字列。 +- `pattern` (`RegExp | string`, オプション): 単語にマッチするパターン。デフォルトは組み込みの Unicode 単語パターン。 + +#### 戻り値 + +(`string[]`): 抽出された単語の配列を返します。 diff --git a/docs/ja/reference/compat/util/bindAll.md b/docs/ja/compat/reference/util/bindAll.md similarity index 100% rename from docs/ja/reference/compat/util/bindAll.md rename to docs/ja/compat/reference/util/bindAll.md diff --git a/docs/ja/reference/compat/util/cond.md b/docs/ja/compat/reference/util/cond.md similarity index 100% rename from docs/ja/reference/compat/util/cond.md rename to docs/ja/compat/reference/util/cond.md diff --git a/docs/ja/reference/compat/util/constant.md b/docs/ja/compat/reference/util/constant.md similarity index 100% rename from docs/ja/reference/compat/util/constant.md rename to docs/ja/compat/reference/util/constant.md diff --git a/docs/ja/reference/compat/util/defaultTo.md b/docs/ja/compat/reference/util/defaultTo.md similarity index 100% rename from docs/ja/reference/compat/util/defaultTo.md rename to docs/ja/compat/reference/util/defaultTo.md diff --git a/docs/ja/reference/compat/util/eq.md b/docs/ja/compat/reference/util/eq.md similarity index 100% rename from docs/ja/reference/compat/util/eq.md rename to docs/ja/compat/reference/util/eq.md diff --git a/docs/ja/reference/compat/util/gt.md b/docs/ja/compat/reference/util/gt.md similarity index 100% rename from docs/ja/reference/compat/util/gt.md rename to docs/ja/compat/reference/util/gt.md diff --git a/docs/ja/reference/compat/util/gte.md b/docs/ja/compat/reference/util/gte.md similarity index 100% rename from docs/ja/reference/compat/util/gte.md rename to docs/ja/compat/reference/util/gte.md diff --git a/docs/ja/reference/compat/util/invoke.md b/docs/ja/compat/reference/util/invoke.md similarity index 100% rename from docs/ja/reference/compat/util/invoke.md rename to docs/ja/compat/reference/util/invoke.md diff --git a/docs/ja/reference/compat/util/iteratee.md b/docs/ja/compat/reference/util/iteratee.md similarity index 100% rename from docs/ja/reference/compat/util/iteratee.md rename to docs/ja/compat/reference/util/iteratee.md diff --git a/docs/ja/reference/compat/util/lt.md b/docs/ja/compat/reference/util/lt.md similarity index 100% rename from docs/ja/reference/compat/util/lt.md rename to docs/ja/compat/reference/util/lt.md diff --git a/docs/ja/reference/compat/util/lte.md b/docs/ja/compat/reference/util/lte.md similarity index 100% rename from docs/ja/reference/compat/util/lte.md rename to docs/ja/compat/reference/util/lte.md diff --git a/docs/ja/reference/compat/util/method.md b/docs/ja/compat/reference/util/method.md similarity index 100% rename from docs/ja/reference/compat/util/method.md rename to docs/ja/compat/reference/util/method.md diff --git a/docs/ja/reference/compat/util/methodOf.md b/docs/ja/compat/reference/util/methodOf.md similarity index 100% rename from docs/ja/reference/compat/util/methodOf.md rename to docs/ja/compat/reference/util/methodOf.md diff --git a/docs/ja/reference/compat/util/now.md b/docs/ja/compat/reference/util/now.md similarity index 100% rename from docs/ja/reference/compat/util/now.md rename to docs/ja/compat/reference/util/now.md diff --git a/docs/ja/reference/compat/util/over.md b/docs/ja/compat/reference/util/over.md similarity index 100% rename from docs/ja/reference/compat/util/over.md rename to docs/ja/compat/reference/util/over.md diff --git a/docs/ja/reference/compat/util/overEvery.md b/docs/ja/compat/reference/util/overEvery.md similarity index 100% rename from docs/ja/reference/compat/util/overEvery.md rename to docs/ja/compat/reference/util/overEvery.md diff --git a/docs/ja/reference/compat/util/overSome.md b/docs/ja/compat/reference/util/overSome.md similarity index 100% rename from docs/ja/reference/compat/util/overSome.md rename to docs/ja/compat/reference/util/overSome.md diff --git a/docs/ja/reference/compat/util/stubArray.md b/docs/ja/compat/reference/util/stubArray.md similarity index 100% rename from docs/ja/reference/compat/util/stubArray.md rename to docs/ja/compat/reference/util/stubArray.md diff --git a/docs/ja/reference/compat/util/stubFalse.md b/docs/ja/compat/reference/util/stubFalse.md similarity index 100% rename from docs/ja/reference/compat/util/stubFalse.md rename to docs/ja/compat/reference/util/stubFalse.md diff --git a/docs/ja/reference/compat/util/stubObject.md b/docs/ja/compat/reference/util/stubObject.md similarity index 100% rename from docs/ja/reference/compat/util/stubObject.md rename to docs/ja/compat/reference/util/stubObject.md diff --git a/docs/ja/reference/compat/util/stubString.md b/docs/ja/compat/reference/util/stubString.md similarity index 100% rename from docs/ja/reference/compat/util/stubString.md rename to docs/ja/compat/reference/util/stubString.md diff --git a/docs/ja/reference/compat/util/stubTrue.md b/docs/ja/compat/reference/util/stubTrue.md similarity index 100% rename from docs/ja/reference/compat/util/stubTrue.md rename to docs/ja/compat/reference/util/stubTrue.md diff --git a/docs/ja/reference/compat/util/times.md b/docs/ja/compat/reference/util/times.md similarity index 100% rename from docs/ja/reference/compat/util/times.md rename to docs/ja/compat/reference/util/times.md diff --git a/docs/ja/reference/compat/util/toArray.md b/docs/ja/compat/reference/util/toArray.md similarity index 100% rename from docs/ja/reference/compat/util/toArray.md rename to docs/ja/compat/reference/util/toArray.md diff --git a/docs/ja/reference/compat/util/toFinite.md b/docs/ja/compat/reference/util/toFinite.md similarity index 100% rename from docs/ja/reference/compat/util/toFinite.md rename to docs/ja/compat/reference/util/toFinite.md diff --git a/docs/ja/reference/compat/util/toInteger.md b/docs/ja/compat/reference/util/toInteger.md similarity index 100% rename from docs/ja/reference/compat/util/toInteger.md rename to docs/ja/compat/reference/util/toInteger.md diff --git a/docs/ja/reference/compat/util/toLength.md b/docs/ja/compat/reference/util/toLength.md similarity index 100% rename from docs/ja/reference/compat/util/toLength.md rename to docs/ja/compat/reference/util/toLength.md diff --git a/docs/ja/reference/compat/util/toNumber.md b/docs/ja/compat/reference/util/toNumber.md similarity index 100% rename from docs/ja/reference/compat/util/toNumber.md rename to docs/ja/compat/reference/util/toNumber.md diff --git a/docs/ja/reference/compat/util/toPath.md b/docs/ja/compat/reference/util/toPath.md similarity index 100% rename from docs/ja/reference/compat/util/toPath.md rename to docs/ja/compat/reference/util/toPath.md diff --git a/docs/ja/reference/compat/util/toPlainObject.md b/docs/ja/compat/reference/util/toPlainObject.md similarity index 100% rename from docs/ja/reference/compat/util/toPlainObject.md rename to docs/ja/compat/reference/util/toPlainObject.md diff --git a/docs/ja/reference/compat/util/toSafeInteger.md b/docs/ja/compat/reference/util/toSafeInteger.md similarity index 100% rename from docs/ja/reference/compat/util/toSafeInteger.md rename to docs/ja/compat/reference/util/toSafeInteger.md diff --git a/docs/ja/reference/compat/util/toString.md b/docs/ja/compat/reference/util/toString.md similarity index 100% rename from docs/ja/reference/compat/util/toString.md rename to docs/ja/compat/reference/util/toString.md diff --git a/docs/ja/reference/compat/util/uniqueId.md b/docs/ja/compat/reference/util/uniqueId.md similarity index 100% rename from docs/ja/reference/compat/util/uniqueId.md rename to docs/ja/compat/reference/util/uniqueId.md diff --git a/docs/ja/compatibility.md b/docs/ja/compatibility.md deleted file mode 100644 index b688339c9..000000000 --- a/docs/ja/compatibility.md +++ /dev/null @@ -1,63 +0,0 @@ -# Lodashとの互換性 - -::: tip ✅ バージョン1.39.3からLodashと100%の互換性を保証します - -`es-toolkit/compat`はLodashのすべての関数と同じように動作しながら、より軽量で高速です。 - -- Lodashの実際のテストコードと同じ動作を保証します。 -- Storybook、Recharts、CKEditorなどの有名なオープンソースライブラリで使用され、Nuxtから推奨されています。 - -すべての互換性関数の詳細なドキュメントは[互換性リファレンス](/ja/reference/compat/array/castArray)でご確認いただけます。 - -::: - -```tsx -// es-toolkit/compatはlodashと100%同じ動作を提供することを目指しています -import { chunk } from 'es-toolkit/compat'; - -// es-toolkitは元々chunkのサイズとして0をサポートしていませんでした -chunk([1, 2, 3, 4], 0); -// es-toolkit/compatはlodashと同じ[]を返します -``` - -`lodash`との最大の互換性を確保するために、2つのライブラリ間のギャップを埋める互換レイヤーである`es-toolkit/compat`を使用してください。 - -`es-toolkit`はスムーズなマイグレーションを保証するために、2つのライブラリ間の動作の違いがない`es-toolkit/compat`ライブラリを開発しています。`lodash`と同じAPIと機能を提供し、スムーズにマイグレーションできるようサポートする予定です。 - -`es-toolkit/compat`は実際の`lodash`テストコードを使用してテストされます。 - -`es-toolkit/compat`は、元の`es-toolkit`と比較して若干のパフォーマンス低下とバンドルサイズの増加があることに注意してください。このモジュールはスムーズな移行を支援するために設計されており、移行が完了したら最適なパフォーマンスを得るために元の`es-toolkit`に置き換えるべきです。 - -## デザイン原則 - -::: info -デザイン原則は変更される可能性があります。 -::: - -`es-toolkit/compat`は以下のような機能について`lodash`と100%同じ機能を提供することを目指しています。 - -- `lodash`のテストケースで作成された機能 -- `@types/lodash`または`@types/lodash-es`の型から推論できる機能 -- `lodash`から`es-toolkit`にコードを移行する際に発見された機能の違い([イシューページ](https://github.com/toss/es-toolkit/issues)に報告してください。) - -以下のような機能は`es-toolkit/compat`ではサポートしていません。 - -- 空文字列を0またはfalseに変換するような暗黙的な型変換 -- [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq)のような特定のタイプの配列に特化した実装を持つ関数 -- `Array.prototype`のようなJavaScriptの組み込みオブジェクトのプロトタイプが変更された場合に対応するコード -- JavaScript Realmに対応するコード -- `_(arr).map(...).filter(...)`のような"Seq"メソッドを通じたメソッドチェーンのサポート - -## 実装ステータス - -::: info -以下の絵文字は各機能の実装ステータスを示しています: - -- ✅: 完了(関数は完全に実装され、lodashのテストコードで全てのテストに合格しています。) -- 📝: レビュー中(関数は実装されていますが、まだlodashのテストコードでテストされていません。) -- ❌: 未実装(関数はまだ実装されていません。) - -"レビュー中"と表示されていても、完全に同じか確認しているだけですでに同じ機能を提供しているかもしれません。 -::: - - diff --git a/docs/ja/index.md b/docs/ja/index.md index f21157555..1b8795fc5 100644 --- a/docs/ja/index.md +++ b/docs/ja/index.md @@ -29,7 +29,7 @@ features: details: 同等の機能を持つ関数を基準に、最大97%小さなJavaScriptサイズを実現しています。 - title: 簡単なLodashの代替 details: es-toolkitはLodashを簡単に代替できる完全な互換性レイヤーを提供します。 - link: /ja/compatibility + link: /ja/compat/intro - title: モダンな実装 details: 最新のJavaScript APIを使用しているため、実装が直感的でシンプルです。 - title: 堅牢な型定義 diff --git a/docs/ja/reference/compat/array/chunk.md b/docs/ja/reference/compat/array/chunk.md deleted file mode 100644 index 829036949..000000000 --- a/docs/ja/reference/compat/array/chunk.md +++ /dev/null @@ -1,70 +0,0 @@ -# chunk(Lodash 互換性) - -::: warning `es-toolkit` の [`chunk`](../../array/chunk.md) を使用してください - -この `chunk` 関数は `null`、`undefined` の処理、`size` のデフォルト値処理などにより動作が遅くなります。 - -より高速でモダンな実装である `es-toolkit` の [chunk](../../array/chunk.md) を使用してください。 - -::: - -配列を指定されたサイズの小さな配列に分割します。 - -```typescript -const chunked = chunk(arr, size); -``` - -## 使用法 - -### `chunk(arr, size?)` - -長い配列を同じサイズの複数の小さな配列に分割したい場合は `chunk` を使用します。配列を均等に分割できない場合、最後の配列に残りの要素が含まれます。 - -```typescript -import { chunk } from 'es-toolkit/compat'; - -// 数値配列をサイズ 2 のチャンクに分割します。 -chunk([1, 2, 3, 4], 2); -// 戻り値: [[1, 2], [3, 4]] - -// 文字列配列をサイズ 3 のチャンクに分割します。 -chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); -// 戻り値: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] - -// 均等に分割できない場合 -chunk([1, 2, 3, 4, 5], 2); -// 戻り値: [[1, 2], [3, 4], [5]] -``` - -`null` または `undefined` は空の配列として扱われます。 - -```typescript -import { chunk } from 'es-toolkit/compat'; - -chunk(null, 2); -// 戻り値: [] - -chunk(undefined, 2); -// 戻り値: [] -``` - -サイズが 0 または負の場合、空の配列を返します。 - -```typescript -import { chunk } from 'es-toolkit/compat'; - -chunk([1, 2, 3], 0); -// 戻り値: [] - -chunk([1, 2, 3], -1); -// 戻り値: [] -``` - -#### パラメータ - -- `arr` (`ArrayLike | null | undefined`): 分割する配列。 -- `size` (`number`, オプション): 各小さな配列のサイズ。デフォルト値は `1`。 - -#### 戻り値 - -(`T[][]`): サイズ `size` で分割された二次元配列を返します。 diff --git a/docs/ja/reference/compat/array/compact.md b/docs/ja/reference/compat/array/compact.md deleted file mode 100644 index c91b21340..000000000 --- a/docs/ja/reference/compat/array/compact.md +++ /dev/null @@ -1,77 +0,0 @@ -# compact (Lodash 互換性) - -::: warning `es-toolkit`の[`compact`](../../array/compact.md)を使用してください - -この `compact` 関数は、`null` や `undefined` の処理、`size` のデフォルト値処理などにより、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [compact](../../array/compact.md) を使用してください。 - -::: - -配列から偽値と評価される値を削除します。 - -```typescript -const compacted = compact(arr); -``` - -## 使用法 - -### `compact(arr)` - -配列から `false`、`null`、`0`、`""`、`undefined`、`NaN` のような偽値と評価される値を削除したい場合、`compact` を使用してください。 - -```typescript -import { compact } from 'es-toolkit/compat'; - -// 偽値と評価される値を削除 -compact([0, 1, false, 2, '', 3]); -// Returns: [1, 2, 3] - -compact(['a', null, 'b', undefined, 'c', NaN]); -// Returns: ['a', 'b', 'c'] - -// BigInt 0も削除 -compact([0n, 1n, false, 2n]); -// Returns: [1n, 2n] - -// 空配列も処理 -compact([]); -// Returns: [] - -// すべての値が偽値と評価される場合 -compact([false, null, 0, '', undefined, NaN]); -// Returns: [] -``` - -真値と評価される値はそのまま保持されます。 - -```typescript -import { compact } from 'es-toolkit/compat'; - -compact([1, 'hello', true, {}, []]); -// Returns: [1, 'hello', true, {}, []] - -// 0以外の数値 -compact([0, -1, 2, -3]); -// Returns: [-1, 2, -3] -``` - -`null` や `undefined` の配列は空配列として処理されます。 - -```typescript -import { compact } from 'es-toolkit/compat'; - -compact(null); -// Returns: [] - -compact(undefined); -// Returns: [] -``` - -#### パラメータ - -- `arr` (`ArrayLike | null | undefined`): 圧縮する配列です。 - -#### 戻り値 - -(`T[]`): 偽値と評価される値が削除された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/countBy.md b/docs/ja/reference/compat/array/countBy.md deleted file mode 100644 index e300d7280..000000000 --- a/docs/ja/reference/compat/array/countBy.md +++ /dev/null @@ -1,88 +0,0 @@ -# countBy (Lodash 互換性) - -::: warning `es-toolkit`の`countBy`を使用してください - -この `countBy` 関数は、複雑な変換関数処理と型変換により、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [countBy](../../array/countBy.md) を使用してください。 - -::: - -配列やオブジェクトの要素を条件に従って分類し、各分類の個数を数えます。 - -```typescript -const counts = countBy(collection, iteratee); -``` - -## 使用法 - -### `countBy(collection, iteratee?)` - -配列やオブジェクトの各要素をある基準でグループ化し、各グループに何個の要素があるかを数えたい場合、`countBy` を使用してください。反復関数が返す値がキーになり、そのキーに該当する要素の個数が値になります。 - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// 数値を小数点以下切り捨てでグループ化 -countBy([6.1, 4.2, 6.3], Math.floor); -// Returns: { '4': 1, '6': 2 } - -// 文字列を長さでグループ化 -countBy(['one', 'two', 'three'], 'length'); -// Returns: { '3': 2, '5': 1 } - -// ユーザーを年齢代でグループ化 -const users = [ - { name: 'Alice', age: 25 }, - { name: 'Bob', age: 35 }, - { name: 'Charlie', age: 25 }, -]; -countBy(users, user => Math.floor(user.age / 10) * 10); -// Returns: { '20': 2, '30': 1 } -``` - -オブジェクトも処理できます。 - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// オブジェクトの値を型で分類 -const obj = { a: 1, b: 'string', c: 2, d: 'text' }; -countBy(obj, value => typeof value); -// Returns: { 'number': 2, 'string': 2 } -``` - -反復関数なしで使用すると、値そのものでグループ化されます。 - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// 値そのものでグループ化 -countBy([1, 2, 1, 3, 2, 1]); -// Returns: { '1': 3, '2': 2, '3': 1 } - -// 真偽値でグループ化 -countBy([true, false, true, true]); -// Returns: { 'true': 3, 'false': 1 } -``` - -`null` や `undefined` のコレクションは空のオブジェクトを返します。 - -```typescript -import { countBy } from 'es-toolkit/compat'; - -countBy(null); -// Returns: {} - -countBy(undefined); -// Returns: {} -``` - -#### パラメータ - -- `collection` (`ArrayLike | object | null | undefined`): 処理する配列またはオブジェクトです。 -- `iteratee` (`ValueIteratee`, 選択): 各要素をグループ化する基準を決定する関数です。関数、プロパティ名、または部分オブジェクトを使用できます。 - -#### 戻り値 - -(`Record`): 各グループのキーとそのグループの要素数を持つオブジェクトを返します。 diff --git a/docs/ja/reference/compat/array/difference.md b/docs/ja/reference/compat/array/difference.md deleted file mode 100644 index a4a555e57..000000000 --- a/docs/ja/reference/compat/array/difference.md +++ /dev/null @@ -1,94 +0,0 @@ -# difference (Lodash 互換性) - -::: warning `es-toolkit`の`difference`を使用してください - -この `difference` 関数は、`null` や `undefined` の処理、複数の配列引数処理により、複雑に動作します。 - -代わりに、より高速で現代的な `es-toolkit` の [difference](../../array/difference.md) を使用してください。 - -::: - -最初の配列から他の配列の値を除いた差集合を求めます。 - -```typescript -const result = difference(arr, ...values); -``` - -## 使用法 - -### `difference(arr, ...values)` - -最初の配列から残りの配列に含まれる値をすべて削除したい場合、`difference` を使用してください。順序は最初の配列の順序を保持します。 - -```typescript -import { difference } from 'es-toolkit/compat'; - -// 基本的な使用法 -const array1 = [1, 2, 3, 4, 5]; -const array2 = [2, 4]; -const array3 = [5, 6]; -difference(array1, array2, array3); -// Returns: [1, 3] - -// 文字列配列 -difference(['a', 'b', 'c'], ['b'], ['c', 'd']); -// Returns: ['a'] - -// 重複する値の処理 -difference([1, 2, 2, 3], [2]); -// Returns: [1, 3] -``` - -空配列や空の差集合も処理します。 - -```typescript -import { difference } from 'es-toolkit/compat'; - -// 空配列との差集合 -difference([1, 2, 3], []); -// Returns: [1, 2, 3] - -// すべての値が除外される場合 -difference([1, 2, 3], [1, 2, 3]); -// Returns: [] - -// 重複する値がない場合 -difference([1, 2], [3, 4]); -// Returns: [1, 2] -``` - -`null` や `undefined` の配列は空配列として処理されます。 - -```typescript -import { difference } from 'es-toolkit/compat'; - -difference(null, [1, 2]); -// Returns: [] - -difference(undefined, [1, 2]); -// Returns: [] - -difference([1, 2, 3], null, undefined); -// Returns: [1, 2, 3] (nullとundefinedは無視されます) -``` - -配列風オブジェクトもサポートします。 - -```typescript -import { difference } from 'es-toolkit/compat'; - -// 配列風オブジェクト -const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; -const arrayLike2 = { 0: 2, 1: 4, length: 2 }; -difference(arrayLike1, arrayLike2); -// Returns: [1, 3] -``` - -#### パラメータ - -- `arr` (`ArrayLike | null | undefined`): 差集合を求める基準配列です。 -- `values` (`...ArrayLike[]`): 除外する値を含む配列です。 - -#### 戻り値 - -(`T[]`): 最初の配列から他の配列の値を除いた新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/differenceBy.md b/docs/ja/reference/compat/array/differenceBy.md deleted file mode 100644 index 4c77c7698..000000000 --- a/docs/ja/reference/compat/array/differenceBy.md +++ /dev/null @@ -1,88 +0,0 @@ -# differenceBy (Lodash 互換性) - -::: warning `es-toolkit`の`differenceBy`を使用してください - -この `differenceBy` 関数は、複雑な引数処理と反復子変換により、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [differenceBy](../../array/differenceBy.md) を使用してください。 - -::: - -反復関数で変換した値を基準に、最初の配列から他の配列の要素を除いた差集合を求めます。 - -```typescript -const result = differenceBy(array, ...values, iteratee); -``` - -## 使用法 - -### `differenceBy(array, ...values, iteratee)` - -最初の配列の各要素と除外する配列の要素を反復関数で変換した後、同じ値になる要素を削除したい場合、`differenceBy` を使用してください。オブジェクト配列で特定のプロパティ値や変換された値を基準に比較する際に便利です。 - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// 小数点以下切り捨てで比較 -differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); -// Returns: [1.2] (Math.floor(2.1) === Math.floor(2.3)のため2.1を除外) - -// 文字列の長さで比較 -differenceBy(['one', 'two', 'three'], ['four', 'eight'], 'length'); -// Returns: ['one', 'two'] (threeとeightは長さが同じためthreeを除外) - -// オブジェクトのプロパティで比較 -const users1 = [ - { id: 1, name: 'Alice' }, - { id: 2, name: 'Bob' }, -]; -const users2 = [{ id: 1, name: 'Different Alice' }]; -differenceBy(users1, users2, 'id'); -// Returns: [{ id: 2, name: 'Bob' }] (idが1のオブジェクトを除外) -``` - -複数の配列を一度に除外できます。 - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// 複数の配列から除外 -differenceBy([2.1, 1.2, 3.5], [2.3], [1.4], [3.2], Math.floor); -// Returns: [] (すべての要素が除外されます) - -// 文字列配列を長さで比較 -differenceBy(['a', 'bb', 'ccc'], ['x'], ['yy'], ['zzz'], 'length'); -// Returns: [] (長さ1、2、3がすべて除外されます) -``` - -反復関数がない場合、通常の `difference` のように動作します。 - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// 反復関数なしで使用 -differenceBy([1, 2, 3], [2, 4]); -// Returns: [1, 3] -``` - -`null` や `undefined` の配列は空配列として処理されます。 - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -differenceBy(null, [1, 2], Math.floor); -// Returns: [] - -differenceBy(undefined, [1, 2], x => x); -// Returns: [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 差集合を求める基準配列です。 -- `values` (`...ArrayLike[]`): 除外する値を含む配列です。 -- `iteratee` (`ValueIteratee`): 各要素を比較する値に変換する関数です。関数、プロパティ名、または部分オブジェクトを使用できます。 - -#### 戻り値 - -(`T[]`): 反復関数で変換した値を基準に除外された要素を除いた新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/differenceWith.md b/docs/ja/reference/compat/array/differenceWith.md deleted file mode 100644 index 2941533c2..000000000 --- a/docs/ja/reference/compat/array/differenceWith.md +++ /dev/null @@ -1,79 +0,0 @@ -# differenceWith (Lodash 互換性) - -::: warning `es-toolkit`の`differenceWith`を使用してください - -この `differenceWith` 関数は、`null` や `undefined` の処理、複数の配列処理、`ArrayLike` 型の処理などにより、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [differenceWith](../../array/differenceWith.md) を使用してください。 - -::: - -比較関数を使用して、最初の配列から他の配列に含まれる要素を削除します。 - -```typescript -const result = differenceWith(array, ...values, comparator); -``` - -## 使用法 - -### `differenceWith(array, ...values, comparator)` - -各要素を比較関数で比較して差を求めたい場合、`differenceWith` を使用してください。最後の引数が比較関数になります。 - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -// オブジェクトをidで比較します。 -const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; -const others = [{ id: 2 }]; -const comparator = (a, b) => a.id === b.id; - -differenceWith(objects, others, comparator); -// Returns: [{ id: 1 }, { id: 3 }] - -// 複数の配列を一度に除外します。 -const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]; -const values1 = [{ id: 2 }]; -const values2 = [{ id: 3 }]; - -differenceWith(array, values1, values2, comparator); -// Returns: [{ id: 1 }, { id: 4 }] -``` - -比較関数を提供しない場合、通常の `difference` のように動作します。 - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -// 比較関数なしで使用すると通常の比較を行います。 -differenceWith([1, 2, 3], [2], [3]); -// Returns: [1] -``` - -複雑な比較ロジックも使用できます。 - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -const users = [ - { name: 'alice', age: 25 }, - { name: 'bob', age: 30 }, - { name: 'charlie', age: 35 }, -]; -const excludeUsers = [{ name: 'bob', age: 25 }]; // 異なる年齢 - -// 名前のみで比較します。 -const compareByName = (a, b) => a.name === b.name; -differenceWith(users, excludeUsers, compareByName); -// Returns: [{ name: 'alice', age: 25 }, { name: 'charlie', age: 35 }] -// bobが除外されます(年齢が違っても名前が同じため) -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 差を求める基準配列です。 -- `...values` (`Array>` + `(a: T, b: T) => boolean`): 除外する要素を含む配列と最後に比較関数です。 - -#### 戻り値 - -(`T[]`): 比較関数を使用して最初の配列から残りの配列の要素を削除した新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/drop.md b/docs/ja/reference/compat/array/drop.md deleted file mode 100644 index 7ffc18ee2..000000000 --- a/docs/ja/reference/compat/array/drop.md +++ /dev/null @@ -1,97 +0,0 @@ -# drop (Lodash 互換性) - -::: warning `es-toolkit` の `drop` を使用してください - -この `drop` 関数は、`null` や `undefined` の処理、`toInteger` 変換などにより複雑に動作します。 - -代わりに、より高速で現代的な `es-toolkit` の [`drop`](../../array/drop.md) を使用してください。 - -::: - -配列の先頭から指定された個数の要素を削除します。 - -```typescript -const result = drop(array, n); -``` - -## 使用法 - -### `drop(array, n?)` - -配列の先頭からいくつかの要素を削除し、残りを取得したい場合に `drop` を使用します。デフォルトでは、最初の要素を1つ削除します。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 基本的な使用法(最初の要素を削除) -drop([1, 2, 3, 4, 5]); -// 戻り値: [2, 3, 4, 5] - -// 最初の2つの要素を削除 -drop([1, 2, 3, 4, 5], 2); -// 戻り値: [3, 4, 5] - -// 最初の3つの要素を削除 -drop(['a', 'b', 'c', 'd'], 3); -// 戻り値: ['d'] -``` - -0または負の数を指定すると、元の配列をそのまま返します。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 0個削除 -drop([1, 2, 3], 0); -// 戻り値: [1, 2, 3] - -// 負の数を指定 -drop([1, 2, 3], -1); -// 戻り値: [1, 2, 3] -``` - -配列より大きい数を指定すると、空の配列を返します。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 配列のサイズより大きい数を指定 -drop([1, 2, 3], 5); -// 戻り値: [] - -// 空の配列から削除 -drop([], 1); -// 戻り値: [] -``` - -`null` または `undefined` の配列は空の配列として処理されます。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -drop(null, 1); -// 戻り値: [] - -drop(undefined, 2); -// 戻り値: [] -``` - -配列風オブジェクトもサポートされています。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 配列風オブジェクト -const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; -drop(arrayLike, 1); -// 戻り値: ['b', 'c'] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 要素を削除する配列です。 -- `n` (`number`, オプション): 削除する要素の個数です。デフォルトは `1` です。 - -#### 戻り値 - -(`T[]`): 先頭から指定された個数の要素が削除された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/dropRight.md b/docs/ja/reference/compat/array/dropRight.md deleted file mode 100644 index a97fb0aa9..000000000 --- a/docs/ja/reference/compat/array/dropRight.md +++ /dev/null @@ -1,55 +0,0 @@ -# dropRight (Lodash 互換性) - -::: warning `es-toolkit` の `dropRight` を使用してください - -この `dropRight` 関数は、`null` や `undefined` の処理、`guard` パラメータ処理、`toInteger` 変換などにより遅く動作します。 - -代わりに、より高速で現代的な `es-toolkit` の [`dropRight`](../../array/dropRight.md) を使用してください。 - -::: - -配列の末尾から指定された個数の要素を削除した新しい配列を返します。 - -```typescript -const result = dropRight(array, itemsCount); -``` - -## 使用法 - -### `dropRight(array, itemsCount)` - -配列の末尾から特定の個数の要素を削除し、残りの要素で新しい配列を作成したい場合に `dropRight` を使用します。 - -```typescript -import { dropRight } from 'es-toolkit/compat'; - -// 数値配列から末尾の2つの要素を削除します。 -dropRight([1, 2, 3, 4, 5], 2); -// 戻り値: [1, 2, 3] - -// 文字列配列から末尾の1つの要素を削除します。 -dropRight(['a', 'b', 'c'], 1); -// 戻り値: ['a', 'b'] - -// 削除する個数を指定しない場合、デフォルト値1が使用されます。 -dropRight([1, 2, 3]); -// 戻り値: [1, 2] -``` - -`null` または `undefined` は空の配列として処理されます。 - -```typescript -import { dropRight } from 'es-toolkit/compat'; - -dropRight(null, 2); // [] -dropRight(undefined, 2); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 要素を削除する配列です。 -- `itemsCount` (`number`, オプション): 配列の末尾から削除する要素の個数です。デフォルトは `1` です。 - -#### 戻り値 - -(`T[]`): 末尾から `itemsCount` 個の要素が削除された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/dropRightWhile.md b/docs/ja/reference/compat/array/dropRightWhile.md deleted file mode 100644 index c3a9fa8cb..000000000 --- a/docs/ja/reference/compat/array/dropRightWhile.md +++ /dev/null @@ -1,65 +0,0 @@ -# dropRightWhile (Lodash 互換性) - -::: warning `es-toolkit` の `dropRightWhile` を使用してください - -この `dropRightWhile` 関数は、`null` や `undefined` の処理、`ArrayLike` 型の処理、様々な条件関数形式のサポートなどにより遅く動作します。 - -代わりに、より高速で現代的な `es-toolkit` の [`dropRightWhile`](../../array/dropRightWhile.md) を使用してください。 - -::: - -条件関数に基づいて配列の末尾から要素を削除します。 - -```typescript -const result = dropRightWhile(array, predicate); -``` - -## 使用法 - -### `dropRightWhile(array, predicate)` - -配列の末尾から特定の条件を満たす要素を連続して削除したい場合に `dropRightWhile` を使用します。条件関数が `false` を返すと削除を中断します。 - -```typescript -import { dropRightWhile } from 'es-toolkit/compat'; - -// 関数を条件として使用します。 -const users = [ - { user: 'barney', active: true }, - { user: 'fred', active: false }, - { user: 'pebbles', active: false }, -]; - -dropRightWhile(users, user => !user.active); -// 戻り値: [{ user: 'barney', active: true }] - -// オブジェクトパターンでマッチングします。 -dropRightWhile(users, { user: 'pebbles', active: false }); -// 戻り値: [{ user: 'barney', active: true }, { user: 'fred', active: false }] - -// 配列形式でプロパティと値を指定します。 -dropRightWhile(users, ['active', false]); -// 戻り値: [{ user: 'barney', active: true }] - -// プロパティ名で条件を確認します。 -dropRightWhile(users, 'active'); -// 戻り値: [{ user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }] -``` - -`null` または `undefined` は空の配列として処理されます。 - -```typescript -import { dropRightWhile } from 'es-toolkit/compat'; - -dropRightWhile(null, x => x > 0); // [] -dropRightWhile(undefined, x => x > 0); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 要素を削除する配列です。 -- `predicate` (`ListIteratee`, オプション): 各要素に適用する条件関数です。関数、オブジェクトパターン、配列パターン、またはプロパティ名を受け取ることができます。 - -#### 戻り値 - -(`T[]`): 条件を満たさない最初の要素からの新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/dropWhile.md b/docs/ja/reference/compat/array/dropWhile.md deleted file mode 100644 index 601984672..000000000 --- a/docs/ja/reference/compat/array/dropWhile.md +++ /dev/null @@ -1,67 +0,0 @@ -# dropWhile (Lodash 互換性) - -::: warning `es-toolkit` の `dropWhile` を使用してください - -この `dropWhile` 関数は、`null` や `undefined` の処理、`ArrayLike` 型の処理、様々な条件関数形式のサポートなどにより遅く動作します。 - -代わりに、より高速で現代的な `es-toolkit` の [`dropWhile`](../../array/dropWhile.md) を使用してください。 - -::: - -条件関数に基づいて配列の先頭から要素を削除します。 - -```typescript -const result = dropWhile(array, predicate); -``` - -## 使用法 - -### `dropWhile(array, predicate)` - -配列の先頭から特定の条件を満たす要素を連続して削除したい場合に `dropWhile` を使用します。条件関数が `false` を返すと削除を中断します。 - -```typescript -import { dropWhile } from 'es-toolkit/compat'; - -// 関数を条件として使用します。 -dropWhile([1, 2, 3, 4, 5], n => n < 3); -// 戻り値: [3, 4, 5] - -// オブジェクトパターンでマッチングします。 -const users = [ - { name: 'alice', active: false }, - { name: 'bob', active: false }, - { name: 'charlie', active: true }, -]; - -dropWhile(users, { active: false }); -// 戻り値: [{ name: 'charlie', active: true }] - -// 配列形式でプロパティと値を指定します。 -dropWhile(users, ['active', false]); -// 戻り値: [{ name: 'charlie', active: true }] - -// プロパティ名で条件を確認します。 -const items = [{ visible: false }, { visible: false }, { visible: true }]; - -dropWhile(items, 'visible'); -// 戻り値: [{ visible: false }, { visible: false }, { visible: true }] -``` - -`null` または `undefined` は空の配列として処理されます。 - -```typescript -import { dropWhile } from 'es-toolkit/compat'; - -dropWhile(null, x => x > 0); // [] -dropWhile(undefined, x => x > 0); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 要素を削除する配列です。 -- `predicate` (`ListIteratee`, オプション): 各要素に適用する条件関数です。関数、オブジェクトパターン、配列パターン、またはプロパティ名を受け取ることができます。デフォルトは `identity` です。 - -#### 戻り値 - -(`T[]`): 条件を満たさない最初の要素からの新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/eachRight.md b/docs/ja/reference/compat/array/eachRight.md deleted file mode 100644 index 721398c4e..000000000 --- a/docs/ja/reference/compat/array/eachRight.md +++ /dev/null @@ -1,58 +0,0 @@ -# eachRight (Lodash 互換性) - -::: warning `es-toolkit` の `forEachRight` を使用してください - -この `eachRight` 関数は、`null` や `undefined` の処理、`ArrayLike` 型の処理、様々な条件関数形式のサポートなどにより遅く動作します。 - -代わりに、より高速で現代的な `es-toolkit` の [`forEachRight`](../../array/forEachRight.md) を使用してください。 - -::: - -配列またはオブジェクトの各要素に対して右から左へ反復操作を実行します。 - -```typescript -const result = eachRight(collection, iteratee); -``` - -## 使用法 - -### `eachRight(collection, iteratee)` - -配列、オブジェクト、文字列の各要素を右から左へ順回しながら与えられた関数を実行します。配列の場合は最後のインデックスから逆順に、オブジェクトの場合は列挙可能なプロパティを逆順に順回します。 - -```typescript -import { eachRight } from 'es-toolkit/compat'; - -// 配列を逆順に順回 -eachRight([1, 2, 3], (value, index) => console.log(value, index)); -// ログ: 3 2, 2 1, 1 0 - -// オブジェクトを逆順に順回 -eachRight({ a: 1, b: 2 }, (value, key) => console.log(key, value)); -// ログ: 'b' 2, 'a' 1 - -// 文字列を逆順に順回 -eachRight('hello', (char, index) => console.log(char, index)); -// ログ: 'o' 4, 'l' 3, 'l' 2, 'e' 1, 'h' 0 -``` - -関数が `false` を返すと順回を中断します。 - -```typescript -import { eachRight } from 'es-toolkit/compat'; - -eachRight([1, 2, 3, 4], value => { - console.log(value); - return value !== 2; // 2で中断 -}); -// ログ: 4, 3, 2 -``` - -#### パラメータ - -- `collection` (`ArrayLike | Record | string | null | undefined`): 順回するコレクションです。 -- `iteratee` (`(item: any, index: any, collection: any) => unknown`, オプション): 各要素に対して実行する関数です。デフォルトは `identity` 関数です。 - -#### 戻り値 - -(`ArrayLike | Record | string | null | undefined`): 元のコレクションを返します。 diff --git a/docs/ja/reference/compat/array/fill.md b/docs/ja/reference/compat/array/fill.md deleted file mode 100644 index 86b465241..000000000 --- a/docs/ja/reference/compat/array/fill.md +++ /dev/null @@ -1,82 +0,0 @@ -# fill (Lodash 互換性) - -::: warning `es-toolkit` の `fill` を使用してください - -この `fill` 関数は、`null` や `undefined` の処理、配列風オブジェクトのサポートなどにより複雑に動作します。 - -代わりに、より高速で現代的な `es-toolkit` の [`fill`](../../array/fill.md) を使用してください。 - -::: - -配列の要素を指定された値で埋めます。 - -```typescript -const result = fill(array, value, start, end); -``` - -## 使用法 - -### `fill(array, value, start?, end?)` - -配列の特定の範囲または全体を同じ値で埋めたい場合に `fill` を使用します。元の配列を直接変更します。 - -```typescript -import { fill } from 'es-toolkit/compat'; - -// 配列全体を埋める -const arr1 = [1, 2, 3]; -fill(arr1, 'a'); -// 戻り値: ['a', 'a', 'a'] - -// 特定の範囲を埋める -const arr2 = [1, 2, 3, 4, 5]; -fill(arr2, '*', 1, 4); -// 戻り値: [1, '*', '*', '*', 5] - -// 負のインデックスを使用 -const arr3 = [1, 2, 3, 4, 5]; -fill(arr3, 'x', -3, -1); -// 戻り値: [1, 2, 'x', 'x', 5] -``` - -配列風オブジェクトもサポートされています。 - -```typescript -import { fill } from 'es-toolkit/compat'; - -const arrayLike = { 0: 1, 1: 2, 2: 3, length: 3 }; -fill(arrayLike, 'a', 1, 2); -// 戻り値: { 0: 1, 1: 'a', 2: 3, length: 3 } -``` - -`null` または `undefined` の配列は空の配列として処理されます。 - -```typescript -import { fill } from 'es-toolkit/compat'; - -fill(null, 'a'); -// 戻り値: [] - -fill(undefined, 'a'); -// 戻り値: [] -``` - -文字列は読み取り専用なのでそのまま返します。 - -```typescript -import { fill } from 'es-toolkit/compat'; - -fill('abc', 'x'); -// 戻り値: 'abc' (変更されません) -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 埋める配列です。 -- `value` (`U`): 配列を埋める値です。 -- `start` (`number`, オプション): 開始位置です。デフォルトは `0` です。 -- `end` (`number`, オプション): 終了位置です(含まれません)。デフォルトは `array.length` です。 - -#### 戻り値 - -(`ArrayLike`): 値で埋められた配列を返します。 diff --git a/docs/ja/reference/compat/array/first.md b/docs/ja/reference/compat/array/first.md deleted file mode 100644 index f2150b1e0..000000000 --- a/docs/ja/reference/compat/array/first.md +++ /dev/null @@ -1,78 +0,0 @@ -# first (Lodash 互換性) - -::: warning `es-toolkit`の`head`を使用してください - -この`first`関数は、`null`や`undefined`の処理と配列のようなオブジェクトの変換により、動作が遅くなります。`es-toolkit`の`head`関数は、これらの追加処理なしで、より高速かつシンプルに動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[head](../../array/head.md)を使用してください。 - -::: - -配列の最初の要素を返します。 - -```typescript -const firstElement = first(array); -``` - -## 使用法 - -### `first(array)` - -配列の最初の要素を取得したい場合は`first`を使用してください。配列が空であるか、`null`、`undefined`の場合は`undefined`を返します。 - -```typescript -import { first } from 'es-toolkit/compat'; - -// 通常の配列から最初の要素を取得 -first([1, 2, 3]); -// Returns: 1 - -// 文字列配列から最初の要素を取得 -first(['a', 'b', 'c']); -// Returns: 'a' - -// 空の配列 -first([]); -// Returns: undefined -``` - -`null`または`undefined`は`undefined`を返します。 - -```typescript -import { first } from 'es-toolkit/compat'; - -first(null); // undefined -first(undefined); // undefined -``` - -配列のようなオブジェクトでも使用できます。 - -```typescript -import { first } from 'es-toolkit/compat'; - -const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; -first(arrayLike); -// Returns: 'a' - -// 文字列も配列のように処理されます -first('hello'); -// Returns: 'h' -``` - -型が保証されたタプルでは、正確な型を返します。 - -```typescript -import { first } from 'es-toolkit/compat'; - -const tuple = [1, 'two', true] as const; -first(tuple); -// Returns: 1 (型は1と推論されます) -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 最初の要素を取得する配列です。 - -#### 戻り値 - -(`T | undefined`): 配列の最初の要素を返します。配列が空または無効な場合は`undefined`を返します。 diff --git a/docs/ja/reference/compat/array/flatMap.md b/docs/ja/reference/compat/array/flatMap.md deleted file mode 100644 index aefbc8322..000000000 --- a/docs/ja/reference/compat/array/flatMap.md +++ /dev/null @@ -1,77 +0,0 @@ -# flatMap (Lodash 互換性) - -::: warning `es-toolkit`の`flatMap`を使用してください - -この`flatMap`関数は、`null`や`undefined`の処理、`ArrayLike`型の処理、様々な条件関数形式のサポートなどにより、動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[flatMap](../../array/flatMap.md)を使用してください。 - -::: - -各要素に関数を適用した後、結果を平坦化します。 - -```typescript -const result = flatMap(collection, iteratee); -``` - -## 使用法 - -### `flatMap(collection, iteratee)` - -コレクションの各要素にイテレータ関数を適用した後、1段階平坦化した配列を返します。配列、オブジェクト、文字列をサポートし、様々な形式のイテレータを使用できます。 - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -// 配列に関数を適用 -function duplicate(n) { - return [n, n]; -} -flatMap([1, 2], duplicate); -// 結果: [1, 1, 2, 2] - -// オブジェクトに関数を適用 -const obj = { a: 1, b: 2 }; -flatMap(obj, (value, key) => [key, value]); -// 結果: ['a', 1, 'b', 2] - -// 文字列プロパティでマッピング -const users = [ - { user: 'barney', hobbies: ['hiking', 'coding'] }, - { user: 'fred', hobbies: ['reading'] }, -]; -flatMap(users, 'hobbies'); -// 結果: ['hiking', 'coding', 'reading'] -``` - -イテレータなしで使用すると、値を1段階平坦化します。 - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -const obj = { a: [1, 2], b: [3, 4] }; -flatMap(obj); -// 結果: [1, 2, 3, 4] -``` - -部分オブジェクトで条件マッピングも可能です。 - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -const users = [ - { user: 'barney', age: 36, active: true }, - { user: 'fred', age: 40, active: false }, -]; -flatMap(users, { active: false }); -// 結果: [false, true] (activeがfalseの要素のマッチング結果) -``` - -#### パラメータ - -- `collection` (`object | null | undefined`): 反復処理するコレクションです。配列、オブジェクト、文字列が可能です。 -- `iteratee` (`ListIterator | ObjectIterator | string | object`, オプション): 各要素に適用するイテレータです。関数、プロパティ名、または部分オブジェクトが可能です。 - -#### 戻り値 - -(`any[]`): マッピング後1段階平坦化された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/flatMapDeep.md b/docs/ja/reference/compat/array/flatMapDeep.md deleted file mode 100644 index feced26a1..000000000 --- a/docs/ja/reference/compat/array/flatMapDeep.md +++ /dev/null @@ -1,77 +0,0 @@ -# flatMapDeep (Lodash 互換性) - -::: warning `es-toolkit`の[`flatMapDeep`](../../array/flatMapDeep.md)を使用してください - -この`flatMapDeep`関数は、複雑なコレクション型の処理と深い平坦化ロジックにより、動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[flatMapDeep](../../array/flatMapDeep.md)を使用してください。 - -::: - -各要素に関数を適用した後、結果を再帰的に平坦化します。 - -```typescript -const result = flatMapDeep(collection, iteratee); -``` - -## 使用法 - -### `flatMapDeep(collection, iteratee)` - -コレクションの各要素にイテレータ関数を適用した後、無限の深さまで平坦化した配列を返します。ネストされた配列構造がすべて平坦化されて1次元配列になります。 - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -// 配列に関数を適用して深く平坦化 -function duplicate(n) { - return [[[n, n]]]; -} -flatMapDeep([1, 2], duplicate); -// 結果: [1, 1, 2, 2] - -// オブジェクトに関数を適用して深く平坦化 -const obj = { a: 1, b: 2 }; -flatMapDeep(obj, (value, key) => [[[key, value]]]); -// 結果: ['a', 1, 'b', 2] - -// 文字列プロパティでマッピングして深く平坦化 -const users = [ - { user: 'barney', hobbies: [['hiking', 'coding']] }, - { user: 'fred', hobbies: [['reading']] }, -]; -flatMapDeep(users, 'hobbies'); -// 結果: ['hiking', 'coding', 'reading'] -``` - -イテレータなしで使用すると、値を再帰的に平坦化します。 - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -const obj = { a: [[1, 2]], b: [[[3]]] }; -flatMapDeep(obj); -// 結果: [1, 2, 3] -``` - -部分オブジェクトで条件マッピングも可能です。 - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -const users = [ - { user: 'barney', active: [true, false] }, - { user: 'fred', active: [false] }, -]; -flatMapDeep(users, { active: [false] }); -// 結果: [true, true] (active配列に[false]が含まれる要素のマッチング結果) -``` - -#### パラメータ - -- `collection` (`object | null | undefined`): 反復処理するコレクションです。配列、オブジェクト、文字列が可能です。 -- `iteratee` (`ListIterator | ObjectIterator | string | object`, オプション): 各要素に適用するイテレータです。関数、プロパティ名、または部分オブジェクトが可能です。 - -#### 戻り値 - -(`any[]`): マッピング後再帰的に平坦化された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/flatMapDepth.md b/docs/ja/reference/compat/array/flatMapDepth.md deleted file mode 100644 index 5360a8d1d..000000000 --- a/docs/ja/reference/compat/array/flatMapDepth.md +++ /dev/null @@ -1,79 +0,0 @@ -# flatMapDepth (Lodash 互換性) - -::: warning `es-toolkit`の[flatMap](../../array/flatMap.md)を使用してください - -この`flatMapDepth`関数は、Lodashとの互換性のために様々な形式のイテレータをサポートし、`null`や`undefined`の処理などにより複雑に実装されています。メインライブラリの`flatMap`関数はシンプルな関数イテレータのみをサポートするため、より高速に動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[flatMap](../../array/flatMap.md)を使用してください。 - -::: - -配列の各要素をイテレータ関数で変換した後、指定された深さまで平坦化します。 - -```typescript -const result = flatMapDepth(collection, iteratee, depth); -``` - -## 使用法 - -### `flatMapDepth(collection, iteratee, depth)` - -配列またはオブジェクトの各要素を与えられた関数で変換した後、結果を指定された深さまで平坦化して新しい配列として返します。ネストされた配列構造を望む深さまでのみ平坦化したいときに便利です。 - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -// 配列を変換して深さ2まで平坦化 -flatMapDepth([1, 2], n => [[n, n]], 2); -// => [1, 1, 2, 2] - -// 深さ1に制限すると完全に平坦化されません -flatMapDepth([1, 2], n => [[n, n]], 1); -// => [[1, 1], [2, 2]] - -// オブジェクトから値を抽出して平坦化 -const users = [ - { user: 'barney', hobbies: [['hiking'], ['coding']] }, - { user: 'fred', hobbies: [['reading']] }, -]; -flatMapDepth(users, 'hobbies', 2); -// => ['hiking', 'coding', 'reading'] -``` - -この関数は様々な形式のイテレータをサポートします。 - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -// 関数を使用した変換 -flatMapDepth([1, 2, 3], n => [[n, n]], 2); - -// プロパティ名で値を抽出 -const objects = [{ items: [['a'], ['b']] }, { items: [['c']] }]; -flatMapDepth(objects, 'items', 2); -// => ['a', 'b', 'c'] - -// オブジェクトの部分一致 -const users = [{ active: [[true], [false]] }, { active: [[false]] }]; -flatMapDepth(users, { active: [[false]] }, 2); -// => [true, true] -``` - -`null`または`undefined`は空の配列として処理されます。 - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -flatMapDepth(null, n => [n], 1); // => [] -flatMapDepth(undefined, n => [n], 1); // => [] -``` - -#### パラメータ - -- `collection` (`ArrayLike | Record | Record | object | null | undefined`): 反復処理する配列またはオブジェクトです。 -- `iteratee` (`((value: T, index: number, collection: any) => any) | string | object`, オプション): 各要素に対して実行する変換関数またはプロパティ名です。デフォルトは`identity`です。 -- `depth` (`number`, オプション): 平坦化する最大深さです。デフォルトは`1`です。 - -#### 戻り値 - -(`T[]`): イテレータで変換された後、指定された深さまで平坦化された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/flatten.md b/docs/ja/reference/compat/array/flatten.md deleted file mode 100644 index 72e91a8ec..000000000 --- a/docs/ja/reference/compat/array/flatten.md +++ /dev/null @@ -1,69 +0,0 @@ -# flatten (Lodash 互換性) - -::: warning `es-toolkit`の`flatten`を使用してください - -この`flatten`関数は、`null`や`undefined`の処理、`ArrayLike`型の処理、様々な条件関数形式のサポートなどにより、動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[flatten](../../array/flatten.md)を使用してください。 - -::: - -配列を1段階平坦化します。 - -```typescript -const result = flatten(array, depth); -``` - -## 使用法 - -### `flatten(value, depth)` - -ネストされた配列を指定された深さだけ平坦化します。デフォルトでは1段階のみ平坦化し、ArgumentsオブジェクトやSymbol.isConcatSpreadableを持つオブジェクトもサポートします。 - -```typescript -import { flatten } from 'es-toolkit/compat'; - -// 基本的な平坦化(1段階) -flatten([1, [2, [3, [4]], 5]]); -// 結果: [1, 2, [3, [4]], 5] - -// 深さを指定 -flatten([1, [2, [3, [4]], 5]], 2); -// 結果: [1, 2, 3, [4], 5] - -// Argumentsオブジェクトのサポート -function example() { - return flatten(arguments); -} -example(1, [2, 3], [[4]]); -// 結果: [1, 2, 3, [4]] -``` - -空の配列やnull、undefinedは空の配列を返します。 - -```typescript -import { flatten } from 'es-toolkit/compat'; - -flatten(null); // [] -flatten(undefined); // [] -flatten([]); // [] -``` - -Symbol.isConcatSpreadableを持つオブジェクトも配列のように平坦化されます。 - -```typescript -import { flatten } from 'es-toolkit/compat'; - -const spreadable = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true }; -flatten([1, spreadable, 3]); -// 結果: [1, 'a', 'b', 3] -``` - -#### パラメータ - -- `value` (`ArrayLike | null | undefined`): 平坦化する配列です。 -- `depth` (`number`, オプション): 平坦化する最大深さです。デフォルトは`1`です。 - -#### 戻り値 - -(`T[]`): 平坦化された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/flattenDeep.md b/docs/ja/reference/compat/array/flattenDeep.md deleted file mode 100644 index 6e8f77358..000000000 --- a/docs/ja/reference/compat/array/flattenDeep.md +++ /dev/null @@ -1,64 +0,0 @@ -# flattenDeep (Lodash 互換性) - -::: warning `es-toolkit`の`flattenDeep`を使用してください - -この`flattenDeep`関数は、`null`や`undefined`の処理、`ArrayLike`型の処理、様々な条件関数形式のサポートなどにより、動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[flattenDeep](../../array/flattenDeep.md)を使用してください。 - -::: - -配列を完全に平坦化します。 - -```typescript -const result = flattenDeep(array); -``` - -## 使用法 - -### `flattenDeep(value)` - -ネストされた配列をすべての深さで再帰的に平坦化します。すべてのネストレベルが削除され、完全に平坦化された1次元配列を返します。 - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -// 深くネストされた配列を完全に平坦化 -flattenDeep([1, [2, [3, [4]], 5]]); -// 結果: [1, 2, 3, 4, 5] - -// 複雑なネスト構造も完全に平坦化 -flattenDeep([1, [2, [3, [[[[4]]]]], 5]]); -// 結果: [1, 2, 3, 4, 5] - -// 混合された型もサポート -flattenDeep(['a', ['b', ['c', [['d']]]]]); -// 結果: ['a', 'b', 'c', 'd'] -``` - -空の配列やnull、undefinedは空の配列を返します。 - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -flattenDeep(null); // [] -flattenDeep(undefined); // [] -flattenDeep([]); // [] -``` - -すでに平坦化された配列はそのままコピーされます。 - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -flattenDeep([1, 2, 3, 4, 5]); -// 結果: [1, 2, 3, 4, 5] -``` - -#### パラメータ - -- `value` (`ListOfRecursiveArraysOrValues | null | undefined`): 完全に平坦化する配列です。 - -#### 戻り値 - -(`Array`): すべてのネストが削除された完全に平坦化された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/flattenDepth.md b/docs/ja/reference/compat/array/flattenDepth.md deleted file mode 100644 index 4bc23bc17..000000000 --- a/docs/ja/reference/compat/array/flattenDepth.md +++ /dev/null @@ -1,55 +0,0 @@ -# flattenDepth (Lodash 互換性) - -::: warning `es-toolkit`の`flatten`を使用してください - -この`flattenDepth`関数は、`null`や`undefined`の処理などにより、動作が遅くなります。`es-toolkit`の`flatten`関数は、これらの追加処理なしで、より高速かつシンプルに動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[flatten](../../array/flatten.md)を使用してください。 - -::: - -配列を指定した深さまで平坦化します。 - -```typescript -const flattened = flattenDepth(array, depth); -``` - -## 使用法 - -### `flattenDepth(array, depth)` - -ネストされた配列を望む深さまで平坦化したい場合は`flattenDepth`を使用してください。深さを指定すると、その深さまでのみネストされた配列を平坦化します。 - -```typescript -import { flattenDepth } from 'es-toolkit/compat'; - -// 深さ1まで平坦化します -flattenDepth([1, [2, [3, [4]], 5]], 1); -// Returns: [1, 2, [3, [4]], 5] - -// 深さ2まで平坦化します -flattenDepth([1, [2, [3, [4]], 5]], 2); -// Returns: [1, 2, 3, [4], 5] - -// 深さを指定しない場合、デフォルト値1で平坦化します -flattenDepth([1, [2, [3, [4]], 5]]); -// Returns: [1, 2, [3, [4]], 5] -``` - -`null`または`undefined`は空の配列として処理されます。 - -```typescript -import { flattenDepth } from 'es-toolkit/compat'; - -flattenDepth(null, 2); // [] -flattenDepth(undefined, 2); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 平坦化する配列です。 -- `depth` (`number`, オプション): 平坦化する最大深さです。デフォルトは`1`です。 - -#### 戻り値 - -(`T[]`): 指定した深さまで平坦化された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/forEachRight.md b/docs/ja/reference/compat/array/forEachRight.md deleted file mode 100644 index 2c866adb9..000000000 --- a/docs/ja/reference/compat/array/forEachRight.md +++ /dev/null @@ -1,75 +0,0 @@ -# forEachRight (Lodash 互換性) - -::: warning `es-toolkit`の`forEachRight`を使用してください - -この`forEachRight`関数は、`null`や`undefined`の処理、`ArrayLike`タイプの処理、さまざまな条件関数形式のサポートなどにより、動作が遅くなります。 - -代わりに、より高速でモダンな`es-toolkit`の[forEachRight](../../array/forEachRight.md)を使用してください。 - -::: - -配列またはオブジェクトの要素を右から左に走査し、各要素に対して関数を実行します。 - -```typescript -forEachRight(collection, callback); -``` - -## 使用法 - -### `forEachRight(collection, callback)` - -配列、オブジェクト、文字列を右から左の順序で走査し、各要素に対してコールバック関数を実行します。コールバックが`false`を返すと走査を中断します。 - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -// 配列を逆順で走査します -forEachRight([1, 2, 3], (value, index) => { - console.log(value, index); -}); -// 出力: 3 2, 2 1, 1 0 - -// 文字列を逆順で走査します -forEachRight('abc', (char, index) => { - console.log(char, index); -}); -// 出力: 'c' 2, 'b' 1, 'a' 0 - -// オブジェクトを逆順で走査します -forEachRight({ a: 1, b: 2, c: 3 }, (value, key) => { - console.log(value, key); -}); -// 出力: 3 'c', 2 'b', 1 'a' -``` - -`null`または`undefined`はそのまま返します。 - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -forEachRight(null, value => console.log(value)); // null -forEachRight(undefined, value => console.log(value)); // undefined -``` - -コールバックが`false`を返すと走査を中断します。 - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -forEachRight([1, 2, 3, 4], value => { - console.log(value); - if (value === 2) { - return false; // 走査を中断 - } -}); -// 出力: 4, 3, 2 -``` - -#### パラメータ - -- `collection` (`ArrayLike | Record | string | null | undefined`): 走査するコレクションです。配列、オブジェクト、文字列、またはnull/undefinedを指定できます。 -- `callback` (`(item: any, index: any, arr: any) => unknown`, 選択): 各要素に対して実行する関数です。`false`を返すと走査を中断します。デフォルトは`identity`関数です。 - -#### 戻り値 - -(`ArrayLike | Record | string | null | undefined`): 元のコレクションをそのまま返します。 diff --git a/docs/ja/reference/compat/array/groupBy.md b/docs/ja/reference/compat/array/groupBy.md deleted file mode 100644 index 259c431f5..000000000 --- a/docs/ja/reference/compat/array/groupBy.md +++ /dev/null @@ -1,79 +0,0 @@ -# groupBy (Lodash 互換性) - -::: warning `es-toolkit`の[groupBy](../../array/groupBy.md)を使用してください - -この`groupBy`関数は、`null`や`undefined`の処理、オブジェクトのサポート、複雑な型処理などにより、動作が遅くなります。 - -代わりに、より高速でモダンな`es-toolkit`の[groupBy](../../array/groupBy.md)を使用してください。 - -::: - -配列またはオブジェクトの要素を与えられた条件に従ってグループ化します。 - -```typescript -const grouped = groupBy(collection, iteratee); -``` - -## 使用法 - -### `groupBy(collection, iteratee)` - -配列またはオブジェクトの各要素を与えられた条件関数に従ってグループ化し、グループ別に分類されたオブジェクトを返します。条件は関数、プロパティ名、部分オブジェクトなど、さまざまな形式で提供できます。 - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -// 関数でグループ化 -const array = [6.1, 4.2, 6.3]; -const result = groupBy(array, Math.floor); -// resultは{ '4': [4.2], '6': [6.1, 6.3] } - -// プロパティ名でグループ化 -const users = [ - { name: 'john', age: 30 }, - { name: 'jane', age: 25 }, - { name: 'bob', age: 30 }, -]; -const byAge = groupBy(users, 'age'); -// byAgeは{ '25': [{ name: 'jane', age: 25 }], '30': [{ name: 'john', age: 30 }, { name: 'bob', age: 30 }] } - -// オブジェクトからグループ化 -const obj = { a: 6.1, b: 4.2, c: 6.3 }; -const groupedObj = groupBy(obj, Math.floor); -// groupedObjは{ '4': [4.2], '6': [6.1, 6.3] } -``` - -`null`または`undefined`は空のオブジェクトとして扱われます。 - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -groupBy(null, x => x); // {} -groupBy(undefined, x => x); // {} -``` - -部分オブジェクトやプロパティ-値ペアでもグループ化できます。 - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -const products = [ - { category: 'fruit', name: 'apple' }, - { category: 'fruit', name: 'banana' }, - { category: 'vegetable', name: 'carrot' }, -]; - -// 部分オブジェクトでグループ化 -const byCategory = groupBy(products, { category: 'fruit' }); -// プロパティ-値ペアでグループ化 -const byName = groupBy(products, ['name', 'apple']); -``` - -#### パラメータ - -- `collection` (`ArrayLike | Record | null | undefined`): グループ化する配列またはオブジェクトです。 -- `iteratee` (`Function | PropertyKey | Array | Object`, 選択): グループ化する条件です。関数、プロパティ名、プロパティ-値ペア、または部分オブジェクトを指定できます。デフォルトは`identity`関数です。 - -#### 戻り値 - -(`Record`): 各キーがグループの条件値で、値がそのグループに属する要素の配列であるオブジェクトを返します。 diff --git a/docs/ja/reference/compat/array/head.md b/docs/ja/reference/compat/array/head.md deleted file mode 100644 index 6187d56aa..000000000 --- a/docs/ja/reference/compat/array/head.md +++ /dev/null @@ -1,61 +0,0 @@ -# head (Lodash 互換性) - -::: warning `es-toolkit`の[head](../../array/head.md)を使用してください - -この`head`関数は、`ArrayLike`オブジェクトの処理と配列変換プロセスにより、動作が遅くなります。 - -代わりに、より高速でモダンな`es-toolkit`の[head](../../array/head.md)を使用してください。 - -::: - -配列の最初の要素を返します。 - -```typescript -const firstElement = head(array); -``` - -## 使用法 - -### `head(array)` - -配列または配列のようなオブジェクトの最初の要素を返します。配列が空または無効な場合は`undefined`を返します。 - -```typescript -import { head } from 'es-toolkit/compat'; - -// 数値配列の最初の要素 -const numbers = [1, 2, 3, 4]; -const first = head(numbers); -// firstは1 - -// 文字列配列の最初の要素 -const strings = ['a', 'b', 'c']; -const firstChar = head(strings); -// firstCharは'a' - -// 配列のようなオブジェクト -const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; -const firstItem = head(arrayLike); -// firstItemは'x' -``` - -空の配列または無効な入力は`undefined`を返します。 - -```typescript -import { head } from 'es-toolkit/compat'; - -const emptyArray: number[] = []; -const noElement = head(emptyArray); -// noElementはundefined - -head(null); // undefined -head(undefined); // undefined -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 最初の要素を取得する配列または配列のようなオブジェクトです。 - -#### 戻り値 - -(`T | undefined`): 配列の最初の要素を返し、配列が空または無効な場合は`undefined`を返します。 diff --git a/docs/ja/reference/compat/array/initial.md b/docs/ja/reference/compat/array/initial.md deleted file mode 100644 index d07c7800f..000000000 --- a/docs/ja/reference/compat/array/initial.md +++ /dev/null @@ -1,65 +0,0 @@ -# initial (Lodash 互換性) - -::: warning `es-toolkit`の[initial](../../array/initial.md)を使用してください - -この`initial`関数は、`ArrayLike`オブジェクトの処理と配列変換プロセスにより、動作が遅くなります。 - -代わりに、より高速でモダンな`es-toolkit`の[initial](../../array/initial.md)を使用してください。 - -::: - -配列から最後の要素を除くすべての要素を新しい配列として返します。 - -```typescript -const result = initial(array); -``` - -## 使用法 - -### `initial(array)` - -配列または配列のようなオブジェクトから最後の要素を除くすべての要素を含む新しい配列を返します。配列が空または要素が1つだけの場合は空の配列を返します。 - -```typescript -import { initial } from 'es-toolkit/compat'; - -// 数値配列から最後の要素を除外 -const numbers = [1, 2, 3, 4]; -const result = initial(numbers); -// resultは[1, 2, 3] - -// 文字列配列から最後の要素を除外 -const strings = ['a', 'b', 'c', 'd']; -const withoutLast = initial(strings); -// withoutLastは['a', 'b', 'c'] - -// 配列のようなオブジェクト -const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; -const items = initial(arrayLike); -// itemsは['x', 'y'] -``` - -空の配列または無効な入力は空の配列を返します。 - -```typescript -import { initial } from 'es-toolkit/compat'; - -const emptyArray: number[] = []; -const result = initial(emptyArray); -// resultは[] - -const singleItem = [42]; -const onlyOne = initial(singleItem); -// onlyOneは[] - -initial(null); // [] -initial(undefined); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 最後の要素を除外する配列または配列のようなオブジェクトです。 - -#### 戻り値 - -(`T[]`): 最後の要素を除外した新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/intersection.md b/docs/ja/reference/compat/array/intersection.md deleted file mode 100644 index fce8e82f1..000000000 --- a/docs/ja/reference/compat/array/intersection.md +++ /dev/null @@ -1,80 +0,0 @@ -# intersection (Lodash 互換性) - -::: warning `es-toolkit`の[intersection](../../array/intersection.md)を使用してください - -この`intersection`関数は、`null`や`undefined`の処理、複数配列のサポート、重複除去プロセスにより、動作が遅くなります。 - -代わりに、より高速でモダンな`es-toolkit`の[intersection](../../array/intersection.md)を使用してください。 - -::: - -複数の配列の共通部分を求めます。 - -```typescript -const result = intersection(...arrays); -``` - -## 使用法 - -### `intersection(...arrays)` - -複数の配列で共通に存在する要素を見つけて新しい配列として返します。結果は重複が除去され、最初の配列の順序を維持します。 - -```typescript -import { intersection } from 'es-toolkit/compat'; - -// 2つの配列の共通部分 -const array1 = [1, 2, 3, 4]; -const array2 = [2, 3, 5, 6]; -const result = intersection(array1, array2); -// resultは[2, 3] - -// 3つの配列の共通部分 -const array3 = [3, 4, 7, 8]; -const multiResult = intersection(array1, array2, array3); -// multiResultは[3] - -// 文字列配列 -const strings1 = ['a', 'b', 'c']; -const strings2 = ['b', 'c', 'd']; -const stringResult = intersection(strings1, strings2); -// stringResultは['b', 'c'] - -// 配列のようなオブジェクト -const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; -const arrayLike2 = { 0: 2, 1: 3, 2: 4, length: 3 }; -const likeResult = intersection(arrayLike1, arrayLike2); -// likeResultは[2, 3] -``` - -`null`または`undefined`配列は空の配列として扱われます。 - -```typescript -import { intersection } from 'es-toolkit/compat'; - -const array1 = [1, 2, 3]; -const result1 = intersection(array1, null); -// result1は[] - -const result2 = intersection(null, undefined); -// result2は[] -``` - -重複した要素は結果から除去されます。 - -```typescript -import { intersection } from 'es-toolkit/compat'; - -const array1 = [1, 1, 2, 3]; -const array2 = [1, 2, 2, 4]; -const result = intersection(array1, array2); -// resultは[1, 2](重複除去されます) -``` - -#### パラメータ - -- `...arrays` (`Array | null | undefined>`): 共通部分を求める配列です。配列のようなオブジェクトやnull/undefinedも許可されます。 - -#### 戻り値 - -(`T[]`): すべての配列で共通に存在する要素の新しい配列を返します。重複は除去され、最初の配列の順序に従います。 diff --git a/docs/ja/reference/compat/array/intersectionBy.md b/docs/ja/reference/compat/array/intersectionBy.md deleted file mode 100644 index 26a1b54c7..000000000 --- a/docs/ja/reference/compat/array/intersectionBy.md +++ /dev/null @@ -1,93 +0,0 @@ -# intersectionBy (Lodash 互換性) - -::: warning `es-toolkit`の[intersectionBy](../../array/intersectionBy.md)を使用してください - -この`intersectionBy`関数は、複雑な条件処理、複数配列のサポート、プロパティパスの解析などにより、動作が遅くなります。 - -代わりに、より高速でモダンな`es-toolkit`の[intersectionBy](../../array/intersectionBy.md)を使用してください。 - -::: - -与えられた条件関数を使用して複数の配列の共通部分を求めます。 - -```typescript -const result = intersectionBy(...arrays, iteratee); -``` - -## 使用法 - -### `intersectionBy(...arrays, iteratee)` - -複数の配列で、各要素を与えられた条件関数で変換した値を基準に共通部分を求めます。条件は関数、プロパティ名、部分オブジェクトなど、さまざまな形式で提供できます。 - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -// 関数で共通部分を求める -const array1 = [2.1, 1.2]; -const array2 = [2.3, 3.4]; -const result = intersectionBy(array1, array2, Math.floor); -// resultは[2.1](Math.floor基準で2が共通) - -// プロパティで共通部分を求める -const users1 = [ - { id: 1, name: 'john' }, - { id: 2, name: 'jane' }, -]; -const users2 = [ - { id: 2, name: 'jane' }, - { id: 3, name: 'bob' }, -]; -const byId = intersectionBy(users1, users2, 'id'); -// byIdは[{ id: 2, name: 'jane' }] - -// 3つの配列の共通部分 -const array3 = [2.5, 4.1]; -const multiResult = intersectionBy(array1, array2, array3, Math.floor); -// multiResultは[2.1] - -// 配列のようなオブジェクト -const arrayLike1 = { 0: { x: 1 }, 1: { x: 2 }, length: 2 }; -const arrayLike2 = { 0: { x: 2 }, 1: { x: 3 }, length: 2 }; -const byProperty = intersectionBy(arrayLike1, arrayLike2, 'x'); -// byPropertyは[{ x: 2 }] -``` - -`null`または`undefined`配列は空の配列として扱われます。 - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -const array1 = [{ x: 1 }, { x: 2 }]; -const result = intersectionBy(array1, null, 'x'); -// resultは[] -``` - -部分オブジェクトやプロパティ-値ペアでも条件を指定できます。 - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -const products1 = [ - { category: 'fruit', name: 'apple' }, - { category: 'vegetable', name: 'carrot' }, -]; -const products2 = [ - { category: 'fruit', name: 'banana' }, - { category: 'meat', name: 'beef' }, -]; - -// 部分オブジェクトで条件を指定 -const byCategory = intersectionBy(products1, products2, { category: 'fruit' }); -// プロパティ-値ペアで条件を指定 -const byCategoryPair = intersectionBy(products1, products2, ['category', 'fruit']); -``` - -#### パラメータ - -- `...arrays` (`Array | null | undefined>`): 共通部分を求める配列です。 -- `iteratee` (`Function | PropertyKey | Array | Object`): 各要素を変換する条件です。関数、プロパティ名、プロパティ-値ペア、または部分オブジェクトを指定できます。 - -#### 戻り値 - -(`T[]`): 変換された値を基準にすべての配列で共通に存在する要素の新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/intersectionWith.md b/docs/ja/reference/compat/array/intersectionWith.md deleted file mode 100644 index 07f295d3d..000000000 --- a/docs/ja/reference/compat/array/intersectionWith.md +++ /dev/null @@ -1,64 +0,0 @@ -# intersectionWith (Lodash 互換性) - -::: warning `es-toolkit`の[intersectionWith](../../array/intersectionWith.md)を使用してください - -この`intersectionWith`関数は、`null`や`undefined`の処理、さまざまなオーバーロードのサポートなどにより、動作が遅くなります。 - -代わりに、より高速でモダンな`es-toolkit`の[intersectionWith](../../array/intersectionWith.md)を使用してください。 - -::: - -カスタム比較関数を使用して、すべての配列に含まれる共通要素の配列を作成します。 - -```typescript -const result = intersectionWith(array, ...otherArrays, comparator); -``` - -## 使用法 - -### `intersectionWith(array, ...otherArrays, comparator)` - -カスタム比較関数を使用して、最初の配列と残りの配列の共通部分を求めます。比較関数で各要素が等しいかを判断し、すべての配列に含まれる要素のみを返します。 - -```typescript -import { intersectionWith } from 'es-toolkit/compat'; - -const objects = [ - { id: 1, name: 'john' }, - { id: 2, name: 'jane' }, -]; -const others = [ - { id: 1, name: 'john' }, - { id: 3, name: 'joe' }, -]; - -intersectionWith(objects, others, (a, b) => a.id === b.id); -// => [{ id: 1, name: 'john' }] - -// 複数の配列と比較することもできます -const array1 = [{ x: 1 }, { x: 2 }]; -const array2 = [{ x: 1 }, { x: 3 }]; -const array3 = [{ x: 1 }, { x: 4 }]; - -intersectionWith(array1, array2, array3, (a, b) => a.x === b.x); -// => [{ x: 1 }] -``` - -`null`または`undefined`は空の配列として扱われます。 - -```typescript -import { intersectionWith } from 'es-toolkit/compat'; - -intersectionWith(null, [1, 2], (a, b) => a === b); // [] -intersectionWith([1, 2], undefined, (a, b) => a === b); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 比較する最初の配列です。 -- `...otherArrays` (`Array | ((a: T, b: T | U) => boolean)>`): 比較する他の配列と、最後の要素として比較関数です。 -- `comparator` (`(a: T, b: T | U) => boolean`): 2つの要素が等しいかを判断する関数です。 - -#### 戻り値 - -(`T[]`): すべての配列で共通に見つかった要素の新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/keyBy.md b/docs/ja/reference/compat/array/keyBy.md deleted file mode 100644 index 32766ed99..000000000 --- a/docs/ja/reference/compat/array/keyBy.md +++ /dev/null @@ -1,64 +0,0 @@ -# keyBy (Lodash 互換性) - -::: warning `es-toolkit` の [keyBy](../../array/keyBy.md) を使用してください - -この `keyBy` 関数は、`null` や `undefined` の処理、さまざまなパラメータ型の処理などにより動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [keyBy](../../array/keyBy.md) を使用してください。 - -::: - -コレクションの要素を指定されたキーに基づいてオブジェクトに構成します。 - -```typescript -const result = keyBy(collection, iteratee); -``` - -## 使用法 - -### `keyBy(collection, iteratee)` - -配列またはオブジェクトの各要素を、指定されたキー生成関数またはプロパティ名を使用してオブジェクトに構成します。同じキーを持つ要素が複数ある場合は、最後の要素が使用されます。 - -```typescript -import { keyBy } from 'es-toolkit/compat'; - -// プロパティ名でキーを生成する -const array = [ - { dir: 'left', code: 97 }, - { dir: 'right', code: 100 }, -]; - -keyBy(array, 'dir'); -// => { left: { dir: 'left', code: 97 }, right: { dir: 'right', code: 100 } } - -// 関数でキーを生成する -keyBy(array, o => String.fromCharCode(o.code)); -// => { a: { dir: 'left', code: 97 }, d: { dir: 'right', code: 100 } } - -// オブジェクトでも使用可能 -const obj = { - a: { id: 1, name: 'john' }, - b: { id: 2, name: 'jane' }, -}; -keyBy(obj, 'name'); -// => { john: { id: 1, name: 'john' }, jane: { id: 2, name: 'jane' } } -``` - -`null` または `undefined` は空のオブジェクトとして扱われます。 - -```typescript -import { keyBy } from 'es-toolkit/compat'; - -keyBy(null, 'id'); // {} -keyBy(undefined, 'id'); // {} -``` - -#### パラメータ - -- `collection` (`ArrayLike | null | undefined`): キーで構成する配列またはオブジェクトです。 -- `iteratee` (`ValueIterateeCustom`, オプション): キーを生成する関数またはプロパティ名です。省略すると、要素自体がキーとして使用されます。 - -#### 戻り値 - -(`Record`): 各要素が生成されたキーにマッピングされた新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/array/last.md b/docs/ja/reference/compat/array/last.md deleted file mode 100644 index 77e9308f1..000000000 --- a/docs/ja/reference/compat/array/last.md +++ /dev/null @@ -1,79 +0,0 @@ -# last (Lodash互換性) - -::: warning `es-toolkit`の[last](../../array/last.md)を使用してください - -この`last`関数は`null`や`undefined`の処理により複雑に動作します。 - -代わりに、より高速でモダンな`es-toolkit`の[last](../../array/last.md)を使用してください。 - -::: - -配列の最後の要素を返します。 - -```typescript -const lastElement = last(array); -``` - -## 使用法 - -### `last(array)` - -配列の最後の要素を取得したいときに`last`を使用してください。配列が空の場合は`undefined`を返します。 - -```typescript -import { last } from 'es-toolkit/compat'; - -// 数値配列の最後の要素 -last([1, 2, 3, 4, 5]); -// Returns: 5 - -// 文字列配列の最後の要素 -last(['a', 'b', 'c']); -// Returns: 'c' - -// オブジェクト配列の最後の要素 -const users = [{ name: 'Alice' }, { name: 'Bob' }]; -last(users); -// Returns: { name: 'Bob' } -``` - -空の配列や`null`、`undefined`は`undefined`を返します。 - -```typescript -import { last } from 'es-toolkit/compat'; - -// 空の配列 -last([]); -// Returns: undefined - -// null配列 -last(null); -// Returns: undefined - -// undefined配列 -last(undefined); -// Returns: undefined -``` - -配列風オブジェクトもサポートしています。 - -```typescript -import { last } from 'es-toolkit/compat'; - -// 配列風オブジェクト -const arrayLike = { 0: 'first', 1: 'second', length: 2 }; -last(arrayLike); -// Returns: 'second' - -// 文字列も配列風オブジェクト -last('hello'); -// Returns: 'o' -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 最後の要素を取得する配列です。 - -#### 戻り値 - -(`T | undefined`): 配列の最後の要素を返し、配列が空または`null`、`undefined`の場合は`undefined`を返します。 diff --git a/docs/ja/reference/compat/array/orderBy.md b/docs/ja/reference/compat/array/orderBy.md deleted file mode 100644 index 2eeae3fa3..000000000 --- a/docs/ja/reference/compat/array/orderBy.md +++ /dev/null @@ -1,82 +0,0 @@ -# orderBy (Lodash 互換性) - -::: warning `es-toolkit` の [orderBy](../../array/orderBy.md) を使用してください - -この `orderBy` 関数は、`null` や `undefined` の処理、複雑なパス探索、様々なソート条件の処理により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [orderBy](../../array/orderBy.md) を使用してください。 - -::: - -複数の条件でコレクションの要素をソートします。 - -```typescript -const result = orderBy(collection, criteria, orders); -``` - -## 使用法 - -### `orderBy(collection, criteria, orders)` - -指定された条件とソート順に従って、配列またはオブジェクトの要素をソートします。複数の条件を使用でき、各条件に対して昇順 (`'asc'`) または降順 (`'desc'`) のソートを指定できます。 - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -const users = [ - { name: 'fred', age: 48 }, - { name: 'barney', age: 34 }, - { name: 'fred', age: 40 }, - { name: 'barney', age: 36 }, -]; - -// 名前昇順、年齢降順でソート -orderBy(users, ['name', 'age'], ['asc', 'desc']); -// => [ -// { name: 'barney', age: 36 }, -// { name: 'barney', age: 34 }, -// { name: 'fred', age: 48 }, -// { name: 'fred', age: 40 } -// ] - -// 関数でソート条件を指定 -orderBy(users, [user => user.name, user => user.age], ['asc', 'desc']); -// => 上記と同じ結果 - -// 単一の条件でソート -orderBy(users, 'age', 'desc'); -// => [{ name: 'fred', age: 48 }, { name: 'fred', age: 40 }, ...] -``` - -オブジェクトの場合、値をソートします。 - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -const obj = { - a: { name: 'fred', age: 48 }, - b: { name: 'barney', age: 34 }, -}; - -orderBy(obj, 'age', 'desc'); -// => [{ name: 'fred', age: 48 }, { name: 'barney', age: 34 }] -``` - -`null` または `undefined` は空の配列として扱われます。 - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -orderBy(null, 'name'); // [] -orderBy(undefined, 'age'); // [] -``` - -#### パラメータ - -- `collection` (`ArrayLike | object | null | undefined`): ソートする配列またはオブジェクトです。 -- `criteria` (`Criterion | Array>`, オプション): ソート条件です。プロパティ名、プロパティパス、関数などを使用できます。デフォルトは `[null]` です。 -- `orders` (`unknown | unknown[]`, オプション): 各条件のソート順です。`'asc'`(昇順)、`'desc'`(降順)、`true`(昇順)、`false`(降順)を使用できます。デフォルトは `[]` です。 - -#### 戻り値 - -(`T[]`): 新しくソートされた配列を返します。 diff --git a/docs/ja/reference/compat/array/partition.md b/docs/ja/reference/compat/array/partition.md deleted file mode 100644 index b15a404d7..000000000 --- a/docs/ja/reference/compat/array/partition.md +++ /dev/null @@ -1,89 +0,0 @@ -# partition (Lodash 互換性) - -::: warning `es-toolkit` の [partition](../../array/partition.md) を使用してください - -この `partition` 関数は、`null` や `undefined` の処理、様々な条件タイプにより動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [partition](../../array/partition.md) を使用してください。 - -::: - -条件に基づいてコレクションの要素を2つのグループに分けます。 - -```typescript -const [truthy, falsy] = partition(collection, predicate); -``` - -## 使用法 - -### `partition(collection, predicate)` - -与えられた条件関数に基づいて、配列またはオブジェクトの要素を2つのグループに分けます。最初のグループには条件が真である要素が含まれ、2番目のグループには条件が偽である要素が含まれます。 - -```typescript -import { partition } from 'es-toolkit/compat'; - -// 数値配列を偶数と奇数に分ける -partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); -// => [[2, 4, 6], [1, 3, 5]] - -// プロパティ名で条件を指定 -const users = [ - { name: 'john', active: true }, - { name: 'jane', active: false }, - { name: 'bob', active: true }, -]; - -partition(users, 'active'); -// => [ -// [{ name: 'john', active: true }, { name: 'bob', active: true }], -// [{ name: 'jane', active: false }] -// ] - -// オブジェクト条件でフィルタリング -partition(users, { active: true }); -// => [ -// [{ name: 'john', active: true }, { name: 'bob', active: true }], -// [{ name: 'jane', active: false }] -// ] - -// 配列条件でフィルタリング -partition(users, ['name', 'john']); -// => [ -// [{ name: 'john', active: true }], -// [{ name: 'jane', active: false }, { name: 'bob', active: true }] -// ] -``` - -オブジェクトの場合、値を分割します。 - -```typescript -import { partition } from 'es-toolkit/compat'; - -const obj = { - a: { score: 90 }, - b: { score: 40 }, - c: { score: 80 }, -}; - -partition(obj, item => item.score >= 80); -// => [[{ score: 90 }, { score: 80 }], [{ score: 40 }]] -``` - -`null` または `undefined` は空の配列として扱われます。 - -```typescript -import { partition } from 'es-toolkit/compat'; - -partition(null, x => x > 0); // [[], []] -partition(undefined, 'active'); // [[], []] -``` - -#### パラメータ - -- `collection` (`ArrayLike | T | null | undefined`): 分割する配列またはオブジェクトです。 -- `predicate` (`((value: T) => unknown) | Partial | [PropertyKey, any] | PropertyKey`, オプション): 各要素をテストする条件です。関数、部分オブジェクト、プロパティ-値配列、またはプロパティ名を使用できます。デフォルトは `identity` です。 - -#### 戻り値 - -(`[T[], T[]]`): 条件を満たす要素の配列と満たさない要素の配列を含む配列を返します。 diff --git a/docs/ja/reference/compat/array/pull.md b/docs/ja/reference/compat/array/pull.md deleted file mode 100644 index 2a08cf310..000000000 --- a/docs/ja/reference/compat/array/pull.md +++ /dev/null @@ -1,44 +0,0 @@ -# pull (Lodash 互換性) - -::: warning `es-toolkit` の [pull](../../array/pull.md) を使用してください - -この `pull` 関数は Lodash 互換性のための関数であり、より複雑な型処理とオーバーロードにより動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [pull](../../array/pull.md) を使用してください。 - -::: - -配列から指定された値をすべて削除します。 - -```typescript -const result = pull(array, ...valuesToRemove); -``` - -## 使用法 - -### `pull(array, ...valuesToRemove)` - -配列から指定された値をすべて削除し、元の配列を変更します。配列をコピーせずに元の配列を直接変更することでメモリを節約できます。 - -```typescript -import { pull } from 'es-toolkit/compat'; - -// 数値配列から特定の値を削除 -const numbers = [1, 2, 3, 2, 4, 2, 5]; -pull(numbers, 2, 3); -console.log(numbers); // [1, 4, 5] - -// 文字列配列から特定の値を削除 -const fruits = ['apple', 'banana', 'apple', 'cherry']; -pull(fruits, 'apple'); -console.log(fruits); // ['banana', 'cherry'] -``` - -#### パラメータ - -- `array` (`T[]`): 変更する配列です。 -- `...valuesToRemove` (`T[]`): 配列から削除する値です。 - -#### 戻り値 - -(`T[]`): 変更された元の配列を返します。 diff --git a/docs/ja/reference/compat/array/pullAt.md b/docs/ja/reference/compat/array/pullAt.md deleted file mode 100644 index 1555c9496..000000000 --- a/docs/ja/reference/compat/array/pullAt.md +++ /dev/null @@ -1,57 +0,0 @@ -# pullAt (Lodash 互換性) - -::: warning `es-toolkit` の [pullAt](../../array/pullAt.md) を使用してください - -この `pullAt` 関数は、複雑な型処理とオーバーロードにより動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [pullAt](../../array/pullAt.md) を使用してください。 - -::: - -指定されたインデックスにある要素を配列から削除し、削除された要素を返します。 - -```typescript -const removed = pullAt(array, ...indexes); -``` - -## 使用法 - -### `pullAt(array, ...indexes)` - -指定されたインデックスにある要素を配列から削除し、削除された要素の配列を返します。元の配列は変更されます。 - -```typescript -import { pullAt } from 'es-toolkit/compat'; - -// 個別のインデックスで削除 -const array = [1, 2, 3, 4, 5]; -const removed = pullAt(array, 1, 3); -console.log(array); // [1, 3, 5] -console.log(removed); // [2, 4] - -// インデックスの配列で削除 -const colors = ['red', 'green', 'blue', 'yellow']; -const removedColors = pullAt(colors, [0, 2]); -console.log(colors); // ['green', 'yellow'] -console.log(removedColors); // ['red', 'blue'] -``` - -存在しないインデックスは `undefined` として扱われます。 - -```typescript -import { pullAt } from 'es-toolkit/compat'; - -const numbers = [10, 20, 30]; -const removed = pullAt(numbers, 1, 5); -console.log(numbers); // [10, 30] -console.log(removed); // [20, undefined] -``` - -#### パラメータ - -- `array` (`ArrayLike`): 変更する配列です。 -- `...indexes` (`Array`): 削除する要素のインデックスです。個別の数値または数値の配列として渡すことができます。 - -#### 戻り値 - -(`ArrayLike`): 削除された要素の配列を返します。 diff --git a/docs/ja/reference/compat/array/remove.md b/docs/ja/reference/compat/array/remove.md deleted file mode 100644 index 12aa48d58..000000000 --- a/docs/ja/reference/compat/array/remove.md +++ /dev/null @@ -1,70 +0,0 @@ -# remove (Lodash 互換性) - -::: warning `es-toolkit`の`remove`を使用してください - -この`remove`関数は、Lodashとの互換性のために様々な形式の述語をサポートするため、複雑に実装されています。メインライブラリの`remove`関数はシンプルな関数述語のみをサポートするため、より高速に動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[remove](../../array/remove.md)を使用してください。 - -::: - -配列から条件に一致する要素を削除し、削除された要素を配列として返します。 - -```typescript -const removedElements = remove(array, predicate); -``` - -## 使用法 - -### `remove(array, predicate)` - -配列を反復処理し、与えられた条件に一致する要素を元の配列から削除し、削除された要素を新しい配列として返します。元の配列が直接変更されることに注意してください。 - -```typescript -import { remove } from 'es-toolkit/compat'; - -// 関数を使用した条件で削除 -const numbers = [1, 2, 3, 4, 5]; -const evens = remove(numbers, n => n % 2 === 0); -console.log(numbers); // => [1, 3, 5] -console.log(evens); // => [2, 4] - -// 部分オブジェクトのマッチングで削除 -const objects = [{ a: 1 }, { a: 2 }, { a: 3 }]; -const removed = remove(objects, { a: 1 }); -console.log(objects); // => [{ a: 2 }, { a: 3 }] -console.log(removed); // => [{ a: 1 }] - -// プロパティ-値ペアで削除 -const items = [{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }]; -const cherries = remove(items, ['name', 'cherry']); -console.log(items); // => [{ name: 'apple' }, { name: 'banana' }] -console.log(cherries); // => [{ name: 'cherry' }] -``` - -この関数は様々な形式の述語をサポートします。 - -```typescript -import { remove } from 'es-toolkit/compat'; - -// 関数を使用した条件 -remove(users, user => user.active === false); - -// 部分オブジェクトのマッチング -remove(users, { status: 'inactive' }); - -// プロパティ-値配列 -remove(users, ['type', 'guest']); - -// プロパティ名で真値を確認 -remove(users, 'isDeleted'); -``` - -#### パラメータ - -- `array` (`ArrayLike`): 変更する配列です。 -- `predicate` (`((value: T, index: number, array: ArrayLike) => boolean) | Partial | [keyof T, unknown] | keyof T`, オプション): 各要素に対して実行する条件です。デフォルトは`identity`です。 - -#### 戻り値 - -(`T[]`): 条件に一致して削除された要素で構成された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/sample.md b/docs/ja/reference/compat/array/sample.md deleted file mode 100644 index 5e3fcac29..000000000 --- a/docs/ja/reference/compat/array/sample.md +++ /dev/null @@ -1,54 +0,0 @@ -# sample(Lodash 互換性) - -::: warning `es-toolkit` の [sample](../../array/sample.md) を使用してください - -この `sample` 関数は、`null` や `undefined` の処理、オブジェクト値の処理などにより、遅く動作します。 - -より高速でモダンな `es-toolkit` の [sample](../../array/sample.md) を使用してください。 - -::: - -配列またはオブジェクトからランダムな要素を1つ取得します。 - -```typescript -const randomItem = sample(collection); -``` - -## 使用法 - -### `sample(collection)` - -配列またはオブジェクトからランダムな要素を1つ選択する場合は `sample` を使用します。配列ではランダムな要素を返し、オブジェクトではランダムな値を返します。 - -```typescript -import { sample } from 'es-toolkit/compat'; - -// 配列からランダムな要素を取得 -sample([1, 2, 3, 4, 5]); -// 1から5の中からランダムな数値を1つ返します - -// オブジェクトからランダムな値を取得 -sample({ a: 1, b: 2, c: 3 }); -// 1、2、3の中からランダムな値を1つ返します - -// 文字列も処理します -sample('hello'); -// 'h'、'e'、'l'、'l'、'o'の中からランダムな文字を1つ返します -``` - -`null` や `undefined` は `undefined` を返します。 - -```typescript -import { sample } from 'es-toolkit/compat'; - -sample(null); // undefined -sample(undefined); // undefined -``` - -#### パラメータ - -- `collection` (`ArrayLike | Record | null | undefined`): サンプリングする配列またはオブジェクト。 - -#### 戻り値 - -(`T | string | undefined`): 配列またはオブジェクトからランダムに選択された要素を返します。コレクションが空であるか `null`、`undefined` の場合は `undefined` を返します。 diff --git a/docs/ja/reference/compat/array/sampleSize.md b/docs/ja/reference/compat/array/sampleSize.md deleted file mode 100644 index 3e5eca3a4..000000000 --- a/docs/ja/reference/compat/array/sampleSize.md +++ /dev/null @@ -1,54 +0,0 @@ -# sampleSize(Lodash 互換性) - -::: warning `es-toolkit` の [sampleSize](../../array/sampleSize.md) を使用してください - -この `sampleSize` 関数は、`null` や `undefined` の処理、オブジェクトのサポート、デフォルト値の処理などにより、遅く動作します。 - -より高速でモダンな `es-toolkit` の [sampleSize](../../array/sampleSize.md) を使用してください。 - -::: - -配列またはオブジェクトから指定された数だけランダムに要素を選択します。 - -```typescript -const sampled = sampleSize(collection, size); -``` - -## 使用法 - -### `sampleSize(collection, size?)` - -配列またはオブジェクトからランダムに要素を選択する場合は `sampleSize` を使用します。Floyd アルゴリズムを使用して重複なく効率的にサンプリングします。 - -```typescript -import { sampleSize } from 'es-toolkit/compat'; - -// 配列から3個の要素をランダムに選択します。 -sampleSize([1, 2, 3, 4, 5], 3); -// 戻り値:[2, 4, 5](実際の結果は異なる場合があります) - -// オブジェクトから2個の値をランダムに選択します。 -sampleSize({ a: 1, b: 2, c: 3, d: 4 }, 2); -// 戻り値:[2, 4](実際の結果は異なる場合があります) -``` - -`null` や `undefined` は空の配列として処理します。 - -```typescript -import { sampleSize } from 'es-toolkit/compat'; - -sampleSize(null, 2); -// 戻り値:[] - -sampleSize(undefined, 2); -// 戻り値:[] -``` - -#### パラメータ - -- `collection` (`Record | Record | T | null | undefined`): サンプリングする配列またはオブジェクト。 -- `size` (`number`、オプション): 選択する要素の個数。デフォルトは `1` です。 - -#### 戻り値 - -(`T[]`):ランダムに選択された要素で構成される新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/shuffle.md b/docs/ja/reference/compat/array/shuffle.md deleted file mode 100644 index 2b5c68f4f..000000000 --- a/docs/ja/reference/compat/array/shuffle.md +++ /dev/null @@ -1,60 +0,0 @@ -# shuffle(Lodash 互換性) - -::: warning `es-toolkit` の `shuffle` を使用してください - -この `shuffle` 関数は、Lodash との互換性のために追加の処理が含まれており、遅く動作します。 - -より高速でモダンな `es-toolkit` の [shuffle](../../array/shuffle.md) を使用してください。 - -::: - -配列またはオブジェクトの要素をランダムにシャッフルして新しい配列を返します。 - -```typescript -const result = shuffle(collection); -``` - -## 使用法 - -### `shuffle(collection)` - -Fisher-Yates アルゴリズムを使用して配列またはオブジェクトの要素をランダムにシャッフルし、新しい配列を返します。元は変更されません。 - -```typescript -import { shuffle } from 'es-toolkit/compat'; - -// 数値配列をシャッフル -const numbers = [1, 2, 3, 4, 5]; -const shuffled1 = shuffle(numbers); -// 戻り値:例えば [3, 1, 5, 2, 4](毎回異なる順序) - -// 文字列配列をシャッフル -const fruits = ['apple', 'banana', 'cherry', 'date']; -const shuffled2 = shuffle(fruits); -// 戻り値:例えば ['cherry', 'apple', 'date', 'banana'] - -// オブジェクトの値をシャッフル -const obj = { a: 1, b: 2, c: 3, d: 4 }; -const shuffled3 = shuffle(obj); -// 戻り値:例えば [3, 1, 4, 2](オブジェクトの値がランダムにシャッフルされる) -``` - -`null` や `undefined` は空の配列として処理します。 - -```typescript -import { shuffle } from 'es-toolkit/compat'; - -shuffle(null); -// 戻り値:[] - -shuffle(undefined); -// 戻り値:[] -``` - -#### パラメータ - -- `collection` (`ArrayLike | T | null | undefined`): シャッフルする配列またはオブジェクト。 - -#### 戻り値 - -(`T[]`):要素がランダムにシャッフルされた新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/tail.md b/docs/ja/reference/compat/array/tail.md deleted file mode 100644 index a053eb78a..000000000 --- a/docs/ja/reference/compat/array/tail.md +++ /dev/null @@ -1,58 +0,0 @@ -# tail (Lodash 互換性) - -::: warning `es-toolkit`の[tail](../../array/tail.md)を使用してください - -この`tail`関数は、`null`や`undefined`の処理などにより遅く動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[tail](../../array/tail.md)を使用してください。 - -::: - -配列の最初の要素を除いた残りの要素を返します。 - -```typescript -const result = tail(array); -``` - -## 使用法 - -### `tail(array)` - -配列の最初の要素を除いたすべての要素を含む新しい配列を作成したい場合は`tail`を使用してください。入力配列が空または要素が1つだけの場合は空の配列を返します。 - -```typescript -import { tail } from 'es-toolkit/compat'; - -// 数値配列から最初の要素を削除します。 -tail([1, 2, 3]); -// Returns: [2, 3] - -// 文字列配列から最初の要素を削除します。 -tail(['a', 'b', 'c']); -// Returns: ['b', 'c'] - -// 要素が1つだけの配列です。 -tail([1]); -// Returns: [] - -// 空の配列です。 -tail([]); -// Returns: [] -``` - -`null`や`undefined`は空の配列として扱われます。 - -```typescript -import { tail } from 'es-toolkit/compat'; - -tail(null); // [] -tail(undefined); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 最初の要素を削除する配列です。 - -#### 戻り値 - -(`T[]`): 最初の要素を除いた残りの要素を含む新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/take.md b/docs/ja/reference/compat/array/take.md deleted file mode 100644 index df5661f68..000000000 --- a/docs/ja/reference/compat/array/take.md +++ /dev/null @@ -1,56 +0,0 @@ -# take (Lodash 互換性) - -::: warning `es-toolkit`の[take](../../array/take.md)を使用してください - -この`take`関数は、Lodashとの互換性のための追加処理が含まれているため遅く動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[take](../../array/take.md)を使用してください。 - -::: - -配列の先頭から指定された個数の要素を取得して新しい配列を作成します。 - -```typescript -const result = take([1, 2, 3, 4, 5], 3); -// resultは[1, 2, 3]になります。 -``` - -## 使用法 - -### `take(array, count)` - -配列の先頭から指定された個数の要素を取得して新しい配列を返します。`count`が配列の長さより大きい場合は、配列全体を返します。 - -```typescript -import { take } from 'es-toolkit/compat'; - -// 基本的な使用法 -const numbers = [1, 2, 3, 4, 5]; -const result1 = take(numbers, 3); -// Returns: [1, 2, 3] - -// 配列の長さより大きい個数を要求 -const result2 = take(numbers, 10); -// Returns: [1, 2, 3, 4, 5] (配列全体) - -// 0個を要求 -const result3 = take(numbers, 0); -// Returns: [] - -// 空の配列を処理 -const result4 = take([], 3); -// Returns: [] - -// 負の数を処理 -const result5 = take(numbers, -1); -// Returns: [] -``` - -#### パラメータ - -- `array` (`T[]`): 要素を取得する配列です。 -- `count` (`number`): 取得する要素の個数です。デフォルト値は1です。 - -#### 戻り値 - -(`T[]`): 先頭から指定された個数の要素を含む新しい配列です。 diff --git a/docs/ja/reference/compat/array/takeRight.md b/docs/ja/reference/compat/array/takeRight.md deleted file mode 100644 index 4315835be..000000000 --- a/docs/ja/reference/compat/array/takeRight.md +++ /dev/null @@ -1,63 +0,0 @@ -# takeRight (Lodash 互換性) - -::: warning `es-toolkit`の[takeRight](../../array/takeRight.md)を使用してください - -この`takeRight`関数は、`null`や`undefined`の処理などにより遅く動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[takeRight](../../array/takeRight.md)を使用してください。 - -::: - -配列の末尾から指定された個数の要素を取得します。 - -```typescript -const result = takeRight(array, count); -``` - -## 使用法 - -### `takeRight(array, count)` - -配列の末尾から指定された個数の要素を取得して新しい配列を作成したい場合は`takeRight`を使用してください。要求された個数が配列の長さより大きい場合は、配列全体を返します。 - -```typescript -import { takeRight } from 'es-toolkit/compat'; - -// 数値配列から末尾の2個の要素を取得します。 -takeRight([1, 2, 3, 4, 5], 2); -// Returns: [4, 5] - -// 文字列配列から末尾の3個の要素を取得します。 -takeRight(['a', 'b', 'c'], 2); -// Returns: ['b', 'c'] - -// 要求された個数が配列の長さより大きい場合 -takeRight([1, 2, 3], 5); -// Returns: [1, 2, 3] - -// 0個を要求 -takeRight([1, 2, 3], 0); -// Returns: [] - -// 負の数を要求 -takeRight([1, 2, 3], -1); -// Returns: [] -``` - -`null`や`undefined`は空の配列として扱われます。 - -```typescript -import { takeRight } from 'es-toolkit/compat'; - -takeRight(null, 2); // [] -takeRight(undefined, 2); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 要素を取得する配列です。 -- `count` (`number`, オプション): 取得する要素の個数です。デフォルト値は`1`です。 - -#### 戻り値 - -(`T[]`): 末尾から指定された個数の要素を含む新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/takeRightWhile.md b/docs/ja/reference/compat/array/takeRightWhile.md deleted file mode 100644 index ff4210f2b..000000000 --- a/docs/ja/reference/compat/array/takeRightWhile.md +++ /dev/null @@ -1,71 +0,0 @@ -# takeRightWhile (Lodash 互換性) - -::: warning `es-toolkit`の[takeRightWhile](../../array/takeRightWhile.md)を使用してください - -この`takeRightWhile`関数は、`null`や`undefined`の処理などにより遅く動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[takeRightWhile](../../array/takeRightWhile.md)を使用してください。 - -::: - -条件を満たす間、配列の末尾から要素を取得します。 - -```typescript -const result = takeRightWhile(array, predicate); -``` - -## 使用法 - -### `takeRightWhile(array, predicate)` - -配列の末尾から開始して条件を満たす間、要素を取得して新しい配列を作成したい場合は`takeRightWhile`を使用してください。条件が偽と評価されると停止します。 - -```typescript -import { takeRightWhile } from 'es-toolkit/compat'; - -// 関数条件を使用 -const numbers = [1, 2, 3, 4, 5]; -takeRightWhile(numbers, x => x > 3); -// Returns: [4, 5] - -// オブジェクトプロパティ条件を使用 -const users = [ - { user: 'barney', active: true }, - { user: 'fred', active: false }, - { user: 'pebbles', active: false }, -]; - -takeRightWhile(users, o => !o.active); -// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] - -// 部分オブジェクトで条件マッチング -takeRightWhile(users, { active: false }); -// Returns: [{ user: 'pebbles', active: false }] - -// プロパティ-値配列で条件マッチング -takeRightWhile(users, ['active', false]); -// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] - -// プロパティ名で真と評価される値を確認 -const items = [{ active: false }, { active: true }, { active: true }]; -takeRightWhile(items, 'active'); -// Returns: [{ active: true }, { active: true }] -``` - -`null`や`undefined`は空の配列として扱われます。 - -```typescript -import { takeRightWhile } from 'es-toolkit/compat'; - -takeRightWhile(null, x => x > 0); // [] -takeRightWhile(undefined, x => x > 0); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 処理する配列です。 -- `predicate` (`ListIteratee`, オプション): 各要素に対して実行する条件です。関数、部分オブジェクト、プロパティ-値配列、プロパティ名を使用できます。デフォルトは恒等関数です。 - -#### 戻り値 - -(`T[]`): 条件を満たす間、配列の末尾から取得した要素の新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/takeWhile.md b/docs/ja/reference/compat/array/takeWhile.md deleted file mode 100644 index 8cf083298..000000000 --- a/docs/ja/reference/compat/array/takeWhile.md +++ /dev/null @@ -1,71 +0,0 @@ -# takeWhile (Lodash 互換性) - -::: warning `es-toolkit`の[takeWhile](../../array/takeWhile.md)を使用してください - -この`takeWhile`関数は、`null`や`undefined`の処理などにより遅く動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[takeWhile](../../array/takeWhile.md)を使用してください。 - -::: - -条件を満たす間、配列の先頭から要素を取得します。 - -```typescript -const result = takeWhile(array, predicate); -``` - -## 使用法 - -### `takeWhile(array, predicate)` - -配列の開始から条件を満たす間、要素を取得して新しい配列を作成したい場合は`takeWhile`を使用してください。条件が偽と評価されると停止します。 - -```typescript -import { takeWhile } from 'es-toolkit/compat'; - -// 関数条件を使用 -const numbers = [1, 2, 3, 4, 5]; -takeWhile(numbers, x => x < 3); -// Returns: [1, 2] - -// オブジェクトプロパティ条件を使用 -const users = [ - { user: 'barney', active: false }, - { user: 'fred', active: false }, - { user: 'pebbles', active: true }, -]; - -takeWhile(users, o => !o.active); -// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] - -// 部分オブジェクトで条件マッチング -takeWhile(users, { active: false }); -// Returns: [{ user: 'barney', active: false }] - -// プロパティ-値配列で条件マッチング -takeWhile(users, ['active', false]); -// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] - -// プロパティ名で真と評価される値を確認 -const items = [{ active: true }, { active: true }, { active: false }]; -takeWhile(items, 'active'); -// Returns: [{ active: true }, { active: true }] -``` - -`null`や`undefined`は空の配列として扱われます。 - -```typescript -import { takeWhile } from 'es-toolkit/compat'; - -takeWhile(null, x => x > 0); // [] -takeWhile(undefined, x => x > 0); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 処理する配列です。 -- `predicate` (`ListIteratee`, オプション): 各要素に対して実行する条件です。関数、部分オブジェクト、プロパティ-値配列、プロパティ名を使用できます。デフォルトは恒等関数です。 - -#### 戻り値 - -(`T[]`): 条件を満たす間、配列の先頭から取得した要素の新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/union.md b/docs/ja/reference/compat/array/union.md deleted file mode 100644 index 55d3de554..000000000 --- a/docs/ja/reference/compat/array/union.md +++ /dev/null @@ -1,62 +0,0 @@ -# union (Lodash互換) - -::: warning `es-toolkit`の[union](../../array/union.md)を使用してください - -この`union`関数は複雑な配列処理により動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[union](../../array/union.md)を使用してください。 - -::: - -複数の配列からユニークな値のみを集めて新しい配列を作成します。 - -```typescript -const result = union(...arrays); -``` - -## 使用法 - -### `union(...arrays)` - -複数の配列をマージして重複を削除し、ユニークな値のみを含む新しい配列を作成したい場合は`union`を使用してください。各値が最初に出現する順序を保持します。 - -```typescript -import { union } from 'es-toolkit/compat'; - -// 数値配列をマージ -union([2], [1, 2]); -// 戻り値: [2, 1] - -// 複数の配列をマージ -union([2], [1, 2], [2, 3]); -// 戻り値: [2, 1, 3] - -// ネストした配列は平坦化されません -union([1, 3, 2], [1, [5]], [2, [4]]); -// 戻り値: [1, 3, 2, [5], [4]] - -// 配列でない値は無視されます -union([0], 3, { '0': 1 }, null, [2, 1]); -// 戻り値: [0, 2, 1] - -// 配列のようなオブジェクトも処理されます -union([0], { 0: 'a', length: 1 }, [2, 1]); -// 戻り値: [0, 'a', 2, 1] -``` - -`null`または`undefined`は無視されます。 - -```typescript -import { union } from 'es-toolkit/compat'; - -union([1, 2], null, undefined, [3, 4]); -// 戻り値: [1, 2, 3, 4] -``` - -#### パラメータ - -- `...arrays` (`Array | null | undefined>`): マージする配列。配列でない値は無視されます。 - -#### 戻り値 - -(`T[]`): すべての配列のユニークな値を含む新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/unionBy.md b/docs/ja/reference/compat/array/unionBy.md deleted file mode 100644 index af17964a7..000000000 --- a/docs/ja/reference/compat/array/unionBy.md +++ /dev/null @@ -1,66 +0,0 @@ -# unionBy (Lodash互換) - -::: warning `es-toolkit`の[unionBy](../../array/unionBy.md)を使用してください - -この`unionBy`関数は複雑な処理により動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[unionBy](../../array/unionBy.md)を使用してください。 - -::: - -複数の配列をマージし、指定された基準に基づいてユニークな値のみを残します。 - -```typescript -const result = unionBy(...arrays, iteratee); -``` - -## 使用法 - -### `unionBy(...arrays, iteratee)` - -複数の配列をマージし、与えられた基準関数に基づいて重複を削除してユニークな値のみを含む新しい配列を作成したい場合は`unionBy`を使用してください。各値が最初に出現する順序を保持します。 - -```typescript -import { unionBy } from 'es-toolkit/compat'; - -// 小数を切り捨てて比較 -unionBy([2.1], [1.2, 2.3], Math.floor); -// 戻り値: [2.1, 1.2] - -// オブジェクトのプロパティで比較 -unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); -// 戻り値: [{ x: 1 }, { x: 2 }] - -// 関数で比較 -unionBy( - [{ id: 1, name: 'a' }], - [ - { id: 2, name: 'b' }, - { id: 1, name: 'c' }, - ], - item => item.id -); -// 戻り値: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }] - -// 部分オブジェクトで比較 -unionBy([{ x: 1, y: 1 }], [{ x: 1, y: 2 }], { x: 1 }); -// 戻り値: [{ x: 1, y: 1 }] -``` - -`null`または`undefined`配列は無視されます。 - -```typescript -import { unionBy } from 'es-toolkit/compat'; - -unionBy([1, 2], null, undefined, [3, 4], x => x); -// 戻り値: [1, 2, 3, 4] -``` - -#### パラメータ - -- `...arrays` (`Array | null | undefined>`): マージする配列。 -- `iteratee` (`ValueIteratee`): ユニーク性を決定する基準。関数、プロパティ名、部分オブジェクト、またはプロパティ-値配列を使用できます。 - -#### 戻り値 - -(`T[]`): 指定された基準に基づいて重複を削除したユニークな値を含む新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/unionWith.md b/docs/ja/reference/compat/array/unionWith.md deleted file mode 100644 index daf3c87e5..000000000 --- a/docs/ja/reference/compat/array/unionWith.md +++ /dev/null @@ -1,64 +0,0 @@ -# unionWith (Lodash互換) - -::: warning `es-toolkit`の[unionWith](../../array/unionWith.md)を使用してください - -この`unionWith`関数は複雑な処理により動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[unionWith](../../array/unionWith.md)を使用してください。 - -::: - -複数の配列をマージし、比較関数を使用してユニークな値のみを残します。 - -```typescript -const result = unionWith(...arrays, comparator); -``` - -## 使用法 - -### `unionWith(...arrays, comparator)` - -複数の配列をマージし、カスタム比較関数を使用して重複を削除し、ユニークな値のみを含む新しい配列を作成したい場合は`unionWith`を使用してください。各値が最初に出現する順序を保持します。 - -```typescript -import { unionWith } from 'es-toolkit/compat'; - -// カスタム比較関数を使用 -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, -]; -const others = [ - { x: 1, y: 1 }, - { x: 1, y: 2 }, -]; - -unionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); -// 戻り値: [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 1, y: 1 }] - -// 単純な等価比較 -unionWith([1, 2], [2, 3], (a, b) => a === b); -// 戻り値: [1, 2, 3] - -// 文字列の長さで比較 -unionWith(['ab', 'cd'], ['ef', 'gh', 'ab'], (a, b) => a.length === b.length); -// 戻り値: ['ab'] -``` - -`null`または`undefined`配列は無視されます。 - -```typescript -import { unionWith } from 'es-toolkit/compat'; - -unionWith([1, 2], null, undefined, [3, 4], (a, b) => a === b); -// 戻り値: [1, 2, 3, 4] -``` - -#### パラメータ - -- `...arrays` (`Array | null | undefined>`): マージする配列。 -- `comparator` (`(a: T, b: T) => boolean`): 2つの値が等しいかどうかを判断する比較関数。 - -#### 戻り値 - -(`T[]`): 比較関数を使用して重複を削除したユニークな値を含む新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/uniq.md b/docs/ja/reference/compat/array/uniq.md deleted file mode 100644 index 8a450cbd7..000000000 --- a/docs/ja/reference/compat/array/uniq.md +++ /dev/null @@ -1,51 +0,0 @@ -# uniq (Lodash互換) - -::: warning `es-toolkit`の[uniq](../../array/uniq.md)を使用してください - -この`uniq`関数はLodash互換性のための追加処理により動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[uniq](../../array/uniq.md)を使用してください。 - -::: - -配列から重複する要素を削除してユニークな要素のみを残した新しい配列を作成します。 - -```typescript -const result = uniq([1, 2, 2, 3, 3, 4]); -// resultは[1, 2, 3, 4]になります。 -``` - -## 使用法 - -### `uniq(array)` - -配列から重複する要素を削除してユニークな要素のみを含む新しい配列を返します。最初に出現する要素のみが保持され、順序は保たれます。 - -```typescript -import { uniq } from 'es-toolkit/compat'; - -// 数値配列から重複を削除 -const numbers = [1, 2, 2, 3, 3, 4, 1]; -const result1 = uniq(numbers); -// 戻り値: [1, 2, 3, 4] - -// 文字列配列から重複を削除 -const strings = ['a', 'b', 'b', 'c', 'a']; -const result2 = uniq(strings); -// 戻り値: ['a', 'b', 'c'] - -// オブジェクト配列から重複を削除(参照値比較) -const obj1 = { id: 1 }; -const obj2 = { id: 2 }; -const objects = [obj1, obj2, obj1]; -const result3 = uniq(objects); -// 戻り値: [{ id: 1 }, { id: 2 }] -``` - -#### パラメータ - -- `array` (`T[]`): 処理する配列。 - -#### 戻り値 - -(`T[]`): 重複が削除された新しい配列。 diff --git a/docs/ja/reference/compat/array/uniqBy.md b/docs/ja/reference/compat/array/uniqBy.md deleted file mode 100644 index 16aaac096..000000000 --- a/docs/ja/reference/compat/array/uniqBy.md +++ /dev/null @@ -1,55 +0,0 @@ -# uniqBy (Lodash互換) - -::: warning `es-toolkit`の[uniqBy](../../array/uniqBy.md)を使用してください - -この`uniqBy`関数は`null`または`undefined`の処理、複雑な引数タイプ処理などにより動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[uniqBy](../../array/uniqBy.md)を使用してください。 - -::: - -配列で変換関数が返す値に基づいて重複を削除し、ユニークな要素で構成される新しい配列を作成します。 - -```typescript -const result = uniqBy(array, iteratee); -``` - -## 使用法 - -### `uniqBy(array, iteratee)` - -配列の各要素に変換関数を適用し、変換結果が同じ要素の中で最初の要素のみを保持します。オブジェクト配列で特定のプロパティを基準に重複を削除したり、数値配列で特定の計算結果を基準に重複を削除するときに便利です。 - -```typescript -import { uniqBy } from 'es-toolkit/compat'; - -// 数値配列でMath.floor結果により重複を削除 -uniqBy([2.1, 1.2, 2.3], Math.floor); -// 戻り値: [2.1, 1.2] - -// オブジェクト配列でプロパティにより重複を削除 -uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); -// 戻り値: [{ x: 1 }, { x: 2 }] - -// 関数で重複を削除 -uniqBy([{ name: 'John' }, { name: 'Jane' }, { name: 'John' }], obj => obj.name); -// 戻り値: [{ name: 'John' }, { name: 'Jane' }] -``` - -`null`または`undefined`は空配列として扱われます。 - -```typescript -import { uniqBy } from 'es-toolkit/compat'; - -uniqBy(null, Math.floor); // [] -uniqBy(undefined, 'x'); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 重複を削除する配列。 -- `iteratee` (`ValueIteratee`): 各要素に適用する変換関数。関数、プロパティ名、部分オブジェクトなどを使用できます。 - -#### 戻り値 - -(`T[]`): 変換関数の結果を基準に重複が削除された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/uniqWith.md b/docs/ja/reference/compat/array/uniqWith.md deleted file mode 100644 index ea80c449b..000000000 --- a/docs/ja/reference/compat/array/uniqWith.md +++ /dev/null @@ -1,60 +0,0 @@ -# uniqWith (Lodash互換) - -::: warning `es-toolkit`の[uniqWith](../../array/uniqWith.md)を使用してください - -この`uniqWith`関数は`null`または`undefined`の処理、複雑な引数タイプ処理などにより動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[uniqWith](../../array/uniqWith.md)を使用してください。 - -::: - -配列で比較関数を使用して重複を削除し、ユニークな要素で構成される新しい配列を作成します。 - -```typescript -const result = uniqWith(array, comparator); -``` - -## 使用法 - -### `uniqWith(array, comparator)` - -配列の各要素を比較関数で比較して重複を削除します。比較関数が`true`を返すと2つの要素が同じと判断され、最初に出現する要素のみが保持されます。比較関数を提供しない場合、デフォルトで浅い等価比較を使用します。 - -```typescript -import { uniqWith } from 'es-toolkit/compat'; - -// 比較関数なしで使用(浅い等価比較) -uniqWith([1, 2, 2, 3]); -// 戻り値: [1, 2, 3] - -// カスタム比較関数で奇数/偶数基準により重複を削除 -uniqWith([1, 2, 3, 4], (a, b) => a % 2 === b % 2); -// 戻り値: [1, 2] - -// オブジェクト配列でプロパティ基準により重複を削除 -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 1, y: 2 }, -]; -uniqWith(objects, (a, b) => a.x === b.x && a.y === b.y); -// 戻り値: [{ x: 1, y: 2 }, { x: 2, y: 1 }] -``` - -`null`または`undefined`は空配列として扱われます。 - -```typescript -import { uniqWith } from 'es-toolkit/compat'; - -uniqWith(null); // [] -uniqWith(undefined); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 重複を削除する配列。 -- `comparator` (`(a: T, b: T) => boolean`, 選択): 2つの要素が等しいか比較する関数。`true`を返すと同じと判断されます。デフォルトは浅い等価比較です。 - -#### 戻り値 - -(`T[]`): 比較関数の結果を基準に重複が削除された新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/unzip.md b/docs/ja/reference/compat/array/unzip.md deleted file mode 100644 index 90a9c2771..000000000 --- a/docs/ja/reference/compat/array/unzip.md +++ /dev/null @@ -1,68 +0,0 @@ -# unzip (Lodash互換) - -::: warning `es-toolkit`の[unzip](../../array/unzip.md)を使用してください - -この`unzip`関数は`null`または`undefined`の処理、配列でない値のフィルタリングなどにより動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[unzip](../../array/unzip.md)を使用してください。 - -::: - -グループ化された配列の同じ位置にある要素を集めて新しい配列を作成します。 - -```typescript -const result = unzip(array); -``` - -## 使用法 - -### `unzip(array)` - -ネストした配列の同じインデックスにある要素を集めて新しい配列として返します。`zip`関数の逆の操作を実行します。行列を転置したり構造化データを再編成するときに便利です。 - -```typescript -import { unzip } from 'es-toolkit/compat'; - -// 文字列、ブール値、数値が混在した配列をアンジップ -const zipped = [ - ['a', true, 1], - ['b', false, 2], -]; -const result = unzip(zipped); -// 戻り値: [['a', 'b'], [true, false], [1, 2]] - -// 数値配列をアンジップ -const numbers = [ - [1, 4], - [2, 5], - [3, 6], -]; -unzip(numbers); -// 戻り値: [[1, 2, 3], [4, 5, 6]] - -// 長さが異なる配列も処理 -const uneven = [ - ['a', 1], - ['b', 2, true], -]; -unzip(uneven); -// 戻り値: [['a', 'b'], [1, 2], [undefined, true]] -``` - -`null`、`undefined`、または空配列は空配列として扱われます。 - -```typescript -import { unzip } from 'es-toolkit/compat'; - -unzip(null); // [] -unzip(undefined); // [] -unzip([]); // [] -``` - -#### パラメータ - -- `array` (`T[][] | ArrayLike> | null | undefined`): アンジップするネストした配列。各内部配列の同じ位置の要素が集められます。 - -#### 戻り値 - -(`T[][]`): 同じ位置の要素が集められた新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/unzipWith.md b/docs/ja/reference/compat/array/unzipWith.md deleted file mode 100644 index d644190fc..000000000 --- a/docs/ja/reference/compat/array/unzipWith.md +++ /dev/null @@ -1,84 +0,0 @@ -# unzipWith (Lodash互換) - -::: warning `es-toolkit`の`unzipWith`を使用してください - -この`unzipWith`関数は`null`または`undefined`の処理、`ArrayLike`タイプ処理、さまざまな条件関数形式のサポートなどにより動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[unzipWith](../../array/unzipWith.md)を使用してください。 - -::: - -グループ化された配列の同じ位置にある要素を集めて変換関数を適用した新しい配列を作成します。 - -```typescript -const result = unzipWith(array, iteratee); -``` - -## 使用法 - -### `unzipWith(array, iteratee)` - -ネストした配列の同じインデックスにある要素を集めて変換関数を適用します。`unzip`関数と似ていますが、各グループに変換関数を適用できます。変換関数を提供しない場合、デフォルトの`unzip`操作を実行します。 - -```typescript -import { unzipWith } from 'es-toolkit/compat'; - -// 同じ位置の要素を足す -unzipWith( - [ - [1, 10, 100], - [2, 20, 200], - ], - (a, b) => a + b -); -// 戻り値: [3, 30, 300] - -// 変換関数なしで使用(デフォルトunzip操作) -unzipWith([ - [1, 4], - [2, 5], - [3, 6], -]); -// 戻り値: [[1, 2, 3], [4, 5, 6]] - -// 文字列連結 -unzipWith( - [ - ['a', 'x'], - ['b', 'y'], - ['c', 'z'], - ], - (a, b) => a + b -); -// 戻り値: ['abc', 'xyz'] - -// 最大値を探す -unzipWith( - [ - [1, 10], - [2, 20], - [3, 5], - ], - Math.max -); -// 戻り値: [3, 20] -``` - -`null`、`undefined`、または空配列は空配列として扱われます。 - -```typescript -import { unzipWith } from 'es-toolkit/compat'; - -unzipWith(null, (a, b) => a + b); // [] -unzipWith(undefined, (a, b) => a + b); // [] -unzipWith([], (a, b) => a + b); // [] -``` - -#### パラメータ - -- `array` (`ArrayLike> | null | undefined`): アンジップするネストした配列。 -- `iteratee` (`(...values: T[]) => R`, 選択): 各グループの要素に適用する変換関数。提供しない場合、デフォルトの`unzip`操作を実行します。 - -#### 戻り値 - -(`R[]`または`T[][]`): 変換関数がある場合は変換された結果の配列を、ない場合はアンジップされた配列を返します。 diff --git a/docs/ja/reference/compat/array/without.md b/docs/ja/reference/compat/array/without.md deleted file mode 100644 index 76789c0fa..000000000 --- a/docs/ja/reference/compat/array/without.md +++ /dev/null @@ -1,49 +0,0 @@ -# without (Lodash互換) - -::: warning `es-toolkit`の[without](../../array/without.md)を使用してください - -この`without`関数はLodash互換性のための追加処理により動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[without](../../array/without.md)を使用してください。 - -::: - -配列から指定された値を除外した新しい配列を作成します。 - -```typescript -const result = without([1, 2, 3, 4, 5], 2, 4); -// resultは[1, 3, 5]になります。 -``` - -## 使用法 - -### `without(array, ...values)` - -配列から指定された値を削除した新しい配列を返します。元の配列は変更されません。 - -```typescript -import { without } from 'es-toolkit/compat'; - -// 数値配列から複数の値を削除 -const numbers = [1, 2, 3, 4, 5, 2, 4]; -const result1 = without(numbers, 2, 4); -// 戻り値: [1, 3, 5] - -// 文字列配列から値を削除 -const fruits = ['apple', 'banana', 'cherry', 'banana']; -const result2 = without(fruits, 'banana'); -// 戻り値: ['apple', 'cherry'] - -// 空配列を処理 -const result3 = without([], 1, 2, 3); -// 戻り値: [] -``` - -#### パラメータ - -- `array` (`T[]`): 処理する元の配列。 -- `...values` (`T[]`): 削除する値。 - -#### 戻り値 - -(`T[]`): 指定された値を削除した新しい配列。 diff --git a/docs/ja/reference/compat/array/xor.md b/docs/ja/reference/compat/array/xor.md deleted file mode 100644 index 00a9d47ca..000000000 --- a/docs/ja/reference/compat/array/xor.md +++ /dev/null @@ -1,61 +0,0 @@ -# xor (Lodash互換) - -::: warning `es-toolkit`の[xor](../../array/xor.md)を使用してください - -この`xor`関数は`null`または`undefined`の処理、複雑な重複計算ロジックなどにより動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[xor](../../array/xor.md)を使用してください。 - -::: - -複数の配列で正確に1つの配列にのみ存在する要素で構成される新しい配列を作成します。 - -```typescript -const result = xor(...arrays); -``` - -## 使用法 - -### `xor(...arrays)` - -複数の配列の対称差集合を計算します。つまり、与えられた配列の中で正確に1つの配列にのみ存在する要素を返します。2つ以上の配列を比較する際に重複しないユニークな要素を見つけたい場合に便利です。 - -```typescript -import { xor } from 'es-toolkit/compat'; - -// 2つの配列の対称差集合 -xor([1, 2, 3, 4], [3, 4, 5, 6]); -// 戻り値: [1, 2, 5, 6] - -// 3つの配列の対称差集合 -xor([1, 2], [2, 3], [4, 5]); -// 戻り値: [1, 3, 4, 5] - -// 文字列配列 -xor(['a', 'b'], ['b', 'c']); -// 戻り値: ['a', 'c'] - -// 1つの配列のみを提供 -xor([1, 2, 3]); -// 戻り値: [1, 2, 3] -``` - -`null`、`undefined`、または空配列は無視され、有効な配列のみが処理されます。 - -```typescript -import { xor } from 'es-toolkit/compat'; - -xor([1, 2], null, [2, 3]); -// 戻り値: [1, 3] - -xor([], [1, 2], [2, 3]); -// 戻り値: [1, 3] -``` - -#### パラメータ - -- `...arrays` (`Array | null | undefined>`): 対称差集合を計算する配列。`null`または`undefined`は無視されます。 - -#### 戻り値 - -(`T[]`): 正確に1つの配列にのみ存在する要素で構成される新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/xorBy.md b/docs/ja/reference/compat/array/xorBy.md deleted file mode 100644 index 470b27ee9..000000000 --- a/docs/ja/reference/compat/array/xorBy.md +++ /dev/null @@ -1,63 +0,0 @@ -# xorBy (Lodash互換) - -::: warning `es-toolkit`の[xorBy](../../array/xorBy.md)を使用してください - -この`xorBy`関数は`null`または`undefined`の処理、複雑な重複計算ロジックなどにより動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[xorBy](../../array/xorBy.md)を使用してください。 - -::: - -複数の配列で変換関数を基準に正確に1つの配列にのみ存在する要素で構成される新しい配列を作成します。 - -```typescript -const result = xorBy(...arrays, iteratee); -``` - -## 使用法 - -### `xorBy(...arrays, iteratee)` - -複数の配列の対称差集合を変換関数を基準に計算します。各要素に変換関数を適用した結果が正確に1つの配列にのみ存在する要素を返します。オブジェクト配列で特定のプロパティを基準に比較したり、数値配列で特定の計算結果を基準に比較するときに便利です。 - -```typescript -import { xorBy } from 'es-toolkit/compat'; - -// Math.floor結果により対称差集合を計算 -xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); -// 戻り値: [1.2, 4.3] - -// オブジェクトのプロパティにより対称差集合を計算 -xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); -// 戻り値: [{ x: 2 }] - -// 関数で対称差集合を計算 -const users1 = [{ name: 'John', age: 30 }]; -const users2 = [ - { name: 'Jane', age: 25 }, - { name: 'John', age: 30 }, -]; -xorBy(users1, users2, user => user.name); -// 戻り値: [{ name: 'Jane', age: 25 }] - -// 3つの配列の対称差集合 -xorBy([1.2, 2.3], [3.4, 4.5], [5.6, 6.7], Math.floor); -// 戻り値: [1.2, 2.3, 3.4, 4.5, 5.6, 6.7] -``` - -`null`または`undefined`は無視されます。 - -```typescript -import { xorBy } from 'es-toolkit/compat'; - -xorBy([2.1, 1.2], null, [4.3, 2.4], Math.floor); -// 戻り値: [1.2, 4.3] -``` - -#### パラメータ - -- `...arrays` (`Array | null | undefined | ValueIteratee>`): 対称差集合を計算する配列と最後の変換関数。関数、プロパティ名、部分オブジェクトなどを使用できます。 - -#### 戻り値 - -(`T[]`): 変換関数の結果を基準に正確に1つの配列にのみ存在する要素で構成される新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/xorWith.md b/docs/ja/reference/compat/array/xorWith.md deleted file mode 100644 index 759312f9b..000000000 --- a/docs/ja/reference/compat/array/xorWith.md +++ /dev/null @@ -1,66 +0,0 @@ -# xorWith (Lodash互換) - -::: warning `es-toolkit`の[xorWith](../../array/xorWith.md)を使用してください - -この`xorWith`関数は`null`または`undefined`の処理、複雑な重複計算ロジックなどにより動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[xorWith](../../array/xorWith.md)を使用してください。 - -::: - -複数の配列で比較関数を使用して正確に1つの配列にのみ存在する要素で構成される新しい配列を作成します。 - -```typescript -const result = xorWith(...arrays, comparator); -``` - -## 使用法 - -### `xorWith(...arrays, comparator)` - -複数の配列の対称差集合を比較関数を使用して計算します。比較関数が`true`を返すと2つの要素が同じと判断され、正確に1つの配列にのみ存在する要素を返します。複雑なオブジェクトやカスタム比較ロジックが必要な場合に便利です。 - -```typescript -import { xorWith } from 'es-toolkit/compat'; - -// 単純な数値比較 -xorWith([1, 2], [2, 3], (a, b) => a === b); -// 戻り値: [1, 3] - -// オブジェクトのプロパティを比較 -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, -]; -const others = [ - { x: 1, y: 1 }, - { x: 1, y: 2 }, -]; -xorWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); -// 戻り値: [{ x: 2, y: 1 }, { x: 1, y: 1 }] - -// 3つの配列の対称差集合 -xorWith([1], [2], [3], (a, b) => a === b); -// 戻り値: [1, 2, 3] - -// 文字列の長さで比較 -xorWith(['hello'], ['world', 'hi'], (a, b) => a.length === b.length); -// 戻り値: ['hi'] -``` - -比較関数を提供しない場合、デフォルトで浅い等価比較を使用します。 - -```typescript -import { xorWith } from 'es-toolkit/compat'; - -xorWith([1, 2], [2, 3]); -// 戻り値: [1, 3] -``` - -#### パラメータ - -- `...arrays` (`Array | null | undefined | ((a: T, b: T) => boolean)>`): 対称差集合を計算する配列と最後の比較関数。比較関数は2つの要素が等しい場合に`true`を返す必要があります。 - -#### 戻り値 - -(`T[]`): 比較関数の結果を基準に正確に1つの配列にのみ存在する要素で構成される新しい配列を返します。 diff --git a/docs/ja/reference/compat/array/zip.md b/docs/ja/reference/compat/array/zip.md deleted file mode 100644 index 0993d5b9b..000000000 --- a/docs/ja/reference/compat/array/zip.md +++ /dev/null @@ -1,48 +0,0 @@ -# zip (Lodash互換) - -::: warning `es-toolkit`の[zip](../../array/zip.md)を使用してください - -この`zip`関数はLodash互換性のための追加処理により動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[zip](../../array/zip.md)を使用してください。 - -::: - -複数の配列を1つのタプルの配列に結合します。 - -```typescript -const result = zip([1, 2], ['a', 'b']); -// resultは[[1, 'a'], [2, 'b']]になります。 -``` - -## 使用法 - -### `zip(...arrs)` - -複数の配列を受け取り、各インデックスの要素を1つのタプルにまとめて新しい配列を作成します。入力配列の長さが異なる場合、結果の配列の長さは最も長い入力配列の長さとなり、欠落した要素は`undefined`で埋められます。 - -```typescript -import { zip } from 'es-toolkit/compat'; - -const arr1 = [1, 2, 3]; -const arr2 = ['a', 'b', 'c']; -const result = zip(arr1, arr2); -// 戻り値: [[1, 'a'], [2, 'b'], [3, 'c']] - -// 長さが異なる配列 -const arr3 = [true, false]; -const result2 = zip(arr1, arr2, arr3); -// 戻り値: [[1, 'a', true], [2, 'b', false], [3, 'c', undefined]] - -// 空配列が含まれる場合 -zip([1, 2], [], ['a', 'b']); -// 戻り値: [[1, undefined, 'a'], [2, undefined, 'b']] -``` - -#### パラメータ - -- `...arrs` (`any[][]`): 結合する配列。 - -#### 戻り値 - -(`any[][]`): 入力配列の各インデックスの要素を含むタプルの新しい配列。 diff --git a/docs/ja/reference/compat/array/zipObject.md b/docs/ja/reference/compat/array/zipObject.md deleted file mode 100644 index b596ad526..000000000 --- a/docs/ja/reference/compat/array/zipObject.md +++ /dev/null @@ -1,50 +0,0 @@ -# zipObject (Lodash互換) - -::: warning `es-toolkit`の[zipObject](../../array/zipObject.md)を使用してください - -この`zipObject`関数はLodash互換性のための追加処理により動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[zipObject](../../array/zipObject.md)を使用してください。 - -::: - -2つの配列を使用してオブジェクトを作成します。最初の配列はプロパティ名として、2番目の配列は対応する値として使用されます。 - -```typescript -const result = zipObject(keys, values); -``` - -## 使用法 - -### `zipObject(keys, values)` - -キー配列と値配列から1つのオブジェクトを作成したい場合は`zipObject`を使用してください。最初の配列の要素をプロパティ名として、2番目の配列の要素を対応する値として使用してオブジェクトを作成します。APIレスポンスの処理やデータの変換時に特に便利です。 - -```typescript -import { zipObject } from 'es-toolkit/compat'; - -// 基本的な使用法 -const keys = ['a', 'b', 'c']; -const values = [1, 2, 3]; -const result = zipObject(keys, values); -// 戻り値: { a: 1, b: 2, c: 3 } - -// 長さが異なる配列 -const keys2 = ['x', 'y', 'z']; -const values2 = [10, 20]; -const result2 = zipObject(keys2, values2); -// 戻り値: { x: 10, y: 20, z: undefined } - -// 空配列が提供された場合 -const result3 = zipObject([], []); -// 戻り値: {} -``` - -#### パラメータ - -- `keys` (`PropertyKey[]`): プロパティ名として使用する配列。 -- `values` (`T[]`): プロパティ値として使用する配列。 - -#### 戻り値 - -(`Record`): 作成されたオブジェクト。 diff --git a/docs/ja/reference/compat/array/zipWith.md b/docs/ja/reference/compat/array/zipWith.md deleted file mode 100644 index 629115ab2..000000000 --- a/docs/ja/reference/compat/array/zipWith.md +++ /dev/null @@ -1,47 +0,0 @@ -# zipWith (Lodash互換) - -::: warning `es-toolkit`の[zipWith](../../array/zipWith.md)を使用してください - -この`zipWith`関数はLodash互換性のための追加処理により動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[zipWith](../../array/zipWith.md)を使用してください。 - -::: - -複数の配列の要素を結合関数を使用して新しい配列に結合します。 - -```typescript -const result = zipWith([1, 2], [3, 4], (a, b) => a + b); -// resultは[4, 6]になります。 -``` - -## 使用法 - -### `zipWith(...arrs, iteratee)` - -複数の配列を受け取り、各インデックスの要素を提供された関数で結合して新しい配列を作成します。配列の長さが異なる場合、最も長い配列の長さまで処理し、欠落した値には`undefined`が渡されます。 - -```typescript -import { zipWith } from 'es-toolkit/compat'; - -// 2つの配列の要素を足す -const result1 = zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b); -// 戻り値: [5, 7, 9] - -// 3つの配列の要素を結合 -const result2 = zipWith([1, 2], [3, 4], [5, 6], (a, b, c) => a + b + c); -// 戻り値: [9, 12] - -// 長さが異なる配列 -const result3 = zipWith([1, 2, 3], [4, 5], (a, b) => (a || 0) + (b || 0)); -// 戻り値: [5, 7, 3] -``` - -#### パラメータ - -- `...arrs` (`any[][]`): 結合する配列。 -- `iteratee` (`Function`): 各インデックスの要素を結合する関数。 - -#### 戻り値 - -(`any[]`): 結合関数を適用した結果からなる新しい配列。 diff --git a/docs/ja/reference/compat/function/after.md b/docs/ja/reference/compat/function/after.md deleted file mode 100644 index 7ebdfd5c9..000000000 --- a/docs/ja/reference/compat/function/after.md +++ /dev/null @@ -1,75 +0,0 @@ -# after (Lodash 互換性) - -::: warning `es-toolkit` の [`after`](../../function/after.md) を使用してください - -この `after` 関数は、複雑な型検証と整数変換処理により動作が遅くなります。 - -代わりに、より高速でモダンな `es-toolkit` の [after](../../function/after.md) を使用してください。 - -::: - -指定された回数呼び出された後にのみ実行される関数を作成します。 - -```typescript -const restrictedFunction = after(n, func); -``` - -## 使用法 - -### `after(n, func)` - -関数が特定の回数呼び出された後にのみ実行されるように制限したい場合は、`after` を使用してください。複数の非同期操作が完了した後にコールバックを実行したり、初期化段階を経た後に関数を有効化する際に便利です。 - -```typescript -import { after } from 'es-toolkit/compat'; - -// 基本的な使用法 -const logAfterThree = after(3, () => { - console.log('3回目の呼び出しから実行されます!'); -}); - -logAfterThree(); // 実行されない -logAfterThree(); // 実行されない -logAfterThree(); // "3回目の呼び出しから実行されます!" が出力される -logAfterThree(); // "3回目の呼び出しから実行されます!" が出力される (実行が続く) -``` - -複数の非同期操作がすべて完了した後に特定のコールバックを実行する際にも使用できます。 - -```typescript -import { after } from 'es-toolkit/compat'; - -const tasks = ['task1', 'task2', 'task3']; -const allTasksComplete = after(tasks.length, () => { - console.log('すべてのタスクが完了しました!'); -}); - -// 各タスクが完了するたびに呼び出される -tasks.forEach(task => { - performAsyncTask(task, () => { - console.log(`${task} 完了`); - allTasksComplete(); // 3回目の呼び出しで "すべてのタスクが完了しました!" が出力される - }); -}); -``` - -0または負の数を渡すと、最初の呼び出しからすぐに実行されます。 - -```typescript -import { after } from 'es-toolkit/compat'; - -const immediate = after(0, () => console.log('すぐに実行')); -immediate(); // "すぐに実行" - -const negative = after(-1, () => console.log('すぐに実行')); -negative(); // "すぐに実行" -``` - -#### パラメータ - -- `n` (`number`): 関数が実行される前に必要な呼び出し回数です。 -- `func` (`TFunc`): 制限する関数です。 - -#### 戻り値 - -(`TFunc`): n回目の呼び出しから元の関数を実行する新しい制限された関数を返します。 diff --git a/docs/ja/reference/compat/function/ary.md b/docs/ja/reference/compat/function/ary.md deleted file mode 100644 index 61710a15d..000000000 --- a/docs/ja/reference/compat/function/ary.md +++ /dev/null @@ -1,90 +0,0 @@ -# ary (Lodash 互換性) - -::: warning `es-toolkit` の [`ary`](../../function/ary.md) を使用してください - -この `ary` 関数は、複雑なパラメータ検証により動作が遅くなります。 - -代わりに、より高速でモダンな `es-toolkit` の [ary](../../function/ary.md) を使用してください。 - -::: - -関数が受け取ることができる引数の数を制限する関数を作成します。 - -```typescript -const cappedFunction = ary(func, n); -``` - -## 使用法 - -### `ary(func, n)` - -関数が受け取る引数の数を制限したい場合は、`ary` を使用してください。あまりにも多くの引数を受け取る関数を安全に使用したり、コールバック関数で不要な引数を無視する際に便利です。 - -```typescript -import { ary } from 'es-toolkit/compat'; - -// 基本的な使用法 -function greet(name, age, city) { - return `こんにちは、${name}さん! ${age}歳、${city}からいらっしゃいました。`; -} - -const limitedGreet = ary(greet, 2); -console.log(limitedGreet('田中', 30, '東京', '追加引数')); -// "こんにちは、田中さん! 30歳、undefinedからいらっしゃいました。" -// 3番目の引数以降は無視される -``` - -配列メソッドと一緒に使用する際、コールバック関数に不要な引数が渡されないようにできます。 - -```typescript -import { ary } from 'es-toolkit/compat'; - -// parseIntは第2引数(基数)を受け取るが、mapのコールバックは3つの引数を渡す -const numbers = ['1', '2', '3', '4', '5']; - -// 誤った使用法 - parseIntがインデックスを基数として受け取る -console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] - -// aryを使用して最初の引数のみ渡す -console.log(numbers.map(ary(parseInt, 1))); // [1, 2, 3, 4, 5] -``` - -関数が希望するパラメータ引数の数だけを受け取るように制限できます。 - -```typescript -import { ary } from 'es-toolkit/compat'; - -function sum(...args) { - return args.reduce((total, num) => total + num, 0); -} - -const sum0 = ary(sum, 0); -const sum1 = ary(sum, 1); -const sum2 = ary(sum, 2); -const sum3 = ary(sum, 3); - -console.log(sum0(1, 2, 3, 4, 5)); // 0 (引数なし) -console.log(sum1(1, 2, 3, 4, 5)); // 1 (最初の引数のみ) -console.log(sum2(1, 2, 3, 4, 5)); // 3 (最初の2つの引数のみ) -console.log(sum3(1, 2, 3, 4, 5)); // 6 (最初の3つの引数のみ) -``` - -負の数や `NaN` を渡すと、0として扱われ、すべての引数が無視されます。 - -```typescript -import { ary } from 'es-toolkit/compat'; - -const func = (a, b, c) => [a, b, c]; - -console.log(ary(func, -1)(1, 2, 3)); // [] (負数は0として扱われる) -console.log(ary(func, NaN)(1, 2, 3)); // [] (NaNは0として扱われる) -``` - -#### パラメータ - -- `func` (`Function`): 引数の数を制限する関数です。 -- `n` (`number`, オプション): 許可する最大引数数です。省略した場合、関数の `length` プロパティを使用します。 - -#### 戻り値 - -(`Function`): 最大 `n` 個の引数のみを受け取る新しい関数を返します。 diff --git a/docs/ja/reference/compat/function/attempt.md b/docs/ja/reference/compat/function/attempt.md deleted file mode 100644 index 52fafb68a..000000000 --- a/docs/ja/reference/compat/function/attempt.md +++ /dev/null @@ -1,66 +0,0 @@ -# attempt (Lodash 互換性) - -::: warning `es-toolkit` の [`attempt`](../../util/attempt.md) 関数または try-catch ブロックを使用してください - -この `attempt` 関数は、エラーと戻り値を区別せずに返すため、使用時に混乱する可能性があります。 - -代わりに、より直接的で明確な [`attempt`](../../util/attempt.md) 関数または try-catch ブロックを使用してください。 - -::: - -関数を実行し、エラーが発生した場合にエラーオブジェクトを返す関数です。 - -```typescript -const result = attempt(func, ...args); -``` - -## 使用法 - -### `attempt(func, ...args)` - -関数を安全に実行したい場合は `attempt` を使用してください。エラーが発生する可能性のある関数を実行する際に、プログラムがクラッシュするのを防ぎ、エラーを戻り値として処理するのに便利です。 - -```typescript -import { attempt } from 'es-toolkit/compat'; - -// 基本的な使用法 - 成功する場合 -const result = attempt((x, y) => x + y, 2, 3); -console.log(result); // 5 - -// エラーが発生する場合 -const errorResult = attempt(() => { - throw new Error('何かがうまくいきませんでした'); -}); -console.log(errorResult); // Error: 何かがうまくいきませんでした -``` - -try-catch ブロックの使用との違いは次のとおりです。 - -```typescript -// attempt を使用 -import { attempt } from 'es-toolkit/compat'; - -const result = attempt(riskyFunction, arg1, arg2); -if (result instanceof Error) { - console.log('エラーが発生しました:', result.message); -} else { - console.log('結果:', result); -} - -// try-catch を使用 (より直接的) -try { - const result = riskyFunction(arg1, arg2); - console.log('結果:', result); -} catch (error) { - console.log('エラーが発生しました:', error.message); -} -``` - -#### パラメータ - -- `func` (`Function`): 実行する関数です。 -- `args` (`...any[]`): 関数に渡す引数です。 - -#### 戻り値 - -(`ReturnType | Error`): 関数が成功した場合は戻り値を、エラーが発生した場合は Error オブジェクトを返します。 diff --git a/docs/ja/reference/compat/function/before.md b/docs/ja/reference/compat/function/before.md deleted file mode 100644 index cc2b47e28..000000000 --- a/docs/ja/reference/compat/function/before.md +++ /dev/null @@ -1,186 +0,0 @@ -# before (Lodash 互換性) - -::: warning `es-toolkit` の [`before`](../../function/before.md) を使用してください - -この `before` 関数は、複雑な型検証と整数変換処理により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [before](../../function/before.md) を使用してください。 - -::: - -指定された回数まで元の関数を実行し、その後は最後の結果を返す関数を作成します。 - -```typescript -const limitedFunction = before(n, func); -``` - -## 使用法 - -### `before(n, func)` - -関数を特定の回数まで実行するように制限したい場合は `before` を使用してください。関数呼び出し回数を制限したり、初期設定段階でのみ関数を実行したい場合に便利です。 - -```typescript -import { before } from 'es-toolkit/compat'; - -// 基本的な使い方 -let count = 0; -const beforeThree = before(3, () => ++count); - -console.log(beforeThree()); // 1 (最初の呼び出し) -console.log(beforeThree()); // 2 (2回目の呼び出し) -console.log(beforeThree()); // 2 (3回目以降は最後の結果を返す) -console.log(beforeThree()); // 2 (引き続き最後の結果を返す) -``` - -クロージャを使用した代替案: - -```typescript -// before を使用 -const beforeThree = before(3, myFunction); - -// クロージャを使用(よりシンプルで高速) -function createBefore(limit, callback) { - let callCount = 0; - let lastResult; - - return function (...args) { - if (callCount < limit - 1) { - lastResult = callback.apply(this, args); - callCount++; - } - return lastResult; - }; -} - -const beforeThreeAlternative = createBefore(3, myFunction); -``` - -初期化関数として活用: - -```typescript -import { before } from 'es-toolkit/compat'; - -class Database { - constructor() { - this.isInitialized = false; - - // 初期化は一度だけ実行 - this.initialize = before(2, () => { - console.log('データベースを初期化中...'); - this.setupConnection(); - this.isInitialized = true; - return '初期化完了'; - }); - } - - setupConnection() { - // 実際の接続設定ロジック - } - - query(sql) { - const initResult = this.initialize(); - console.log(initResult); // 最初の呼び出し: "初期化完了"、以降:同じ結果 - - // クエリ実行ロジック - return `クエリを実行: ${sql}`; - } -} - -const db = new Database(); -db.query('SELECT * FROM users'); // 初期化実行 -db.query('SELECT * FROM products'); // 初期化は実行されない -``` - -API 呼び出しの制限: - -```typescript -import { before } from 'es-toolkit/compat'; - -// API 呼び出しを最大5回まで許可 -const limitedApiCall = before(6, endpoint => { - console.log(`API 呼び出し: ${endpoint}`); - return fetch(endpoint).then(res => res.json()); -}); - -// 最初の5回は実際の API 呼び出し -limitedApiCall('/api/data1'); // 実際の呼び出し -limitedApiCall('/api/data2'); // 実際の呼び出し -limitedApiCall('/api/data3'); // 実際の呼び出し -limitedApiCall('/api/data4'); // 実際の呼び出し -limitedApiCall('/api/data5'); // 実際の呼び出し -limitedApiCall('/api/data6'); // 最後の結果を返す(API 呼び出しなし) -``` - -イベントリスナーの制限: - -```typescript -import { before } from 'es-toolkit/compat'; - -// クリックイベントを3回まで処理 -const limitedClickHandler = before(4, event => { - console.log('クリック処理:', event.target.id); - return `処理完了: ${Date.now()}`; -}); - -document.getElementById('button').addEventListener('click', limitedClickHandler); -// 最初の3回のクリックのみ処理され、その後は最後の結果を返す -``` - -パラメータと戻り値の処理: - -```typescript -import { before } from 'es-toolkit/compat'; - -const limitedCalculator = before(3, (operation, a, b) => { - const result = operation === 'add' ? a + b : a - b; - console.log(`計算: ${a} ${operation} ${b} = ${result}`); - return result; -}); - -console.log(limitedCalculator('add', 5, 3)); // "計算: 5 add 3 = 8"、返す: 8 -console.log(limitedCalculator('subtract', 10, 4)); // "計算: 10 subtract 4 = 6"、返す: 6 -console.log(limitedCalculator('multiply', 7, 2)); // 計算しない、返す: 6(最後の結果) -``` - -0または1を渡すと関数が実行されません: - -```typescript -import { before } from 'es-toolkit/compat'; - -const neverCalled = before(0, () => { - console.log('この関数は実行されません'); - return '結果'; -}); - -const onceOnly = before(1, () => { - console.log('この関数も実行されません'); - return '結果'; -}); - -console.log(neverCalled()); // undefined -console.log(onceOnly()); // undefined -``` - -リソースクリーンアップの最適化: - -```typescript -import { before } from 'es-toolkit/compat'; - -// 関数参照が自動的にクリーンアップされてメモリリークを防止 -const limitedProcessor = before(2, data => { - // 複雑なデータ処理 - return processComplexData(data); -}); - -// 2回目の呼び出し後、元の関数参照が削除される(ガベージコレクション) -``` - -#### パラメータ - -- `n` (`number`): 関数を実行する最大回数。n-1回まで実行され、n回目以降は最後の結果を返します。 -- `func` (`Function`): 制限する関数。 - -#### 戻り値 - -(`Function`): 指定された回数まで元の関数を実行し、その後は最後の結果を返す新しい関数を返します。 diff --git a/docs/ja/reference/compat/function/curry.md b/docs/ja/reference/compat/function/curry.md deleted file mode 100644 index 863662578..000000000 --- a/docs/ja/reference/compat/function/curry.md +++ /dev/null @@ -1,222 +0,0 @@ -# curry (Lodash 互換性) - -::: warning `es-toolkit` の `curry` または手動クロージャを使用してください -この `curry` 関数は、複雑なプレースホルダー処理、引数個数検証、引数合成ロジックにより、動作が遅くなります。 - -プレースホルダーが必要ない場合は、より高速な `es-toolkit` の [`curry`](../../function/curry.md) またはシンプルなクロージャを使用してください。 -::: - -関数をカリー化して、引数を一つずつ受け取るか、複数個を一度に受け取ることができる関数を作成します。 - -```typescript -const curriedFunction = curry(func, arity); -``` - -## 使用法 - -### `curry(func, arity)` - -部分適用を容易にするために関数をカリー化したい場合に `curry` を使用します。引数を段階的に提供する場合や、プレースホルダーを使用して特定の位置の引数を後で提供する場合に便利です。 - -```typescript -import { curry } from 'es-toolkit/compat'; - -// 基本的な使用法 -function add(a, b, c) { - return a + b + c; -} - -const curriedAdd = curry(add); - -// さまざまな方法で呼び出し可能 -console.log(curriedAdd(1)(2)(3)); // 6 -console.log(curriedAdd(1, 2)(3)); // 6 -console.log(curriedAdd(1)(2, 3)); // 6 -console.log(curriedAdd(1, 2, 3)); // 6 -``` - -メインライブラリの curry との比較: - -```typescript -// compat バージョン (柔軟、ただし遅い) -import { curry } from 'es-toolkit/compat'; -const curriedCompat = curry(add); -curriedCompat(1, 2)(3); // サポート -curriedCompat(1)(curry.placeholder, 3)(2); // プレースホルダーサポート - -// メインライブラリバージョン (より速い、ただし一度に一つずつのみ) -import { curry } from 'es-toolkit'; -const curriedMain = curry(add); -curriedMain(1)(2)(3); // サポート -curriedMain(1, 2)(3); // サポートされていない -``` - -プレースホルダー機能の使用: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function greet(greeting, name, punctuation) { - return `${greeting}, ${name}${punctuation}`; -} - -const curriedGreet = curry(greet); - -// プレースホルダーで中間引数をスキップ -const greetWithExclamation = curriedGreet(curry.placeholder, curry.placeholder, '!'); -console.log(greetWithExclamation('Hello', 'John')); // "Hello, John!" - -const sayHello = curriedGreet('Hello'); -console.log(sayHello(curry.placeholder, '~')('Jane')); // "Hello, Jane~" -``` - -関数型プログラミングでの活用: - -```typescript -import { curry } from 'es-toolkit/compat'; - -// マッピング関数を作成 -const map = curry((fn, array) => array.map(fn)); -const filter = curry((predicate, array) => array.filter(predicate)); - -const numbers = [1, 2, 3, 4, 5]; - -// 再利用可能な関数を生成 -const double = x => x * 2; -const isEven = x => x % 2 === 0; - -const mapDouble = map(double); -const filterEven = filter(isEven); - -console.log(mapDouble(numbers)); // [2, 4, 6, 8, 10] -console.log(filterEven(numbers)); // [2, 4] - -// 関数合成 -const processNumbers = nums => mapDouble(filterEven(nums)); -console.log(processNumbers(numbers)); // [4, 8] -``` - -API クライアントの構成: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function apiRequest(method, baseUrl, endpoint, options) { - return fetch(`${baseUrl}${endpoint}`, { - method, - ...options, - }); -} - -const curriedApiRequest = curry(apiRequest); - -// デフォルト設定で特化した関数を生成 -const apiGet = curriedApiRequest('GET', 'https://api.example.com'); -const apiPost = curriedApiRequest('POST', 'https://api.example.com'); - -// 認証ヘッダーを含む -const authenticatedPost = apiPost(curry.placeholder, { - headers: { Authorization: 'Bearer token123' }, -}); - -// 使用 -apiGet('/users'); // GET https://api.example.com/users -authenticatedPost('/users'); // POST with auth headers -``` - -数学演算関数: - -```typescript -import { curry } from 'es-toolkit/compat'; - -const calculate = curry((operation, a, b) => { - switch (operation) { - case '+': - return a + b; - case '-': - return a - b; - case '*': - return a * b; - case '/': - return a / b; - default: - throw new Error('サポートされていない演算'); - } -}); - -// 特化した演算関数 -const add = calculate('+'); -const subtract = calculate('-'); -const multiply = calculate('*'); - -console.log(add(5, 3)); // 8 -console.log(subtract(10)(4)); // 6 -console.log(multiply(3, 4)); // 12 - -// プレースホルダーで第二オペランドを固定 -const addFive = calculate('+', curry.placeholder, 5); -console.log(addFive(10)); // 15 -``` - -引数個数の指定: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function variableArgsFunction(a, b, c, ...rest) { - return [a, b, c, rest]; -} - -// 引数個数を 3 に制限 -const curriedFixed = curry(variableArgsFunction, 3); - -console.log(curriedFixed(1)(2)(3)); // [1, 2, 3, []] -console.log(curriedFixed(1, 2)(3)); // [1, 2, 3, []] - -// 引数個数なしで使用 (デフォルト値: function.length) -const curriedDefault = curry(variableArgsFunction); // arity = 3 -``` - -シンプルなカリー化の代替: - -```typescript -// curry を使用 -const curriedAdd = curry((a, b, c) => a + b + c); - -// 手動クロージャ (より速い) -const manualCurry = a => b => c => a + b + c; - -// どちらも同じ結果 -console.log(curriedAdd(1)(2)(3)); // 6 -console.log(manualCurry(1)(2)(3)); // 6 -``` - -コンストラクタ関数もサポート: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function Person(name, age, city) { - this.name = name; - this.age = age; - this.city = city; -} - -const CurriedPerson = curry(Person); -const SeoulPerson = CurriedPerson(curry.placeholder, curry.placeholder, 'Seoul'); - -const person1 = new SeoulPerson('John', 30); -const person2 = new SeoulPerson('Jane', 25); - -console.log(person1.city); // "Seoul" -console.log(person2.city); // "Seoul" -``` - -#### パラメータ - -- `func` (`Function`): カリー化する関数。 -- `arity` (`number`, オプション): 関数の引数個数。省略すると `func.length` が使用されます。 - -#### 戻り値 - -(`Function & { placeholder: symbol }`): カリー化された関数を返します。`placeholder` プロパティで引数の位置を制御できます。 diff --git a/docs/ja/reference/compat/function/curryRight.md b/docs/ja/reference/compat/function/curryRight.md deleted file mode 100644 index 8f95c253c..000000000 --- a/docs/ja/reference/compat/function/curryRight.md +++ /dev/null @@ -1,242 +0,0 @@ -# curryRight (Lodash 互換性) - -::: warning `es-toolkit` の [`curryRight`](../../function/curryRight.md) または手動クロージャを使用してください - -この `curryRight` 関数は、複雑なプレースホルダー処理、引数数の検証、引数合成ロジックにより動作が遅くなります。 - -プレースホルダーが不要な場合は、より高速な `es-toolkit` の [`curryRight`](../../function/curryRight.md) またはシンプルなクロージャを使用してください。 - -::: - -関数を右からカリー化し、最後の引数から1つずつまたは複数ずつ受け取ることができる関数を作成します。 - -```typescript -const curriedFunction = curryRight(func, arity); -``` - -## 使用法 - -### `curryRight(func, arity)` - -関数を右からカリー化し、最後の引数から部分適用したい場合は `curryRight` を使用します。通常の `curry` とは異なり、最後の引数から先に処理します。 - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 基本的な使用法 -function subtract(a, b, c) { - return a - b - c; -} - -const curriedSubtract = curryRight(subtract); - -// 右から(最後の引数から)カリー化 -console.log(curriedSubtract(1)(2)(5)); // 5 - 2 - 1 = 2 -console.log(curriedSubtract(1, 2)(5)); // 5 - 2 - 1 = 2 -console.log(curriedSubtract(1)(2, 5)); // 2 - 5 - 1 = -4 -console.log(curriedSubtract(1, 2, 5)); // 1 - 2 - 5 = -6 -``` - -`curry` と `curryRight` の違い: - -```typescript -import { curry, curryRight } from 'es-toolkit/compat'; - -function divide(a, b, c) { - return a / b / c; -} - -// 通常の curry(左から) -const leftCurried = curry(divide); -console.log(leftCurried(12)(3)(2)); // ((12 / 3) / 2) = 2 - -// curryRight(右から) -const rightCurried = curryRight(divide); -console.log(rightCurried(2)(3)(12)); // ((12 / 3) / 2) = 2 -// 最後に渡した 12 が最初の引数(a)になる -``` - -メインライブラリとの比較: - -```typescript -// compat バージョン(柔軟だが遅い) -import { curryRight } from 'es-toolkit/compat'; -const curriedCompat = curryRight(subtract); -curriedCompat(1, 2)(3); // サポート -curriedCompat(1)(curryRight.placeholder, 3)(2); // プレースホルダーサポート - -// メインライブラリバージョン(より高速だが一度に1つのみ) -import { curryRight } from 'es-toolkit'; -const curriedMain = curryRight(subtract); -curriedMain(1)(2)(3); // サポート -curriedMain(1, 2)(3); // サポートされていない -``` - -プレースホルダー機能の使用: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function formatMessage(name, action, time) { - return `${name}さんが${action}を${time}に行いました`; -} - -const curriedFormat = curryRight(formatMessage); - -// プレースホルダーで特定の位置をスキップ -const todayAction = curriedFormat('今日'); -const todayLoginAction = todayAction(curryRight.placeholder, 'ログイン'); - -console.log(todayLoginAction('田中')); -// "田中さんがログインを今日に行いました" - -// 時間を先に固定 -const morningFormat = curriedFormat('朝9時'); -console.log(morningFormat('コメント作成', '佐藤')); -// "佐藤さんがコメント作成を朝9時に行いました" -``` - -配列処理での活用: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 配列の末尾から特定の数だけ取得 -function takeFromEnd(array, count, separator = ', ') { - return array.slice(-count).join(separator); -} - -const curriedTake = curryRight(takeFromEnd); - -// カンマ区切りの関数を作成 -const takeWithComma = curriedTake(', '); - -// 最後の3つを取得 -const takeLast3 = takeWithComma(3); - -const fruits = ['りんご', 'バナナ', 'オレンジ', 'ぶどう', 'キウイ']; -console.log(takeLast3(fruits)); // "オレンジ, ぶどう, キウイ" - -// 異なる区切り文字を使用 -const takeWithDash = curriedTake(' - '); -console.log(takeWithDash(2, fruits)); // "ぶどう - キウイ" -``` - -関数合成での活用: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// ログ出力関数 -function logWithPrefix(message, level, timestamp) { - return `[${timestamp}] ${level}: ${message}`; -} - -const curriedLog = curryRight(logWithPrefix); - -// 現在時刻で固定 -const currentTimeLog = curriedLog(new Date().toISOString()); - -// レベル別のロガーを作成 -const errorLog = currentTimeLog('ERROR'); -const infoLog = currentTimeLog('INFO'); -const debugLog = currentTimeLog('DEBUG'); - -// 使用 -console.log(errorLog('データベース接続失敗')); -console.log(infoLog('サーバー起動')); -console.log(debugLog('ユーザーリクエスト処理中')); -``` - -関数型プログラミングパイプライン: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// データ変換関数 -const mapWith = curryRight((array, fn) => array.map(fn)); -const filterWith = curryRight((array, predicate) => array.filter(predicate)); -const reduceWith = curryRight((array, reducer, initial) => array.reduce(reducer, initial)); - -const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - -// 変換関数を定義 -const double = x => x * 2; -const isEven = x => x % 2 === 0; -const sum = (acc, val) => acc + val; - -// パイプラインを構成(右から優先) -const processNumbers = nums => { - return reduceWith(filterWith(mapWith(nums, double), isEven), sum, 0); -}; - -console.log(processNumbers(numbers)); // すべての数を2倍にして偶数のみフィルタリングして合計 -``` - -API リクエストビルダー: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function makeRequest(url, method, headers, body) { - return fetch(url, { method, headers, body }); -} - -const curriedRequest = curryRight(makeRequest); - -// body から設定 -const withJsonBody = curriedRequest(JSON.stringify({ data: 'test' })); - -// headers を追加 -const withHeaders = withJsonBody({ - 'Content-Type': 'application/json', - Authorization: 'Bearer token123', -}); - -// POST メソッドを設定 -const postRequest = withHeaders('POST'); - -// 最終的な使用 -postRequest('/api/data') - .then(response => response.json()) - .then(data => console.log(data)); -``` - -手動カリー化の代替: - -```typescript -// curryRight を使用 -const curriedSubtract = curryRight((a, b, c) => a - b - c); - -// 手動クロージャ(より高速、右から) -const manualCurryRight = c => b => a => a - b - c; - -// 両方とも同じ結果 -console.log(curriedSubtract(1)(2)(5)); // 2 -console.log(manualCurryRight(1)(2)(5)); // 2 -``` - -引数数の指定: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function variableArgsFunction(a, b, c, ...rest) { - return { a, b, c, rest }; -} - -// 引数数を3に制限(rest は無視) -const curriedFixed = curryRight(variableArgsFunction, 3); - -// 右から c, b, a の順序で受け取る -console.log(curriedFixed(3)(2)(1)); // { a: 1, b: 2, c: 3, rest: [] } -``` - -#### パラメータ - -- `func` (`Function`): 右からカリー化する関数です。 -- `arity` (`number`, オプション): 関数の引数数です。省略すると `func.length` が使用されます。 - -#### 戻り値 - -(`Function & { placeholder: symbol }`): 右からカリー化された関数を返します。`placeholder` プロパティで引数の位置を制御できます。 diff --git a/docs/ja/reference/compat/function/debounce.md b/docs/ja/reference/compat/function/debounce.md deleted file mode 100644 index bd68149cd..000000000 --- a/docs/ja/reference/compat/function/debounce.md +++ /dev/null @@ -1,264 +0,0 @@ -# debounce (Lodash 互換) - -::: warning `es-toolkit` の [`debounce`](../../function/debounce.md) を使用してください - -この `debounce` 関数は、複雑な `maxWait` 処理と Lodash 互換のオプション構造によるオーバーヘッドがあります。 - -代わりに、より高速で現代的な `es-toolkit` の [`debounce`](../../function/debounce.md) を使用してください。 - -::: - -関数呼び出しを遅延させ、最後の呼び出しから指定された時間が経過した後にのみ実行されるデバウンス関数を作成します。 - -```typescript -const debouncedFunction = debounce(func, wait, options); -``` - -## 使用法 - -### `debounce(func, wait, options)` - -関数呼び出しを遅延させたい場合は `debounce` を使用してください。検索入力、スクロールイベント、ボタンクリックなどでの過度な呼び出しを防ぐのに便利です。 - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// 基本的な使用法 -const searchFunction = debounce(query => { - console.log('検索:', query); -}, 300); - -// 300ms 以内に再度呼び出されなければ実行される -searchFunction('React'); // 実行されない -searchFunction('Vue'); // 実行されない -searchFunction('Angular'); // 300ms 後に "検索: Angular" と出力 -``` - -メインライブラリの debounce との比較: - -```typescript -// compat バージョン(Lodash 互換、maxWait などの追加オプション) -import { debounce } from 'es-toolkit/compat'; -const debouncedCompat = debounce(func, 300, { - leading: true, - trailing: false, - maxWait: 1000 -}); - -// メインライブラリバージョン(より高速でシンプル) -import { debounce } from 'es-toolkit'; -const debouncedMain = debounce(func, 300, { - edges: ['leading'] // leading/trailing の代わりに edges を使用 -}); -``` - -leading と trailing オプション: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const func = () => console.log('実行されました'); - -// leading: true - 最初の呼び出し時に即座に実行 -const leadingDebounce = debounce(func, 1000, { leading: true }); -leadingDebounce(); // 即座に "実行されました" と出力 -leadingDebounce(); // 1秒待機 -// 1秒後に追加の実行なし - -// trailing: true(デフォルト) - 最後の呼び出し後の遅延時間後に実行 -const trailingDebounce = debounce(func, 1000, { trailing: true }); -trailingDebounce(); // 1秒待機 -trailingDebounce(); // 1秒待機(前のタイマーをキャンセル) -// 1秒後に "実行されました" と出力 - -// 両方とも true - 開始時と終了時に実行 -const bothDebounce = debounce(func, 1000, { - leading: true, - trailing: true, -}); -bothDebounce(); // 即座に "実行されました" と出力 -bothDebounce(); // 1秒待機 -// 1秒後に "実行されました" と出力(trailing) -``` - -maxWait オプション: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// 最大2秒ごとには必ず実行 -const debouncedWithMaxWait = debounce(() => console.log('保存されました'), 500, { maxWait: 2000 }); - -// 高速に連続呼び出しされても、最大2秒ごとに実行される -setInterval(() => { - debouncedWithMaxWait(); -}, 100); // 100ms ごとに呼び出されるが、2秒ごとに "保存されました" と出力 -``` - -実際の検索例: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -class SearchComponent { - constructor() { - this.searchInput = document.getElementById('search'); - - // ユーザー入力を 300ms デバウンス - this.debouncedSearch = debounce(this.performSearch.bind(this), 300, { - leading: false, // 入力開始時に即座に検索しない - trailing: true, // 入力停止後に検索 - }); - - this.searchInput.addEventListener('input', e => { - this.debouncedSearch(e.target.value); - }); - } - - performSearch(query) { - if (query.length < 2) return; - - console.log('API 呼び出し:', query); - // fetch(`/api/search?q=${query}`)... - } -} -``` - -スクロールイベントの最適化: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// スクロールイベントを 100ms デバウンスするが、最大 500ms ごとには実行 -const optimizedScrollHandler = debounce( - () => { - const scrollTop = window.pageYOffset; - console.log('スクロール位置:', scrollTop); - - // ヘッダーの非表示/表示ロジック - if (scrollTop > 100) { - document.header.classList.add('hidden'); - } else { - document.header.classList.remove('hidden'); - } - }, - 100, - { maxWait: 500 } -); - -window.addEventListener('scroll', optimizedScrollHandler); -``` - -API 呼び出しの制限: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -class AutoSave { - constructor() { - // 500ms デバウンス、最大5秒ごとには保存 - this.debouncedSave = debounce(this.saveToServer.bind(this), 500, { maxWait: 5000 }); - } - - onTextChange(content) { - this.pendingContent = content; - this.debouncedSave(); - } - - saveToServer() { - if (!this.pendingContent) return; - - console.log('サーバーに保存:', this.pendingContent); - // fetch('/api/save', { ... }) - - this.pendingContent = null; - } -} -``` - -cancel と flush メソッド: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const debouncedFunc = debounce(() => { - console.log('実行されました'); -}, 1000); - -debouncedFunc(); // 1秒待機中 - -// 待機中の実行をキャンセル -debouncedFunc.cancel(); - -// または即座に実行 -debouncedFunc(); // 1秒待機開始 -debouncedFunc.flush(); // 即座に "実行されました" と出力し、タイマーをキャンセル -``` - -ボタンクリックの重複防止: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const handleSubmit = debounce( - async formData => { - console.log('フォーム送信中...'); - try { - const response = await fetch('/api/submit', { - method: 'POST', - body: formData, - }); - console.log('送信完了'); - } catch (error) { - console.error('送信失敗:', error); - } - }, - 1000, - { leading: true, trailing: false } // 最初のクリックのみ処理 -); - -document.getElementById('submit-btn').addEventListener('click', e => { - const formData = new FormData(e.target.form); - handleSubmit(formData); -}); -``` - -リサイズイベント処理: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const handleResize = debounce( - () => { - const width = window.innerWidth; - const height = window.innerHeight; - - console.log('ウィンドウサイズ変更:', { width, height }); - - // レイアウトの再計算 - recalculateLayout(); - }, - 250, - { leading: false, trailing: true } -); - -window.addEventListener('resize', handleResize); - -// ページ終了時にクリーンアップ -window.addEventListener('beforeunload', () => { - handleResize.cancel(); -}); -``` - -#### パラメータ - -- `func` (`Function`): デバウンスする関数です。 -- `wait` (`number`, オプション): 遅延するミリ秒数です。デフォルトは `0` です。 -- `options` (`DebounceSettings`, オプション): オプションオブジェクトです。 - - `leading` (`boolean`): `true` の場合、遅延開始時点で関数を実行します。デフォルトは `false` です。 - - `trailing` (`boolean`): `true` の場合、遅延終了時点で関数を実行します。デフォルトは `true` です。 - - `maxWait` (`number`): 関数実行が遅延できる最大時間です。デフォルトは `Infinity` です。 - -#### 戻り値 - -(`DebouncedFunc`): デバウンスされた関数を返します。`cancel()` と `flush()` メソッドが含まれています。 diff --git a/docs/ja/reference/compat/function/flow.md b/docs/ja/reference/compat/function/flow.md deleted file mode 100644 index bbc64f612..000000000 --- a/docs/ja/reference/compat/function/flow.md +++ /dev/null @@ -1,87 +0,0 @@ -# flow (Lodash 互換性) - -::: warning `es-toolkit` の `flow` を使用してください -この `flow` 関数は Lodash 互換性のために配列のフラット化処理が追加されており、複雑です。 - -代わりに、より高速で現代的な `es-toolkit` の [flow](../../function/flow.md) を使用してください。 -::: - -与えられた関数を左から右へ順次実行する新しい関数を作成します。 - -```typescript -const combinedFunc = flow(...functions); -``` - -## 使用法 - -### `flow(...functions)` - -複数の関数を左から右へ順次実行する1つの合成関数を作成したい場合は `flow` を使用してください。データ変換パイプラインを作成する際に便利です。 - -```typescript -import { flow } from 'es-toolkit/compat'; - -// 基本的な使い方 -function add(x, y) { - return x + y; -} - -function square(n) { - return n * n; -} - -function double(n) { - return n * 2; -} - -// 左から右へ実行: double(square(add(x, y))) -const calculate = flow(add, square, double); -console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 - -// 配列で関数を渡す -const calculate2 = flow([add, square], double); -console.log(calculate2(2, 3)); // 50 - -// 現代的な代替案(推奨) -const modernCalculate = (x, y) => double(square(add(x, y))); -console.log(modernCalculate(1, 2)); // 18 - -// パイプ演算子を使用(将来の JavaScript) -const pipeCalculate = (x, y) => add(x, y) |> square |> double; - -// またはチェーンパターン -class Calculator { - constructor(value) { - this.value = value; - } - - add(n) { - this.value += n; - return this; - } - - square() { - this.value *= this.value; - return this; - } - - double() { - this.value *= 2; - return this; - } - - valueOf() { - return this.value; - } -} - -const chainedResult = new Calculator(3).square().double().valueOf(); // 18 -``` - -#### パラメータ - -- `...functions` (`Array`): 左から右へ実行する関数です。配列で渡すこともできます。 - -#### 戻り値 - -(`Function`): すべての関数を左から右へ順次実行する新しい合成関数を返します。 diff --git a/docs/ja/reference/compat/function/flowRight.md b/docs/ja/reference/compat/function/flowRight.md deleted file mode 100644 index f88887466..000000000 --- a/docs/ja/reference/compat/function/flowRight.md +++ /dev/null @@ -1,65 +0,0 @@ -# flowRight (Lodash 互換性) - -::: warning `es-toolkit` の `flowRight` を使用してください -この `flowRight` 関数は Lodash 互換性のために配列のフラット化処理が追加されており、複雑です。 - -代わりに、より高速で現代的な `es-toolkit` の [flowRight](../../function/flowRight.md) を使用してください。 -::: - -与えられた関数を右から左へ順次実行する新しい関数を作成します。 - -```typescript -const combinedFunc = flowRight(...functions); -``` - -## 使用法 - -### `flowRight(...functions)` - -複数の関数を右から左へ順次実行する1つの合成関数を作成したい場合は `flowRight` を使用してください。データ変換パイプラインを作成する際に便利です。 - -```typescript -import { flowRight } from 'es-toolkit/compat'; - -// 基本的な使い方 -function add(x, y) { - return x + y; -} - -function square(n) { - return n * n; -} - -function double(n) { - return n * 2; -} - -// 右から左へ実行: double(square(add(x, y))) -const calculate = flowRight(double, square, add); -console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 - -// 配列で関数を渡す -const calculate2 = flowRight([double, square], add); -console.log(calculate2(2, 3)); // 50 - -// 現代的な代替案(推奨) -const modernCalculate = (x, y) => double(square(add(x, y))); -console.log(modernCalculate(1, 2)); // 18 - -// または関数チェーンを使用 -const chainedCalculate = (x, y) => [x, y] - .reduce((acc, val, idx) => idx === 0 ? val : acc + val) - .valueOf() - |> (n => n * n) - |> (n => n * 2); -``` - -一般的に `flow` と反対の順序で動作します。合成関数と似た方式で動作するため直感的です。 - -#### パラメータ - -- `...functions` (`Array`): 右から左へ実行する関数です。配列で渡すこともできます。 - -#### 戻り値 - -(`Function`): すべての関数を右から左へ順次実行する新しい合成関数を返します。 diff --git a/docs/ja/reference/compat/function/identity.md b/docs/ja/reference/compat/function/identity.md deleted file mode 100644 index d964c980c..000000000 --- a/docs/ja/reference/compat/function/identity.md +++ /dev/null @@ -1,62 +0,0 @@ -# identity (Lodash 互換性) - -::: warning `es-toolkit` の `identity` を使用してください -この `identity` 関数は `es-toolkit` のメインライブラリにも同じ機能の関数があります。単に入力値をそのまま返す機能です。 - -代わりに、より高速で現代的な `es-toolkit` の [identity](../../function/identity.md) を使用してください。 -::: - -受け取った値をそのまま返します。 - -```typescript -const result = identity(value); -``` - -## 使用法 - -### `identity(value)` - -受け取った値をそのまま返したい場合は `identity` を使用してください。主にデフォルト値やプレースホルダー関数として使用され、関数型プログラミングでよく使われます。 - -```typescript -import { identity } from 'es-toolkit/compat'; - -// 基本的な使い方 -console.log(identity(5)); // 5 -console.log(identity('hello')); // 'hello' -console.log(identity({ key: 'value' })); // { key: 'value' } - -// 配列の map と一緒に使用(値のコピー) -const numbers = [1, 2, 3, 4, 5]; -const copied = numbers.map(identity); -console.log(copied); // [1, 2, 3, 4, 5] - -// フィルタリングでデフォルト値として使用 -const values = [1, 0, '', 'hello', null, undefined, false, true]; -const filtered = values.filter(identity); // 真と評価される値だけを残す -console.log(filtered); // [1, 'hello', true] - -// デフォルトの変換関数として使用 -function processData(data, transform = identity) { - return transform(data); -} - -console.log(processData('hello')); // 'hello' -console.log(processData('hello', x => x.toUpperCase())); // 'HELLO' -``` - -ほとんどの場合、より簡単なアロー関数 `x => x` で置き換えることができます: - -```typescript -// identity の代わりにアロー関数を使用(推奨) -const copied = numbers.map(x => x); -const filtered = values.filter(x => x); -``` - -#### パラメータ - -- `value` (`T`): 返す値です。 - -#### 戻り値 - -(`T`): 受け取った値をそのまま返します。 diff --git a/docs/ja/reference/compat/function/memoize.md b/docs/ja/reference/compat/function/memoize.md deleted file mode 100644 index 63a8279bf..000000000 --- a/docs/ja/reference/compat/function/memoize.md +++ /dev/null @@ -1,66 +0,0 @@ -# memoize (Lodash 互換性) - -::: warning `es-toolkit` の `memoize` を使用してください -この `memoize` 関数は `resolver` 関数の `null` チェック、`MapCache` インターフェースの複雑な型処理、そして Lodash 互換性のための追加のオーバーヘッドにより遅く動作します。 - -代わりに、より高速で現代的な `es-toolkit` の [memoize](../../function/memoize.md) を使用してください。 -::: - -関数の結果をキャッシュして、同じ引数で呼び出されたときにパフォーマンスを向上させます。 - -```typescript -const memoizedFunc = memoize(func, resolver); -``` - -## 使用法 - -### `memoize(func, resolver)` - -関数の結果をメモ化して、同じ引数で呼び出されたときに以前の結果を再利用したい場合は `memoize` を使用してください。コストのかかる計算や API 呼び出しに便利です。 - -```typescript -import { memoize } from 'es-toolkit/compat'; - -// 基本的な使い方 -function expensiveCalculation(n) { - console.log('計算中...', n); - return n * n; -} - -const memoizedCalc = memoize(expensiveCalculation); - -console.log(memoizedCalc(5)); // '計算中... 5', 25 -console.log(memoizedCalc(5)); // 25 (キャッシュされた結果、計算しない) -console.log(memoizedCalc(10)); // '計算中... 10', 100 - -// カスタムリゾルバーを使用 -function fetchUserData(userId, includeProfile) { - console.log('ユーザーデータを取得中...', userId, includeProfile); - return { id: userId, profile: includeProfile ? 'プロフィールデータ' : null }; -} - -// すべての引数を考慮したキャッシュキーを生成 -const memoizedFetch = memoize(fetchUserData, (userId, includeProfile) => { - return `${userId}_${includeProfile}`; -}); - -memoizedFetch(1, true); // 'ユーザーデータを取得中... 1 true' -memoizedFetch(1, true); // キャッシュされた結果を使用 -memoizedFetch(1, false); // 'ユーザーデータを取得中... 1 false' (異なるキャッシュキー) - -// キャッシュへのアクセスと変更 -console.log(memoizedCalc.cache.get(5)); // 25 -memoizedCalc.cache.set(7, 49); // 手動でキャッシュを設定 -console.log(memoizedCalc(7)); // 49 (計算せずにキャッシュされた値を使用) -``` - -ほとんどの場合、基本的なハッシュマップを使用しますが、必要に応じてカスタムキャッシュ実装を使用することもできます。 - -#### パラメータ - -- `func` (`Function`): メモ化する関数です。 -- `resolver` (`Function`, オプション): キャッシュキーを決定する関数です。提供されない場合は最初の引数をキーとして使用します。 - -#### 戻り値 - -(`Function & { cache: MapCache }`): メモ化された関数を返します。返された関数には `cache` プロパティがあり、キャッシュに直接アクセスできます。 diff --git a/docs/ja/reference/compat/function/noop.md b/docs/ja/reference/compat/function/noop.md deleted file mode 100644 index 3659bd73c..000000000 --- a/docs/ja/reference/compat/function/noop.md +++ /dev/null @@ -1,60 +0,0 @@ -# noop (Lodash 互換性) - -::: warning `es-toolkit` の `noop` を使用してください - -`es-toolkit` にも同じ動作をする [noop](../../function/noop.md) 関数があります。 - -::: - -何もしない空の関数です。 - -```typescript -noop(); -``` - -## 使用法 - -### `noop(...args)` - -何もしないプレースホルダー関数が必要な場合は `noop` を使用してください。デフォルト値やコールバック関数としてよく使われます。 - -```typescript -import { noop } from 'es-toolkit/compat'; - -// 基本的な使用法 -noop(); // 何もしない -noop(1, 2, 3); // 引数を受け取るが何もしない - -// デフォルトのコールバックとして使用 -function processData(data, callback = noop) { - // データ処理 - console.log('データ処理中...', data); - - // コールバック呼び出し(提供されていなければ noop) - callback(data); -} - -processData('テスト'); // コールバックが提供されていなくてもエラーなく動作 - -// 現代的な代替案(推奨) -function modernProcessData(data, callback = () => {}) { - console.log('データ処理中...', data); - callback(data); -} - -// またはオプショナルなコールバックを使用 -function processDataOptional(data, callback) { - console.log('データ処理中...', data); - callback?.(data); // コールバックが提供された場合のみ呼び出し -} -``` - -デフォルト値やプレースホルダーが必要な状況で便利ですが、現代の JavaScript ではオプショナルチェイニング(`?.`)やデフォルトパラメータを使用する方が一般的です。 - -#### パラメータ - -- `...args` (`any[]`): どんな引数でも受け取れますが、すべて無視されます。 - -#### 戻り値 - -(`void`): 何も返しません。 diff --git a/docs/ja/reference/compat/function/once.md b/docs/ja/reference/compat/function/once.md deleted file mode 100644 index ef5cd63a8..000000000 --- a/docs/ja/reference/compat/function/once.md +++ /dev/null @@ -1,56 +0,0 @@ -# once (Lodash 互換性) - -::: warning `es-toolkit` の `once` を使用してください - -この `once` 関数は、`es-toolkit` のメインライブラリ [once](../../function/once.md) 関数と同じ機能を持っています。 - -::: - -関数が1回だけ呼び出されるように制限します。 - -```typescript -const limitedFunc = once(func); -``` - -## 使用法 - -### `once(func)` - -関数を1回だけ呼び出すように制限したい場合は `once` を使用してください。最初の呼び出し後は結果がキャッシュされ、同じ値を返します。 - -```typescript -import { once } from 'es-toolkit/compat'; - -// 基本的な使用法 -let count = 0; -const increment = once(() => { - count++; - console.log('カウンター増加:', count); - return count; -}); - -increment(); // 'カウンター増加: 1' を出力、1 を返す -increment(); // 何も出力しない、1 を返す -increment(); // 何も出力しない、1 を返す - -// 実用的な例 - 初期化関数 -const initialize = once(() => { - console.log('アプリケーション初期化中...'); - // コストのかかる初期化操作 - return '初期化完了'; -}); - -// 複数回呼び出しても、初期化は1回だけ実行される -initialize(); // 'アプリケーション初期化中...' を出力 -initialize(); // 何も出力しない -``` - -コストのかかる初期化操作やセットアップ関数を作成する際に便利です。例えば、データベース接続、APIトークンの初期化などに使用できます。 - -#### パラメータ - -- `func` (`Function`): 1回だけ呼び出すように制限する関数です。 - -#### 戻り値 - -(`Function`): 1回だけ呼び出される新しい関数を返します。2回目の呼び出し以降は、最初の呼び出しの結果を返します。 diff --git a/docs/ja/reference/compat/function/partial.md b/docs/ja/reference/compat/function/partial.md deleted file mode 100644 index 8d21064aa..000000000 --- a/docs/ja/reference/compat/function/partial.md +++ /dev/null @@ -1,59 +0,0 @@ -# partial (Lodash 互換性) - -::: warning `es-toolkit` の `partial` を使用してください - -この `partial` 関数は多くのオーバーロードとユニオン型処理により非効率的です。また、ほとんどの場合、より簡単なアロー関数で代替できます。 - -代わりに、より高速で現代的な `es-toolkit` の [`partial`](../../function/partial.md) を使用してください。 - -::: - -関数の引数を事前に埋めて部分適用された関数を作成します。 - -```typescript -const partialFunc = partial(func, ...args); -``` - -## 使用法 - -### `partial(func, ...args)` - -関数の引数を事前に埋めて部分適用された関数を作成したい場合は `partial` を使用してください。主に引数の順序が重要な関数で最初の引数を固定する際に便利です。 - -```typescript -import { partial } from 'es-toolkit/compat'; - -// 基本的な使用法 -function greet(greeting, name, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// 最初の引数を事前設定 -const sayHello = partial(greet, 'Hello'); -sayHello('Alice', '!'); // 'Hello Alice!' - -// 複数の引数を事前設定 -const greetAlice = partial(greet, 'Hello', 'Alice'); -greetAlice('!'); // 'Hello Alice!' - -// placeholder を使用して引数の順序を調整 -const greetWithExclamation = partial(greet, partial.placeholder, 'Alice', '!'); -greetWithExclamation('Hi'); // 'Hi Alice!' -``` - -ほとんどの場合、アロー関数で代替できます: - -```typescript -// partial の代わりにアロー関数を使用(推奨) -const sayHello = (name, punctuation) => greet('Hello', name, punctuation); -const greetAlice = punctuation => greet('Hello', 'Alice', punctuation); -``` - -#### パラメータ - -- `func` (`Function`): 部分適用する関数です。 -- `...args` (`any[]`): 事前に埋める引数です。`partial.placeholder` を使用して引数の順序を調整できます。 - -#### 戻り値 - -(`Function`): 引数が事前に埋められた新しい関数を返します。 diff --git a/docs/ja/reference/compat/function/partialRight.md b/docs/ja/reference/compat/function/partialRight.md deleted file mode 100644 index ed3fe0895..000000000 --- a/docs/ja/reference/compat/function/partialRight.md +++ /dev/null @@ -1,59 +0,0 @@ -# partialRight (Lodash 互換性) - -::: warning `es-toolkit` の `partialRight` を使用してください - -この `partialRight` 関数は多くのオーバーロードとユニオン型処理により非効率的です。また、ほとんどの場合、より簡単なアロー関数で代替できます。 - -代わりに、より高速で現代的な `es-toolkit` の [`partialRight`](../../function/partialRight.md) を使用してください。 - -::: - -関数の右側から引数を事前に埋めて部分適用された関数を作成します。 - -```typescript -const partialFunc = partialRight(func, ...args); -``` - -## 使用法 - -### `partialRight(func, ...args)` - -関数の右側から引数を事前に埋めて部分適用された関数を作成したい場合は `partialRight` を使用してください。主に引数の順序が重要な関数で最後の引数を固定する際に便利です。 - -```typescript -import { partialRight } from 'es-toolkit/compat'; - -// 基本的な使用法 -function greet(greeting, name, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// 最後の引数を事前設定 -const greetWithExclamation = partialRight(greet, '!'); -greetWithExclamation('Hello', 'Alice'); // 'Hello Alice!' - -// 複数の引数を事前設定 -const sayHiToAlice = partialRight(greet, 'Alice', '!'); -sayHiToAlice('Hi'); // 'Hi Alice!' - -// placeholder を使用して引数の順序を調整 -const greetAliceWithCustom = partialRight(greet, 'Alice', partialRight.placeholder); -greetAliceWithCustom('Hello', '?'); // 'Hello Alice?' -``` - -ほとんどの場合、アロー関数で代替できます: - -```typescript -// partialRight の代わりにアロー関数を使用(推奨) -const greetWithExclamation = (greeting, name) => greet(greeting, name, '!'); -const sayHiToAlice = greeting => greet(greeting, 'Alice', '!'); -``` - -#### パラメータ - -- `func` (`Function`): 部分適用する関数です。 -- `...args` (`any[]`): 事前に埋める引数です。`partialRight.placeholder` を使用して引数の順序を調整できます。 - -#### 戻り値 - -(`Function`): 右側から引数が事前に埋められた新しい関数を返します。 diff --git a/docs/ja/reference/compat/function/rest.md b/docs/ja/reference/compat/function/rest.md deleted file mode 100644 index 8497917be..000000000 --- a/docs/ja/reference/compat/function/rest.md +++ /dev/null @@ -1,54 +0,0 @@ -# rest (Lodash 互換性) - -::: warning `es-toolkit` の `rest` を使用してください - -この `rest` 関数は、デフォルト値処理やインデックス検証などの追加ロジックにより、パフォーマンスが低下する可能性があります。 - -代わりに、より高速で現代的な `es-toolkit` の [rest](../../function/rest.md) を使用してください。 - -::: - -指定されたインデックスから残りの引数を配列にグループ化する関数を作成します。 - -```typescript -const restFunc = rest(func, start); -``` - -## 使用法 - -### `rest(func, start)` - -指定されたインデックスから残りの引数を配列にグループ化して関数の引数を変換したい場合は、`rest` を使用してください。可変長引数を受け取る関数を作成するのに便利です。 - -```typescript -import { rest } from 'es-toolkit/compat'; - -// 基本的な使用法 - 最後の引数を配列にグループ化 -function logMessage(level, message, ...details) { - console.log(`[${level}] ${message}`, details); -} - -const restLogger = rest(logMessage, 2); -restLogger('ERROR', 'エラーが発生しました', '詳細情報 1', '詳細情報 2'); -// 内部的に logMessage('ERROR', 'エラーが発生しました', [['詳細情報 1', '詳細情報 2']]) として呼び出されます - -// 別のインデックスの例 -function process(action, target, ...args) { - return { action, target, args }; -} - -const restProcess = rest(process, 1); -restProcess('update', 'user', 'name', 'John', 'age', 25); -// { action: 'update', target: ['user', 'name', 'John', 'age', 25], args: [] } -``` - -関数の最後の引数を配列として受け取りたい場合に使用します。現代の JavaScript では、残余パラメータ構文(`...args`)を使用するのがより一般的です。 - -#### パラメータ - -- `func` (`Function`): 変換する関数です。 -- `start` (`number`, オプション): 配列へのグループ化を開始するインデックスです。デフォルト値は `func.length - 1` です。 - -#### 戻り値 - -(`Function`): 指定されたインデックスから残りの引数を配列にグループ化する新しい関数を返します。 diff --git a/docs/ja/reference/compat/function/throttle.md b/docs/ja/reference/compat/function/throttle.md deleted file mode 100644 index 5a650ae64..000000000 --- a/docs/ja/reference/compat/function/throttle.md +++ /dev/null @@ -1,52 +0,0 @@ -# throttle (Lodash 互換性) - -::: warning `es-toolkit` の `throttle` を使用してください - -この `throttle` 関数は、Lodash 互換性のために内部的に debounce 関数を使用しているため、少し複雑になっています。また、デフォルト値やオプションの処理もより複雑です。 - -代わりに、より高速で現代的な `es-toolkit` の [throttle](../../function/throttle.md) を使用してください。 - -::: - -関数呼び出しを指定された時間間隔で最大1回実行されるように制限します。 - -```typescript -const throttledFunc = throttle(func, wait, options); -``` - -## 使用法 - -### `throttle(func, wait, options)` - -関数呼び出しを指定された時間間隔で最大1回実行されるように制限したい場合は、`throttle` を使用してください。イベントハンドラーや API 呼び出しの頻度を制限するのに便利です。 - -```typescript -import { throttle } from 'es-toolkit/compat'; - -// 基本的な使用法 - 1秒に最大1回実行 -const throttledLog = throttle(() => { - console.log('イベント発生!'); -}, 1000); - -// オプションを使用した例 -const throttledScroll = throttle(handleScroll, 100, { - leading: true, // 最初にすぐ実行 - trailing: false, // 最後に実行しない -}); - -window.addEventListener('scroll', throttledScroll); -``` - -スクロールイベントやリサイズイベントのように速く発生するイベントを処理する際、パフォーマンスのために必須です。 - -#### パラメータ - -- `func` (`Function`): スロットリングする関数です。 -- `wait` (`number`, オプション): ミリ秒単位の待機時間です。デフォルト値は `0` です。 -- `options` (`ThrottleSettings`, オプション): スロットリングオプションです。 - - `leading` (`boolean`): 最初の呼び出しですぐに実行するかどうかです。デフォルト値は `true` です。 - - `trailing` (`boolean`): 最後の呼び出し後に実行するかどうかです。デフォルト値は `true` です。 - -#### 戻り値 - -(`DebouncedFunc`): スロットリングされた関数を返します。`cancel()` メソッドで待機中の実行をキャンセルできます。 diff --git a/docs/ja/reference/compat/function/unary.md b/docs/ja/reference/compat/function/unary.md deleted file mode 100644 index 8d80adfbe..000000000 --- a/docs/ja/reference/compat/function/unary.md +++ /dev/null @@ -1,46 +0,0 @@ -# unary (Lodash 互換性) - -::: warning `es-toolkit` の `ary` を使用してください - -この `unary` 関数は `ary` 関数の特殊なケースとして実装されています。より多くの制御が必要な場合は、`es-toolkit` の [ary](../../function/ary.md) を直接使用する方が効率的です。 - -代わりに、より高速で現代的な `es-toolkit` の [ary](../../function/ary.md) を使用してください。 - -::: - -関数が最大1つの引数のみを受け取るように制限します。 - -```typescript -const limitedFunc = unary(func); -``` - -## 使用法 - -### `unary(func)` - -関数が最大1つの引数のみを受け取るように制限したい場合は、`unary` を使用してください。追加で渡される引数はすべて無視されます。 - -```typescript -import { unary } from 'es-toolkit/compat'; - -function greet(name, greeting, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// 最初の引数のみを受け取る関数に変換 -const greetOne = unary(greet); -greetOne('Alice', 'Hello', '!'); // greet('Alice') と同じように動作 - -// 配列の map 関数と一緒に使用すると便利 -const numbers = ['1', '2', '3']; -numbers.map(parseInt); // [1, NaN, NaN] - 予期しない結果 -numbers.map(unary(parseInt)); // [1, 2, 3] - 正しい結果 -``` - -#### パラメータ - -- `func` (`(...args: any[]) => any`): 引数を制限する関数です。 - -#### 戻り値 - -(`(...args: any[]) => any`): 最大1つの引数のみを受け取る新しい関数を返します。 diff --git a/docs/ja/reference/compat/math/clamp.md b/docs/ja/reference/compat/math/clamp.md deleted file mode 100644 index 802e88786..000000000 --- a/docs/ja/reference/compat/math/clamp.md +++ /dev/null @@ -1,82 +0,0 @@ -# clamp (Lodash 互換性) - -::: warning `es-toolkit`の[clamp](../../math/clamp.md)を使用してください - -この `clamp` 関数はNaN検証と処理により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [clamp](../../math/clamp.md) を使用してください。 - -::: - -数値を指定された範囲内に制限します。 - -```typescript -const clamped = clamp(number, lower, upper); -``` - -## 使用法 - -### `clamp(number, lower, upper)` - -数値を指定された最小値と最大値の間に制限したい場合は `clamp` を使用してください。 - -```typescript -import { clamp } from 'es-toolkit/compat'; - -// 基本的な使用法 -clamp(3, 2, 4); -// Returns: 3 (範囲内にある) - -clamp(0, 5, 10); -// Returns: 5 (最小値で制限) - -clamp(15, 5, 10); -// Returns: 10 (最大値で制限) - -// 負の数も処理 -clamp(-5, -10, -1); -// Returns: -5 - -clamp(-15, -10, -1); -// Returns: -10 (最小値で制限) -``` - -### `clamp(number, upper)` - -1つの引数のみを提供すると、その値を最大値として使用します。 - -```typescript -import { clamp } from 'es-toolkit/compat'; - -// 最大値のみ指定 -clamp(5, 3); -// Returns: 3 (最大値で制限) - -clamp(2, 3); -// Returns: 2 (範囲内にある) - -clamp(1, 5); -// Returns: 1 -``` - -NaN値は0として処理されます。 - -```typescript -import { clamp } from 'es-toolkit/compat'; - -clamp(5, NaN, 10); -// Returns: 5 (NaNが0として処理され、範囲は0〜10) - -clamp(5, 2, NaN); -// Returns: 2 (NaNが0として処理され、範囲は0〜2) -``` - -#### パラメータ - -- `number` (`number`): 制限する数値です。 -- `lower` (`number`): 最小値です。2番目のパラメータのみがある場合は最大値になります。 -- `upper` (`number`, オプション): 最大値です。 - -#### 戻り値 - -(`number`): 指定された範囲内に制限された数値を返します。 diff --git a/docs/ja/reference/compat/math/inRange.md b/docs/ja/reference/compat/math/inRange.md deleted file mode 100644 index 8345e11b2..000000000 --- a/docs/ja/reference/compat/math/inRange.md +++ /dev/null @@ -1,101 +0,0 @@ -# inRange (Lodash 互換性) - -::: warning `es-toolkit`の[inRange](../../math/inRange.md)を使用してください - -この `inRange` 関数は複雑な型変換とnull/undefined処理により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [inRange](../../math/inRange.md) を使用してください。 - -::: - -数値が指定された範囲内にあるかを確認します。 - -```typescript -const result = inRange(value, minimum, maximum); -``` - -## 使用法 - -### `inRange(value, minimum, maximum?)` - -数値が特定の範囲内にあるかを確認したい場合は `inRange` を使用してください。最小値は含まれ、最大値は含まれません。 - -```typescript -import { inRange } from 'es-toolkit/compat'; - -// 基本的な使用法 -inRange(3, 2, 4); -// Returns: true (2 ≤ 3 < 4) - -inRange(1, 2, 5); -// Returns: false (1 < 2) - -inRange(5, 2, 5); -// Returns: false (5は含まれない) - -// 範囲境界値 -inRange(2, 2, 4); -// Returns: true (最小値は含まれる) - -inRange(4, 2, 4); -// Returns: false (最大値は含まれない) -``` - -### `inRange(value, maximum)` - -2つの引数のみを提供すると、0からmaximumまでの範囲として処理されます。 - -```typescript -import { inRange } from 'es-toolkit/compat'; - -inRange(3, 5); -// Returns: true (0 ≤ 3 < 5) - -inRange(-1, 5); -// Returns: false (-1 < 0) - -inRange(0, 5); -// Returns: true (0 ≤ 0 < 5) - -inRange(5, 5); -// Returns: false (5は含まれない) -``` - -最小値が最大値より大きい場合は自動的に交換されます。 - -```typescript -import { inRange } from 'es-toolkit/compat'; - -inRange(3, 5, 2); -// Returns: true (範囲が2〜5に変更され、2 ≤ 3 < 5) - -inRange(1, 5, 2); -// Returns: false (1 < 2) -``` - -不正な値は適切に変換されます。 - -```typescript -import { inRange } from 'es-toolkit/compat'; - -// 文字列数値変換 -inRange(3, '2', '4'); -// Returns: true - -// falsy値は0として処理 -inRange(1, null, 5); -// Returns: true (nullが0として処理され、0〜5の範囲) - -inRange(3, false, 5); -// Returns: true (falseが0として処理) -``` - -#### パラメータ - -- `value` (`number`): 範囲内にあるかを確認する数値です。 -- `minimum` (`number`): 範囲の最小値です(含まれる)。`maximum`がない場合、この値が最大値になります。 -- `maximum` (`number`, オプション): 範囲の最大値です(含まれない)。 - -#### 戻り値 - -(`boolean`): 値が指定された範囲内にある場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/math/maxBy.md b/docs/ja/reference/compat/math/maxBy.md deleted file mode 100644 index 9526f5161..000000000 --- a/docs/ja/reference/compat/math/maxBy.md +++ /dev/null @@ -1,114 +0,0 @@ -# maxBy (Lodash 互換性) - -::: warning es-toolkitの[maxBy](../../array/maxBy.md)を使用してください - -この `maxBy` 関数はiteratee関数処理と型変換により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [maxBy](../../array/maxBy.md) を使用してください。 - -::: - -条件に合う値の中から最大値要素を見つけます。 - -```typescript -const maxItem = maxBy(array, iteratee); -``` - -## 使用法 - -### `maxBy(array, iteratee)` - -配列から関数で計算した値が最も大きい要素を見つけます。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -// オブジェクト配列から特定のプロパティが最大の要素 -const people = [ - { name: '홍길동', age: 25 }, - { name: '김철수', age: 30 }, - { name: '이영희', age: 35 }, -]; - -maxBy(people, person => person.age); -// Returns: { name: '이영희', age: 35 } - -// プロパティ名でも可能 -maxBy(people, 'age'); -// Returns: { name: '이영희', age: 35 } -``` - -関数で値を変換して最大値を見つけます。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -maxBy(items, x => x.a); -// Returns: { a: 3 } - -const numbers = [-1, -2, -3]; -maxBy(numbers, x => Math.abs(x)); -// Returns: -3 (絶対値が最も大きい要素) -``` - -配列要素でアクセスします。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const arrays = [ - [1, 2], - [3, 4], - [0, 5], -]; -maxBy(arrays, 0); // 最初の要素が最大の配列 -// Returns: [3, 4] - -maxBy(arrays, 1); // 2番目の要素が最大の配列 -// Returns: [0, 5] -``` - -オブジェクトの特定プロパティと値が一致する場合を見つけます。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const users = [ - { name: '홍길동', age: 25, active: true }, - { name: '김철수', age: 30, active: false }, - { name: '이영희', age: 35, active: true }, -]; - -// activeがtrueの要素の中から最初のもの -maxBy(users, ['active', true]); -// Returns: { name: '홍길동', age: 25, active: true } - -// オブジェクトで条件指定 -maxBy(users, { active: true }); -// Returns: { name: '홍길동', age: 25, active: true } -``` - -空の配列はundefinedを返します。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -maxBy([], x => x.a); -// Returns: undefined - -maxBy(null); -// Returns: undefined - -maxBy(undefined); -// Returns: undefined -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 検索する配列です。 -- `iteratee` (`ValueIteratee`, オプション): 各要素に適用する関数、プロパティ名、または条件です。 - -#### 戻り値 - -(`T | undefined`): 条件に合う値が最も大きい要素を返します。空の配列の場合は `undefined` を返します。 diff --git a/docs/ja/reference/compat/math/mean.md b/docs/ja/reference/compat/math/mean.md deleted file mode 100644 index 8fb51e37a..000000000 --- a/docs/ja/reference/compat/math/mean.md +++ /dev/null @@ -1,76 +0,0 @@ -# mean (Lodash 互換性) - -::: warning es-toolkitの[mean](../../math/mean.md)を使用してください - -この `mean` 関数は型変換とnull/undefined処理により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [mean](../../math/mean.md) を使用してください。 - -::: - -配列の平均値を計算します。 - -```typescript -const average = mean(array); -``` - -## 使用法 - -### `mean(array)` - -数値配列の平均値を計算します。 - -```typescript -import { mean } from 'es-toolkit/compat'; - -// 数値配列 -mean([1, 2, 3, 4, 5]); -// Returns: 3 - -mean([10, 20, 30]); -// Returns: 20 - -mean([1.5, 2.5, 3.5]); -// Returns: 2.5 -``` - -空の配列はNaNを返します。 - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean([]); -// Returns: NaN - -mean(null); -// Returns: NaN - -mean(undefined); -// Returns: NaN -``` - -無効な値は0として扱われ、計算に含まれます。 - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean([1, undefined, 2, null, 3]); -// Returns: 1.2 (1 + 2 + 3) / 5 = 1.2 -``` - -文字列は連結されます。 - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean(['1', '2', '3']); -// Returns: 41 (123 / 3 = 41) -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 平均を計算する数値が含まれる配列です。 - -#### 戻り値 - -(`number`): 配列の平均値を返します。空の配列の場合は `NaN` を返します。 diff --git a/docs/ja/reference/compat/math/meanBy.md b/docs/ja/reference/compat/math/meanBy.md deleted file mode 100644 index 6315924e8..000000000 --- a/docs/ja/reference/compat/math/meanBy.md +++ /dev/null @@ -1,103 +0,0 @@ -# meanBy (Lodash 互換性) - -::: warning es-toolkitの[meanBy](../../math/meanBy.md)を使用してください - -この `meanBy` 関数はiteratee関数処理と型変換により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [meanBy](../../math/meanBy.md) を使用してください。 - -::: - -条件に合う値の平均を計算します。 - -```typescript -const average = meanBy(array, iteratee); -``` - -## 使用法 - -### `meanBy(array, iteratee)` - -配列の各要素に関数を適用した結果の平均を計算します。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -// オブジェクト配列から特定プロパティの平均 -const people = [ - { name: '홍길동', age: 25 }, - { name: '김철수', age: 30 }, - { name: '이영희', age: 35 }, -]; - -meanBy(people, person => person.age); -// Returns: 30 - -// プロパティ名でも可能 -meanBy(people, 'age'); -// Returns: 30 -``` - -関数で値を変換して平均を計算します。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const numbers = [1.5, 2.7, 3.2, 4.8]; -meanBy(numbers, x => Math.floor(x)); -// Returns: 2.5 (1 + 2 + 3 + 4) / 4 - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -meanBy(items, x => x.a); -// Returns: 2 -``` - -配列要素でアクセスします。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const arrays = [[2], [3], [1]]; -meanBy(arrays, 0); // 最初の要素の平均 -// Returns: 2 -``` - -オブジェクトの特定プロパティと値が一致する場合のみ計算します。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const users = [ - { name: '홍길동', age: 25, active: true }, - { name: '김철수', age: 30, active: false }, - { name: '이영희', age: 35, active: true }, -]; - -// activeがtrueの人のみ -meanBy(users, { active: true }); -// Returns: 0.6666666 (active が true の人の割合) -``` - -空の配列はNaNを返します。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -meanBy([], x => x.a); -// Returns: NaN - -meanBy(null); -// Returns: NaN - -meanBy(undefined); -// Returns: NaN -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 処理する配列です。 -- `iteratee` (`ValueIteratee`, オプション): 各要素に適用する関数、プロパティ名、または条件です。 - -#### 戻り値 - -(`number`): 条件に合う値の平均を返します。空の配列の場合は `NaN` を返します。 diff --git a/docs/ja/reference/compat/math/minBy.md b/docs/ja/reference/compat/math/minBy.md deleted file mode 100644 index 8f42c4dea..000000000 --- a/docs/ja/reference/compat/math/minBy.md +++ /dev/null @@ -1,114 +0,0 @@ -# minBy (Lodash 互換性) - -::: warning es-toolkitの[minBy](../../array/minBy.md)を使用してください - -この `minBy` 関数はiteratee関数処理と型変換により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [minBy](../../array/minBy.md) を使用してください。 - -::: - -条件に合致する値の中で最小値要素を見つけます。 - -```typescript -const minItem = minBy(array, iteratee); -``` - -## 使用法 - -### `minBy(array, iteratee)` - -配列から関数で計算した値が最小の要素を見つけます。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -// オブジェクト配列から特定のプロパティが最小の要素 -const people = [ - { name: 'ホンギルドン', age: 25 }, - { name: 'キムチョルス', age: 30 }, - { name: 'イヨンヒ', age: 35 }, -]; - -minBy(people, person => person.age); -// Returns: { name: 'ホンギルドン', age: 25 } - -// プロパティ名でも可能 -minBy(people, 'age'); -// Returns: { name: 'ホンギルドン', age: 25 } -``` - -関数で値を変換して最小値を見つけます。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -minBy(items, x => x.a); -// Returns: { a: 1 } - -const numbers = [-1, -2, -3]; -minBy(numbers, x => Math.abs(x)); -// Returns: -1 (絶対値が最小の要素) -``` - -配列要素でアクセスします。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const arrays = [ - [1, 2], - [3, 4], - [0, 5], -]; -minBy(arrays, 0); // 最初の要素が最小の配列 -// Returns: [0, 5] - -minBy(arrays, 1); // 2番目の要素が最小の配列 -// Returns: [1, 2] -``` - -オブジェクトの特定プロパティと値が一致する場合を見つけます。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const users = [ - { name: 'ホンギルドン', age: 25, active: true }, - { name: 'キムチョルス', age: 30, active: false }, - { name: 'イヨンヒ', age: 35, active: true }, -]; - -// activeがtrueの要素の中で最初ではないものを見つける -minBy(users, ['active', true]); -// Returns: { name: 'キムチョルス', age: 30, active: false } - -// オブジェクトで条件を指定 -minBy(users, { active: true }); -// Returns: { name: 'キムチョルス', age: 30, active: false } -``` - -空の配列はundefinedを返します。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -minBy([], x => x.a); -// Returns: undefined - -minBy(null); -// Returns: undefined - -minBy(undefined); -// Returns: undefined -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 検索する配列です。 -- `iteratee` (`ValueIteratee`, オプション): 各要素に適用する関数、プロパティ名、または条件です。 - -#### 戻り値 - -(`T | undefined`): 条件に合致する値が最小の要素を返します。空の配列の場合は `undefined` を返します。 diff --git a/docs/ja/reference/compat/math/range.md b/docs/ja/reference/compat/math/range.md deleted file mode 100644 index 074b26cc7..000000000 --- a/docs/ja/reference/compat/math/range.md +++ /dev/null @@ -1,99 +0,0 @@ -# range (Lodash 互換性) - -::: warning es-toolkitの[range](../../math/range.md)を使用してください - -この `range` 関数は複雑な引数処理と型変換により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [range](../../math/range.md) を使用してください。 - -::: - -数値範囲の配列を作成します。 - -```typescript -const numbers = range(start, end, step); -``` - -## 使用法 - -### `range(end)` - -0からendまで1ずつ増加する配列を作成します。 - -```typescript -import { range } from 'es-toolkit/compat'; - -range(4); -// Returns: [0, 1, 2, 3] - -range(0); -// Returns: [] - -range(-4); -// Returns: [0, -1, -2, -3] -``` - -### `range(start, end)` - -startからendまで1ずつ増加する配列を作成します。 - -```typescript -import { range } from 'es-toolkit/compat'; - -range(1, 5); -// Returns: [1, 2, 3, 4] - -range(5, 1); -// Returns: [5, 4, 3, 2] (自動的に-1ずつ減少) - -range(-2, 3); -// Returns: [-2, -1, 0, 1, 2] -``` - -### `range(start, end, step)` - -startからendまでstepずつ増加する配列を作成します。 - -```typescript -import { range } from 'es-toolkit/compat'; - -range(0, 20, 5); -// Returns: [0, 5, 10, 15] - -range(0, -4, -1); -// Returns: [0, -1, -2, -3] - -range(1, 4, 0); -// Returns: [1, 1, 1] -``` - -小数のstepも可能です。 - -```typescript -import { range } from 'es-toolkit/compat'; - -range(0, 1, 0.2); -// Returns: [0, 0.2, 0.4, 0.6, 0.8] - -range(1, 0, -0.25); -// Returns: [1, 0.75, 0.5, 0.25] -``` - -iterateeとして使用する場合はguardオブジェクトで処理されます。 - -```typescript -import { range } from 'es-toolkit/compat'; - -[1, 2, 3].map(range); -// Returns: [[0], [0, 1], [0, 1, 2]] -``` - -#### パラメータ - -- `start` (`number`): 範囲の開始値です(含まれます)。`end`がない場合、この値がendになります。 -- `end` (`number`, オプション): 範囲の終了値です(含まれません)。 -- `step` (`number`, オプション): 増加幅です。デフォルトは1または-1です。 - -#### 戻り値 - -(`number[]`): 指定された範囲の数値配列を返します。 diff --git a/docs/ja/reference/compat/math/rangeRight.md b/docs/ja/reference/compat/math/rangeRight.md deleted file mode 100644 index 867b9c1f1..000000000 --- a/docs/ja/reference/compat/math/rangeRight.md +++ /dev/null @@ -1,99 +0,0 @@ -# rangeRight (Lodash 互換性) - -::: warning es-toolkitの[rangeRight](../../math/rangeRight.md)を使用してください - -この `rangeRight` 関数は複雑な引数処理と型変換により動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [rangeRight](../../math/rangeRight.md) を使用してください。 - -::: - -数値範囲の配列を逆順で作成します。 - -```typescript -const numbers = rangeRight(start, end, step); -``` - -## 使用法 - -### `rangeRight(end)` - -0からendまで1ずつ増加させた後、逆順で配列を作成します。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(4); -// Returns: [3, 2, 1, 0] - -rangeRight(0); -// Returns: [] - -rangeRight(-4); -// Returns: [-3, -2, -1, 0] -``` - -### `rangeRight(start, end)` - -startからendまで1ずつ増加させた後、逆順で配列を作成します。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(1, 5); -// Returns: [4, 3, 2, 1] - -rangeRight(5, 1); -// Returns: [2, 3, 4, 5] (自動的に-1ずつ減少してから逆順) - -rangeRight(-2, 3); -// Returns: [2, 1, 0, -1, -2] -``` - -### `rangeRight(start, end, step)` - -startからendまでstepずつ増加させた後、逆順で配列を作成します。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(0, 8, 2); -// Returns: [6, 4, 2, 0] - -rangeRight(0, -4, -1); -// Returns: [-3, -2, -1, 0] - -rangeRight(1, 4, 0); -// Returns: [1, 1, 1] -``` - -小数のstepも可能です。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(0, 1, 0.2); -// Returns: [0.8, 0.6, 0.4, 0.2, 0] - -rangeRight(1, 0, -0.25); -// Returns: [0.25, 0.5, 0.75, 1] -``` - -iterateeとして使用する場合はguardオブジェクトで処理されます。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -[1, 2, 3].map(rangeRight); -// Returns: [[0], [1, 0], [2, 1, 0]] -``` - -#### パラメータ - -- `start` (`number`): 範囲の開始値です(含まれます)。`end`がない場合、この値がendになります。 -- `end` (`number`, オプション): 範囲の終了値です(含まれません)。 -- `step` (`number`, オプション): 増加幅です。デフォルトは1または-1です。 - -#### 戻り値 - -(`number[]`): 指定された範囲の数値配列を逆順で返します。 diff --git a/docs/ja/reference/compat/math/sum.md b/docs/ja/reference/compat/math/sum.md deleted file mode 100644 index ffb85498d..000000000 --- a/docs/ja/reference/compat/math/sum.md +++ /dev/null @@ -1,73 +0,0 @@ -# sum (Lodash 互換性) - -::: warning es-toolkitの[sum](../../math/sum.md)を使用してください - -この`sum`関数は型変換とnull/undefined処理により動作が遅いです。 - -代わりにより高速で現代的な`es-toolkit`の[sum](../../math/sum.md)を使用してください。 - -::: - -配列のすべての値を足します。 - -```typescript -const total = sum(array); -``` - -## 使用法 - -### `sum(array)` - -配列内のすべての数値を足して合計を求めます。 - -```typescript -import { sum } from 'es-toolkit/compat'; - -// 数値配列 -sum([1, 2, 3]); -// Returns: 6 - -sum([1.5, 2.5, 3]); -// Returns: 7 - -// 空配列 -sum([]); -// Returns: 0 -``` - -BigIntと文字列も処理します。 - -```typescript -import { sum } from 'es-toolkit/compat'; - -// BigInt配列 -sum([1n, 2n, 3n]); -// Returns: 6n - -// 文字列配列(連結される) -sum(['1', '2']); -// Returns: '12' -``` - -無効な値は無視します。 - -```typescript -import { sum } from 'es-toolkit/compat'; - -sum([1, undefined, 2]); -// Returns: 3 (undefinedを無視) - -sum(null); -// Returns: 0 - -sum(undefined); -// Returns: 0 -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 足す値が含まれる配列です。 - -#### 戻り値 - -(`number`): すべての値を足した合計を返します。 diff --git a/docs/ja/reference/compat/math/sumBy.md b/docs/ja/reference/compat/math/sumBy.md deleted file mode 100644 index 6ed2e51cc..000000000 --- a/docs/ja/reference/compat/math/sumBy.md +++ /dev/null @@ -1,103 +0,0 @@ -# sumBy (Lodash 互換性) - -::: warning es-toolkitの[sumBy](../../math/sumBy.md)を使用してください - -この`sumBy`関数はiteratee関数処理と型変換により動作が遅いです。 - -代わりにより高速で現代的な`es-toolkit`の[sumBy](../../math/sumBy.md)を使用してください。 - -::: - -条件に合う値を足します。 - -```typescript -const total = sumBy(array, iteratee); -``` - -## 使用法 - -### `sumBy(array, iteratee)` - -配列の各要素に関数を適用した結果を足します。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -// 数値配列 -sumBy([1, 2, 3], value => value); -// Returns: 6 - -sumBy([1.5, 2.5, 3.5], value => Math.floor(value)); -// Returns: 6 (1 + 2 + 3) - -// 空配列 -sumBy([], value => value); -// Returns: 0 -``` - -### `sumBy(array)` - -関数を渡さない場合、配列の値をそのまま足します。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -sumBy([1, 2, 3]); -// Returns: 6 - -sumBy([1n, 2n, 3n]); -// Returns: 6n -``` - -オブジェクト配列から特定のプロパティを足します。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -const people = [ - { name: '田中太郎', age: 25 }, - { name: '佐藤次郎', age: 30 }, - { name: '鈴木花子', age: 35 }, -]; - -sumBy(people, person => person.age); -// Returns: 90 - -// プロパティ名でも可能 -sumBy(people, 'age'); -// Returns: 90 -``` - -文字列も連結します。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -const items = [{ a: '1' }, { a: '2' }]; -sumBy(items, obj => obj.a); -// Returns: '12' -``` - -無効な値は無視します。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -sumBy([1, undefined, 2], value => value); -// Returns: 3 (undefinedを無視) - -sumBy(null); -// Returns: 0 - -sumBy(undefined); -// Returns: 0 -``` - -#### パラメータ - -- `array` (`ArrayLike | null | undefined`): 処理する配列です。 -- `iteratee` (`((value: T) => number) | string`, オプション): 各要素に適用する関数またはプロパティ名です。 - -#### 戻り値 - -(`number`): 条件に合う値を足した合計を返します。 diff --git a/docs/ja/reference/compat/object/clone.md b/docs/ja/reference/compat/object/clone.md deleted file mode 100644 index b758c31f3..000000000 --- a/docs/ja/reference/compat/object/clone.md +++ /dev/null @@ -1,89 +0,0 @@ -# clone (Lodash 互換性) - -::: warning `es-toolkit`の`clone`を使用してください - -この `clone` 関数は、特殊なオブジェクトタイプを処理する複雑なロジックにより相対的に遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [clone](../../object/clone.md) を使用してください。 - -::: - -オブジェクトの浅いコピーを作成します。 - -```typescript -const cloned = clone(value); -``` - -## 使用法 - -### `clone(value)` - -値の浅いコピーを作成したい場合は、`clone`を使用してください。さまざまなタイプのオブジェクトと原始値をコピーできます。 - -```typescript -import { clone } from 'es-toolkit/compat'; - -// 原始値のコピー -const num = 42; -const clonedNum = clone(num); -// Returns: 42 (同じ値) - -// 配列のコピー -const arr = [1, 2, 3]; -const clonedArr = clone(arr); -// Returns: [1, 2, 3] (新しい配列インスタンス) - -// オブジェクトのコピー -const obj = { a: 1, b: 'hello' }; -const clonedObj = clone(obj); -// Returns: { a: 1, b: 'hello' } (新しいオブジェクトインスタンス) - -// Dateオブジェクトのコピー -const date = new Date('2023-01-01'); -const clonedDate = clone(date); -// Returns: new Date('2023-01-01') (新しいDateインスタンス) - -// 正規表現のコピー -const regex = /hello/gi; -regex.lastIndex = 3; -const clonedRegex = clone(regex); -// Returns: /hello/gi with lastIndex = 3 - -// Mapのコピー -const map = new Map([ - ['a', 1], - ['b', 2], -]); -const clonedMap = clone(map); -// Returns: new Map([['a', 1], ['b', 2]]) - -// Setのコピー -const set = new Set([1, 2, 3]); -const clonedSet = clone(set); -// Returns: new Set([1, 2, 3]) -``` - -ネストされたオブジェクトは浅いコピーのみが行われます。 - -```typescript -import { clone } from 'es-toolkit/compat'; - -const nested = { - a: 1, - b: { - c: 2, - }, -}; -const clonedNested = clone(nested); - -console.log(clonedNested !== nested); // true (異なるオブジェクト) -console.log(clonedNested.b === nested.b); // true (ネストされたオブジェクトは同じ参照) -``` - -#### パラメータ - -- `value` (`T`): コピーする値です。 - -#### 戻り値 - -(`T`): コピーされた値を返します。 diff --git a/docs/ja/reference/compat/object/cloneDeep.md b/docs/ja/reference/compat/object/cloneDeep.md deleted file mode 100644 index ae2457c14..000000000 --- a/docs/ja/reference/compat/object/cloneDeep.md +++ /dev/null @@ -1,88 +0,0 @@ -# cloneDeep (Lodash 互換性) - -::: warning `es-toolkit`の`cloneDeep`を使用してください - -この `cloneDeep` 関数は、特殊なオブジェクトタイプを処理する複雑なロジックにより相対的に遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [cloneDeep](../../object/cloneDeep.md) を使用してください。 - -::: - -オブジェクトの深いコピーを作成します。 - -```typescript -const cloned = cloneDeep(value); -``` - -## 使用法 - -### `cloneDeep(value)` - -値の深いコピーを作成したい場合は、`cloneDeep`を使用してください。ネストされたオブジェクトと配列を完全に新しいインスタンスとしてコピーします。 - -```typescript -import { cloneDeep } from 'es-toolkit/compat'; - -// 原始値のコピー -const num = 42; -const clonedNum = cloneDeep(num); -// Returns: 42 (同じ値) - -// 配列の深いコピー -const arr = [1, [2, 3], { a: 4 }]; -const clonedArr = cloneDeep(arr); -clonedArr[1][0] = 99; -console.log(arr[1][0]); // 2 (元の値は変更されない) -console.log(clonedArr[1][0]); // 99 - -// オブジェクトの深いコピー -const obj = { - a: 1, - b: { - c: 2, - d: { - e: 3, - }, - }, -}; -const clonedObj = cloneDeep(obj); -clonedObj.b.d.e = 99; -console.log(obj.b.d.e); // 3 (元の値は変更されない) -console.log(clonedObj.b.d.e); // 99 - -// Dateオブジェクトの深いコピー -const date = new Date('2023-01-01'); -const clonedDate = cloneDeep(date); -// Returns: new Date('2023-01-01') (新しいDateインスタンス) - -// 複雑なネスト構造 -const complex = { - arr: [1, { nested: true }], - map: new Map([['key', { value: 1 }]]), - set: new Set([{ item: 1 }]), - date: new Date(), -}; -const clonedComplex = cloneDeep(complex); -// すべてのネストされたオブジェクトが完全に新しいインスタンスとしてコピーされる -``` - -循環参照も正しく処理されます。 - -```typescript -import { cloneDeep } from 'es-toolkit/compat'; - -const obj = { a: 1 }; -obj.self = obj; // 循環参照 - -const cloned = cloneDeep(obj); -console.log(cloned !== obj); // true -console.log(cloned.self === cloned); // true (循環参照が保持される) -``` - -#### パラメータ - -- `value` (`T`): 深くコピーする値です。 - -#### 戻り値 - -(`T`): 深くコピーされた値を返します。 diff --git a/docs/ja/reference/compat/object/findKey.md b/docs/ja/reference/compat/object/findKey.md deleted file mode 100644 index 037ecd4ea..000000000 --- a/docs/ja/reference/compat/object/findKey.md +++ /dev/null @@ -1,61 +0,0 @@ -# findKey (Lodash 互換性) - -::: warning `es-toolkit`の`findKey`を使用してください - -この`findKey`関数は、さまざまな条件タイプの処理と互換性ロジックにより、複雑に動作します。 - -代わりに、より高速で現代的な`es-toolkit`の[findKey](../../object/findKey.md)を使用してください。 - -::: - -条件に一致する最初の要素のキーを検索します。 - -```typescript -const key = findKey(obj, predicate); -``` - -## 使用法 - -### `findKey(obj, predicate)` - -オブジェクト内で条件に一致する最初の要素のキーを検索するには`findKey`を使用してください。関数、オブジェクト、配列、文字列など、さまざまな形式の条件を使用できます。 - -```typescript -import { findKey } from 'es-toolkit/compat'; - -// 関数条件でキーを検索 -const users = { - alice: { age: 25, active: true }, - bob: { age: 30, active: false }, - charlie: { age: 35, active: true }, -}; - -findKey(users, user => user.age > 30); -// 戻り値: 'charlie' - -// オブジェクト条件でキーを検索 -findKey(users, { active: false }); -// 戻り値: 'bob' - -// プロパティパスでキーを検索 -findKey(users, 'active'); -// 戻り値: 'alice' -``` - -条件に一致する要素がない場合は`undefined`を返します。 - -```typescript -import { findKey } from 'es-toolkit/compat'; - -findKey({ a: 1, b: 2 }, value => value > 5); -// 戻り値: undefined -``` - -#### パラメータ - -- `obj` (`T | null | undefined`): 検索するオブジェクトです。 -- `predicate` (`ObjectIteratee`, オプション): 各要素に適用する条件です。関数、オブジェクト、配列、文字列を指定できます。 - -#### 戻り値 - -(`string | undefined`): 条件に一致する最初の要素のキーを返します。一致するものがない場合は`undefined`を返します。 diff --git a/docs/ja/reference/compat/object/invert.md b/docs/ja/reference/compat/object/invert.md deleted file mode 100644 index 50a6a0663..000000000 --- a/docs/ja/reference/compat/object/invert.md +++ /dev/null @@ -1,60 +0,0 @@ -# invert (Lodash 互換性) - -::: warning `es-toolkit`の`invert`を使用してください - -この`invert`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[`invert`](../../object/invert.md)を使用してください。 - -::: - -オブジェクトのキーと値を入れ替えます。 - -```typescript -const inverted = invert(object); -``` - -## 使用法 - -### `invert(object)` - -オブジェクトのキーと値を入れ替えたい場合は`invert`を使用してください。元のオブジェクトのキーは新しいオブジェクトの値になり、元のオブジェクトの値は新しいオブジェクトのキーになります。 - -```typescript -import { invert } from 'es-toolkit/compat'; - -// 基本的なキー・値の入れ替え -const object = { a: 1, b: 2, c: 3 }; -invert(object); -// => { '1': 'a', '2': 'b', '3': 'c' } - -// 文字列値の入れ替え -const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' }; -invert(colors); -// => { '#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue' } - -// 混合キーと値のタイプ -const mixed = { a: 1, 2: 'b', c: 3, 4: 'd' }; -invert(mixed); -// => { '1': 'a', 'b': '2', '3': 'c', 'd': '4' } -``` - -重複した値がある場合、最後のキーが使用されます。 - -```typescript -import { invert } from 'es-toolkit/compat'; - -// 重複した値がある場合 -const object = { a: 1, b: 1, c: 2 }; -invert(object); -// => { '1': 'b', '2': 'c' } -// 'a'は上書きされて失われます -``` - -#### パラメータ - -- `object` (`object`): 入れ替えるオブジェクトです。 - -#### 戻り値 - -(`Record`): キーと値が入れ替わった新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/mapKeys.md b/docs/ja/reference/compat/object/mapKeys.md deleted file mode 100644 index fec0bdf93..000000000 --- a/docs/ja/reference/compat/object/mapKeys.md +++ /dev/null @@ -1,63 +0,0 @@ -# mapKeys (Lodash 互換性) - -::: warning `es-toolkit`の`mapKeys`を使用してください - -この `mapKeys` 関数は、`null`や`undefined`の処理、`iteratee`変換過程により相対的に遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[`mapKeys`](../../object/mapKeys.md)を使用してください。 - -::: - -値をそのままにしてキーを変換し、新しいオブジェクトを作成します。 - -```typescript -const result = mapKeys(obj, iteratee); -``` - -## 使用法 - -### `mapKeys(object, iteratee)` - -`iteratee`関数を使用してオブジェクト内の各キーを変換し、新しいオブジェクトを作成します。値は変更されず、キーのみが変更されます。オブジェクトのキーを変換または正規化する際に便利です。 - -```typescript -import { mapKeys } from 'es-toolkit/compat'; - -// キーに接頭辞を追加 -const obj = { a: 1, b: 2, c: 3 }; -const result = mapKeys(obj, (value, key) => 'prefix_' + key); -// 結果: { prefix_a: 1, prefix_b: 2, prefix_c: 3 } - -// キーを大文字に変換 -const data = { name: 'John', age: 30 }; -const uppercased = mapKeys(data, (value, key) => key.toUpperCase()); -// 結果: { NAME: 'John', AGE: 30 } - -// 配列のインデックスをキーに変換 -const arr = ['apple', 'banana', 'orange']; -const indexed = mapKeys(arr, (value, index) => `item_${index}`); -// 結果: { item_0: 'apple', item_1: 'banana', item_2: 'orange' } - -// キーと値を組み合わせて新しいキーを生成 -const scores = { math: 90, science: 85, english: 92 }; -const detailed = mapKeys(scores, (value, key) => `${key}_score_${value}`); -// 結果: { math_score_90: 90, science_score_85: 85, english_score_92: 92 } -``` - -`null`または`undefined`は空のオブジェクトとして処理されます。 - -```typescript -import { mapKeys } from 'es-toolkit/compat'; - -mapKeys(null, iteratee); // {} -mapKeys(undefined, iteratee); // {} -``` - -#### パラメータ - -- `object` (`ArrayLike | T | null | undefined`): キーを変換するオブジェクトまたは配列です。 -- `iteratee` (`ListIteratee | ObjectIteratee`, オプション): 各キーを変換する関数です。デフォルトは`identity`関数です。 - -#### 戻り値 - -(`Record | Record`): 変換されたキーを持つ新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/mapValues.md b/docs/ja/reference/compat/object/mapValues.md deleted file mode 100644 index 4e6dcbd36..000000000 --- a/docs/ja/reference/compat/object/mapValues.md +++ /dev/null @@ -1,71 +0,0 @@ -# mapValues (Lodash 互換性) - -::: warning `es-toolkit`の`mapValues`を使用してください - -この `mapValues` 関数は、`null`や`undefined`の処理、`iteratee`変換過程により相対的に遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[`mapValues`](../../object/mapValues.md)を使用してください。 - -::: - -キーをそのままにして値を変換し、新しいオブジェクトを作成します。 - -```typescript -const result = mapValues(obj, iteratee); -``` - -## 使用法 - -### `mapValues(object, iteratee)` - -`iteratee`関数を使用してオブジェクト内の各値を変換し、新しいオブジェクトを作成します。キーは変更されず、値のみが変更されます。文字列、配列、オブジェクトすべてを処理できます。データを変換または計算する際に便利です。 - -```typescript -import { mapValues } from 'es-toolkit/compat'; - -// オブジェクトの値を変換 -const obj = { a: 1, b: 2, c: 3 }; -const doubled = mapValues(obj, value => value * 2); -// 結果: { a: 2, b: 4, c: 6 } - -// 文字列を大文字に変換 -const names = { first: 'john', last: 'doe' }; -const uppercased = mapValues(names, value => value.toUpperCase()); -// 結果: { first: 'JOHN', last: 'DOE' } - -// 文字列の各文字を変換 -const str = 'abc'; -const charMap = mapValues(str, char => char.toUpperCase()); -// 結果: { '0': 'A', '1': 'B', '2': 'C' } - -// 配列をオブジェクトに変換 -const arr = [10, 20, 30]; -const arrMap = mapValues(arr, (value, index) => value + index); -// 結果: { '0': 10, '1': 21, '2': 32 } - -// プロパティパスで値を抽出 -const users = { - user1: { profile: { name: 'Alice' } }, - user2: { profile: { name: 'Bob' } }, -}; -const userNames = mapValues(users, 'profile.name'); -// 結果: { user1: 'Alice', user2: 'Bob' } -``` - -`null`または`undefined`は空のオブジェクトとして処理されます。 - -```typescript -import { mapValues } from 'es-toolkit/compat'; - -mapValues(null, iteratee); // {} -mapValues(undefined, iteratee); // {} -``` - -#### パラメータ - -- `object` (`string | T[] | T | null | undefined`): 値を変換するオブジェクト、配列、または文字列です。 -- `iteratee` (`ValueIteratee`, オプション): 各値を変換する関数、プロパティパス、またはマッチングオブジェクトです。デフォルトは`identity`関数です。 - -#### 戻り値 - -(`Record | { [P in keyof T]: U } | Record | Record | Partial`): 変換された値を持つ新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/merge.md b/docs/ja/reference/compat/object/merge.md deleted file mode 100644 index cb0d31c86..000000000 --- a/docs/ja/reference/compat/object/merge.md +++ /dev/null @@ -1,82 +0,0 @@ -# merge (Lodash 互換性) - -::: warning `es-toolkit`の`merge`を使用してください - -この `merge` 関数は、内部的に複雑な `mergeWith` 関数を呼び出すため相対的に遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[`merge`](../../object/merge.md)を使用してください。 - -::: - -複数のオブジェクトを深くマージして1つのオブジェクトにします。 - -```typescript -const result = merge(target, ...sources); -``` - -## 使用法 - -### `merge(object, ...sources)` - -ターゲットオブジェクトに1つ以上のソースオブジェクトを深くマージします。ネストされたオブジェクトと配列は再帰的にマージされます。ソースオブジェクトのプロパティが`undefined`の場合、ターゲットオブジェクトの既存の値は上書きされません。オブジェクト設定のマージやデフォルト値の適用に便利です。 - -```typescript -import { merge } from 'es-toolkit/compat'; - -// 基本的なオブジェクトのマージ -const target = { a: 1, b: { x: 1, y: 2 } }; -const source = { b: { y: 3, z: 4 }, c: 5 }; -const result = merge(target, source); -// 結果: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } - -// 配列のマージ -const obj1 = { arr: [1, 2] }; -const obj2 = { arr: [3, 4] }; -const merged = merge(obj1, obj2); -// 結果: { arr: [3, 4] } (配列は置き換えられる) - -// 複数のオブジェクトをマージ -const base = { a: 1 }; -const ext1 = { b: 2 }; -const ext2 = { c: 3 }; -const ext3 = { d: 4 }; -const combined = merge(base, ext1, ext2, ext3); -// 結果: { a: 1, b: 2, c: 3, d: 4 } - -// ネストされたオブジェクトのマージ -const config = { - api: { url: 'https://api.example.com', timeout: 5000 }, - features: { auth: true }, -}; -const overrides = { - api: { timeout: 10000, retries: 3 }, - features: { analytics: true }, -}; -const finalConfig = merge(config, overrides); -// 結果: { -// api: { url: 'https://api.example.com', timeout: 10000, retries: 3 }, -// features: { auth: true, analytics: true } -// } -``` - -ターゲットオブジェクトは変更されるため、元を保持したい場合は空のオブジェクトを使用してください。 - -```typescript -import { merge } from 'es-toolkit/compat'; - -const original = { a: 1, b: { x: 1 } }; -const source = { b: { y: 2 } }; - -// 元を保持 -const result = merge({}, original, source); -// original は変更されない -``` - -#### パラメータ - -- `object` (`any`): マージ先となるターゲットオブジェクトです。このオブジェクトは変更されます。 -- `...sources` (`any[]`): マージするソースオブジェクトです。 - -#### 戻り値 - -(`any`): マージされたターゲットオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/mergeWith.md b/docs/ja/reference/compat/object/mergeWith.md deleted file mode 100644 index 2bfb7f630..000000000 --- a/docs/ja/reference/compat/object/mergeWith.md +++ /dev/null @@ -1,94 +0,0 @@ -# mergeWith (Lodash 互換性) - -::: warning `es-toolkit`の`mergeWith`を使用してください - -この `mergeWith` 関数は、複雑な型チェック、循環参照処理、特殊オブジェクト処理により相対的に遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[`mergeWith`](../../object/mergeWith.md)を使用してください。 - -::: - -カスタマイザー関数でマージ方法を制御しながら、複数のオブジェクトを深くマージします。 - -```typescript -const result = mergeWith(target, ...sources, customizer); -``` - -## 使用法 - -### `mergeWith(object, ...sources, customizer)` - -ターゲットオブジェクトに1つ以上のソースオブジェクトを深くマージしますが、カスタマイザー関数でマージ方法を制御します。カスタマイザー関数が`undefined`を返す場合、デフォルトのマージロジックが使用されます。配列の連結や特別なマージルールが必要な場合に便利です。 - -```typescript -import { mergeWith } from 'es-toolkit/compat'; - -// 数値を加算 -const obj1 = { a: 1, b: 2 }; -const obj2 = { b: 3, c: 4 }; -const result = mergeWith(obj1, obj2, (objValue, srcValue) => { - if (typeof objValue === 'number' && typeof srcValue === 'number') { - return objValue + srcValue; - } -}); -// 結果: { a: 1, b: 5, c: 4 } - -// 配列を連結 -const arr1 = { items: [1, 2] }; -const arr2 = { items: [3, 4] }; -const merged = mergeWith(arr1, arr2, (objValue, srcValue) => { - if (Array.isArray(objValue)) { - return objValue.concat(srcValue); - } -}); -// 結果: { items: [1, 2, 3, 4] } - -// 文字列を連結 -const str1 = { message: 'Hello' }; -const str2 = { message: 'World' }; -const combined = mergeWith(str1, str2, (objValue, srcValue, key) => { - if (key === 'message' && typeof objValue === 'string') { - return objValue + ' ' + srcValue; - } -}); -// 結果: { message: 'Hello World' } - -// 複数のソースオブジェクトとカスタマイザー -const base = { scores: [80] }; -const quiz1 = { scores: [90] }; -const quiz2 = { scores: [85] }; -const final = mergeWith(base, quiz1, quiz2, (objValue, srcValue) => { - if (Array.isArray(objValue)) { - return objValue.concat(srcValue); - } -}); -// 結果: { scores: [80, 90, 85] } -``` - -カスタマイザー関数は様々なパラメータを受け取ります。 - -```typescript -import { mergeWith } from 'es-toolkit/compat'; - -const customizer = (objValue, srcValue, key, object, source, stack) => { - console.log('マージ中:', key, objValue, '->', srcValue); - - // 特定のキーに対してのみカスタマイズ - if (key === 'specialField') { - return `${objValue}_${srcValue}`; - } - - // undefinedを返すとデフォルトのマージロジックを使用 - return undefined; -}; -``` - -#### パラメータ - -- `object` (`any`): マージ先となるターゲットオブジェクトです。このオブジェクトは変更されます。 -- `...sources` (`any[]`): マージするソースオブジェクトです。 -- `customizer` (`MergeWithCustomizer`): 値の割り当てをカスタマイズする関数です。形式: `(objValue, srcValue, key, object, source, stack) => any`。 - -#### 戻り値 - -(`any`): マージされたターゲットオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/omit.md b/docs/ja/reference/compat/object/omit.md deleted file mode 100644 index cca6bdfc6..000000000 --- a/docs/ja/reference/compat/object/omit.md +++ /dev/null @@ -1,82 +0,0 @@ -# omit (Lodash 互換性) - -::: warning `es-toolkit`の`omit`を使用してください - -この `omit` 関数は、深いコピーと `unset` 関数の呼び出しにより相対的に遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[`omit`](../../object/omit.md)を使用してください。 - -::: - -オブジェクトから指定されたキーを除外した新しいオブジェクトを作成します。 - -```typescript -const result = omit(obj, ...keys); -``` - -## 使用法 - -### `omit(object, ...paths)` - -オブジェクトから指定されたキーを除外した新しいオブジェクトを作成します。深いキーパスをサポートし、配列を使用して一度に複数のキーを指定することもできます。オブジェクトから機密情報を削除したり、必要なプロパティのみを選択する際に便利です。 - -```typescript -import { omit } from 'es-toolkit/compat'; - -// 基本的なキーの削除 -const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }; -const publicUser = omit(user, 'password', 'email'); -// 結果: { id: 1, name: 'John' } - -// 配列で複数のキーを削除 -const data = { a: 1, b: 2, c: 3, d: 4 }; -const filtered = omit(data, ['a', 'c']); -// 結果: { b: 2, d: 4 } - -// 深いキーパスの削除 -const nested = { - user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, - admin: true, -}; -const result = omit(nested, 'user.profile.age', 'admin'); -// 結果: { user: { profile: { name: 'John' }, settings: { theme: 'dark' } } } - -// ネストされた配列とキーの組み合わせ -const complex = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; -const simplified = omit(complex, 'a', ['b', 'c'], 'd.f'); -// 結果: { d: { e: 4 } } -``` - -配列、文字列、キーパスを自由に組み合わせることができます。 - -```typescript -import { omit } from 'es-toolkit/compat'; - -const config = { - api: { url: 'https://api.example.com', key: 'secret', timeout: 5000 }, - ui: { theme: 'dark', language: 'en' }, - debug: true, -}; - -// 複数の方法でキーを指定 -const cleaned = omit(config, 'api.key', ['debug'], 'ui.language'); -// 結果: { api: { url: 'https://api.example.com', timeout: 5000 }, ui: { theme: 'dark' } } -``` - -`null`または`undefined`は空のオブジェクトとして処理されます。 - -```typescript -import { omit } from 'es-toolkit/compat'; - -omit(null, 'key'); // {} -omit(undefined, 'key'); // {} -``` - -#### パラメータ - -- `object` (`T | null | undefined`): キーを削除する元のオブジェクトです。 -- `...paths` (`Array>`): 削除するキーです。単一のキー、キーの配列、または深いキーパスを指定できます。 - -#### 戻り値 - -(`Partial`): 指定されたキーが削除された新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/omitBy.md b/docs/ja/reference/compat/object/omitBy.md deleted file mode 100644 index d929de1e3..000000000 --- a/docs/ja/reference/compat/object/omitBy.md +++ /dev/null @@ -1,76 +0,0 @@ -# omitBy (Lodash 互換性) - -::: warning `es-toolkit`の`omitBy`を使用してください - -この `omitBy` 関数は、配列様オブジェクトのチェック、`iteratee`変換、キー変換過程により相対的に遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[`omitBy`](../../object/omitBy.md)を使用してください。 - -::: - -述語関数がtrueを返すプロパティを除外した新しいオブジェクトを作成します。 - -```typescript -const result = omitBy(obj, predicate); -``` - -## 使用法 - -### `omitBy(object, predicate)` - -オブジェクトの各プロパティに対して述語関数を実行し、述語がtrueを返すプロパティを除外した新しいオブジェクトを作成します。条件に基づいてプロパティを動的にフィルタリングする際に便利です。 - -```typescript -import { omitBy } from 'es-toolkit/compat'; - -// 特定の型の値を削除 -const data = { a: 1, b: 'remove', c: 3, d: 'keep' }; -const numbers = omitBy(data, value => typeof value === 'string'); -// 結果: { a: 1, c: 3 } - -// 条件に基づいてプロパティを削除 -const user = { id: 1, name: 'John', age: 0, active: false, email: '' }; -const validData = omitBy(user, value => !value); -// 結果: { id: 1, name: 'John' } (偽値を削除) - -// キー名でフィルタリング -const settings = { userSetting: true, adminSetting: false, debugMode: true }; -const userOnly = omitBy(settings, (value, key) => key.startsWith('admin')); -// 結果: { userSetting: true, debugMode: true } - -// 数値プロパティのみ削除 -const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; -const noNumbers = omitBy(mixed, value => typeof value === 'number'); -// 結果: { str: 'hello', bool: true, obj: {} } - -// 配列でも使用可能 -const arr = [1, 2, 3, 4, 5]; -const filtered = omitBy(arr, value => value % 2 === 0); -// 結果: { '0': 1, '2': 3, '4': 5 } (偶数インデックスの奇数値) - -// 値、キー、元のオブジェクトをすべて活用 -const scores = { math: 90, science: 75, english: 85, art: 60 }; -const passingGrades = omitBy(scores, (value, key, obj) => { - console.log(`${key}: ${value} (平均: ${Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length})`); - return value < 80; -}); -// 結果: { math: 90, english: 85 } -``` - -`null`または`undefined`は空のオブジェクトとして処理されます。 - -```typescript -import { omitBy } from 'es-toolkit/compat'; - -omitBy(null, () => true); // {} -omitBy(undefined, () => true); // {} -``` - -#### パラメータ - -- `object` (`Record | Record | object | null | undefined`): フィルタリングする元のオブジェクトです。 -- `predicate` (`ValueKeyIteratee | ValueKeyIteratee`, オプション): 各プロパティに対して実行する述語関数です。これがtrueを返すプロパティは削除されます。デフォルトは`identity`関数です。 - -#### 戻り値 - -(`Record | Record | Partial`): 条件に合致しないプロパティで構成された新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/pick.md b/docs/ja/reference/compat/object/pick.md deleted file mode 100644 index 1f3e5929d..000000000 --- a/docs/ja/reference/compat/object/pick.md +++ /dev/null @@ -1,73 +0,0 @@ -# pick (Lodash 互換性) - -::: warning `es-toolkit`の`pick`を使用してください - -この `pick` 関数は、複雑なパス処理、`get`/`set`関数の呼び出し、`null`/`undefined`の処理により相対的に遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[`pick`](../../object/pick.md)を使用してください。 - -::: - -オブジェクトから指定したプロパティのみを選択して新しいオブジェクトを作成します。 - -```typescript -const result = pick(obj, ...keys); -``` - -## 使用法 - -### `pick(object, ...props)` - -オブジェクトから必要なプロパティのみを選んで新しいオブジェクトを作りたい場合は`pick`を使用してください。配列で複数のキーを一度に渡すか、個別の引数として1つずつ渡すことができます。深いキーパスもサポートしているため、ネストされたプロパティも選択できます。 - -```typescript -import { pick } from 'es-toolkit/compat'; - -// 基本的な使用法 -const obj = { a: 1, b: 2, c: 3, d: 4 }; -const result = pick(obj, ['a', 'c']); -// 結果: { a: 1, c: 3 } - -// 個別の引数として渡す -const result2 = pick(obj, 'a', 'c'); -// 結果: { a: 1, c: 3 } - -// 深いパスを選択 -const nested = { - user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, - admin: true, -}; -const userInfo = pick(nested, 'user.profile.name', 'admin'); -// 結果: { user: { profile: { name: 'John' } }, admin: true } - -// 配列と個別のキーを混在 -const mixed = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; -const selected = pick(mixed, ['a', 'b'], 'c', 'd.e'); -// 結果: { a: 1, b: 2, c: 3, d: { e: 4 } } - -// ドット表記キーと実際のドット付きキーを区別 -const ambiguous = { - 'a.b': 1, // 実際のキー 'a.b' - a: { b: 2, c: 3 }, // ネストされたオブジェクト -}; -const dotKey = pick(ambiguous, 'a.b'); -// 結果: { 'a.b': 1 } (実際のキーが優先) -``` - -`null`または`undefined`は空のオブジェクトとして処理されます。 - -```typescript -import { pick } from 'es-toolkit/compat'; - -pick(null, ['a', 'b']); // {} -pick(undefined, ['a', 'b']); // {} -``` - -#### パラメータ - -- `object` (`T | null | undefined`): プロパティを選択するオブジェクトです。 -- `...props` (`Array>`): 選択するプロパティのキーです。単一のキー、キーの配列、または深いキーパスを指定できます。 - -#### 戻り値 - -(`Pick | Partial`): 指定されたプロパティのみを含む新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/object/pickBy.md b/docs/ja/reference/compat/object/pickBy.md deleted file mode 100644 index 1c283cf5f..000000000 --- a/docs/ja/reference/compat/object/pickBy.md +++ /dev/null @@ -1,86 +0,0 @@ -# pickBy (Lodash 互換性) - -::: warning `es-toolkit`の`pickBy`を使用してください - -この `pickBy` 関数は、配列様オブジェクトのチェック、`iteratee`変換、キー変換過程により相対的に遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[`pickBy`](../../object/pickBy.md)を使用してください。 - -::: - -述語関数がtrueを返すプロパティのみを選択して新しいオブジェクトを作成します。 - -```typescript -const result = pickBy(obj, predicate); -``` - -## 使用法 - -### `pickBy(object, predicate)` - -オブジェクトの各プロパティに対して述語関数を実行し、述語がtrueを返すプロパティのみを含む新しいオブジェクトを作成します。条件に基づいてプロパティを動的に選択する際に便利です。 - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -// 特定の型の値のみを選択 -const data = { a: 1, b: 'keep', c: 3, d: 'select' }; -const strings = pickBy(data, value => typeof value === 'string'); -// 結果: { b: 'keep', d: 'select' } - -// 条件に基づいてプロパティを選択 -const user = { id: 1, name: 'John', age: 0, active: true, email: '' }; -const validData = pickBy(user, value => Boolean(value)); -// 結果: { id: 1, name: 'John', active: true } (真値のみ) - -// キー名でフィルタリング -const settings = { userSetting: true, adminSetting: false, debugMode: true }; -const userOnly = pickBy(settings, (value, key) => key.startsWith('user')); -// 結果: { userSetting: true } - -// 数値プロパティのみを選択 -const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; -const numbersOnly = pickBy(mixed, value => typeof value === 'number'); -// 結果: { num1: 42, num2: 0 } - -// 配列でも使用可能 -const arr = [1, 2, 3, 4, 5]; -const evens = pickBy(arr, value => value % 2 === 0); -// 結果: { '1': 2, '3': 4 } (偶数のインデックスと値) - -// 値、キー、元のオブジェクトをすべて活用 -const scores = { math: 90, science: 75, english: 85, art: 60 }; -const highScores = pickBy(scores, (value, key, obj) => { - const average = Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length; - return value > average; -}); -// 結果: { math: 90, english: 85 } -``` - -述語関数なしで呼び出すと、真値のみが選択されます。 - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -const data = { a: 1, b: '', c: 0, d: 'hello', e: null, f: true }; -const truthyValues = pickBy(data); -// 結果: { a: 1, d: 'hello', f: true } -``` - -`null`または`undefined`は空のオブジェクトとして処理されます。 - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -pickBy(null, () => true); // {} -pickBy(undefined, () => true); // {} -``` - -#### パラメータ - -- `object` (`Record | Record | object | null | undefined`): フィルタリングする元のオブジェクトです。 -- `predicate` (`ValueKeyIterateeTypeGuard | ValueKeyIteratee | ValueKeyIteratee`, オプション): 各プロパティに対して実行する述語関数です。これがtrueを返すプロパティが選択されます。デフォルトは`identity`関数です。 - -#### 戻り値 - -(`Record | Record | Partial`): 条件に合致するプロパティで構成された新しいオブジェクトを返します。 diff --git a/docs/ja/reference/compat/predicate/isArrayBuffer.md b/docs/ja/reference/compat/predicate/isArrayBuffer.md deleted file mode 100644 index 308d8e38f..000000000 --- a/docs/ja/reference/compat/predicate/isArrayBuffer.md +++ /dev/null @@ -1,44 +0,0 @@ -# isArrayBuffer (Lodash互換性) - -::: warning es-toolkitの[isArrayBuffer](../../predicate/isArrayBuffer.md)を使用してください -この`isArrayBuffer`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より速く現代的な`es-toolkit`の[isArrayBuffer](../../predicate/isArrayBuffer.md)を使用してください。 -::: - -値がArrayBufferかどうかを確認します。 - -```typescript -const result = isArrayBuffer(value); -``` - -## 使用法 - -### `isArrayBuffer(value)` - -値がArrayBufferかどうかを型安全に確認したい場合は`isArrayBuffer`を使用してください。TypeScriptでタイプガードとしても動作します。 - -```typescript -import { isArrayBuffer } from 'es-toolkit/compat'; - -// ArrayBufferの確認 -const buffer = new ArrayBuffer(16); -isArrayBuffer(buffer); // true - -// 他の型はfalse -isArrayBuffer(new Array()); // false -isArrayBuffer(new Map()); // false -isArrayBuffer({}); // false -isArrayBuffer('hello'); // false -isArrayBuffer(123); // false -isArrayBuffer(null); // false -isArrayBuffer(undefined); // false -``` - -#### パラメータ - -- `value` (`unknown`): ArrayBufferかどうかを確認する値です。 - -#### 戻り値 - -(`value is ArrayBuffer`): 値がArrayBufferの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isBuffer.md b/docs/ja/reference/compat/predicate/isBuffer.md deleted file mode 100644 index 955a7f38e..000000000 --- a/docs/ja/reference/compat/predicate/isBuffer.md +++ /dev/null @@ -1,43 +0,0 @@ -# isBuffer (Lodash互換性) - -::: warning es-toolkitの[isBuffer](../../predicate/isBuffer.md)を使用してください -この`isBuffer`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より速く現代的な`es-toolkit`の[isBuffer](../../predicate/isBuffer.md)を使用してください。 -::: - -値がBufferインスタンスかどうかを確認します。 - -```typescript -const result = isBuffer(value); -``` - -## 使用法 - -### `isBuffer(value)` - -値がBufferインスタンスかどうかを型安全に確認したい場合は`isBuffer`を使用してください。Node.js環境でBufferオブジェクトを扱う際に便利です。TypeScriptでタイプガードとしても動作します。 - -```typescript -import { isBuffer } from 'es-toolkit/compat'; - -// Bufferインスタンスの確認 -const buffer = Buffer.from('hello'); -isBuffer(buffer); // true - -// 他の型はfalse -isBuffer('hello'); // false -isBuffer([1, 2, 3]); // false -isBuffer(new Uint8Array([1, 2, 3])); // false -isBuffer({}); // false -isBuffer(null); // false -isBuffer(undefined); // false -``` - -#### パラメータ - -- `value` (`unknown`): Bufferインスタンスかどうかを確認する値です。 - -#### 戻り値 - -(`boolean`): 値がBufferインスタンスの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isDate.md b/docs/ja/reference/compat/predicate/isDate.md deleted file mode 100644 index 4d34996b3..000000000 --- a/docs/ja/reference/compat/predicate/isDate.md +++ /dev/null @@ -1,46 +0,0 @@ -# isDate (Lodash互換性) - -::: warning es-toolkitの[isDate](../../predicate/isDate.md)を使用してください -この`isDate`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より速く現代的な`es-toolkit`の[isDate](../../predicate/isDate.md)を使用してください。 -::: - -値がDateオブジェクトかどうかを確認します。 - -```typescript -const result = isDate(value); -``` - -## 使用法 - -### `isDate(value)` - -値がDateオブジェクトかどうかを型安全に確認したい場合は`isDate`を使用してください。TypeScriptでタイプガードとしても動作します。 - -```typescript -import { isDate } from 'es-toolkit/compat'; - -// Dateオブジェクトの確認 -const date = new Date(); -isDate(date); // true - -// 無効なDateもDateオブジェクトとして認識します -const invalidDate = new Date('invalid'); -isDate(invalidDate); // true - -// 他の型はfalse -isDate('2024-01-01'); // false -isDate(1640995200000); // false -isDate({}); // false -isDate(null); // false -isDate(undefined); // false -``` - -#### パラメータ - -- `value` (`unknown`): Dateオブジェクトかどうかを確認する値です。 - -#### 戻り値 - -(`value is Date`): 値がDateオブジェクトの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isEqual.md b/docs/ja/reference/compat/predicate/isEqual.md deleted file mode 100644 index 3bb1ab0fe..000000000 --- a/docs/ja/reference/compat/predicate/isEqual.md +++ /dev/null @@ -1,82 +0,0 @@ -# isEqual (Lodash互換性) - -::: warning `es-toolkit`の[isEqual](../../predicate/isEqual.md)を使用してください -この`isEqual`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より速く現代的な`es-toolkit`の[isEqual](../../predicate/isEqual.md)を使用してください。 -::: - -二つの値が同じかどうかを深く比較して確認します。 - -```typescript -const result = isEqual(value1, value2); -``` - -## 使用法 - -### `isEqual(a, b)` - -二つの値が同じかどうかを深く比較して確認したい場合は`isEqual`を使用してください。Date、RegExp、オブジェクト、配列などの複雑な型も内容まで比較します。 - -```typescript -import { isEqual } from 'es-toolkit/compat'; - -// 基本型の比較 -isEqual(1, 1); // true -isEqual('hello', 'hello'); // true -isEqual(true, true); // true - -// オブジェクトの深い比較 -isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true -isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true -isEqual({ a: 1 }, { a: 1, b: undefined }); // false - -// 配列の深い比較 -isEqual([1, 2, 3], [1, 2, 3]); // true -isEqual([1, [2, 3]], [1, [2, 3]]); // true - -// Dateオブジェクトの比較 -isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true -isEqual(new Date('2020-01-01'), new Date('2020-01-02')); // false - -// RegExpオブジェクトの比較 -isEqual(/abc/g, /abc/g); // true -isEqual(/abc/g, /abc/i); // false -``` - -ネストされたオブジェクトや配列も再帰的に比較します。 - -```typescript -import { isEqual } from 'es-toolkit/compat'; - -const obj1 = { - user: { - name: 'John', - details: { - age: 30, - hobbies: ['reading', 'gaming'], - }, - }, -}; - -const obj2 = { - user: { - name: 'John', - details: { - age: 30, - hobbies: ['reading', 'gaming'], - }, - }, -}; - -isEqual(obj1, obj2); // true -``` - -#### パラメータ - -- `a` (`unknown`): 比較する最初の値です。 -- `b` (`unknown`): 比較する2番目の値です。 - -#### 戻り値 - -(`boolean`): 二つの値が同じ場合は`true`、異なる場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isEqualWith.md b/docs/ja/reference/compat/predicate/isEqualWith.md deleted file mode 100644 index acb40db68..000000000 --- a/docs/ja/reference/compat/predicate/isEqualWith.md +++ /dev/null @@ -1,92 +0,0 @@ -# isEqualWith (Lodash互換性) - -::: warning es-toolkitの[isEqualWith](../../predicate/isEqualWith.md)を使用してください -この`isEqualWith`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より速く現代的な`es-toolkit`の[isEqualWith](../../predicate/isEqualWith.md)を使用してください。 -::: - -カスタム比較関数を使用して二つの値が同じかどうかを確認します。 - -```typescript -const result = isEqualWith(a, b, customizer); -``` - -## 使用法 - -### `isEqualWith(a, b, areValuesEqual?)` - -カスタム比較関数を使用して二つの値を深く比較します。カスタム関数がboolean値を返す場合はその結果を使用し、`undefined`を返す場合はデフォルトの等価性比較を使用します。 - -カスタム比較関数はオブジェクト、配列、Map、Setなどの複雑な構造の内部の値を比較する際にも使用され、深い比較を保証します。 - -```typescript -import { isEqualWith } from 'es-toolkit/compat'; - -// 大文字小文字を無視した文字列比較 -const customizer = (a: any, b: any) => { - if (typeof a === 'string' && typeof b === 'string') { - return a.toLowerCase() === b.toLowerCase(); - } -}; - -isEqualWith('Hello', 'hello', customizer); // true -isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true - -// 数値の絶対値で比較 -const absCustomizer = (a: any, b: any) => { - if (typeof a === 'number' && typeof b === 'number') { - return Math.abs(a) === Math.abs(b); - } -}; - -isEqualWith([-1, 2], [1, -2], absCustomizer); // true - -// 複雑なオブジェクトの比較 -const obj1 = { - name: 'JOHN', - details: { age: 30, city: 'NYC' }, -}; -const obj2 = { - name: 'john', - details: { age: 30, city: 'nyc' }, -}; - -isEqualWith(obj1, obj2, customizer); // true -``` - -MapとSetに対しては特別な処理を行います。 - -```typescript -import { isEqualWith } from 'es-toolkit/compat'; - -const customizer = (a: any, b: any) => { - if (typeof a === 'string' && typeof b === 'string') { - return a.toLowerCase() === b.toLowerCase(); - } -}; - -const map1 = new Map([['KEY', 'value']]); -const map2 = new Map([['key', 'value']]); -isEqualWith(map1, map2, customizer); // true - -const set1 = new Set(['HELLO']); -const set2 = new Set(['hello']); -isEqualWith(set1, set2, customizer); // true -``` - -#### パラメータ - -- `a` (`any`): 比較する最初の値です。 -- `b` (`any`): 比較する2番目の値です。 -- `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): カスタム比較関数です。 - - `x`: 最初のオブジェクト`a`からの値 - - `y`: 2番目のオブジェクト`b`からの値 - - `property`: `x`と`y`を取得する際に使用したプロパティキー - - `xParent`: 最初の値`x`の親オブジェクト - - `yParent`: 2番目の値`y`の親オブジェクト - - `stack`: 循環参照を処理する内部スタック (Map) - -#### 戻り値 - -(`boolean`): カスタム関数によって二つの値が同じ場合は`true`、異なる場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isError.md b/docs/ja/reference/compat/predicate/isError.md deleted file mode 100644 index c4e6a84ce..000000000 --- a/docs/ja/reference/compat/predicate/isError.md +++ /dev/null @@ -1,47 +0,0 @@ -# isError (Lodash互換性) - -::: warning es-toolkitの[isError](../../predicate/isError.md)を使用してください -この`isError`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より速く現代的な`es-toolkit`の[isError](../../predicate/isError.md)を使用してください。 -::: - -値がErrorオブジェクトかどうかを確認します。 - -```typescript -const result = isError(value); -``` - -## 使用法 - -### `isError(value)` - -値がErrorオブジェクトかどうかを型安全に確認したい場合は`isError`を使用してください。TypeScriptでタイプガードとしても動作します。 - -```typescript -import { isError } from 'es-toolkit/compat'; - -// Errorオブジェクトの確認 -isError(new Error()); // true -isError(new TypeError('Type error')); // true -isError(new ReferenceError('Reference error')); // true - -// Errorを継承したカスタムエラー -class CustomError extends Error {} -isError(new CustomError()); // true - -// 他の型はfalse -isError('Error'); // false -isError({ name: 'Error', message: 'Something went wrong' }); // false -isError({}); // false -isError(null); // false -isError(undefined); // false -``` - -#### パラメータ - -- `value` (`unknown`): Errorオブジェクトかどうかを確認する値です。 - -#### 戻り値 - -(`value is Error`): 値がErrorオブジェクトの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isFunction.md b/docs/ja/reference/compat/predicate/isFunction.md deleted file mode 100644 index 8507cbd10..000000000 --- a/docs/ja/reference/compat/predicate/isFunction.md +++ /dev/null @@ -1,52 +0,0 @@ -# isFunction (Lodash互換性) - -::: warning es-toolkitの[isFunction](../../predicate/isFunction.md)を使用してください -この`isFunction`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より速く現代的な`es-toolkit`の[isFunction](../../predicate/isFunction.md)を使用してください。 -::: - -値が関数かどうかを確認します。 - -```typescript -const result = isFunction(value); -``` - -## 使用法 - -### `isFunction(value)` - -値が関数かどうかを型安全に確認したい場合は`isFunction`を使用してください。TypeScriptでタイプガードとしても動作します。 - -```typescript -import { isFunction } from 'es-toolkit/compat'; - -// 通常の関数 -isFunction(function () {}); // true -isFunction(() => {}); // true - -// 内蔵関数とコンストラクタ -isFunction(Array.prototype.slice); // true -isFunction(Proxy); // true -isFunction(Int8Array); // true - -// 非同期関数とジェネレータ関数 -isFunction(async function () {}); // true -isFunction(function* () {}); // true - -// 他の型はfalse -isFunction('function'); // false -isFunction({}); // false -isFunction([]); // false -isFunction(null); // false -isFunction(undefined); // false -isFunction(123); // false -``` - -#### パラメータ - -- `value` (`unknown`): 関数かどうかを確認する値です。 - -#### 戻り値 - -(`value is (...args: any[]) => any`): 値が関数の場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isLength.md b/docs/ja/reference/compat/predicate/isLength.md deleted file mode 100644 index 66809e720..000000000 --- a/docs/ja/reference/compat/predicate/isLength.md +++ /dev/null @@ -1,63 +0,0 @@ -# isLength (Lodash互換性) - -::: warning es-toolkitの[isLength](../../predicate/isLength.md)を使用してください -この`isLength`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より速く現代的な`es-toolkit`の[isLength](../../predicate/isLength.md)を使用してください。 -::: - -値が有効な長さかどうかを確認します。 - -```typescript -const result = isLength(value); -``` - -## 使用法 - -### `isLength(value)` - -値が有効な長さかどうかを確認したい場合は`isLength`を使用してください。有効な長さは数値型で、非負の整数であり、JavaScriptの最大安全整数(`Number.MAX_SAFE_INTEGER`)以下である必要があります。TypeScriptでタイプガードとしても動作します。 - -```typescript -import { isLength } from 'es-toolkit/compat'; - -// 有効な長さ -isLength(0); // true -isLength(42); // true -isLength(100); // true -isLength(Number.MAX_SAFE_INTEGER); // true - -// 無効な長さ -isLength(-1); // false (負数) -isLength(1.5); // false (整数ではない) -isLength(Number.MAX_SAFE_INTEGER + 1); // false (安全範囲超過) -isLength('3'); // false (文字列) -isLength(null); // false -isLength(undefined); // false -isLength({}); // false -isLength([]); // false -``` - -配列や文字列のlengthプロパティが有効かどうかを確認する際に便利です。 - -```typescript -import { isLength } from 'es-toolkit/compat'; - -function validateArrayLength(arr: any[]) { - if (isLength(arr.length)) { - console.log(`配列の長さ${arr.length}は有効です`); - return true; - } - return false; -} - -validateArrayLength([1, 2, 3]); // "配列の長さ3は有効です" -``` - -#### パラメータ - -- `value` (`any`): 有効な長さかどうかを確認する値です。 - -#### 戻り値 - -(`boolean`): 値が有効な長さの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isMap.md b/docs/ja/reference/compat/predicate/isMap.md deleted file mode 100644 index fd7333076..000000000 --- a/docs/ja/reference/compat/predicate/isMap.md +++ /dev/null @@ -1,63 +0,0 @@ -# isMap (Lodash互換性) - -::: warning es-toolkitの[isMap](../../predicate/isMap.md)を使用してください - -この`isMap`関数はLodash互換性のための複雑な処理により動作が遅くなります。 - -代わりに、より速く現代的な`es-toolkit`の[isMap](../../predicate/isMap.md)を使用してください。 - -::: - -値がMapかどうかを確認します。 - -```typescript -const result = isMap(value); -``` - -## 使用法 - -### `isMap(value)` - -値がMapかどうかを型安全に確認したい場合は`isMap`を使用してください。TypeScriptでタイプガードとしても動作します。 - -```typescript -import { isMap } from 'es-toolkit/compat'; - -// Mapの確認 -const map = new Map(); -isMap(map); // true - -// 他の型はfalse -isMap(new Set()); // false -isMap(new WeakMap()); // false -isMap({}); // false -isMap([]); // false -isMap('map'); // false -isMap(123); // false -isMap(null); // false -isMap(undefined); // false -``` - -Mapと似た他のコレクションとも区別します。 - -```typescript -import { isMap } from 'es-toolkit/compat'; - -// Map vs Set vs WeakMap -isMap(new Map([['key', 'value']])); // true -isMap(new Set(['value'])); // false -isMap(new WeakMap()); // false - -// Map vs 通常のオブジェクト -isMap({}); // false -isMap({ key: 'value' }); // false -isMap(Object.create(null)); // false -``` - -#### パラメータ - -- `value` (`unknown`): Mapかどうかを確認する値です。 - -#### 戻り値 - -(`value is Map`): 値がMapの場合は`true`、そうでない場合は`false`を返します。 diff --git a/docs/ja/reference/compat/predicate/isNil.md b/docs/ja/reference/compat/predicate/isNil.md deleted file mode 100644 index cbc4d2027..000000000 --- a/docs/ja/reference/compat/predicate/isNil.md +++ /dev/null @@ -1,62 +0,0 @@ -# isNil (Lodash 互換性) - -::: warning es-toolkitの [isNil](../../predicate/isNil.md)を使用してください - -この `isNil` 関数はLodash互換性のための複雑な処理により遅く動作します。 - -代わりにより高速で現代的な `es-toolkit` の [isNil](../../predicate/isNil.md) を使用してください。 - -::: - -値が `null` または `undefined` かどうかを確認します。 - -```typescript -const result = isNil(value); -``` - -## 使用法 - -### `isNil(x)` - -値が `null` または `undefined` かどうかを型安全に確認したい場合に `isNil` を使用してください。TypeScript で型ガードとしても動作します。 - -```typescript -import { isNil } from 'es-toolkit/compat'; - -// nullとundefinedはtrue -isNil(null); // true -isNil(undefined); // true - -// その他すべての値はfalse -isNil(0); // false -isNil(''); // false -isNil(false); // false -isNil([]); // false -isNil({}); // false -isNil('hello'); // false -isNil(42); // false -``` - -falsy として評価されるが `null` や `undefined` でない値と区別します。 - -```typescript -import { isNil } from 'es-toolkit/compat'; - -// falsyとして評価されるがnull/undefinedでない値 -isNil(0); // false -isNil(''); // false -isNil(false); // false -isNil(NaN); // false - -// nullとundefinedのみtrue -isNil(null); // true -isNil(undefined); // true -``` - -#### パラメータ - -- `x` (`any`): `null` または `undefined` かどうかを確認する値です。 - -#### 戻り値 - -(`x is null | undefined`): 値が `null` または `undefined` の場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/predicate/isNull.md b/docs/ja/reference/compat/predicate/isNull.md deleted file mode 100644 index 496dc5a97..000000000 --- a/docs/ja/reference/compat/predicate/isNull.md +++ /dev/null @@ -1,68 +0,0 @@ -# isNull (Lodash 互換性) - -::: warning es-toolkitの [isNull](../../predicate/isNull.md)を使用してください - -この `isNull` 関数はLodash互換性のための関数ですが、メインライブラリと同じ実装です。 - -代わりにより高速で現代的な `es-toolkit` の [isNull](../../predicate/isNull.md) を使用してください。 - -::: - -値が `null` かどうかを確認します。 - -```typescript -const result = isNull(value); -``` - -## 使用法 - -### `isNull(value)` - -値が正確に `null` かどうかを型安全に確認したい場合に `isNull` を使用してください。TypeScript で型ガードとしても動作します。 - -```typescript -import { isNull } from 'es-toolkit/compat'; - -// nullのみtrue -isNull(null); // true - -// undefinedもfalse -isNull(undefined); // false - -// その他すべての値もfalse -isNull(0); // false -isNull(''); // false -isNull(false); // false -isNull([]); // false -isNull({}); // false -isNull('null'); // false -isNull(NaN); // false -``` - -`null` と `undefined` を区別して確認することができます。 - -```typescript -import { isNull } from 'es-toolkit/compat'; - -function handleValue(value: string | null | undefined) { - if (isNull(value)) { - console.log('値が明示的にnullです'); - } else if (value === undefined) { - console.log('値がundefinedです'); - } else { - console.log(`値があります: ${value}`); - } -} - -handleValue(null); // "値が明示的にnullです" -handleValue(undefined); // "値がundefinedです" -handleValue('hello'); // "値があります: hello" -``` - -#### パラメータ - -- `value` (`any`): `null` かどうかを確認する値です。 - -#### 戻り値 - -(`value is null`): 値が `null` の場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/predicate/isPlainObject.md b/docs/ja/reference/compat/predicate/isPlainObject.md deleted file mode 100644 index 06304c5eb..000000000 --- a/docs/ja/reference/compat/predicate/isPlainObject.md +++ /dev/null @@ -1,85 +0,0 @@ -# isPlainObject (Lodash 互換性) - -::: warning es-toolkitの [isPlainObject](../../predicate/isPlainObject.md)を使用してください - -この `isPlainObject` 関数はLodash互換性のための複雑な処理により遅く動作します。 - -代わりにより高速で現代的な `es-toolkit` の [isPlainObject](../../predicate/isPlainObject.md) を使用してください。 - -::: - -値がプレーンオブジェクトかどうかを確認します。 - -```typescript -const result = isPlainObject(object); -``` - -## 使用法 - -### `isPlainObject(object)` - -値がプレーンオブジェクトかどうかを確認したい場合に `isPlainObject` を使用してください。プレーンオブジェクトは `{}` リテラル、`new Object()`、または `Object.create(null)` で生成されたオブジェクトです。TypeScript で型ガードとしても動作します。 - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -// プレーンオブジェクト -isPlainObject({}); // true -isPlainObject(new Object()); // true -isPlainObject(Object.create(null)); // true -isPlainObject({ name: 'John', age: 30 }); // true - -// プレーンオブジェクトでない値 -isPlainObject([]); // false (配列) -isPlainObject(new Date()); // false (Date インスタンス) -isPlainObject(new Map()); // false (Map インスタンス) -isPlainObject(new Set()); // false (Set インスタンス) -isPlainObject(/regex/); // false (正規表現) -isPlainObject(function () {}); // false (関数) -isPlainObject(null); // false -isPlainObject(undefined); // false -isPlainObject('object'); // false (文字列) -isPlainObject(42); // false (数値) -``` - -クラスインスタンスとプレーンオブジェクトを区別します。 - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -class Person { - name: string; - constructor(name: string) { - this.name = name; - } -} - -const person = new Person('John'); -const plainObj = { name: 'John' }; - -isPlainObject(person); // false (クラスインスタンス) -isPlainObject(plainObj); // true (プレーンオブジェクト) -``` - -カスタム `Symbol.toStringTag` プロパティも正しく処理します。 - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -// 書き込み可能な Symbol.toStringTag -const obj1 = {}; -obj1[Symbol.toStringTag] = 'CustomObject'; -isPlainObject(obj1); // true - -// 読み取り専用 Symbol.toStringTag(内蔵オブジェクト) -const date = new Date(); -isPlainObject(date); // false -``` - -#### パラメータ - -- `object` (`any`): プレーンオブジェクトかどうかを確認する値です。 - -#### 戻り値 - -(`boolean`): 値がプレーンオブジェクトの場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/predicate/isRegExp.md b/docs/ja/reference/compat/predicate/isRegExp.md deleted file mode 100644 index 240be2ee5..000000000 --- a/docs/ja/reference/compat/predicate/isRegExp.md +++ /dev/null @@ -1,82 +0,0 @@ -# isRegExp (Lodash 互換性) - -::: warning es-toolkitの [isRegExp](../../predicate/isRegExp.md)を使用してください - -この `isRegExp` 関数はLodash互換性のための関数ですが、単純な型確認です。 - -代わりにより高速で現代的な `es-toolkit` の [isRegExp](../../predicate/isRegExp.md) を使用してください。 - -::: - -値が正規表現かどうかを確認します。 - -```typescript -const result = isRegExp(value); -``` - -## 使用法 - -### `isRegExp(value)` - -値が正規表現かどうかを型安全に確認したい場合に `isRegExp` を使用してください。TypeScript で型ガードとしても動作します。 - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// 正規表現 -isRegExp(/abc/); // true -isRegExp(new RegExp('abc')); // true -isRegExp(/[a-z]+/g); // true -isRegExp(/pattern/gi); // true - -// その他の型はfalse -isRegExp('/abc/'); // false (文字列) -isRegExp('pattern'); // false (文字列) -isRegExp({}); // false (オブジェクト) -isRegExp([]); // false (配列) -isRegExp(null); // false -isRegExp(undefined); // false -isRegExp(123); // false (数値) -``` - -正規表現文字列と実際の正規表現オブジェクトを区別します。 - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// 正規表現 vs 正規表現文字列 -isRegExp(/test/); // true -isRegExp('/test/'); // false -isRegExp('\\d+'); // false -isRegExp('/\\d+/g'); // false - -// 様々な正規表現フラグ -isRegExp(/test/i); // true (大文字小文字無視) -isRegExp(/test/g); // true (グローバル検索) -isRegExp(/test/m); // true (複数行) -isRegExp(/test/gim); // true (すべてのフラグの組み合わせ) -``` - -動的に生成された正規表現も認識します。 - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// RegExp コンストラクタで作成した正規表現 -const dynamicRegex = new RegExp('\\d{3}-\\d{4}', 'g'); -isRegExp(dynamicRegex); // true - -// 文字列を通じて生成した正規表現 -const pattern = 'hello'; -const flags = 'gi'; -const regex = new RegExp(pattern, flags); -isRegExp(regex); // true -``` - -#### パラメータ - -- `value` (`any`): 正規表現かどうかを確認する値です。 - -#### 戻り値 - -(`value is RegExp`): 値が正規表現の場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/predicate/isSet.md b/docs/ja/reference/compat/predicate/isSet.md deleted file mode 100644 index 587532b5e..000000000 --- a/docs/ja/reference/compat/predicate/isSet.md +++ /dev/null @@ -1,67 +0,0 @@ -# isSet (Lodash 互換性) - -::: warning `es-toolkit`の [isSet](../../predicate/isSet.md)を使用してください - -この `isSet` 関数はLodash互換性のための関数ですが、メインライブラリと同じ実装です。 - -代わりにより高速で現代的な `es-toolkit` の [isSet](../../predicate/isSet.md) を使用してください。 - -::: - -値がSetかどうかを確認します。 - -```typescript -const result = isSet(value); -``` - -## 使用法 - -### `isSet(value)` - -値がSetかどうかを型安全に確認したい場合に `isSet` を使用してください。TypeScript で型ガードとしても動作します。 - -```typescript -import { isSet } from 'es-toolkit/compat'; - -// Set確認 -const set = new Set(); -isSet(set); // true - -// その他の型はfalse -isSet(new Map()); // false -isSet(new WeakSet()); // false -isSet([]); // false -isSet({}); // false -isSet('set'); // false -isSet(123); // false -isSet(null); // false -isSet(undefined); // false -``` - -Setと似た他のコレクションとも区別します。 - -```typescript -import { isSet } from 'es-toolkit/compat'; - -// Set vs Map vs WeakSet -isSet(new Set([1, 2, 3])); // true -isSet(new Map([['key', 'value']])); // false -isSet(new WeakSet()); // false - -// Set vs 配列 -isSet(new Set([1, 2, 3])); // true -isSet([1, 2, 3]); // false - -// Set vs 一般オブジェクト -isSet(new Set()); // true -isSet({}); // false -isSet(Object.create(null)); // false -``` - -#### パラメータ - -- `value` (`unknown`): Setかどうかを確認する値です。 - -#### 戻り値 - -(`value is Set`): 値がSetの場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/predicate/isUndefined.md b/docs/ja/reference/compat/predicate/isUndefined.md deleted file mode 100644 index 7106a3955..000000000 --- a/docs/ja/reference/compat/predicate/isUndefined.md +++ /dev/null @@ -1,92 +0,0 @@ -# isUndefined (Lodash 互換性) - -::: warning es-toolkitの [isUndefined](../../predicate/isUndefined.md)を使用してください - -この `isUndefined` 関数はLodash互換性のための複雑な処理により遅く動作します。 - -代わりにより高速で現代的な `es-toolkit` の [isUndefined](../../predicate/isUndefined.md) を使用してください。 - -::: - -値が `undefined` かどうかを確認します。 - -```typescript -const result = isUndefined(value); -``` - -## 使用法 - -### `isUndefined(x)` - -値が正確に `undefined` かどうかを型安全に確認したい場合に `isUndefined` を使用してください。TypeScript で型ガードとしても動作します。 - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -// undefinedのみtrue -isUndefined(undefined); // true - -// nullもfalse -isUndefined(null); // false - -// その他すべての値もfalse -isUndefined(0); // false -isUndefined(''); // false -isUndefined(false); // false -isUndefined([]); // false -isUndefined({}); // false -isUndefined('undefined'); // false -isUndefined(NaN); // false -``` - -`undefined` と `null` を区別して確認することができます。 - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -function handleValue(value: string | null | undefined) { - if (isUndefined(value)) { - console.log('値がundefinedです'); - } else if (value === null) { - console.log('値が明示的にnullです'); - } else { - console.log(`値があります: ${value}`); - } -} - -handleValue(undefined); // "値がundefinedです" -handleValue(null); // "値が明示的にnullです" -handleValue('hello'); // "値があります: hello" -``` - -宣言されていない変数や初期化されていないプロパティを確認する際に便利です。 - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -const obj: { name?: string; age?: number } = { name: 'John' }; - -if (isUndefined(obj.age)) { - console.log('年齢が設定されていません'); - obj.age = 25; // デフォルト値を設定 -} - -// 関数パラメータのデフォルト値処理 -function greet(name: string, title?: string) { - if (isUndefined(title)) { - title = 'さん'; - } - console.log(`こんにちは、${name}${title}!`); -} - -greet('田中'); // "こんにちは、田中さん!" -greet('田中', '先生'); // "こんにちは、田中先生!" -``` - -#### パラメータ - -- `x` (`any`): `undefined` かどうかを確認する値です。 - -#### 戻り値 - -(`x is undefined`): 値が `undefined` の場合は `true`、そうでなければ `false` を返します。 diff --git a/docs/ja/reference/compat/string/camelCase.md b/docs/ja/reference/compat/string/camelCase.md deleted file mode 100644 index 5c9be15a1..000000000 --- a/docs/ja/reference/compat/string/camelCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# camelCase (Lodash 互換性) - -::: warning `es-toolkit` の `camelCase` を使用してください - -この `camelCase` 関数は、文字列以外の入力値の処理と短縮アポストロフィの除去などにより、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [camelCase](../../string/camelCase.md) を使用してください。 - -::: - -文字列をキャメルケースに変換します。 - -```typescript -const result = camelCase(str); -``` - -## 使用法 - -### `camelCase(str)` - -文字列をキャメルケースに変換します。キャメルケースは、最初の単語を小文字で始め、後続の単語の最初の文字を大文字にして、スペースなしで連結する命名規則です。 - -```typescript -import { camelCase } from 'es-toolkit/compat'; - -camelCase('camelCase'); // 'camelCase' -camelCase('some whitespace'); // 'someWhitespace' -camelCase('hyphen-text'); // 'hyphenText' -camelCase('HTTPRequest'); // 'httpRequest' -``` - -文字列以外の値も文字列に変換して処理します。 - -```typescript -import { camelCase } from 'es-toolkit/compat'; - -camelCase(123); // '123' -camelCase(null); // '' -camelCase(undefined); // '' -``` - -#### パラメータ - -- `str` (`string | object`,オプション): キャメルケースに変換する値です。 - -#### 戻り値 - -(`string`): キャメルケースに変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/capitalize.md b/docs/ja/reference/compat/string/capitalize.md deleted file mode 100644 index b957b49c3..000000000 --- a/docs/ja/reference/compat/string/capitalize.md +++ /dev/null @@ -1,48 +0,0 @@ -# capitalize (Lodash 互換性) - -::: warning `es-toolkit` の `capitalize` を使用してください - -この `capitalize` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [capitalize](../../string/capitalize.md) を使用してください。 - -::: - -文字列の最初の文字を大文字に、残りの文字を小文字に変換します。 - -```typescript -const result = capitalize(str); -``` - -## 使用法 - -### `capitalize(str)` - -文字列の最初の文字を大文字に、残りの文字を小文字に変換します。単語の第一印象を良くしたり、タイトル形式にする際に便利です。 - -```typescript -import { capitalize } from 'es-toolkit/compat'; - -capitalize('fred'); // 'Fred' -capitalize('FRED'); // 'Fred' -capitalize('fRED'); // 'Fred' -``` - -空文字列や文字列以外の値も処理できます。 - -```typescript -import { capitalize } from 'es-toolkit/compat'; - -capitalize(''); // '' -capitalize(123); // '123' -capitalize(null); // '' -capitalize(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`,オプション): 最初の文字を大文字に変換する文字列です。 - -#### 戻り値 - -(`string`): 最初の文字が大文字で残りが小文字の文字列を返します。 diff --git a/docs/ja/reference/compat/string/deburr.md b/docs/ja/reference/compat/string/deburr.md deleted file mode 100644 index 542aa4c6c..000000000 --- a/docs/ja/reference/compat/string/deburr.md +++ /dev/null @@ -1,47 +0,0 @@ -# deburr (Lodash 互換性) - -::: warning `es-toolkit` の `deburr` を使用してください - -この `deburr` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [deburr](../../string/deburr.md) を使用してください。 - -::: - -文字列内の特殊文字と発音区別記号をASCII文字に変換します。 - -```typescript -const result = deburr(str); -``` - -## 使用法 - -### `deburr(str)` - -文字列内の特殊文字と発音区別記号をASCII文字に変換します。多言語テキストを検索やソートに使いやすくする際に便利です。 - -```typescript -import { deburr } from 'es-toolkit/compat'; - -deburr('Æthelred'); // 'Aethelred' -deburr('München'); // 'Munchen' -deburr('Crème brûlée'); // 'Creme brulee' -``` - -文字列以外の値も文字列に変換して処理します。 - -```typescript -import { deburr } from 'es-toolkit/compat'; - -deburr(123); // '123' -deburr(null); // '' -deburr(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`,オプション): 特殊文字を削除する文字列です。 - -#### 戻り値 - -(`string`): 特殊文字と発音区別記号がASCII文字に変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/escape.md b/docs/ja/reference/compat/string/escape.md deleted file mode 100644 index 31024a228..000000000 --- a/docs/ja/reference/compat/string/escape.md +++ /dev/null @@ -1,48 +0,0 @@ -# escape (Lodash 互換性) - -::: warning `es-toolkit` の `escape` を使用してください - -この `escape` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [escape](../../string/escape.md) を使用してください。 - -::: - -文字列内のHTML特殊文字をHTMLエンティティに変換します。 - -```typescript -const result = escape(str); -``` - -## 使用法 - -### `escape(str)` - -文字列内の `&`、`<`、`>`、`"`、`'` 文字を対応するHTMLエンティティに変換します。HTML文書にテキストを安全に挿入する際にXSS攻撃を防ぐのに便利です。 - -```typescript -import { escape } from 'es-toolkit/compat'; - -escape('This is a
element.'); // 'This is a <div> element.' -escape('This is a "quote"'); // 'This is a "quote"' -escape("This is a 'quote'"); // 'This is a 'quote'' -escape('This is a & symbol'); // 'This is a & symbol' -``` - -文字列以外の値も文字列に変換して処理します。 - -```typescript -import { escape } from 'es-toolkit/compat'; - -escape(123); // '123' -escape(null); // '' -escape(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`,オプション): HTML特殊文字をエスケープする文字列です。 - -#### 戻り値 - -(`string`): HTML特殊文字がエンティティに変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/escapeRegExp.md b/docs/ja/reference/compat/string/escapeRegExp.md deleted file mode 100644 index c4baafd9f..000000000 --- a/docs/ja/reference/compat/string/escapeRegExp.md +++ /dev/null @@ -1,49 +0,0 @@ -# escapeRegExp (Lodash 互換性) - -::: warning `es-toolkit` の `escapeRegExp` を使用してください - -この `escapeRegExp` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [escapeRegExp](../../string/escapeRegExp.md) を使用してください。 - -::: - -文字列内の正規表現特殊文字をエスケープします。 - -```typescript -const result = escapeRegExp(str); -``` - -## 使用法 - -### `escapeRegExp(str)` - -文字列内の正規表現特殊文字 `^`、`$`、`\`、`.`、`*`、`+`、`?`、`(`、`)`、`[`、`]`、`{`、`}`、`|` をエスケープします。動的に正規表現を生成する際に文字列を文字通り処理したい場合に便利です。 - -```typescript -import { escapeRegExp } from 'es-toolkit/compat'; - -escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); -// '\\[es-toolkit\\]\\(https://es-toolkit\\.dev/\\)' - -escapeRegExp('$^{}.+*?()[]|\\'); -// '\\$\\^\\{\\}\\.\\+\\*\\?\\(\\)\\[\\]\\|\\\\' -``` - -文字列以外の値も文字列に変換して処理します。 - -```typescript -import { escapeRegExp } from 'es-toolkit/compat'; - -escapeRegExp(123); // '123' -escapeRegExp(null); // '' -escapeRegExp(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`,オプション): 正規表現特殊文字をエスケープする文字列です。 - -#### 戻り値 - -(`string`): 正規表現特殊文字がエスケープされた文字列を返します。 diff --git a/docs/ja/reference/compat/string/kebabCase.md b/docs/ja/reference/compat/string/kebabCase.md deleted file mode 100644 index 02d851e40..000000000 --- a/docs/ja/reference/compat/string/kebabCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# kebabCase (Lodash 互換性) - -::: warning `es-toolkit` の `kebabCase` を使用してください - -この `kebabCase` 関数は、文字列以外の入力値の処理と短縮アポストロフィの除去などにより、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [kebabCase](../../string/kebabCase.md) を使用してください。 - -::: - -文字列をケバブケースに変換します。 - -```typescript -const result = kebabCase(str); -``` - -## 使用法 - -### `kebabCase(str)` - -文字列をケバブケースに変換します。ケバブケースは、各単語を小文字で書き、ダッシュ(-)文字で連結する命名規則です。URLやCSSクラス名で主に使用されます。 - -```typescript -import { kebabCase } from 'es-toolkit/compat'; - -kebabCase('camelCase'); // 'camel-case' -kebabCase('some whitespace'); // 'some-whitespace' -kebabCase('hyphen-text'); // 'hyphen-text' -kebabCase('HTTPRequest'); // 'http-request' -``` - -文字列以外の値も文字列に変換して処理します。 - -```typescript -import { kebabCase } from 'es-toolkit/compat'; - -kebabCase(123); // '123' -kebabCase(null); // '' -kebabCase(undefined); // '' -``` - -#### パラメータ - -- `str` (`string | object`,オプション): ケバブケースに変換する値です。 - -#### 戻り値 - -(`string`): ケバブケースに変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/lowerCase.md b/docs/ja/reference/compat/string/lowerCase.md deleted file mode 100644 index 0e86b1635..000000000 --- a/docs/ja/reference/compat/string/lowerCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# lowerCase (Lodash 互換性) - -::: warning `es-toolkit` の `lowerCase` を使用してください - -この `lowerCase` 関数は、文字列以外の入力値の処理と短縮アポストロフィの除去などにより、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [lowerCase](../../string/lowerCase.md) を使用してください。 - -::: - -文字列を小文字の単語にスペースで区切って変換します。 - -```typescript -const result = lowerCase(str); -``` - -## 使用法 - -### `lowerCase(str)` - -文字列を小文字の単語にスペースで区切って変換します。各単語は小文字に変換され、スペース文字で連結されます。人間が読みやすいテキスト形式にする際に便利です。 - -```typescript -import { lowerCase } from 'es-toolkit/compat'; - -lowerCase('camelCase'); // 'camel case' -lowerCase('some whitespace'); // 'some whitespace' -lowerCase('hyphen-text'); // 'hyphen text' -lowerCase('HTTPRequest'); // 'http request' -``` - -文字列以外の値も文字列に変換して処理します。 - -```typescript -import { lowerCase } from 'es-toolkit/compat'; - -lowerCase(123); // '123' -lowerCase(null); // '' -lowerCase(undefined); // '' -``` - -#### パラメータ - -- `str` (`string | object`,オプション): 小文字形式に変換する値です。 - -#### 戻り値 - -(`string`): 小文字の単語がスペースで区切られた文字列を返します。 diff --git a/docs/ja/reference/compat/string/lowerFirst.md b/docs/ja/reference/compat/string/lowerFirst.md deleted file mode 100644 index d126854f7..000000000 --- a/docs/ja/reference/compat/string/lowerFirst.md +++ /dev/null @@ -1,48 +0,0 @@ -# lowerFirst (Lodash 互換性) - -::: warning `es-toolkit` の `lowerFirst` を使用してください - -この `lowerFirst` 関数は、文字列以外の入力値の処理により、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [lowerFirst](../../string/lowerFirst.md) を使用してください。 - -::: - -文字列の最初の文字を小文字に変換します。 - -```typescript -const result = lowerFirst(str); -``` - -## 使用法 - -### `lowerFirst(str)` - -文字列の最初の文字を小文字に変換します。残りの文字はそのまま維持されます。camelCase変数名を作成したり、最初の文字だけ小文字にしたい場合に便利です。 - -```typescript -import { lowerFirst } from 'es-toolkit/compat'; - -lowerFirst('fred'); // 'fred' -lowerFirst('Fred'); // 'fred' -lowerFirst('FRED'); // 'fRED' -lowerFirst(''); // '' -``` - -文字列以外の値も文字列に変換して処理します。 - -```typescript -import { lowerFirst } from 'es-toolkit/compat'; - -lowerFirst(123); // '123' -lowerFirst(null); // '' -lowerFirst(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`,オプション): 最初の文字を小文字に変換する文字列です。 - -#### 戻り値 - -(`string`): 最初の文字が小文字に変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/pad.md b/docs/ja/reference/compat/string/pad.md deleted file mode 100644 index 1e1247161..000000000 --- a/docs/ja/reference/compat/string/pad.md +++ /dev/null @@ -1,60 +0,0 @@ -# pad (Lodash 互換性) - -::: warning `es-toolkit` の `pad` を使用してください - -この `pad` 関数は、`null` や `undefined` の処理などにより、動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [pad](../../string/pad.md) を使用してください。 - -::: - -文字列の前後にパディング文字を追加して、指定された長さに合わせます。 - -```typescript -const padded = pad(str, length, chars); -``` - -## 使用法 - -### `pad(str, length, chars)` - -文字列が希望する長さより短い場合に、前後にパディング文字を追加して長さを合わせたい場合は `pad` を使用してください。パディング文字が均等に分割されない場合、追加の文字は右側に配置されます。 - -```typescript -import { pad } from 'es-toolkit/compat'; - -// デフォルトの空白でパディング -pad('abc', 8); -// Returns: ' abc ' - -// 指定した文字でパディング -pad('abc', 8, '_-'); -// Returns: '_-abc_-_' - -// すでに十分な長さならそのまま返す -pad('abc', 3); -// Returns: 'abc' - -// 長さがより短いならそのまま返す -pad('abc', 2); -// Returns: 'abc' -``` - -`null` や `undefined` は空文字列として処理されます。 - -```typescript -import { pad } from 'es-toolkit/compat'; - -pad(null, 5); // ' ' -pad(undefined, 3, '*'); // '***' -``` - -#### パラメータ - -- `str` (`string`,オプション): パディングする文字列です。 -- `length` (`number`,オプション): 目標の長さです。デフォルトは `0` です。 -- `chars` (`string`,オプション): パディングに使用する文字です。デフォルトは空白 `' '` です。 - -#### 戻り値 - -(`string`): 指定された長さまでパディングされた文字列を返します。 diff --git a/docs/ja/reference/compat/string/snakeCase.md b/docs/ja/reference/compat/string/snakeCase.md deleted file mode 100644 index b8cb0be98..000000000 --- a/docs/ja/reference/compat/string/snakeCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# snakeCase (Lodash 互換性) - -::: warning `es-toolkit` の `snakeCase` を使用してください - -この `snakeCase` 関数は、`null` または `undefined` を処理するための正規化ロジックにより動作が遅くなります。 - -代わりに、より高速で現代的な `es-toolkit` の [snakeCase](../../string/snakeCase.md) を使用してください。 - -::: - -文字列をスネークケースに変換します。 - -```typescript -const snakeCased = snakeCase(str); -``` - -## 使用法 - -### `snakeCase(str)` - -文字列をスネークケース (snake*case) に変換したい場合は `snakeCase` を使用してください。スネークケースは、各単語を小文字で書き、アンダースコア (*) で連結する命名規則です。 - -```typescript -import { snakeCase } from 'es-toolkit/compat'; - -// キャメルケースの変換 -snakeCase('camelCase'); -// Returns: 'camel_case' - -// 空白で区切られた文字列の変換 -snakeCase('some whitespace'); -// Returns: 'some_whitespace' - -// ハイフンで区切られた文字列の変換 -snakeCase('hyphen-text'); -// Returns: 'hyphen_text' - -// 連続する大文字の処理 -snakeCase('HTTPRequest'); -// Returns: 'http_request' -``` - -`null` または `undefined` は空文字列として扱われます。 - -```typescript -import { snakeCase } from 'es-toolkit/compat'; - -snakeCase(null); // '' -snakeCase(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`, オプション): スネークケースに変換する文字列です。 - -#### 戻り値 - -(`string`): スネークケースに変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/startCase.md b/docs/ja/reference/compat/string/startCase.md deleted file mode 100644 index 411195ab5..000000000 --- a/docs/ja/reference/compat/string/startCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# startCase (Lodash 互換性) - -::: warning `es-toolkit`の`startCase`を使用してください - -この`startCase`関数は、`null`または`undefined`を処理するための正規化ロジックにより、動作が遅くなります。 - -代わりに、より高速で現代的な`es-toolkit`の[startCase](../../string/startCase.md)を使用してください。 - -::: - -文字列をスタートケースに変換します。 - -```typescript -const startCased = startCase(str); -``` - -## 使用法 - -### `startCase(str)` - -文字列をスタートケース(Start Case)に変換したい場合は、`startCase`を使用してください。スタートケースは、各単語の最初の文字を大文字にし、スペースで区切る命名規則です。 - -```typescript -import { startCase } from 'es-toolkit/compat'; - -// 通常の文字列を変換 -startCase('hello world'); -// 戻り値: 'Hello World' - -// すでに大文字の単語はそのまま保持 -startCase('HELLO WORLD'); -// 戻り値: 'HELLO WORLD' - -// ハイフンで区切られた文字列を変換 -startCase('hello-world'); -// 戻り値: 'Hello World' - -// アンダースコアで区切られた文字列を変換 -startCase('hello_world'); -// 戻り値: 'Hello World' -``` - -`null`または`undefined`は空文字列として処理されます。 - -```typescript -import { startCase } from 'es-toolkit/compat'; - -startCase(null); // '' -startCase(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`, オプション): スタートケースに変換する文字列です。 - -#### 戻り値 - -(`string`): スタートケースに変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/trim.md b/docs/ja/reference/compat/string/trim.md deleted file mode 100644 index e19b5a135..000000000 --- a/docs/ja/reference/compat/string/trim.md +++ /dev/null @@ -1,55 +0,0 @@ -# trim (Lodash 互換性) - -::: warning `es-toolkit` の `trim` を使用してください - -この `trim` 関数は、`null` や `undefined` の処理、配列型の `chars` 処理などにより動作が遅くなります。 - -代わりに、より高速でモダンな `es-toolkit` の [trim](../../string/trim.md) を使用してください。 - -::: - -文字列の先頭と末尾の空白または指定された文字を削除します。 - -```typescript -const trimmed = trim(str, chars); -``` - -## 使用法 - -### `trim(str, chars)` - -文字列の先頭と末尾から空白または特定の文字を削除したい場合は `trim` を使用します。`chars` を指定しない場合は、先頭と末尾の空白のみが削除されます。 - -```typescript -import { trim } from 'es-toolkit/compat'; - -// 先頭と末尾の空白を削除 -trim(' hello '); -// 戻り値: 'hello' - -// 指定された文字を削除 -trim('--hello--', '-'); -// 戻り値: 'hello' - -// 配列で複数の文字を削除 -trim('##hello##', ['#', 'o']); -// 戻り値: 'hell' -``` - -`null` または `undefined` は空文字列として扱われます。 - -```typescript -import { trim } from 'es-toolkit/compat'; - -trim(null); // '' -trim(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`, オプション): トリミングする文字列。 -- `chars` (`string`, オプション): 削除する文字。指定しない場合は空白が削除されます。 - -#### 戻り値 - -(`string`): 先頭と末尾から指定された文字が削除された文字列を返します。 diff --git a/docs/ja/reference/compat/string/trimEnd.md b/docs/ja/reference/compat/string/trimEnd.md deleted file mode 100644 index a5da217c3..000000000 --- a/docs/ja/reference/compat/string/trimEnd.md +++ /dev/null @@ -1,55 +0,0 @@ -# trimEnd (Lodash 互換性) - -::: warning `es-toolkit` の `trimEnd` を使用してください - -この `trimEnd` 関数は、`null` や `undefined` の処理、パラメータの順序変更などにより動作が遅くなります。 - -代わりに、より高速でモダンな `es-toolkit` の [trimEnd](../../string/trimEnd.md) を使用してください。 - -::: - -文字列の末尾の空白または指定された文字を削除します。 - -```typescript -const trimmed = trimEnd(str, chars); -``` - -## 使用法 - -### `trimEnd(str, chars)` - -文字列の末尾から空白または特定の文字を削除したい場合は `trimEnd` を使用します。`chars` を指定しない場合は、末尾の空白のみが削除されます。 - -```typescript -import { trimEnd } from 'es-toolkit/compat'; - -// 末尾の空白を削除 -trimEnd(' abc '); -// 戻り値: ' abc' - -// 指定された文字を削除 -trimEnd('-_-abc-_-', '_-'); -// 戻り値: '-_-abc' - -// 文字列の末尾にのみ適用 -trimEnd('abc', 'a'); -// 戻り値: 'abc' -``` - -`null` または `undefined` は空文字列として扱われます。 - -```typescript -import { trimEnd } from 'es-toolkit/compat'; - -trimEnd(null); // '' -trimEnd(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`, オプション): 末尾をトリミングする文字列。 -- `chars` (`string`, オプション): 削除する文字。指定しない場合は空白が削除されます。 - -#### 戻り値 - -(`string`): 末尾から指定された文字が削除された文字列を返します。 diff --git a/docs/ja/reference/compat/string/trimStart.md b/docs/ja/reference/compat/string/trimStart.md deleted file mode 100644 index 4ff150553..000000000 --- a/docs/ja/reference/compat/string/trimStart.md +++ /dev/null @@ -1,55 +0,0 @@ -# trimStart (Lodash 互換性) - -::: warning `es-toolkit` の `trimStart` を使用してください - -この `trimStart` 関数は、`null` や `undefined` の処理、パラメータの順序変更などにより動作が遅くなります。 - -代わりに、より高速でモダンな `es-toolkit` の [trimStart](../../string/trimStart.md) を使用してください。 - -::: - -文字列の先頭の空白または指定された文字を削除します。 - -```typescript -const trimmed = trimStart(str, chars); -``` - -## 使用法 - -### `trimStart(str, chars)` - -文字列の先頭から空白または特定の文字を削除したい場合は `trimStart` を使用します。`chars` を指定しない場合は、先頭の空白のみが削除されます。 - -```typescript -import { trimStart } from 'es-toolkit/compat'; - -// 先頭の空白を削除 -trimStart(' abc '); -// 戻り値: 'abc ' - -// 指定された文字を削除 -trimStart('-_-abc-_-', '_-'); -// 戻り値: 'abc-_-' - -// 文字列の先頭にのみ適用 -trimStart('abc', 'c'); -// 戻り値: 'abc' -``` - -`null` または `undefined` は空文字列として扱われます。 - -```typescript -import { trimStart } from 'es-toolkit/compat'; - -trimStart(null); // '' -trimStart(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`, オプション): 先頭をトリミングする文字列。 -- `chars` (`string`, オプション): 削除する文字。指定しない場合は空白が削除されます。 - -#### 戻り値 - -(`string`): 先頭から指定された文字が削除された文字列を返します。 diff --git a/docs/ja/reference/compat/string/unescape.md b/docs/ja/reference/compat/string/unescape.md deleted file mode 100644 index 1b9cc82cc..000000000 --- a/docs/ja/reference/compat/string/unescape.md +++ /dev/null @@ -1,58 +0,0 @@ -# unescape (Lodash 互換性) - -::: warning `es-toolkit` の `unescape` を使用してください - -この `unescape` 関数は、`null` や `undefined` の処理のための変換ロジックにより動作が遅くなります。 - -代わりに、より高速でモダンな `es-toolkit` の [unescape](../../string/unescape.md) を使用してください。 - -::: - -HTML エンティティを元の文字に変換します。 - -```typescript -const unescaped = unescape(str); -``` - -## 使用法 - -### `unescape(str)` - -HTML エンティティ `&`、`<`、`>`、`"`、`'` を元の文字に戻したい場合は `unescape` を使用します。これは `escape` 関数の逆の操作です。 - -```typescript -import { unescape } from 'es-toolkit/compat'; - -// HTML タグをアンエスケープ -unescape('This is a <div> element.'); -// 戻り値: 'This is a
element.' - -// 引用符をアンエスケープ -unescape('This is a "quote"'); -// 戻り値: 'This is a "quote"' - -// アポストロフィをアンエスケープ -unescape('This is a 'quote''); -// 戻り値: 'This is a 'quote'' - -// アンパサンドをアンエスケープ -unescape('This is a & symbol'); -// 戻り値: 'This is a & symbol' -``` - -`null` または `undefined` は空文字列として扱われます。 - -```typescript -import { unescape } from 'es-toolkit/compat'; - -unescape(null); // '' -unescape(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`, オプション): アンエスケープする文字列。 - -#### 戻り値 - -(`string`): HTML エンティティが元の文字に変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/upperCase.md b/docs/ja/reference/compat/string/upperCase.md deleted file mode 100644 index b85cb9f2e..000000000 --- a/docs/ja/reference/compat/string/upperCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# upperCase (Lodash 互換性) - -::: warning `es-toolkit` の `upperCase` を使用してください - -この `upperCase` 関数は、`null` や `undefined` の処理のための正規化ロジックにより動作が遅くなります。 - -代わりに、より高速でモダンな `es-toolkit` の [upperCase](../../string/upperCase.md) を使用してください。 - -::: - -文字列をアッパーケースに変換します。 - -```typescript -const upperCased = upperCase(str); -``` - -## 使用法 - -### `upperCase(str)` - -文字列をアッパーケース (UPPER CASE) に変換したい場合は `upperCase` を使用します。アッパーケースは、各単語を大文字で書き、スペースで接続する命名規則です。 - -```typescript -import { upperCase } from 'es-toolkit/compat'; - -// キャメルケースを変換 -upperCase('camelCase'); -// 戻り値: 'CAMEL CASE' - -// スペース区切りの文字列を変換 -upperCase('some whitespace'); -// 戻り値: 'SOME WHITESPACE' - -// ハイフン区切りの文字列を変換 -upperCase('hyphen-text'); -// 戻り値: 'HYPHEN TEXT' - -// 大文字が連続して現れる場合 -upperCase('HTTPRequest'); -// 戻り値: 'HTTP REQUEST' -``` - -`null` または `undefined` は空文字列として扱われます。 - -```typescript -import { upperCase } from 'es-toolkit/compat'; - -upperCase(null); // '' -upperCase(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`, オプション): アッパーケースに変換する文字列。 - -#### 戻り値 - -(`string`): アッパーケースに変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/upperFirst.md b/docs/ja/reference/compat/string/upperFirst.md deleted file mode 100644 index f4ee13118..000000000 --- a/docs/ja/reference/compat/string/upperFirst.md +++ /dev/null @@ -1,54 +0,0 @@ -# upperFirst (Lodash 互換性) - -::: warning `es-toolkit` の `upperFirst` を使用してください - -この `upperFirst` 関数は、`null` や `undefined` の処理のための変換ロジックにより動作が遅くなります。 - -代わりに、より高速でモダンな `es-toolkit` の [upperFirst](../../string/upperFirst.md) を使用してください。 - -::: - -文字列の最初の文字を大文字に変換します。 - -```typescript -const upperCased = upperFirst(str); -``` - -## 使用法 - -### `upperFirst(str)` - -文字列の最初の文字のみを大文字にしたい場合は `upperFirst` を使用します。残りの文字はそのまま保持されます。 - -```typescript -import { upperFirst } from 'es-toolkit/compat'; - -// 小文字で始まる文字列 -upperFirst('fred'); -// 戻り値: 'Fred' - -// すでに大文字で始まる文字列 -upperFirst('Fred'); -// 戻り値: 'Fred' - -// すべて大文字の文字列 -upperFirst('FRED'); -// 戻り値: 'FRED' -``` - -`null` または `undefined` は空文字列として扱われます。 - -```typescript -import { upperFirst } from 'es-toolkit/compat'; - -upperFirst(null); // '' -upperFirst(undefined); // '' -``` - -#### パラメータ - -- `str` (`string`, オプション): 最初の文字を大文字に変換する文字列。 - -#### 戻り値 - -(`string`): 最初の文字が大文字に変換された文字列を返します。 diff --git a/docs/ja/reference/compat/string/words.md b/docs/ja/reference/compat/string/words.md deleted file mode 100644 index 79c07eae8..000000000 --- a/docs/ja/reference/compat/string/words.md +++ /dev/null @@ -1,69 +0,0 @@ -# words (Lodash 互換性) - -::: warning `es-toolkit` の `words` を使用してください - -この `words` 関数は、`null` や `undefined` の処理、複雑な Unicode サポートなどにより動作が遅くなります。 - -代わりに、より高速でモダンな `es-toolkit` の [words](../../string/words.md) を使用してください。 - -::: - -文字列を単語の配列に分割します。 - -```typescript -const wordArray = words(str, pattern); -``` - -## 使用法 - -### `words(str, pattern)` - -文字列を単語単位で分割したい場合は `words` を使用します。デフォルトでは、英字、数字、絵文字などを認識して単語を抽出します。 - -```typescript -import { words } from 'es-toolkit/compat'; - -// 基本的な単語抽出 -words('fred, barney, & pebbles'); -// 戻り値: ['fred', 'barney', 'pebbles'] - -// キャメルケースから単語を抽出 -words('camelCaseWord'); -// 戻り値: ['camel', 'Case', 'Word'] - -// 数字を含む文字列 -words('hello123world'); -// 戻り値: ['hello', '123', 'world'] -``` - -カスタムパターンを使用して単語を抽出することもできます。 - -```typescript -import { words } from 'es-toolkit/compat'; - -// 正規表現を使用した単語抽出 -words('hello world', /\w+/g); -// 戻り値: ['hello', 'world'] - -// 文字列パターンを使用 -words('one-two-three', '-'); -// 戻り値: ['-'] -``` - -`null` または `undefined` は空の配列として扱われます。 - -```typescript -import { words } from 'es-toolkit/compat'; - -words(null); // [] -words(undefined); // [] -``` - -#### パラメータ - -- `str` (`string`, オプション): 単語に分割する文字列。 -- `pattern` (`RegExp | string`, オプション): 単語にマッチするパターン。デフォルトは組み込みの Unicode 単語パターン。 - -#### 戻り値 - -(`string[]`): 抽出された単語の配列を返します。 diff --git a/docs/ko/compat/intro.md b/docs/ko/compat/intro.md new file mode 100644 index 000000000..cf41a71d2 --- /dev/null +++ b/docs/ko/compat/intro.md @@ -0,0 +1,66 @@ +# es-toolkit/compat + +`es-toolkit/compat`은 [Lodash](https://lodash.com)와 똑같은 인터페이스와 동작을 제공하는 모듈이에요. 기존에 Lodash로 쓰던 코드를 그대로 두고 천천히 `es-toolkit`으로 옮겨갈 수 있도록 만들어졌어요. + +기존에 Lodash를 쓰고 있던 프로젝트가 아니라면 [`es-toolkit`](/ko/intro)을 사용해 주세요. + +::: tip ✅ 1.39.3 버전부터 Lodash와 100% 호환성을 보장해요 +Lodash가 직접 쓰는 테스트 코드를 그대로 통과해요. 동작은 같으면서 더 가볍고 빨라요. +::: + +```ts +// lodash와 같은 호출 형태를 es-toolkit/compat에서 그대로 사용할 수 있어요 +import { chunk } from 'es-toolkit/compat'; + +chunk([1, 2, 3, 4], 0); +// []을 반환해요. lodash와 동일해요. +``` + +## 마이그레이션 흐름 + +기존 코드에서 Lodash를 걷어낼 때는 다음 순서를 추천해요. + +1. `lodash` / `lodash-es`의 import 경로를 `es-toolkit/compat`으로 바꿔주세요. 호출하는 코드는 그대로 두면 돼요. +2. 시간을 두고 호출하는 부분을 정리해 가며 import를 [`es-toolkit`](/ko/intro)으로 바꿔주세요. 다 옮기고 나면 번들이 더 작고 더 빨라져요. + +## `es-toolkit`과의 차이점 + +- **API 모양**: Lodash와 1:1로 일치해요. 자동 타입 변환, 여러 가지 인자 형태, 더 이상 권장되지 않는 함수까지 그대로 들어 있어요. [`es-toolkit`](/ko/intro)은 타입이 안전하고 깔끔한 형태만 제공해요. +- **번들 크기와 속도**: [`es-toolkit`](/ko/intro)보다 살짝 크고 살짝 느려요. Lodash와 동작을 맞추기 위한 추가 처리가 들어가기 때문이에요. +- **권장되지 않는 함수**: Lodash에서 더 이상 권장하지 않는 함수도 호환을 위해 `compat`에는 남아있지만 [`es-toolkit`](/ko/intro)에는 들어가지 않아요. 마이그레이션 중에 같이 정리해 주세요. + +함수별 자세한 문서는 [호환성 레퍼런스](/ko/compat/reference/array/castArray)에서 확인할 수 있어요. + +## 설계 원칙 + +::: info +`es-toolkit/compat` 설계 원칙의 방향성은 변경될 수 있어요. +::: + +`es-toolkit/compat`은 다음과 같은 기능들에 대해서 `lodash`와 100% 동일한 기능을 제공하는 것을 목표로 해요. + +- `lodash`의 테스트 케이스로 작성된 기능 +- `@types/lodash` 또는 `@types/lodash-es`의 타입에서 추론할 수 있는 기능 +- `lodash`에서 `es-toolkit`으로 코드를 마이그레이션하는 동안 발견된 기능 차이점 ([이슈 페이지](https://github.com/toss/es-toolkit/issues)에 제보해 주세요.) + +아래와 같은 기능은 `es-toolkit/compat`에서 지원하지 않아요. + +- 암시적 타입 변환: 빈 문자열을 0 또는 false로 변환하는 것과 같은 동작 +- 어떤 경우에 특화된 구현: [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq)와 같이 정렬된 배열만 받는 함수 +- `Array.prototype`과 같은 JavaScript 내장 객체의 프로토타입이 수정된 경우에 대한 처리 +- JavaScript Realm에 대응하는 코드 +- 메서드 체이닝: `_(arr).map(...).filter(...)`와 같은 메서드 체이닝 + +## 구현 상태 + +::: info +아래 이모지로 현재 구현 상태를 나타내고 있어요. + +- ✅: 완료 (구현됐고, lodash 테스트 코드를 모두 통과해요.) +- 📝: 리뷰 중 (구현됐지만, lodash 테스트 코드로 테스트되지는 않았어요.) +- ❌: 아직 구현되지 않음 + +"리뷰 중"으로 표시되었더라고 하더라도, 이미 lodash와 100% 동일한 기능을 제공하고 있을 수도 있어요. +::: + + diff --git a/docs/ko/reference/compat/array/castArray.md b/docs/ko/compat/reference/array/castArray.md similarity index 100% rename from docs/ko/reference/compat/array/castArray.md rename to docs/ko/compat/reference/array/castArray.md diff --git a/docs/ko/compat/reference/array/chunk.md b/docs/ko/compat/reference/array/chunk.md new file mode 100644 index 000000000..d93d5bea0 --- /dev/null +++ b/docs/ko/compat/reference/array/chunk.md @@ -0,0 +1,70 @@ +# chunk (Lodash 호환성) + +::: warning `es-toolkit`의 [`chunk`](../../../reference/array/chunk.md)를 사용하세요 + +이 `chunk` 함수는 `null`이나 `undefined` 처리, `size` 기본값 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [chunk](../../../reference/array/chunk.md)를 사용하세요. + +::: + +배열을 정해진 크기의 작은 배열들로 나눠요. + +```typescript +const chunked = chunk(arr, size); +``` + +## 사용법 + +### `chunk(arr, size?)` + +긴 배열을 같은 크기의 여러 작은 배열로 나누고 싶을 때 `chunk`를 사용하세요. 배열을 똑같이 나눌 수 없다면, 마지막 배열이 남은 요소들을 포함해요. + +```typescript +import { chunk } from 'es-toolkit/compat'; + +// 숫자 배열을 크기 2로 나눠요. +chunk([1, 2, 3, 4], 2); +// Returns: [[1, 2], [3, 4]] + +// 문자열 배열을 크기 3으로 나눠요. +chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); +// Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] + +// 나누어떨어지지 않는 경우 +chunk([1, 2, 3, 4, 5], 2); +// Returns: [[1, 2], [3, 4], [5]] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { chunk } from 'es-toolkit/compat'; + +chunk(null, 2); +// Returns: [] + +chunk(undefined, 2); +// Returns: [] +``` + +크기가 0이거나 음수면 빈 배열을 반환해요. + +```typescript +import { chunk } from 'es-toolkit/compat'; + +chunk([1, 2, 3], 0); +// Returns: [] + +chunk([1, 2, 3], -1); +// Returns: [] +``` + +#### 파라미터 + +- `arr` (`ArrayLike | null | undefined`): 나눌 배열이에요. +- `size` (`number`, 선택): 각 작은 배열의 크기예요. 기본값은 `1`이에요. + +#### 반환 값 + +(`T[][]`): 크기 `size`로 나눠진 2차원 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/compact.md b/docs/ko/compat/reference/array/compact.md new file mode 100644 index 000000000..33df4337d --- /dev/null +++ b/docs/ko/compat/reference/array/compact.md @@ -0,0 +1,77 @@ +# compact (Lodash 호환성) + +::: warning `es-toolkit`의 [`compact`](../../../reference/array/compact.md)를 사용하세요 + +이 `compact` 함수는 `null`이나 `undefined` 처리, `size` 기본값 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [compact](../../../reference/array/compact.md)를 사용하세요. + +::: + +배열에서 거짓으로 평가되는 값들을 제거해요. + +```typescript +const compacted = compact(arr); +``` + +## 사용법 + +### `compact(arr)` + +배열에서 `false`, `null`, `0`, `""`, `undefined`, `NaN` 같은 거짓으로 평가되는 값들을 제거하고 싶을 때 `compact`를 사용하세요. + +```typescript +import { compact } from 'es-toolkit/compat'; + +// 거짓으로 평가되는 값들 제거 +compact([0, 1, false, 2, '', 3]); +// Returns: [1, 2, 3] + +compact(['a', null, 'b', undefined, 'c', NaN]); +// Returns: ['a', 'b', 'c'] + +// 빅인트 0도 제거 +compact([0n, 1n, false, 2n]); +// Returns: [1n, 2n] + +// 빈 배열도 처리 +compact([]); +// Returns: [] + +// 모든 값이 거짓으로 평가되는 경우 +compact([false, null, 0, '', undefined, NaN]); +// Returns: [] +``` + +참으로 평가되는 값들은 그대로 유지돼요. + +```typescript +import { compact } from 'es-toolkit/compat'; + +compact([1, 'hello', true, {}, []]); +// Returns: [1, 'hello', true, {}, []] + +// 0이 아닌 숫자들 +compact([0, -1, 2, -3]); +// Returns: [-1, 2, -3] +``` + +`null`이나 `undefined` 배열은 빈 배열로 처리해요. + +```typescript +import { compact } from 'es-toolkit/compat'; + +compact(null); +// Returns: [] + +compact(undefined); +// Returns: [] +``` + +#### 파라미터 + +- `arr` (`ArrayLike | null | undefined`): 압축할 배열이에요. + +#### 반환 값 + +(`T[]`): 거짓으로 평가되는 값들이 제거된 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/concat.md b/docs/ko/compat/reference/array/concat.md similarity index 100% rename from docs/ko/reference/compat/array/concat.md rename to docs/ko/compat/reference/array/concat.md diff --git a/docs/ko/compat/reference/array/countBy.md b/docs/ko/compat/reference/array/countBy.md new file mode 100644 index 000000000..5f9be4508 --- /dev/null +++ b/docs/ko/compat/reference/array/countBy.md @@ -0,0 +1,88 @@ +# countBy (Lodash 호환성) + +::: warning `es-toolkit`의 `countBy`를 사용하세요 + +이 `countBy` 함수는 복잡한 변환 함수 처리와 타입 변환으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [countBy](../../../reference/array/countBy.md)를 사용하세요. + +::: + +배열이나 객체의 요소들을 조건에 따라 분류해서 각 분류의 개수를 세어요. + +```typescript +const counts = countBy(collection, iteratee); +``` + +## 사용법 + +### `countBy(collection, iteratee?)` + +배열이나 객체의 각 요소를 어떤 기준으로 그룹화하고, 각 그룹에 몇 개의 요소가 있는지 세고 싶을 때 `countBy`를 사용하세요. 반복자 함수가 반환하는 값이 키가 되고, 그 키에 해당하는 요소들의 개수가 값이 돼요. + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// 숫자를 소수점 아래 버림으로 그룹화 +countBy([6.1, 4.2, 6.3], Math.floor); +// Returns: { '4': 1, '6': 2 } + +// 문자열을 길이로 그룹화 +countBy(['one', 'two', 'three'], 'length'); +// Returns: { '3': 2, '5': 1 } + +// 사용자를 나이대로 그룹화 +const users = [ + { name: 'Alice', age: 25 }, + { name: 'Bob', age: 35 }, + { name: 'Charlie', age: 25 }, +]; +countBy(users, user => Math.floor(user.age / 10) * 10); +// Returns: { '20': 2, '30': 1 } +``` + +객체도 처리할 수 있어요. + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// 객체의 값들을 타입으로 분류 +const obj = { a: 1, b: 'string', c: 2, d: 'text' }; +countBy(obj, value => typeof value); +// Returns: { 'number': 2, 'string': 2 } +``` + +반복자 함수 없이 사용하면 값 자체로 그룹화해요. + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// 값 자체로 그룹화 +countBy([1, 2, 1, 3, 2, 1]); +// Returns: { '1': 3, '2': 2, '3': 1 } + +// 불린 값으로 그룹화 +countBy([true, false, true, true]); +// Returns: { 'true': 3, 'false': 1 } +``` + +`null`이나 `undefined` 컬렉션은 빈 객체를 반환해요. + +```typescript +import { countBy } from 'es-toolkit/compat'; + +countBy(null); +// Returns: {} + +countBy(undefined); +// Returns: {} +``` + +#### 파라미터 + +- `collection` (`ArrayLike | object | null | undefined`): 처리할 배열이나 객체예요. +- `iteratee` (`ValueIteratee`, 선택): 각 요소를 그룹화할 기준을 정하는 함수예요. 함수, 프로퍼티 이름, 또는 부분 객체를 사용할 수 있어요. + +#### 반환 값 + +(`Record`): 각 그룹의 키와 해당 그룹의 요소 개수를 가진 객체를 반환해요. diff --git a/docs/ko/compat/reference/array/difference.md b/docs/ko/compat/reference/array/difference.md new file mode 100644 index 000000000..31a250a26 --- /dev/null +++ b/docs/ko/compat/reference/array/difference.md @@ -0,0 +1,94 @@ +# difference (Lodash 호환성) + +::: warning `es-toolkit`의 `difference`를 사용하세요 + +이 `difference` 함수는 `null`이나 `undefined` 처리, 여러 배열 인자 처리로 인해 복잡하게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [difference](../../../reference/array/difference.md)를 사용하세요. + +::: + +첫 번째 배열에서 다른 배열들의 값들을 제외한 차집합을 구해요. + +```typescript +const result = difference(arr, ...values); +``` + +## 사용법 + +### `difference(arr, ...values)` + +첫 번째 배열에서 나머지 배열들에 포함된 값들을 모두 제거하고 싶을 때 `difference`를 사용하세요. 순서는 첫 번째 배열의 순서를 유지해요. + +```typescript +import { difference } from 'es-toolkit/compat'; + +// 기본 사용법 +const array1 = [1, 2, 3, 4, 5]; +const array2 = [2, 4]; +const array3 = [5, 6]; +difference(array1, array2, array3); +// Returns: [1, 3] + +// 문자열 배열 +difference(['a', 'b', 'c'], ['b'], ['c', 'd']); +// Returns: ['a'] + +// 중복된 값 처리 +difference([1, 2, 2, 3], [2]); +// Returns: [1, 3] +``` + +빈 배열이나 빈 차집합도 처리해요. + +```typescript +import { difference } from 'es-toolkit/compat'; + +// 빈 배열과의 차집합 +difference([1, 2, 3], []); +// Returns: [1, 2, 3] + +// 모든 값이 제외되는 경우 +difference([1, 2, 3], [1, 2, 3]); +// Returns: [] + +// 겹치는 값이 없는 경우 +difference([1, 2], [3, 4]); +// Returns: [1, 2] +``` + +`null`이나 `undefined` 배열은 빈 배열로 처리해요. + +```typescript +import { difference } from 'es-toolkit/compat'; + +difference(null, [1, 2]); +// Returns: [] + +difference(undefined, [1, 2]); +// Returns: [] + +difference([1, 2, 3], null, undefined); +// Returns: [1, 2, 3] (null과 undefined는 무시됨) +``` + +유사 배열 객체도 지원해요. + +```typescript +import { difference } from 'es-toolkit/compat'; + +// 유사 배열 객체 +const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; +const arrayLike2 = { 0: 2, 1: 4, length: 2 }; +difference(arrayLike1, arrayLike2); +// Returns: [1, 3] +``` + +#### 파라미터 + +- `arr` (`ArrayLike | null | undefined`): 차집합을 구할 기준 배열이에요. +- `values` (`...ArrayLike[]`): 제외할 값들을 포함한 배열들이에요. + +#### 반환 값 + +(`T[]`): 첫 번째 배열에서 다른 배열들의 값들을 제외한 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/differenceBy.md b/docs/ko/compat/reference/array/differenceBy.md new file mode 100644 index 000000000..caf4d3251 --- /dev/null +++ b/docs/ko/compat/reference/array/differenceBy.md @@ -0,0 +1,88 @@ +# differenceBy (Lodash 호환성) + +::: warning `es-toolkit`의 `differenceBy`를 사용하세요 + +이 `differenceBy` 함수는 복잡한 인자 처리와 반복자 변환으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [differenceBy](../../../reference/array/differenceBy.md)를 사용하세요. + +::: + +반복자 함수로 변환한 값들을 기준으로 첫 번째 배열에서 다른 배열들의 요소를 제외한 차집합을 구해요. + +```typescript +const result = differenceBy(array, ...values, iteratee); +``` + +## 사용법 + +### `differenceBy(array, ...values, iteratee)` + +첫 번째 배열의 각 요소와 제외할 배열들의 요소들을 반복자 함수로 변환한 후, 같은 값이 나오는 요소들을 제거하고 싶을 때 `differenceBy`를 사용하세요. 객체 배열에서 특정 프로퍼티 값이나 변환된 값을 기준으로 비교할 때 유용해요. + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// 소수점 버림으로 비교 +differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); +// Returns: [1.2] (Math.floor(2.1) === Math.floor(2.3)이므로 2.1 제외) + +// 문자열 길이로 비교 +differenceBy(['one', 'two', 'three'], ['four', 'eight'], 'length'); +// Returns: ['one', 'two'] (three와 eight은 길이가 같으므로 three 제외) + +// 객체의 프로퍼티로 비교 +const users1 = [ + { id: 1, name: 'Alice' }, + { id: 2, name: 'Bob' }, +]; +const users2 = [{ id: 1, name: 'Different Alice' }]; +differenceBy(users1, users2, 'id'); +// Returns: [{ id: 2, name: 'Bob' }] (id가 1인 객체 제외) +``` + +여러 배열을 한 번에 제외할 수 있어요. + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// 여러 배열에서 제외 +differenceBy([2.1, 1.2, 3.5], [2.3], [1.4], [3.2], Math.floor); +// Returns: [] (모든 요소가 제외됨) + +// 문자열 배열에서 길이로 비교 +differenceBy(['a', 'bb', 'ccc'], ['x'], ['yy'], ['zzz'], 'length'); +// Returns: [] (길이 1, 2, 3 모두 제외됨) +``` + +반복자 함수가 없으면 일반 `difference`처럼 동작해요. + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// 반복자 함수 없이 사용 +differenceBy([1, 2, 3], [2, 4]); +// Returns: [1, 3] +``` + +`null`이나 `undefined` 배열은 빈 배열로 처리해요. + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +differenceBy(null, [1, 2], Math.floor); +// Returns: [] + +differenceBy(undefined, [1, 2], x => x); +// Returns: [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 차집합을 구할 기준 배열이에요. +- `values` (`...ArrayLike[]`): 제외할 값들을 포함한 배열들이에요. +- `iteratee` (`ValueIteratee`): 각 요소를 비교할 값으로 변환하는 함수예요. 함수, 프로퍼티 이름, 또는 부분 객체를 사용할 수 있어요. + +#### 반환 값 + +(`T[]`): 반복자 함수로 변환한 값들을 기준으로 제외된 요소들을 뺀 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/differenceWith.md b/docs/ko/compat/reference/array/differenceWith.md new file mode 100644 index 000000000..f87f97482 --- /dev/null +++ b/docs/ko/compat/reference/array/differenceWith.md @@ -0,0 +1,79 @@ +# differenceWith (Lodash 호환성) + +::: warning `es-toolkit`의 `differenceWith`를 사용하세요 + +이 `differenceWith` 함수는 `null`이나 `undefined` 처리, 여러 배열 처리, `ArrayLike` 타입 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [differenceWith](../../../reference/array/differenceWith.md)를 사용하세요. + +::: + +비교 함수를 사용해서 첫 번째 배열에서 다른 배열들에 포함된 요소들을 제거해요. + +```typescript +const result = differenceWith(array, ...values, comparator); +``` + +## 사용법 + +### `differenceWith(array, ...values, comparator)` + +각 요소를 비교 함수로 비교해서 차이를 구하고 싶을 때 `differenceWith`를 사용하세요. 마지막 인수가 비교 함수가 돼요. + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +// 객체를 id로 비교해요. +const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; +const others = [{ id: 2 }]; +const comparator = (a, b) => a.id === b.id; + +differenceWith(objects, others, comparator); +// Returns: [{ id: 1 }, { id: 3 }] + +// 여러 배열을 한 번에 제외해요. +const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]; +const values1 = [{ id: 2 }]; +const values2 = [{ id: 3 }]; + +differenceWith(array, values1, values2, comparator); +// Returns: [{ id: 1 }, { id: 4 }] +``` + +비교 함수를 제공하지 않으면 일반적인 `difference`처럼 동작해요. + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +// 비교 함수 없이 사용하면 일반적인 비교를 해요. +differenceWith([1, 2, 3], [2], [3]); +// Returns: [1] +``` + +복잡한 비교 로직도 사용할 수 있어요. + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +const users = [ + { name: 'alice', age: 25 }, + { name: 'bob', age: 30 }, + { name: 'charlie', age: 35 }, +]; +const excludeUsers = [{ name: 'bob', age: 25 }]; // 다른 나이 + +// 이름만으로 비교해요. +const compareByName = (a, b) => a.name === b.name; +differenceWith(users, excludeUsers, compareByName); +// Returns: [{ name: 'alice', age: 25 }, { name: 'charlie', age: 35 }] +// bob이 제외돼요 (나이는 달라도 이름이 같아서) +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 차이를 구할 기준 배열이에요. +- `...values` (`Array>` + `(a: T, b: T) => boolean`): 제외할 요소들이 포함된 배열들과 마지막에 비교 함수예요. + +#### 반환 값 + +(`T[]`): 비교 함수를 사용해서 첫 번째 배열에서 나머지 배열들의 요소를 제거한 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/drop.md b/docs/ko/compat/reference/array/drop.md new file mode 100644 index 000000000..32838fe20 --- /dev/null +++ b/docs/ko/compat/reference/array/drop.md @@ -0,0 +1,97 @@ +# drop (Lodash 호환성) + +::: warning `es-toolkit`의 `drop`을 사용하세요 + +이 `drop` 함수는 `null`이나 `undefined` 처리, `toInteger` 변환 등으로 인해 복잡하게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [drop](../../../reference/array/drop.md)을 사용하세요. + +::: + +배열의 앞에서부터 지정된 개수만큼 요소들을 제거해요. + +```typescript +const result = drop(array, n); +``` + +## 사용법 + +### `drop(array, n?)` + +배열의 처음 부분에서 몇 개의 요소를 제거하고 나머지를 얻고 싶을 때 `drop`을 사용하세요. 기본적으로 첫 번째 요소 하나를 제거해요. + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 기본 사용법 (첫 번째 요소 제거) +drop([1, 2, 3, 4, 5]); +// Returns: [2, 3, 4, 5] + +// 처음 2개 요소 제거 +drop([1, 2, 3, 4, 5], 2); +// Returns: [3, 4, 5] + +// 처음 3개 요소 제거 +drop(['a', 'b', 'c', 'd'], 3); +// Returns: ['d'] +``` + +0이나 음수를 지정하면 원본 배열을 그대로 반환해요. + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 0개 제거 +drop([1, 2, 3], 0); +// Returns: [1, 2, 3] + +// 음수 지정 +drop([1, 2, 3], -1); +// Returns: [1, 2, 3] +``` + +배열보다 큰 수를 지정하면 빈 배열을 반환해요. + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 배열 크기보다 큰 수 지정 +drop([1, 2, 3], 5); +// Returns: [] + +// 빈 배열에서 제거 +drop([], 1); +// Returns: [] +``` + +`null`이나 `undefined` 배열은 빈 배열로 처리해요. + +```typescript +import { drop } from 'es-toolkit/compat'; + +drop(null, 1); +// Returns: [] + +drop(undefined, 2); +// Returns: [] +``` + +유사 배열 객체도 지원해요. + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 유사 배열 객체 +const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; +drop(arrayLike, 1); +// Returns: ['b', 'c'] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 요소를 제거할 배열이에요. +- `n` (`number`, 선택): 제거할 요소의 개수예요. 기본값은 `1`이에요. + +#### 반환 값 + +(`T[]`): 앞에서 지정된 개수만큼 제거된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/dropRight.md b/docs/ko/compat/reference/array/dropRight.md new file mode 100644 index 000000000..ce1417533 --- /dev/null +++ b/docs/ko/compat/reference/array/dropRight.md @@ -0,0 +1,55 @@ +# dropRight (Lodash 호환성) + +::: warning `es-toolkit`의 `dropRight`를 사용하세요 + +이 `dropRight` 함수는 `null`이나 `undefined` 처리, `guard` 파라미터 처리, `toInteger` 변환 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [dropRight](../../../reference/array/dropRight.md)를 사용하세요. + +::: + +배열의 끝에서부터 지정된 개수만큼 요소를 제거한 새로운 배열을 반환해요. + +```typescript +const result = dropRight(array, itemsCount); +``` + +## 사용법 + +### `dropRight(array, itemsCount)` + +배열의 끝부터 특정 개수의 요소를 제거하고 나머지 요소들로 새로운 배열을 만들고 싶을 때 `dropRight`를 사용하세요. + +```typescript +import { dropRight } from 'es-toolkit/compat'; + +// 숫자 배열에서 끝의 2개 요소를 제거해요. +dropRight([1, 2, 3, 4, 5], 2); +// Returns: [1, 2, 3] + +// 문자열 배열에서 끝의 1개 요소를 제거해요. +dropRight(['a', 'b', 'c'], 1); +// Returns: ['a', 'b'] + +// 제거할 개수를 지정하지 않으면 기본값 1을 사용해요. +dropRight([1, 2, 3]); +// Returns: [1, 2] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { dropRight } from 'es-toolkit/compat'; + +dropRight(null, 2); // [] +dropRight(undefined, 2); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 요소를 제거할 배열이에요. +- `itemsCount` (`number`, 선택): 배열의 끝에서부터 제거할 요소의 개수예요. 기본값은 `1`이에요. + +#### 반환 값 + +(`T[]`): 끝에서부터 `itemsCount`개의 요소가 제거된 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/dropRightWhile.md b/docs/ko/compat/reference/array/dropRightWhile.md new file mode 100644 index 000000000..f447a2f71 --- /dev/null +++ b/docs/ko/compat/reference/array/dropRightWhile.md @@ -0,0 +1,65 @@ +# dropRightWhile (Lodash 호환성) + +::: warning `es-toolkit`의 `dropRightWhile`을 사용하세요 + +이 `dropRightWhile` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [dropRightWhile](../../../reference/array/dropRightWhile.md)을 사용하세요. + +::: + +조건 함수에 따라 배열의 끝에서부터 요소를 제거해요. + +```typescript +const result = dropRightWhile(array, predicate); +``` + +## 사용법 + +### `dropRightWhile(array, predicate)` + +배열의 끝에서부터 특정 조건을 만족하는 요소들을 연속으로 제거하고 싶을 때 `dropRightWhile`을 사용하세요. 조건 함수가 `false`를 반환하면 제거를 중단해요. + +```typescript +import { dropRightWhile } from 'es-toolkit/compat'; + +// 함수를 조건으로 사용해요. +const users = [ + { user: 'barney', active: true }, + { user: 'fred', active: false }, + { user: 'pebbles', active: false }, +]; + +dropRightWhile(users, user => !user.active); +// Returns: [{ user: 'barney', active: true }] + +// 객체 패턴으로 매칭해요. +dropRightWhile(users, { user: 'pebbles', active: false }); +// Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }] + +// 배열 형태로 속성과 값을 지정해요. +dropRightWhile(users, ['active', false]); +// Returns: [{ user: 'barney', active: true }] + +// 속성 이름으로 조건을 확인해요. +dropRightWhile(users, 'active'); +// Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { dropRightWhile } from 'es-toolkit/compat'; + +dropRightWhile(null, x => x > 0); // [] +dropRightWhile(undefined, x => x > 0); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 요소를 제거할 배열이에요. +- `predicate` (`ListIteratee`, 선택): 각 요소에 적용할 조건 함수예요. 함수, 객체 패턴, 배열 패턴, 또는 속성 이름을 받을 수 있어요. + +#### 반환 값 + +(`T[]`): 조건을 만족하지 않는 첫 번째 요소부터의 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/dropWhile.md b/docs/ko/compat/reference/array/dropWhile.md new file mode 100644 index 000000000..99b1d4397 --- /dev/null +++ b/docs/ko/compat/reference/array/dropWhile.md @@ -0,0 +1,67 @@ +# dropWhile (Lodash 호환성) + +::: warning `es-toolkit`의 `dropWhile`을 사용하세요 + +이 `dropWhile` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [dropWhile](../../../reference/array/dropWhile.md)을 사용하세요. + +::: + +조건 함수에 따라 배열의 시작에서부터 요소를 제거해요. + +```typescript +const result = dropWhile(array, predicate); +``` + +## 사용법 + +### `dropWhile(array, predicate)` + +배열의 시작에서부터 특정 조건을 만족하는 요소들을 연속으로 제거하고 싶을 때 `dropWhile`을 사용하세요. 조건 함수가 `false`를 반환하면 제거를 중단해요. + +```typescript +import { dropWhile } from 'es-toolkit/compat'; + +// 함수를 조건으로 사용해요. +dropWhile([1, 2, 3, 4, 5], n => n < 3); +// Returns: [3, 4, 5] + +// 객체 패턴으로 매칭해요. +const users = [ + { name: 'alice', active: false }, + { name: 'bob', active: false }, + { name: 'charlie', active: true }, +]; + +dropWhile(users, { active: false }); +// Returns: [{ name: 'charlie', active: true }] + +// 배열 형태로 속성과 값을 지정해요. +dropWhile(users, ['active', false]); +// Returns: [{ name: 'charlie', active: true }] + +// 속성 이름으로 조건을 확인해요. +const items = [{ visible: false }, { visible: false }, { visible: true }]; + +dropWhile(items, 'visible'); +// Returns: [{ visible: false }, { visible: false }, { visible: true }] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { dropWhile } from 'es-toolkit/compat'; + +dropWhile(null, x => x > 0); // [] +dropWhile(undefined, x => x > 0); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 요소를 제거할 배열이에요. +- `predicate` (`ListIteratee`, 선택): 각 요소에 적용할 조건 함수예요. 함수, 객체 패턴, 배열 패턴, 또는 속성 이름을 받을 수 있어요. 기본값은 `identity`예요. + +#### 반환 값 + +(`T[]`): 조건을 만족하지 않는 첫 번째 요소부터의 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/each.md b/docs/ko/compat/reference/array/each.md similarity index 100% rename from docs/ko/reference/compat/array/each.md rename to docs/ko/compat/reference/array/each.md diff --git a/docs/ko/compat/reference/array/eachRight.md b/docs/ko/compat/reference/array/eachRight.md new file mode 100644 index 000000000..4705d1f03 --- /dev/null +++ b/docs/ko/compat/reference/array/eachRight.md @@ -0,0 +1,58 @@ +# eachRight (Lodash 호환성) + +::: warning `es-toolkit`의 `forEachRight`을 사용하세요 + +이 `eachRight` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [forEachRight](../../../reference/array/forEachRight.md)을 사용하세요. + +::: + +배열이나 객체의 각 요소에 대해 오른쪽부터 왼쪽으로 반복 작업을 수행해요. + +```typescript +const result = eachRight(collection, iteratee); +``` + +## 사용법 + +### `eachRight(collection, iteratee)` + +배열, 객체, 문자열의 각 요소를 오른쪽부터 왼쪽으로 순회하면서 주어진 함수를 실행해요. 배열의 경우 마지막 인덱스부터 역순으로, 객체의 경우 열거 가능한 속성들을 역순으로 순회해요. + +```typescript +import { eachRight } from 'es-toolkit/compat'; + +// 배열 역순 순회 +eachRight([1, 2, 3], (value, index) => console.log(value, index)); +// 로그: 3 2, 2 1, 1 0 + +// 객체 역순 순회 +eachRight({ a: 1, b: 2 }, (value, key) => console.log(key, value)); +// 로그: 'b' 2, 'a' 1 + +// 문자열 역순 순회 +eachRight('hello', (char, index) => console.log(char, index)); +// 로그: 'o' 4, 'l' 3, 'l' 2, 'e' 1, 'h' 0 +``` + +함수가 `false`를 반환하면 순회를 중단해요. + +```typescript +import { eachRight } from 'es-toolkit/compat'; + +eachRight([1, 2, 3, 4], value => { + console.log(value); + return value !== 2; // 2에서 중단 +}); +// 로그: 4, 3, 2 +``` + +#### 파라미터 + +- `collection` (`ArrayLike | Record | string | null | undefined`): 순회할 컬렉션이에요. +- `iteratee` (`(item: any, index: any, collection: any) => unknown`, 선택): 각 요소에 대해 실행할 함수예요. 기본값은 `identity` 함수예요. + +#### 반환 값 + +(`ArrayLike | Record | string | null | undefined`): 원본 컬렉션을 반환해요. diff --git a/docs/ko/reference/compat/array/every.md b/docs/ko/compat/reference/array/every.md similarity index 100% rename from docs/ko/reference/compat/array/every.md rename to docs/ko/compat/reference/array/every.md diff --git a/docs/ko/compat/reference/array/fill.md b/docs/ko/compat/reference/array/fill.md new file mode 100644 index 000000000..37bfe029b --- /dev/null +++ b/docs/ko/compat/reference/array/fill.md @@ -0,0 +1,82 @@ +# fill (Lodash 호환성) + +::: warning `es-toolkit`의 `fill`을 사용하세요 + +이 `fill` 함수는 `null`이나 `undefined` 처리, 유사 배열 객체 지원 등으로 인해 복잡하게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [fill](../../../reference/array/fill.md)을 사용하세요. + +::: + +배열의 요소들을 지정된 값으로 채워요. + +```typescript +const result = fill(array, value, start, end); +``` + +## 사용법 + +### `fill(array, value, start?, end?)` + +배열의 특정 범위나 전체를 동일한 값으로 채우고 싶을 때 `fill`을 사용하세요. 원본 배열을 직접 수정해요. + +```typescript +import { fill } from 'es-toolkit/compat'; + +// 전체 배열 채우기 +const arr1 = [1, 2, 3]; +fill(arr1, 'a'); +// Returns: ['a', 'a', 'a'] + +// 특정 범위 채우기 +const arr2 = [1, 2, 3, 4, 5]; +fill(arr2, '*', 1, 4); +// Returns: [1, '*', '*', '*', 5] + +// 음수 인덱스 사용 +const arr3 = [1, 2, 3, 4, 5]; +fill(arr3, 'x', -3, -1); +// Returns: [1, 2, 'x', 'x', 5] +``` + +유사 배열 객체도 지원해요. + +```typescript +import { fill } from 'es-toolkit/compat'; + +const arrayLike = { 0: 1, 1: 2, 2: 3, length: 3 }; +fill(arrayLike, 'a', 1, 2); +// Returns: { 0: 1, 1: 'a', 2: 3, length: 3 } +``` + +`null`이나 `undefined` 배열은 빈 배열로 처리해요. + +```typescript +import { fill } from 'es-toolkit/compat'; + +fill(null, 'a'); +// Returns: [] + +fill(undefined, 'a'); +// Returns: [] +``` + +문자열은 읽기 전용이므로 그대로 반환해요. + +```typescript +import { fill } from 'es-toolkit/compat'; + +fill('abc', 'x'); +// Returns: 'abc' (변경되지 않음) +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 채울 배열이에요. +- `value` (`U`): 배열을 채울 값이에요. +- `start` (`number`, 선택): 시작 위치예요. 기본값은 `0`이에요. +- `end` (`number`, 선택): 끝 위치예요 (포함되지 않음). 기본값은 `array.length`예요. + +#### 반환 값 + +(`ArrayLike`): 값으로 채워진 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/filter.md b/docs/ko/compat/reference/array/filter.md similarity index 100% rename from docs/ko/reference/compat/array/filter.md rename to docs/ko/compat/reference/array/filter.md diff --git a/docs/ko/reference/compat/array/find.md b/docs/ko/compat/reference/array/find.md similarity index 100% rename from docs/ko/reference/compat/array/find.md rename to docs/ko/compat/reference/array/find.md diff --git a/docs/ko/reference/compat/array/findIndex.md b/docs/ko/compat/reference/array/findIndex.md similarity index 100% rename from docs/ko/reference/compat/array/findIndex.md rename to docs/ko/compat/reference/array/findIndex.md diff --git a/docs/ko/reference/compat/array/findLast.md b/docs/ko/compat/reference/array/findLast.md similarity index 100% rename from docs/ko/reference/compat/array/findLast.md rename to docs/ko/compat/reference/array/findLast.md diff --git a/docs/ko/reference/compat/array/findLastIndex.md b/docs/ko/compat/reference/array/findLastIndex.md similarity index 100% rename from docs/ko/reference/compat/array/findLastIndex.md rename to docs/ko/compat/reference/array/findLastIndex.md diff --git a/docs/ko/compat/reference/array/first.md b/docs/ko/compat/reference/array/first.md new file mode 100644 index 000000000..f3e1d8653 --- /dev/null +++ b/docs/ko/compat/reference/array/first.md @@ -0,0 +1,78 @@ +# first (Lodash 호환성) + +::: warning `es-toolkit`의 `head`를 사용하세요 + +이 `first` 함수는 `null`이나 `undefined` 처리와 배열 형태의 객체 변환으로 인해 느리게 동작해요. `es-toolkit`의 `head` 함수는 이러한 추가 처리 없이 더 빠르고 간단하게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [head](../../../reference/array/head.md)를 사용하세요. + +::: + +배열의 첫 번째 요소를 반환해요. + +```typescript +const firstElement = first(array); +``` + +## 사용법 + +### `first(array)` + +배열의 첫 번째 요소를 가져오고 싶을 때 `first`를 사용하세요. 배열이 비어있거나 `null`, `undefined`인 경우 `undefined`를 반환해요. + +```typescript +import { first } from 'es-toolkit/compat'; + +// 일반 배열에서 첫 번째 요소 가져오기 +first([1, 2, 3]); +// Returns: 1 + +// 문자열 배열에서 첫 번째 요소 가져오기 +first(['a', 'b', 'c']); +// Returns: 'a' + +// 빈 배열 +first([]); +// Returns: undefined +``` + +`null`이나 `undefined`는 `undefined`를 반환해요. + +```typescript +import { first } from 'es-toolkit/compat'; + +first(null); // undefined +first(undefined); // undefined +``` + +배열 형태의 객체에서도 사용할 수 있어요. + +```typescript +import { first } from 'es-toolkit/compat'; + +const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; +first(arrayLike); +// Returns: 'a' + +// 문자열도 배열처럼 처리됨 +first('hello'); +// Returns: 'h' +``` + +타입이 보장된 튜플에서는 정확한 타입을 반환해요. + +```typescript +import { first } from 'es-toolkit/compat'; + +const tuple = [1, 'two', true] as const; +first(tuple); +// Returns: 1 (타입이 1로 추론됨) +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 첫 번째 요소를 가져올 배열이에요. + +#### 반환 값 + +(`T | undefined`): 배열의 첫 번째 요소를 반환해요. 배열이 비어있거나 유효하지 않으면 `undefined`를 반환해요. diff --git a/docs/ko/compat/reference/array/flatMap.md b/docs/ko/compat/reference/array/flatMap.md new file mode 100644 index 000000000..910a3188b --- /dev/null +++ b/docs/ko/compat/reference/array/flatMap.md @@ -0,0 +1,77 @@ +# flatMap (Lodash 호환성) + +::: warning `es-toolkit`의 `flatMap`을 사용하세요 + +이 `flatMap` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [flatMap](../../../reference/array/flatMap.md)을 사용하세요. + +::: + +각 요소에 함수를 적용한 후 결과를 평탄화해요. + +```typescript +const result = flatMap(collection, iteratee); +``` + +## 사용법 + +### `flatMap(collection, iteratee)` + +컬렉션의 각 요소에 반복자 함수를 적용한 후 한 단계 평탄화한 배열을 반환해요. 배열, 객체, 문자열을 지원하며 다양한 형태의 반복자를 사용할 수 있어요. + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +// 배열에 함수 적용 +function duplicate(n) { + return [n, n]; +} +flatMap([1, 2], duplicate); +// 결과: [1, 1, 2, 2] + +// 객체에 함수 적용 +const obj = { a: 1, b: 2 }; +flatMap(obj, (value, key) => [key, value]); +// 결과: ['a', 1, 'b', 2] + +// 문자열 속성으로 매핑 +const users = [ + { user: 'barney', hobbies: ['hiking', 'coding'] }, + { user: 'fred', hobbies: ['reading'] }, +]; +flatMap(users, 'hobbies'); +// 결과: ['hiking', 'coding', 'reading'] +``` + +반복자 없이 사용하면 값들을 한 단계 평탄화해요. + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +const obj = { a: [1, 2], b: [3, 4] }; +flatMap(obj); +// 결과: [1, 2, 3, 4] +``` + +부분 객체로 조건 매핑도 가능해요. + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +const users = [ + { user: 'barney', age: 36, active: true }, + { user: 'fred', age: 40, active: false }, +]; +flatMap(users, { active: false }); +// 결과: [false, true] (active가 false인 요소들의 매칭 결과) +``` + +#### 파라미터 + +- `collection` (`object | null | undefined`): 순회할 컬렉션이에요. 배열, 객체, 문자열이 될 수 있어요. +- `iteratee` (`ListIterator | ObjectIterator | string | object`, 선택): 각 요소에 적용할 반복자예요. 함수, 속성 이름, 또는 부분 객체가 될 수 있어요. + +#### 반환 값 + +(`any[]`): 매핑 후 한 단계 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/flatMapDeep.md b/docs/ko/compat/reference/array/flatMapDeep.md new file mode 100644 index 000000000..27076d0c8 --- /dev/null +++ b/docs/ko/compat/reference/array/flatMapDeep.md @@ -0,0 +1,77 @@ +# flatMapDeep (Lodash 호환성) + +::: warning `es-toolkit`의 [`flatMapDeep`](../../../reference/array/flatMapDeep.md)를 사용하세요 + +이 `flatMapDeep` 함수는 복잡한 컬렉션 타입 처리와 깊은 평탄화 로직으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [flatMapDeep](../../../reference/array/flatMapDeep.md)를 사용하세요. + +::: + +각 요소에 함수를 적용한 후 결과를 재귀적으로 평탄화해요. + +```typescript +const result = flatMapDeep(collection, iteratee); +``` + +## 사용법 + +### `flatMapDeep(collection, iteratee)` + +컬렉션의 각 요소에 반복자 함수를 적용한 후 무한 깊이로 평탄화한 배열을 반환해요. 중첩된 배열 구조가 모두 평탄화되어 1차원 배열이 됩니다. + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +// 배열에 함수 적용 후 깊은 평탄화 +function duplicate(n) { + return [[[n, n]]]; +} +flatMapDeep([1, 2], duplicate); +// 결과: [1, 1, 2, 2] + +// 객체에 함수 적용 후 깊은 평탄화 +const obj = { a: 1, b: 2 }; +flatMapDeep(obj, (value, key) => [[[key, value]]]); +// 결과: ['a', 1, 'b', 2] + +// 문자열 속성으로 매핑 후 깊은 평탄화 +const users = [ + { user: 'barney', hobbies: [['hiking', 'coding']] }, + { user: 'fred', hobbies: [['reading']] }, +]; +flatMapDeep(users, 'hobbies'); +// 결과: ['hiking', 'coding', 'reading'] +``` + +반복자 없이 사용하면 값들을 재귀적으로 평탄화해요. + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +const obj = { a: [[1, 2]], b: [[[3]]] }; +flatMapDeep(obj); +// 결과: [1, 2, 3] +``` + +부분 객체로 조건 매핑도 가능해요. + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +const users = [ + { user: 'barney', active: [true, false] }, + { user: 'fred', active: [false] }, +]; +flatMapDeep(users, { active: [false] }); +// 결과: [true, true] (active 배열에 [false]가 포함된 요소들의 매칭 결과) +``` + +#### 파라미터 + +- `collection` (`object | null | undefined`): 순회할 컬렉션이에요. 배열, 객체, 문자열이 될 수 있어요. +- `iteratee` (`ListIterator | ObjectIterator | string | object`, 선택): 각 요소에 적용할 반복자예요. 함수, 속성 이름, 또는 부분 객체가 될 수 있어요. + +#### 반환 값 + +(`any[]`): 매핑 후 재귀적으로 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/flatMapDepth.md b/docs/ko/compat/reference/array/flatMapDepth.md new file mode 100644 index 000000000..5cba7aebf --- /dev/null +++ b/docs/ko/compat/reference/array/flatMapDepth.md @@ -0,0 +1,79 @@ +# flatMapDepth (Lodash 호환성) + +::: warning `es-toolkit`의 [flatMap](../../../reference/array/flatMap.md)을 사용하세요 + +이 `flatMapDepth` 함수는 Lodash와의 호환성을 위해 여러 형태의 iteratee를 지원하고 `null`이나 `undefined` 처리 등으로 인해 복잡하게 구현되어 있어요. 메인 라이브러리의 `flatMap` 함수는 간단한 함수 iteratee만 지원하므로 더 빠르게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [flatMap](../../../reference/array/flatMap.md)를 사용하세요. + +::: + +배열의 각 요소를 iteratee 함수로 변환한 후 지정된 깊이까지 평탄화해요. + +```typescript +const result = flatMapDepth(collection, iteratee, depth); +``` + +## 사용법 + +### `flatMapDepth(collection, iteratee, depth)` + +배열이나 객체의 각 요소를 주어진 함수로 변환한 후, 결과를 지정된 깊이까지 평탄화해서 새 배열로 반환해요. 중첩된 배열 구조를 원하는 깊이까지만 평탄화할 때 유용해요. + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +// 배열을 변환하고 깊이 2까지 평탄화 +flatMapDepth([1, 2], n => [[n, n]], 2); +// => [1, 1, 2, 2] + +// 깊이 1로 제한하면 완전히 평탄화되지 않아요 +flatMapDepth([1, 2], n => [[n, n]], 1); +// => [[1, 1], [2, 2]] + +// 객체에서 값을 추출하고 평탄화 +const users = [ + { user: 'barney', hobbies: [['hiking'], ['coding']] }, + { user: 'fred', hobbies: [['reading']] }, +]; +flatMapDepth(users, 'hobbies', 2); +// => ['hiking', 'coding', 'reading'] +``` + +이 함수는 다양한 형태의 iteratee를 지원해요. + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +// 함수를 사용한 변환 +flatMapDepth([1, 2, 3], n => [[n, n]], 2); + +// 속성명으로 값 추출 +const objects = [{ items: [['a'], ['b']] }, { items: [['c']] }]; +flatMapDepth(objects, 'items', 2); +// => ['a', 'b', 'c'] + +// 객체의 부분 매칭 +const users = [{ active: [[true], [false]] }, { active: [[false]] }]; +flatMapDepth(users, { active: [[false]] }, 2); +// => [true, true] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +flatMapDepth(null, n => [n], 1); // => [] +flatMapDepth(undefined, n => [n], 1); // => [] +``` + +#### 파라미터 + +- `collection` (`ArrayLike | Record | Record | object | null | undefined`): 순회할 배열이나 객체예요. +- `iteratee` (`((value: T, index: number, collection: any) => any) | string | object`, 선택): 각 요소에 대해 실행할 변환 함수나 속성명이에요. 기본값은 `identity`예요. +- `depth` (`number`, 선택): 평탄화할 최대 깊이예요. 기본값은 `1`이에요. + +#### 반환 값 + +(`T[]`): iteratee로 변환된 후 지정된 깊이까지 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/flatten.md b/docs/ko/compat/reference/array/flatten.md new file mode 100644 index 000000000..68227f49c --- /dev/null +++ b/docs/ko/compat/reference/array/flatten.md @@ -0,0 +1,69 @@ +# flatten (Lodash 호환성) + +::: warning `es-toolkit`의 `flatten`을 사용하세요 + +이 `flatten` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [flatten](../../../reference/array/flatten.md)을 사용하세요. + +::: + +배열을 한 단계 평탄화해요. + +```typescript +const result = flatten(array, depth); +``` + +## 사용법 + +### `flatten(value, depth)` + +중첩 배열을 지정된 깊이만큼 평탄화해요. 기본적으로 한 단계만 평탄화하며, Arguments 객체나 Symbol.isConcatSpreadable을 가진 객체도 지원해요. + +```typescript +import { flatten } from 'es-toolkit/compat'; + +// 기본 평탄화 (한 단계) +flatten([1, [2, [3, [4]], 5]]); +// 결과: [1, 2, [3, [4]], 5] + +// 깊이 지정 +flatten([1, [2, [3, [4]], 5]], 2); +// 결과: [1, 2, 3, [4], 5] + +// Arguments 객체 지원 +function example() { + return flatten(arguments); +} +example(1, [2, 3], [[4]]); +// 결과: [1, 2, 3, [4]] +``` + +빈 배열이나 null, undefined는 빈 배열을 반환해요. + +```typescript +import { flatten } from 'es-toolkit/compat'; + +flatten(null); // [] +flatten(undefined); // [] +flatten([]); // [] +``` + +Symbol.isConcatSpreadable을 가진 객체도 배열처럼 평탄화돼요. + +```typescript +import { flatten } from 'es-toolkit/compat'; + +const spreadable = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true }; +flatten([1, spreadable, 3]); +// 결과: [1, 'a', 'b', 3] +``` + +#### 파라미터 + +- `value` (`ArrayLike | null | undefined`): 평탄화할 배열이에요. +- `depth` (`number`, 선택): 평탄화할 최대 깊이예요. 기본값은 `1`이에요. + +#### 반환 값 + +(`T[]`): 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/flattenDeep.md b/docs/ko/compat/reference/array/flattenDeep.md new file mode 100644 index 000000000..2a0cc34d0 --- /dev/null +++ b/docs/ko/compat/reference/array/flattenDeep.md @@ -0,0 +1,64 @@ +# flattenDeep (Lodash 호환성) + +::: warning `es-toolkit`의 `flattenDeep`을 사용하세요 + +이 `flattenDeep` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [flattenDeep](../../../reference/array/flattenDeep.md)을 사용하세요. + +::: + +배열을 완전히 평탄화해요. + +```typescript +const result = flattenDeep(array); +``` + +## 사용법 + +### `flattenDeep(value)` + +중첩 배열을 모든 깊이에서 재귀적으로 평탄화해요. 모든 중첩 수준이 제거되어 완전히 평탄화된 1차원 배열을 반환해요. + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +// 깊이 중첩된 배열 완전 평탄화 +flattenDeep([1, [2, [3, [4]], 5]]); +// 결과: [1, 2, 3, 4, 5] + +// 복잡한 중첩 구조도 완전 평탄화 +flattenDeep([1, [2, [3, [[[[4]]]]], 5]]); +// 결과: [1, 2, 3, 4, 5] + +// 혼합된 타입도 지원 +flattenDeep(['a', ['b', ['c', [['d']]]]]); +// 결과: ['a', 'b', 'c', 'd'] +``` + +빈 배열이나 null, undefined는 빈 배열을 반환해요. + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +flattenDeep(null); // [] +flattenDeep(undefined); // [] +flattenDeep([]); // [] +``` + +이미 평탄화된 배열은 그대로 복사돼요. + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +flattenDeep([1, 2, 3, 4, 5]); +// 결과: [1, 2, 3, 4, 5] +``` + +#### 파라미터 + +- `value` (`ListOfRecursiveArraysOrValues | null | undefined`): 완전히 평탄화할 배열이에요. + +#### 반환 값 + +(`Array`): 모든 중첩이 제거된 완전히 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/flattenDepth.md b/docs/ko/compat/reference/array/flattenDepth.md new file mode 100644 index 000000000..1c83ce944 --- /dev/null +++ b/docs/ko/compat/reference/array/flattenDepth.md @@ -0,0 +1,55 @@ +# flattenDepth (Lodash 호환성) + +::: warning `es-toolkit`의 `flatten`를 사용하세요 + +이 `flattenDepth` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. `es-toolkit`의 `flatten` 함수는 이러한 추가 처리 없이 더 빠르고 간단하게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [flatten](../../../reference/array/flatten.md)를 사용하세요. + +::: + +배열을 지정한 깊이까지 평탄화해요. + +```typescript +const flattened = flattenDepth(array, depth); +``` + +## 사용법 + +### `flattenDepth(array, depth)` + +중첩된 배열을 원하는 깊이까지 평탄화하고 싶을 때 `flattenDepth`를 사용하세요. 깊이를 지정하면 그 깊이까지만 중첩된 배열을 평탄화해요. + +```typescript +import { flattenDepth } from 'es-toolkit/compat'; + +// 깊이 1까지 평탄화해요. +flattenDepth([1, [2, [3, [4]], 5]], 1); +// Returns: [1, 2, [3, [4]], 5] + +// 깊이 2까지 평탄화해요. +flattenDepth([1, [2, [3, [4]], 5]], 2); +// Returns: [1, 2, 3, [4], 5] + +// 깊이를 지정하지 않으면 기본값 1로 평탄화해요. +flattenDepth([1, [2, [3, [4]], 5]]); +// Returns: [1, 2, [3, [4]], 5] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { flattenDepth } from 'es-toolkit/compat'; + +flattenDepth(null, 2); // [] +flattenDepth(undefined, 2); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 평탄화할 배열이에요. +- `depth` (`number`, 선택): 평탄화할 최대 깊이예요. 기본값은 `1`이에요. + +#### 반환 값 + +(`T[]`): 지정한 깊이까지 평탄화된 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/forEach.md b/docs/ko/compat/reference/array/forEach.md similarity index 100% rename from docs/ko/reference/compat/array/forEach.md rename to docs/ko/compat/reference/array/forEach.md diff --git a/docs/ko/compat/reference/array/forEachRight.md b/docs/ko/compat/reference/array/forEachRight.md new file mode 100644 index 000000000..545a90754 --- /dev/null +++ b/docs/ko/compat/reference/array/forEachRight.md @@ -0,0 +1,75 @@ +# forEachRight (Lodash 호환성) + +::: warning `es-toolkit`의 `forEachRight`을 사용하세요 + +이 `forEachRight` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [forEachRight](../../../reference/array/forEachRight.md)을 사용하세요. + +::: + +배열이나 객체의 요소들을 오른쪽에서 왼쪽으로 순회하면서 각 요소에 대해 함수를 실행해요. + +```typescript +forEachRight(collection, callback); +``` + +## 사용법 + +### `forEachRight(collection, callback)` + +배열, 객체, 문자열을 오른쪽에서 왼쪽 순서로 순회하면서 각 요소에 대해 콜백 함수를 실행해요. 콜백이 `false`를 반환하면 순회를 중단해요. + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +// 배열을 역순으로 순회해요 +forEachRight([1, 2, 3], (value, index) => { + console.log(value, index); +}); +// 출력: 3 2, 2 1, 1 0 + +// 문자열을 역순으로 순회해요 +forEachRight('abc', (char, index) => { + console.log(char, index); +}); +// 출력: 'c' 2, 'b' 1, 'a' 0 + +// 객체를 역순으로 순회해요 +forEachRight({ a: 1, b: 2, c: 3 }, (value, key) => { + console.log(value, key); +}); +// 출력: 3 'c', 2 'b', 1 'a' +``` + +`null`이나 `undefined`는 그대로 반환해요. + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +forEachRight(null, value => console.log(value)); // null +forEachRight(undefined, value => console.log(value)); // undefined +``` + +콜백이 `false`를 반환하면 순회를 중단해요. + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +forEachRight([1, 2, 3, 4], value => { + console.log(value); + if (value === 2) { + return false; // 순회 중단 + } +}); +// 출력: 4, 3, 2 +``` + +#### 파라미터 + +- `collection` (`ArrayLike | Record | string | null | undefined`): 순회할 컬렉션이에요. 배열, 객체, 문자열, 또는 null/undefined일 수 있어요. +- `callback` (`(item: any, index: any, arr: any) => unknown`, 선택): 각 요소에 대해 실행할 함수예요. `false`를 반환하면 순회를 중단해요. 기본값은 `identity` 함수예요. + +#### 반환 값 + +(`ArrayLike | Record | string | null | undefined`): 원본 컬렉션을 그대로 반환해요. diff --git a/docs/ko/compat/reference/array/groupBy.md b/docs/ko/compat/reference/array/groupBy.md new file mode 100644 index 000000000..880174d6e --- /dev/null +++ b/docs/ko/compat/reference/array/groupBy.md @@ -0,0 +1,79 @@ +# groupBy (Lodash 호환성) + +::: warning `es-toolkit`의 [groupBy](../../../reference/array/groupBy.md)를 사용하세요 + +이 `groupBy` 함수는 `null`이나 `undefined` 처리, 객체 지원, 복잡한 타입 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [groupBy](../../../reference/array/groupBy.md)를 사용하세요. + +::: + +배열이나 객체의 요소들을 주어진 조건에 따라 그룹으로 나눠요. + +```typescript +const grouped = groupBy(collection, iteratee); +``` + +## 사용법 + +### `groupBy(collection, iteratee)` + +배열이나 객체의 각 요소를 주어진 조건 함수에 따라 그룹으로 나누고, 그룹별로 분류된 객체를 반환해요. 조건은 함수, 프로퍼티 이름, 부분 객체 등 다양한 형태로 제공할 수 있어요. + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +// 함수로 그룹 나누기 +const array = [6.1, 4.2, 6.3]; +const result = groupBy(array, Math.floor); +// result는 { '4': [4.2], '6': [6.1, 6.3] } + +// 프로퍼티 이름으로 그룹 나누기 +const users = [ + { name: 'john', age: 30 }, + { name: 'jane', age: 25 }, + { name: 'bob', age: 30 }, +]; +const byAge = groupBy(users, 'age'); +// byAge는 { '25': [{ name: 'jane', age: 25 }], '30': [{ name: 'john', age: 30 }, { name: 'bob', age: 30 }] } + +// 객체에서 그룹 나누기 +const obj = { a: 6.1, b: 4.2, c: 6.3 }; +const groupedObj = groupBy(obj, Math.floor); +// groupedObj는 { '4': [4.2], '6': [6.1, 6.3] } +``` + +`null`이나 `undefined`는 빈 객체로 처리해요. + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +groupBy(null, x => x); // {} +groupBy(undefined, x => x); // {} +``` + +부분 객체나 프로퍼티-값 쌍으로도 그룹을 나눌 수 있어요. + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +const products = [ + { category: 'fruit', name: 'apple' }, + { category: 'fruit', name: 'banana' }, + { category: 'vegetable', name: 'carrot' }, +]; + +// 부분 객체로 그룹 나누기 +const byCategory = groupBy(products, { category: 'fruit' }); +// 프로퍼티-값 쌍으로 그룹 나누기 +const byName = groupBy(products, ['name', 'apple']); +``` + +#### 파라미터 + +- `collection` (`ArrayLike | Record | null | undefined`): 그룹으로 나눌 배열이나 객체예요. +- `iteratee` (`Function | PropertyKey | Array | Object`, 선택): 그룹을 나누는 조건이에요. 함수, 프로퍼티 이름, 프로퍼티-값 쌍, 또는 부분 객체일 수 있어요. 기본값은 `identity` 함수예요. + +#### 반환 값 + +(`Record`): 각 키가 그룹의 조건값이고, 값이 해당 그룹에 속하는 요소들의 배열인 객체를 반환해요. diff --git a/docs/ko/compat/reference/array/head.md b/docs/ko/compat/reference/array/head.md new file mode 100644 index 000000000..598b92415 --- /dev/null +++ b/docs/ko/compat/reference/array/head.md @@ -0,0 +1,61 @@ +# head (Lodash 호환성) + +::: warning `es-toolkit`의 [head](../../../reference/array/head.md)를 사용하세요 + +이 `head` 함수는 `ArrayLike` 객체 처리와 배열 변환 과정으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [head](../../../reference/array/head.md)를 사용하세요. + +::: + +배열의 첫 번째 요소를 반환해요. + +```typescript +const firstElement = head(array); +``` + +## 사용법 + +### `head(array)` + +배열이나 배열 형태 객체의 첫 번째 요소를 반환해요. 배열이 비어있거나 유효하지 않으면 `undefined`를 반환해요. + +```typescript +import { head } from 'es-toolkit/compat'; + +// 숫자 배열의 첫 번째 요소 +const numbers = [1, 2, 3, 4]; +const first = head(numbers); +// first는 1 + +// 문자열 배열의 첫 번째 요소 +const strings = ['a', 'b', 'c']; +const firstChar = head(strings); +// firstChar는 'a' + +// 배열 형태 객체 +const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; +const firstItem = head(arrayLike); +// firstItem은 'x' +``` + +빈 배열이나 유효하지 않은 입력은 `undefined`를 반환해요. + +```typescript +import { head } from 'es-toolkit/compat'; + +const emptyArray: number[] = []; +const noElement = head(emptyArray); +// noElement는 undefined + +head(null); // undefined +head(undefined); // undefined +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 첫 번째 요소를 가져올 배열이나 배열 형태 객체예요. + +#### 반환 값 + +(`T | undefined`): 배열의 첫 번째 요소를 반환하고, 배열이 비어있거나 유효하지 않으면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/array/includes.md b/docs/ko/compat/reference/array/includes.md similarity index 100% rename from docs/ko/reference/compat/array/includes.md rename to docs/ko/compat/reference/array/includes.md diff --git a/docs/ko/reference/compat/array/indexOf.md b/docs/ko/compat/reference/array/indexOf.md similarity index 100% rename from docs/ko/reference/compat/array/indexOf.md rename to docs/ko/compat/reference/array/indexOf.md diff --git a/docs/ko/compat/reference/array/initial.md b/docs/ko/compat/reference/array/initial.md new file mode 100644 index 000000000..875ccebb8 --- /dev/null +++ b/docs/ko/compat/reference/array/initial.md @@ -0,0 +1,65 @@ +# initial (Lodash 호환성) + +::: warning `es-toolkit`의 [initial](../../../reference/array/initial.md)을 사용하세요 + +이 `initial` 함수는 `ArrayLike` 객체 처리와 배열 변환 과정으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [initial](../../../reference/array/initial.md)을 사용하세요. + +::: + +배열에서 마지막 요소를 제외한 모든 요소를 새 배열로 반환해요. + +```typescript +const result = initial(array); +``` + +## 사용법 + +### `initial(array)` + +배열이나 배열 형태 객체에서 마지막 요소를 제외한 모든 요소를 포함하는 새 배열을 반환해요. 배열이 비어있거나 요소가 하나뿐이면 빈 배열을 반환해요. + +```typescript +import { initial } from 'es-toolkit/compat'; + +// 숫자 배열에서 마지막 요소 제외 +const numbers = [1, 2, 3, 4]; +const result = initial(numbers); +// result는 [1, 2, 3] + +// 문자열 배열에서 마지막 요소 제외 +const strings = ['a', 'b', 'c', 'd']; +const withoutLast = initial(strings); +// withoutLast는 ['a', 'b', 'c'] + +// 배열 형태 객체 +const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; +const items = initial(arrayLike); +// items는 ['x', 'y'] +``` + +빈 배열이나 유효하지 않은 입력은 빈 배열을 반환해요. + +```typescript +import { initial } from 'es-toolkit/compat'; + +const emptyArray: number[] = []; +const result = initial(emptyArray); +// result는 [] + +const singleItem = [42]; +const onlyOne = initial(singleItem); +// onlyOne은 [] + +initial(null); // [] +initial(undefined); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 마지막 요소를 제외할 배열이나 배열 형태 객체예요. + +#### 반환 값 + +(`T[]`): 마지막 요소를 제외한 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/intersection.md b/docs/ko/compat/reference/array/intersection.md new file mode 100644 index 000000000..aa72b9a1e --- /dev/null +++ b/docs/ko/compat/reference/array/intersection.md @@ -0,0 +1,80 @@ +# intersection (Lodash 호환성) + +::: warning `es-toolkit`의 [intersection](../../../reference/array/intersection.md)을 사용하세요 + +이 `intersection` 함수는 `null`이나 `undefined` 처리, 다중 배열 지원, 중복 제거 과정으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [intersection](../../../reference/array/intersection.md)을 사용하세요. + +::: + +여러 배열의 교집합을 구해요. + +```typescript +const result = intersection(...arrays); +``` + +## 사용법 + +### `intersection(...arrays)` + +여러 배열에서 공통으로 존재하는 요소들을 찾아서 새 배열로 반환해요. 결과는 중복이 제거되고 첫 번째 배열의 순서를 유지해요. + +```typescript +import { intersection } from 'es-toolkit/compat'; + +// 두 배열의 교집합 +const array1 = [1, 2, 3, 4]; +const array2 = [2, 3, 5, 6]; +const result = intersection(array1, array2); +// result는 [2, 3] + +// 세 개 배열의 교집합 +const array3 = [3, 4, 7, 8]; +const multiResult = intersection(array1, array2, array3); +// multiResult는 [3] + +// 문자열 배열 +const strings1 = ['a', 'b', 'c']; +const strings2 = ['b', 'c', 'd']; +const stringResult = intersection(strings1, strings2); +// stringResult는 ['b', 'c'] + +// 배열 형태 객체 +const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; +const arrayLike2 = { 0: 2, 1: 3, 2: 4, length: 3 }; +const likeResult = intersection(arrayLike1, arrayLike2); +// likeResult는 [2, 3] +``` + +`null`이나 `undefined` 배열은 빈 배열로 처리해요. + +```typescript +import { intersection } from 'es-toolkit/compat'; + +const array1 = [1, 2, 3]; +const result1 = intersection(array1, null); +// result1는 [] + +const result2 = intersection(null, undefined); +// result2는 [] +``` + +중복된 요소가 있어도 결과에서는 제거돼요. + +```typescript +import { intersection } from 'es-toolkit/compat'; + +const array1 = [1, 1, 2, 3]; +const array2 = [1, 2, 2, 4]; +const result = intersection(array1, array2); +// result는 [1, 2] (중복 제거됨) +``` + +#### 파라미터 + +- `...arrays` (`Array | null | undefined>`): 교집합을 구할 배열들이에요. 배열 형태 객체나 null/undefined도 허용해요. + +#### 반환 값 + +(`T[]`): 모든 배열에 공통으로 존재하는 요소들의 새 배열을 반환해요. 중복은 제거되고 첫 번째 배열의 순서를 따라요. diff --git a/docs/ko/compat/reference/array/intersectionBy.md b/docs/ko/compat/reference/array/intersectionBy.md new file mode 100644 index 000000000..f906b98f8 --- /dev/null +++ b/docs/ko/compat/reference/array/intersectionBy.md @@ -0,0 +1,93 @@ +# intersectionBy (Lodash 호환성) + +::: warning `es-toolkit`의 [intersectionBy](../../../reference/array/intersectionBy.md)를 사용하세요 + +이 `intersectionBy` 함수는 복잡한 조건 처리, 다중 배열 지원, 프로퍼티 경로 해석 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [intersectionBy](../../../reference/array/intersectionBy.md)를 사용하세요. + +::: + +주어진 조건 함수를 사용해서 여러 배열의 교집합을 구해요. + +```typescript +const result = intersectionBy(...arrays, iteratee); +``` + +## 사용법 + +### `intersectionBy(...arrays, iteratee)` + +여러 배열에서 각 요소를 주어진 조건 함수로 변환한 값을 기준으로 교집합을 구해요. 조건은 함수, 프로퍼티 이름, 부분 객체 등 다양한 형태로 제공할 수 있어요. + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +// 함수로 교집합 구하기 +const array1 = [2.1, 1.2]; +const array2 = [2.3, 3.4]; +const result = intersectionBy(array1, array2, Math.floor); +// result는 [2.1] (Math.floor 기준으로 2가 공통) + +// 프로퍼티로 교집합 구하기 +const users1 = [ + { id: 1, name: 'john' }, + { id: 2, name: 'jane' }, +]; +const users2 = [ + { id: 2, name: 'jane' }, + { id: 3, name: 'bob' }, +]; +const byId = intersectionBy(users1, users2, 'id'); +// byId는 [{ id: 2, name: 'jane' }] + +// 세 개 배열의 교집합 +const array3 = [2.5, 4.1]; +const multiResult = intersectionBy(array1, array2, array3, Math.floor); +// multiResult는 [2.1] + +// 배열 형태 객체 +const arrayLike1 = { 0: { x: 1 }, 1: { x: 2 }, length: 2 }; +const arrayLike2 = { 0: { x: 2 }, 1: { x: 3 }, length: 2 }; +const byProperty = intersectionBy(arrayLike1, arrayLike2, 'x'); +// byProperty는 [{ x: 2 }] +``` + +`null`이나 `undefined` 배열은 빈 배열로 처리해요. + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +const array1 = [{ x: 1 }, { x: 2 }]; +const result = intersectionBy(array1, null, 'x'); +// result는 [] +``` + +부분 객체나 프로퍼티-값 쌍으로도 조건을 지정할 수 있어요. + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +const products1 = [ + { category: 'fruit', name: 'apple' }, + { category: 'vegetable', name: 'carrot' }, +]; +const products2 = [ + { category: 'fruit', name: 'banana' }, + { category: 'meat', name: 'beef' }, +]; + +// 부분 객체로 조건 지정 +const byCategory = intersectionBy(products1, products2, { category: 'fruit' }); +// 프로퍼티-값 쌍으로 조건 지정 +const byCategoryPair = intersectionBy(products1, products2, ['category', 'fruit']); +``` + +#### 파라미터 + +- `...arrays` (`Array | null | undefined>`): 교집합을 구할 배열들이에요. +- `iteratee` (`Function | PropertyKey | Array | Object`): 각 요소를 변환할 조건이에요. 함수, 프로퍼티 이름, 프로퍼티-값 쌍, 또는 부분 객체일 수 있어요. + +#### 반환 값 + +(`T[]`): 변환된 값을 기준으로 모든 배열에 공통으로 존재하는 요소들의 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/intersectionWith.md b/docs/ko/compat/reference/array/intersectionWith.md new file mode 100644 index 000000000..139c4a1ad --- /dev/null +++ b/docs/ko/compat/reference/array/intersectionWith.md @@ -0,0 +1,64 @@ +# intersectionWith (Lodash 호환성) + +::: warning `es-toolkit`의 [intersectionWith](../../../reference/array/intersectionWith.md)를 사용하세요 + +이 `intersectionWith` 함수는 `null`이나 `undefined` 처리, 다양한 오버로딩 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [intersectionWith](../../../reference/array/intersectionWith.md)를 사용하세요. + +::: + +사용자 정의 비교 함수를 사용해서 모든 배열에 포함된 공통 요소들의 배열을 만들어요. + +```typescript +const result = intersectionWith(array, ...otherArrays, comparator); +``` + +## 사용법 + +### `intersectionWith(array, ...otherArrays, comparator)` + +사용자 정의 비교 함수를 사용해서 첫 번째 배열과 나머지 배열들의 교집합을 구해요. 비교 함수로 각 요소가 동일한지 판단하고, 모든 배열에 포함된 요소들만 결과로 반환해요. + +```typescript +import { intersectionWith } from 'es-toolkit/compat'; + +const objects = [ + { id: 1, name: 'john' }, + { id: 2, name: 'jane' }, +]; +const others = [ + { id: 1, name: 'john' }, + { id: 3, name: 'joe' }, +]; + +intersectionWith(objects, others, (a, b) => a.id === b.id); +// => [{ id: 1, name: 'john' }] + +// 여러 배열과 비교할 수도 있어요 +const array1 = [{ x: 1 }, { x: 2 }]; +const array2 = [{ x: 1 }, { x: 3 }]; +const array3 = [{ x: 1 }, { x: 4 }]; + +intersectionWith(array1, array2, array3, (a, b) => a.x === b.x); +// => [{ x: 1 }] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { intersectionWith } from 'es-toolkit/compat'; + +intersectionWith(null, [1, 2], (a, b) => a === b); // [] +intersectionWith([1, 2], undefined, (a, b) => a === b); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 비교할 첫 번째 배열이에요. +- `...otherArrays` (`Array | ((a: T, b: T | U) => boolean)>`): 비교할 나머지 배열들과 마지막 요소로 비교 함수예요. +- `comparator` (`(a: T, b: T | U) => boolean`): 두 요소가 같은지 판단하는 함수예요. + +#### 반환 값 + +(`T[]`): 모든 배열에서 공통으로 찾은 요소들의 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/invokeMap.md b/docs/ko/compat/reference/array/invokeMap.md similarity index 100% rename from docs/ko/reference/compat/array/invokeMap.md rename to docs/ko/compat/reference/array/invokeMap.md diff --git a/docs/ko/reference/compat/array/join.md b/docs/ko/compat/reference/array/join.md similarity index 100% rename from docs/ko/reference/compat/array/join.md rename to docs/ko/compat/reference/array/join.md diff --git a/docs/ko/compat/reference/array/keyBy.md b/docs/ko/compat/reference/array/keyBy.md new file mode 100644 index 000000000..168c3f852 --- /dev/null +++ b/docs/ko/compat/reference/array/keyBy.md @@ -0,0 +1,64 @@ +# keyBy (Lodash 호환성) + +::: warning `es-toolkit`의 [keyBy](../../../reference/array/keyBy.md)를 사용하세요 + +이 `keyBy` 함수는 `null`이나 `undefined` 처리, 다양한 매개변수 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [keyBy](../../../reference/array/keyBy.md)를 사용하세요. + +::: + +컬렉션의 요소들을 지정된 키를 기준으로 객체로 구성해요. + +```typescript +const result = keyBy(collection, iteratee); +``` + +## 사용법 + +### `keyBy(collection, iteratee)` + +배열이나 객체의 각 요소를 지정된 키 생성 함수나 속성 이름을 사용해서 객체로 구성해요. 같은 키를 가진 요소가 여러 개 있으면 마지막 요소가 사용돼요. + +```typescript +import { keyBy } from 'es-toolkit/compat'; + +// 속성 이름으로 키 생성하기 +const array = [ + { dir: 'left', code: 97 }, + { dir: 'right', code: 100 }, +]; + +keyBy(array, 'dir'); +// => { left: { dir: 'left', code: 97 }, right: { dir: 'right', code: 100 } } + +// 함수로 키 생성하기 +keyBy(array, o => String.fromCharCode(o.code)); +// => { a: { dir: 'left', code: 97 }, d: { dir: 'right', code: 100 } } + +// 객체에서도 사용 가능해요 +const obj = { + a: { id: 1, name: 'john' }, + b: { id: 2, name: 'jane' }, +}; +keyBy(obj, 'name'); +// => { john: { id: 1, name: 'john' }, jane: { id: 2, name: 'jane' } } +``` + +`null`이나 `undefined`는 빈 객체로 처리해요. + +```typescript +import { keyBy } from 'es-toolkit/compat'; + +keyBy(null, 'id'); // {} +keyBy(undefined, 'id'); // {} +``` + +#### 파라미터 + +- `collection` (`ArrayLike | null | undefined`): 키로 구성할 배열이나 객체예요. +- `iteratee` (`ValueIterateeCustom`, 선택): 키를 생성할 함수나 속성 이름이에요. 생략하면 요소 자체를 키로 사용해요. + +#### 반환 값 + +(`Record`): 각 요소가 생성된 키에 매핑된 새로운 객체를 반환해요. diff --git a/docs/ko/compat/reference/array/last.md b/docs/ko/compat/reference/array/last.md new file mode 100644 index 000000000..833c7cbc4 --- /dev/null +++ b/docs/ko/compat/reference/array/last.md @@ -0,0 +1,79 @@ +# last (Lodash 호환성) + +::: warning `es-toolkit`의 [last](../../../reference/array/last.md)를 사용하세요 + +이 `last` 함수는 `null`이나 `undefined` 처리로 인해 복잡하게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [last](../../../reference/array/last.md)를 사용하세요. + +::: + +배열의 마지막 요소를 반환해요. + +```typescript +const lastElement = last(array); +``` + +## 사용법 + +### `last(array)` + +배열의 맨 뒤 요소를 가져오고 싶을 때 `last`를 사용하세요. 배열이 비어있으면 `undefined`를 반환해요. + +```typescript +import { last } from 'es-toolkit/compat'; + +// 숫자 배열의 마지막 요소 +last([1, 2, 3, 4, 5]); +// Returns: 5 + +// 문자열 배열의 마지막 요소 +last(['a', 'b', 'c']); +// Returns: 'c' + +// 객체 배열의 마지막 요소 +const users = [{ name: 'Alice' }, { name: 'Bob' }]; +last(users); +// Returns: { name: 'Bob' } +``` + +빈 배열이나 `null`, `undefined`는 `undefined`를 반환해요. + +```typescript +import { last } from 'es-toolkit/compat'; + +// 빈 배열 +last([]); +// Returns: undefined + +// null 배열 +last(null); +// Returns: undefined + +// undefined 배열 +last(undefined); +// Returns: undefined +``` + +유사 배열 객체도 지원해요. + +```typescript +import { last } from 'es-toolkit/compat'; + +// 유사 배열 객체 +const arrayLike = { 0: 'first', 1: 'second', length: 2 }; +last(arrayLike); +// Returns: 'second' + +// 문자열도 유사 배열 객체 +last('hello'); +// Returns: 'o' +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 마지막 요소를 가져올 배열이에요. + +#### 반환 값 + +(`T | undefined`): 배열의 마지막 요소를 반환하고, 배열이 비어있거나 `null`, `undefined`이면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/array/lastIndexOf.md b/docs/ko/compat/reference/array/lastIndexOf.md similarity index 100% rename from docs/ko/reference/compat/array/lastIndexOf.md rename to docs/ko/compat/reference/array/lastIndexOf.md diff --git a/docs/ko/reference/compat/array/map.md b/docs/ko/compat/reference/array/map.md similarity index 100% rename from docs/ko/reference/compat/array/map.md rename to docs/ko/compat/reference/array/map.md diff --git a/docs/ko/reference/compat/array/nth.md b/docs/ko/compat/reference/array/nth.md similarity index 100% rename from docs/ko/reference/compat/array/nth.md rename to docs/ko/compat/reference/array/nth.md diff --git a/docs/ko/compat/reference/array/orderBy.md b/docs/ko/compat/reference/array/orderBy.md new file mode 100644 index 000000000..2a7a1121c --- /dev/null +++ b/docs/ko/compat/reference/array/orderBy.md @@ -0,0 +1,82 @@ +# orderBy (Lodash 호환성) + +::: warning `es-toolkit`의 [orderBy](../../../reference/array/orderBy.md)를 사용하세요 + +이 `orderBy` 함수는 `null`이나 `undefined` 처리, 복잡한 경로 탐색, 다양한 정렬 기준 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [orderBy](../../../reference/array/orderBy.md)를 사용하세요. + +::: + +여러 기준으로 컬렉션의 요소들을 정렬해요. + +```typescript +const result = orderBy(collection, criteria, orders); +``` + +## 사용법 + +### `orderBy(collection, criteria, orders)` + +배열이나 객체의 요소들을 지정된 기준과 정렬 순서에 따라 정렬해요. 여러 기준을 사용할 수 있고, 각 기준마다 오름차순(`'asc'`) 또는 내림차순(`'desc'`) 정렬을 지정할 수 있어요. + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +const users = [ + { name: 'fred', age: 48 }, + { name: 'barney', age: 34 }, + { name: 'fred', age: 40 }, + { name: 'barney', age: 36 }, +]; + +// 이름 오름차순, 나이 내림차순으로 정렬 +orderBy(users, ['name', 'age'], ['asc', 'desc']); +// => [ +// { name: 'barney', age: 36 }, +// { name: 'barney', age: 34 }, +// { name: 'fred', age: 48 }, +// { name: 'fred', age: 40 } +// ] + +// 함수로 정렬 기준 지정하기 +orderBy(users, [user => user.name, user => user.age], ['asc', 'desc']); +// => 위와 동일한 결과 + +// 단일 기준으로 정렬 +orderBy(users, 'age', 'desc'); +// => [{ name: 'fred', age: 48 }, { name: 'fred', age: 40 }, ...] +``` + +객체의 경우 값들을 정렬해요. + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +const obj = { + a: { name: 'fred', age: 48 }, + b: { name: 'barney', age: 34 }, +}; + +orderBy(obj, 'age', 'desc'); +// => [{ name: 'fred', age: 48 }, { name: 'barney', age: 34 }] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +orderBy(null, 'name'); // [] +orderBy(undefined, 'age'); // [] +``` + +#### 파라미터 + +- `collection` (`ArrayLike | object | null | undefined`): 정렬할 배열이나 객체예요. +- `criteria` (`Criterion | Array>`, 선택): 정렬 기준이에요. 속성 이름, 속성 경로, 함수 등을 사용할 수 있어요. 기본값은 `[null]`이에요. +- `orders` (`unknown | unknown[]`, 선택): 각 기준의 정렬 순서예요. `'asc'`(오름차순), `'desc'`(내림차순), `true`(오름차순), `false`(내림차순)를 사용할 수 있어요. 기본값은 `[]`이에요. + +#### 반환 값 + +(`T[]`): 정렬된 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/partition.md b/docs/ko/compat/reference/array/partition.md new file mode 100644 index 000000000..28dcf8d27 --- /dev/null +++ b/docs/ko/compat/reference/array/partition.md @@ -0,0 +1,89 @@ +# partition (Lodash 호환성) + +::: warning `es-toolkit`의 [partition](../../../reference/array/partition.md)를 사용하세요 + +이 `partition` 함수는 `null`이나 `undefined` 처리, 다양한 조건 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [partition](../../../reference/array/partition.md)를 사용하세요. + +::: + +컬렉션의 요소들을 조건에 따라 두 그룹으로 나누어요. + +```typescript +const [truthy, falsy] = partition(collection, predicate); +``` + +## 사용법 + +### `partition(collection, predicate)` + +배열이나 객체의 요소들을 주어진 조건 함수에 따라 두 그룹으로 나누어요. 첫 번째 그룹은 조건이 참인 요소들이고, 두 번째 그룹은 조건이 거짓인 요소들이에요. + +```typescript +import { partition } from 'es-toolkit/compat'; + +// 숫자 배열을 짝수와 홀수로 나누기 +partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); +// => [[2, 4, 6], [1, 3, 5]] + +// 속성 이름으로 조건 지정하기 +const users = [ + { name: 'john', active: true }, + { name: 'jane', active: false }, + { name: 'bob', active: true }, +]; + +partition(users, 'active'); +// => [ +// [{ name: 'john', active: true }, { name: 'bob', active: true }], +// [{ name: 'jane', active: false }] +// ] + +// 객체 조건으로 필터링하기 +partition(users, { active: true }); +// => [ +// [{ name: 'john', active: true }, { name: 'bob', active: true }], +// [{ name: 'jane', active: false }] +// ] + +// 배열 조건으로 필터링하기 +partition(users, ['name', 'john']); +// => [ +// [{ name: 'john', active: true }], +// [{ name: 'jane', active: false }, { name: 'bob', active: true }] +// ] +``` + +객체의 경우 값들을 분할해요. + +```typescript +import { partition } from 'es-toolkit/compat'; + +const obj = { + a: { score: 90 }, + b: { score: 40 }, + c: { score: 80 }, +}; + +partition(obj, item => item.score >= 80); +// => [[{ score: 90 }, { score: 80 }], [{ score: 40 }]] +``` + +`null`이나 `undefined`는 빈 배열들로 처리해요. + +```typescript +import { partition } from 'es-toolkit/compat'; + +partition(null, x => x > 0); // [[], []] +partition(undefined, 'active'); // [[], []] +``` + +#### 파라미터 + +- `collection` (`ArrayLike | T | null | undefined`): 분할할 배열이나 객체예요. +- `predicate` (`((value: T) => unknown) | Partial | [PropertyKey, any] | PropertyKey`, 선택): 각 요소를 테스트할 조건이에요. 함수, 부분 객체, 속성-값 배열, 속성 이름을 사용할 수 있어요. 기본값은 `identity`예요. + +#### 반환 값 + +(`[T[], T[]]`): 조건을 만족하는 요소들의 배열과 만족하지 않는 요소들의 배열로 구성된 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/pull.md b/docs/ko/compat/reference/array/pull.md new file mode 100644 index 000000000..00d08d19a --- /dev/null +++ b/docs/ko/compat/reference/array/pull.md @@ -0,0 +1,44 @@ +# pull (Lodash 호환성) + +::: warning `es-toolkit`의 [pull](../../../reference/array/pull.md)을 사용하세요 + +이 `pull` 함수는 Lodash의 호환성을 위한 함수로, 더 복잡한 타입 처리와 오버로딩으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [pull](../../../reference/array/pull.md)을 사용하세요. + +::: + +배열에서 지정한 값들을 모두 제거해요. + +```typescript +const result = pull(array, ...valuesToRemove); +``` + +## 사용법 + +### `pull(array, ...valuesToRemove)` + +배열에서 지정한 값들을 모두 제거하고 원본 배열을 수정해요. 배열을 복사하지 않고 원본 배열을 직접 변경하므로 메모리를 절약할 수 있어요. + +```typescript +import { pull } from 'es-toolkit/compat'; + +// 숫자 배열에서 특정 값들 제거 +const numbers = [1, 2, 3, 2, 4, 2, 5]; +pull(numbers, 2, 3); +console.log(numbers); // [1, 4, 5] + +// 문자열 배열에서 특정 값들 제거 +const fruits = ['apple', 'banana', 'apple', 'cherry']; +pull(fruits, 'apple'); +console.log(fruits); // ['banana', 'cherry'] +``` + +#### 파라미터 + +- `array` (`T[]`): 수정할 배열이에요. +- `...valuesToRemove` (`T[]`): 배열에서 제거할 값들이에요. + +#### 반환 값 + +(`T[]`): 수정된 원본 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/pullAll.md b/docs/ko/compat/reference/array/pullAll.md similarity index 100% rename from docs/ko/reference/compat/array/pullAll.md rename to docs/ko/compat/reference/array/pullAll.md diff --git a/docs/ko/reference/compat/array/pullAllBy.md b/docs/ko/compat/reference/array/pullAllBy.md similarity index 100% rename from docs/ko/reference/compat/array/pullAllBy.md rename to docs/ko/compat/reference/array/pullAllBy.md diff --git a/docs/ko/reference/compat/array/pullAllWith.md b/docs/ko/compat/reference/array/pullAllWith.md similarity index 100% rename from docs/ko/reference/compat/array/pullAllWith.md rename to docs/ko/compat/reference/array/pullAllWith.md diff --git a/docs/ko/compat/reference/array/pullAt.md b/docs/ko/compat/reference/array/pullAt.md new file mode 100644 index 000000000..3f3f2834c --- /dev/null +++ b/docs/ko/compat/reference/array/pullAt.md @@ -0,0 +1,57 @@ +# pullAt (Lodash 호환성) + +::: warning `es-toolkit`의 [pullAt](../../../reference/array/pullAt.md)을 사용하세요 + +이 `pullAt` 함수는 복잡한 타입 처리와 오버로딩으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [pullAt](../../../reference/array/pullAt.md)을 사용하세요. + +::: + +지정된 인덱스에 있는 요소들을 배열에서 제거하고 제거된 요소들을 반환해요. + +```typescript +const removed = pullAt(array, ...indexes); +``` + +## 사용법 + +### `pullAt(array, ...indexes)` + +배열에서 지정된 인덱스에 있는 요소들을 제거하고 제거된 요소들의 배열을 반환하세요. 원본 배열이 변경돼요. + +```typescript +import { pullAt } from 'es-toolkit/compat'; + +// 단일 인덱스로 제거해요 +const array = [1, 2, 3, 4, 5]; +const removed = pullAt(array, 1, 3); +console.log(array); // [1, 3, 5] +console.log(removed); // [2, 4] + +// 배열 형태의 인덱스로 제거해요 +const colors = ['red', 'green', 'blue', 'yellow']; +const removedColors = pullAt(colors, [0, 2]); +console.log(colors); // ['green', 'yellow'] +console.log(removedColors); // ['red', 'blue'] +``` + +존재하지 않는 인덱스는 `undefined`로 처리돼요. + +```typescript +import { pullAt } from 'es-toolkit/compat'; + +const numbers = [10, 20, 30]; +const removed = pullAt(numbers, 1, 5); +console.log(numbers); // [10, 30] +console.log(removed); // [20, undefined] +``` + +#### 파라미터 + +- `array` (`ArrayLike`): 변경할 배열이에요. +- `...indexes` (`Array`): 제거할 요소들의 인덱스예요. 개별 숫자나 숫자 배열로 전달할 수 있어요. + +#### 반환 값 + +(`ArrayLike`): 제거된 요소들의 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/reduce.md b/docs/ko/compat/reference/array/reduce.md similarity index 100% rename from docs/ko/reference/compat/array/reduce.md rename to docs/ko/compat/reference/array/reduce.md diff --git a/docs/ko/reference/compat/array/reduceRight.md b/docs/ko/compat/reference/array/reduceRight.md similarity index 100% rename from docs/ko/reference/compat/array/reduceRight.md rename to docs/ko/compat/reference/array/reduceRight.md diff --git a/docs/ko/reference/compat/array/reject.md b/docs/ko/compat/reference/array/reject.md similarity index 100% rename from docs/ko/reference/compat/array/reject.md rename to docs/ko/compat/reference/array/reject.md diff --git a/docs/ko/compat/reference/array/remove.md b/docs/ko/compat/reference/array/remove.md new file mode 100644 index 000000000..768fd949f --- /dev/null +++ b/docs/ko/compat/reference/array/remove.md @@ -0,0 +1,70 @@ +# remove (Lodash 호환성) + +::: warning `es-toolkit`의 `remove`를 사용하세요 + +이 `remove` 함수는 Lodash와의 호환성을 위해 여러 형태의 predicate를 지원하므로 복잡하게 구현되어 있어요. 메인 라이브러리의 `remove` 함수는 간단한 함수 predicate만 지원하므로 더 빠르게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [remove](../../../reference/array/remove.md)를 사용하세요. + +::: + +배열에서 조건에 맞는 요소들을 제거하고 제거된 요소들을 배열로 반환해요. + +```typescript +const removedElements = remove(array, predicate); +``` + +## 사용법 + +### `remove(array, predicate)` + +배열을 순회하며 주어진 조건에 맞는 요소들을 원본 배열에서 제거하고, 제거된 요소들을 새 배열로 반환해요. 원본 배열이 직접 수정되므로 주의해야 해요. + +```typescript +import { remove } from 'es-toolkit/compat'; + +// 함수를 사용한 조건으로 제거 +const numbers = [1, 2, 3, 4, 5]; +const evens = remove(numbers, n => n % 2 === 0); +console.log(numbers); // => [1, 3, 5] +console.log(evens); // => [2, 4] + +// 객체의 부분 매칭으로 제거 +const objects = [{ a: 1 }, { a: 2 }, { a: 3 }]; +const removed = remove(objects, { a: 1 }); +console.log(objects); // => [{ a: 2 }, { a: 3 }] +console.log(removed); // => [{ a: 1 }] + +// 속성-값 쌍으로 제거 +const items = [{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }]; +const cherries = remove(items, ['name', 'cherry']); +console.log(items); // => [{ name: 'apple' }, { name: 'banana' }] +console.log(cherries); // => [{ name: 'cherry' }] +``` + +이 함수는 다양한 형태의 predicate를 지원해요. + +```typescript +import { remove } from 'es-toolkit/compat'; + +// 함수를 사용한 조건 +remove(users, user => user.active === false); + +// 객체의 부분 매칭 +remove(users, { status: 'inactive' }); + +// 속성-값 배열 +remove(users, ['type', 'guest']); + +// 속성명으로 truthy 값 확인 +remove(users, 'isDeleted'); +``` + +#### 파라미터 + +- `array` (`ArrayLike`): 수정할 배열이에요. +- `predicate` (`((value: T, index: number, array: ArrayLike) => boolean) | Partial | [keyof T, unknown] | keyof T`, 선택): 각 요소에 대해 실행할 조건이에요. 기본값은 `identity`예요. + +#### 반환 값 + +(`T[]`): 조건에 맞아서 제거된 요소들로 구성된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/reverse.md b/docs/ko/compat/reference/array/reverse.md similarity index 100% rename from docs/ko/reference/compat/array/reverse.md rename to docs/ko/compat/reference/array/reverse.md diff --git a/docs/ko/compat/reference/array/sample.md b/docs/ko/compat/reference/array/sample.md new file mode 100644 index 000000000..b9a63a90f --- /dev/null +++ b/docs/ko/compat/reference/array/sample.md @@ -0,0 +1,54 @@ +# sample (Lodash 호환성) + +::: warning `es-toolkit`의 [sample](../../../reference/array/sample.md)을 사용하세요 + +이 `sample` 함수는 `null`이나 `undefined` 처리, 객체 값 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [sample](../../../reference/array/sample.md)을 사용하세요. + +::: + +배열이나 객체에서 랜덤한 요소 하나를 가져와요. + +```typescript +const randomItem = sample(collection); +``` + +## 사용법 + +### `sample(collection)` + +배열이나 객체에서 랜덤한 요소를 하나 선택할 때 `sample`을 사용하세요. 배열에서는 랜덤한 요소를 반환하고, 객체에서는 랜덤한 값을 반환해요. + +```typescript +import { sample } from 'es-toolkit/compat'; + +// 배열에서 랜덤한 요소 가져오기 +sample([1, 2, 3, 4, 5]); +// 1부터 5까지 중 랜덤한 숫자 하나를 반환해요 + +// 객체에서 랜덤한 값 가져오기 +sample({ a: 1, b: 2, c: 3 }); +// 1, 2, 3 중 랜덤한 값 하나를 반환해요 + +// 문자열도 처리해요 +sample('hello'); +// 'h', 'e', 'l', 'l', 'o' 중 랜덤한 문자 하나를 반환해요 +``` + +`null`이나 `undefined`는 `undefined`를 반환해요. + +```typescript +import { sample } from 'es-toolkit/compat'; + +sample(null); // undefined +sample(undefined); // undefined +``` + +#### 파라미터 + +- `collection` (`ArrayLike | Record | null | undefined`): 샘플링할 배열이나 객체예요. + +#### 반환 값 + +(`T | string | undefined`): 배열이나 객체에서 랜덤하게 선택된 요소를 반환해요. 컬렉션이 비어있거나 `null`, `undefined`면 `undefined`를 반환해요. diff --git a/docs/ko/compat/reference/array/sampleSize.md b/docs/ko/compat/reference/array/sampleSize.md new file mode 100644 index 000000000..aab7f6168 --- /dev/null +++ b/docs/ko/compat/reference/array/sampleSize.md @@ -0,0 +1,54 @@ +# sampleSize (Lodash 호환성) + +::: warning `es-toolkit`의 [sampleSize](../../../reference/array/sampleSize.md)를 사용하세요 + +이 `sampleSize` 함수는 `null`이나 `undefined` 처리, 객체 지원, 기본값 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [sampleSize](../../../reference/array/sampleSize.md)를 사용하세요. + +::: + +배열이나 객체에서 지정된 개수만큼 무작위로 요소를 선택해요. + +```typescript +const sampled = sampleSize(collection, size); +``` + +## 사용법 + +### `sampleSize(collection, size?)` + +배열이나 객체에서 무작위로 요소를 선택할 때 `sampleSize`를 사용하세요. Floyd 알고리즘을 사용해서 중복 없이 효율적으로 샘플링해요. + +```typescript +import { sampleSize } from 'es-toolkit/compat'; + +// 배열에서 3개의 요소를 무작위로 선택해요. +sampleSize([1, 2, 3, 4, 5], 3); +// Returns: [2, 4, 5] (실제 결과는 달라질 수 있어요) + +// 객체에서 2개의 값을 무작위로 선택해요. +sampleSize({ a: 1, b: 2, c: 3, d: 4 }, 2); +// Returns: [2, 4] (실제 결과는 달라질 수 있어요) +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { sampleSize } from 'es-toolkit/compat'; + +sampleSize(null, 2); +// Returns: [] + +sampleSize(undefined, 2); +// Returns: [] +``` + +#### 파라미터 + +- `collection` (`Record | Record | T | null | undefined`): 샘플링할 배열이나 객체예요. +- `size` (`number`, 선택): 선택할 요소의 개수예요. 기본값은 `1`이에요. + +#### 반환 값 + +(`T[]`): 무작위로 선택된 요소들로 구성된 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/shuffle.md b/docs/ko/compat/reference/array/shuffle.md new file mode 100644 index 000000000..a113c61d4 --- /dev/null +++ b/docs/ko/compat/reference/array/shuffle.md @@ -0,0 +1,60 @@ +# shuffle (Lodash 호환성) + +::: warning `es-toolkit`의 `shuffle`을 사용하세요 + +이 `shuffle` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [shuffle](../../../reference/array/shuffle.md)을 사용하세요. + +::: + +배열이나 객체의 요소들을 무작위로 섞어서 새로운 배열을 반환해요. + +```typescript +const result = shuffle(collection); +``` + +## 사용법 + +### `shuffle(collection)` + +Fisher-Yates 알고리즘을 사용하여 배열이나 객체의 요소들을 무작위로 섞어서 새로운 배열을 반환해요. 원본은 변경되지 않아요. + +```typescript +import { shuffle } from 'es-toolkit/compat'; + +// 숫자 배열 섞기 +const numbers = [1, 2, 3, 4, 5]; +const shuffled1 = shuffle(numbers); +// Returns: 예를 들어 [3, 1, 5, 2, 4] (매번 다른 순서) + +// 문자열 배열 섞기 +const fruits = ['apple', 'banana', 'cherry', 'date']; +const shuffled2 = shuffle(fruits); +// Returns: 예를 들어 ['cherry', 'apple', 'date', 'banana'] + +// 객체의 값들 섞기 +const obj = { a: 1, b: 2, c: 3, d: 4 }; +const shuffled3 = shuffle(obj); +// Returns: 예를 들어 [3, 1, 4, 2] (객체 값들이 무작위로 섞임) +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { shuffle } from 'es-toolkit/compat'; + +shuffle(null); +// Returns: [] + +shuffle(undefined); +// Returns: [] +``` + +#### 파라미터 + +- `collection` (`ArrayLike | T | null | undefined`): 섞을 배열이나 객체예요. + +#### 반환 값 + +(`T[]`): 요소들이 무작위로 섞인 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/size.md b/docs/ko/compat/reference/array/size.md similarity index 100% rename from docs/ko/reference/compat/array/size.md rename to docs/ko/compat/reference/array/size.md diff --git a/docs/ko/reference/compat/array/slice.md b/docs/ko/compat/reference/array/slice.md similarity index 100% rename from docs/ko/reference/compat/array/slice.md rename to docs/ko/compat/reference/array/slice.md diff --git a/docs/ko/reference/compat/array/some.md b/docs/ko/compat/reference/array/some.md similarity index 100% rename from docs/ko/reference/compat/array/some.md rename to docs/ko/compat/reference/array/some.md diff --git a/docs/ko/reference/compat/array/sortBy.md b/docs/ko/compat/reference/array/sortBy.md similarity index 100% rename from docs/ko/reference/compat/array/sortBy.md rename to docs/ko/compat/reference/array/sortBy.md diff --git a/docs/ko/reference/compat/array/sortedIndex.md b/docs/ko/compat/reference/array/sortedIndex.md similarity index 100% rename from docs/ko/reference/compat/array/sortedIndex.md rename to docs/ko/compat/reference/array/sortedIndex.md diff --git a/docs/ko/reference/compat/array/sortedIndexBy.md b/docs/ko/compat/reference/array/sortedIndexBy.md similarity index 100% rename from docs/ko/reference/compat/array/sortedIndexBy.md rename to docs/ko/compat/reference/array/sortedIndexBy.md diff --git a/docs/ko/reference/compat/array/sortedIndexOf.md b/docs/ko/compat/reference/array/sortedIndexOf.md similarity index 100% rename from docs/ko/reference/compat/array/sortedIndexOf.md rename to docs/ko/compat/reference/array/sortedIndexOf.md diff --git a/docs/ko/reference/compat/array/sortedLastIndex.md b/docs/ko/compat/reference/array/sortedLastIndex.md similarity index 100% rename from docs/ko/reference/compat/array/sortedLastIndex.md rename to docs/ko/compat/reference/array/sortedLastIndex.md diff --git a/docs/ko/reference/compat/array/sortedLastIndexBy.md b/docs/ko/compat/reference/array/sortedLastIndexBy.md similarity index 100% rename from docs/ko/reference/compat/array/sortedLastIndexBy.md rename to docs/ko/compat/reference/array/sortedLastIndexBy.md diff --git a/docs/ko/reference/compat/array/sortedLastIndexOf.md b/docs/ko/compat/reference/array/sortedLastIndexOf.md similarity index 100% rename from docs/ko/reference/compat/array/sortedLastIndexOf.md rename to docs/ko/compat/reference/array/sortedLastIndexOf.md diff --git a/docs/ko/compat/reference/array/tail.md b/docs/ko/compat/reference/array/tail.md new file mode 100644 index 000000000..32a858213 --- /dev/null +++ b/docs/ko/compat/reference/array/tail.md @@ -0,0 +1,58 @@ +# tail (Lodash 호환성) + +::: warning `es-toolkit`의 [tail](../../../reference/array/tail.md)을 사용하세요 + +이 `tail` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [tail](../../../reference/array/tail.md)을 사용하세요. + +::: + +배열의 첫 번째 요소를 제외한 나머지 요소들을 반환해요. + +```typescript +const result = tail(array); +``` + +## 사용법 + +### `tail(array)` + +배열의 첫 번째 요소를 제외한 모든 요소들을 포함하는 새로운 배열을 만들고 싶을 때 `tail`을 사용하세요. 입력 배열이 비어있거나 요소가 하나만 있다면 빈 배열을 반환해요. + +```typescript +import { tail } from 'es-toolkit/compat'; + +// 숫자 배열에서 첫 번째 요소를 제거해요. +tail([1, 2, 3]); +// Returns: [2, 3] + +// 문자열 배열에서 첫 번째 요소를 제거해요. +tail(['a', 'b', 'c']); +// Returns: ['b', 'c'] + +// 하나의 요소만 있는 배열이에요. +tail([1]); +// Returns: [] + +// 빈 배열이에요. +tail([]); +// Returns: [] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { tail } from 'es-toolkit/compat'; + +tail(null); // [] +tail(undefined); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 첫 번째 요소를 제거할 배열이에요. + +#### 반환 값 + +(`T[]`): 첫 번째 요소를 제외한 나머지 요소들을 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/take.md b/docs/ko/compat/reference/array/take.md new file mode 100644 index 000000000..640f34fe7 --- /dev/null +++ b/docs/ko/compat/reference/array/take.md @@ -0,0 +1,56 @@ +# take (Lodash 호환성) + +::: warning `es-toolkit`의 [take](../../../reference/array/take.md)를 사용하세요 + +이 `take` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [take](../../../reference/array/take.md)를 사용하세요. + +::: + +배열의 앞에서부터 지정된 개수만큼의 요소를 가져와서 새로운 배열을 만들어요. + +```typescript +const result = take([1, 2, 3, 4, 5], 3); +// result는 [1, 2, 3]이 돼요. +``` + +## 사용법 + +### `take(array, count)` + +배열의 앞에서부터 지정된 개수만큼의 요소를 가져와서 새로운 배열을 반환해요. `count`가 배열의 길이보다 크면 전체 배열을 반환해요. + +```typescript +import { take } from 'es-toolkit/compat'; + +// 기본 사용법 +const numbers = [1, 2, 3, 4, 5]; +const result1 = take(numbers, 3); +// Returns: [1, 2, 3] + +// 배열 길이보다 큰 개수 요청 +const result2 = take(numbers, 10); +// Returns: [1, 2, 3, 4, 5] (전체 배열) + +// 0개 요청 +const result3 = take(numbers, 0); +// Returns: [] + +// 빈 배열 처리 +const result4 = take([], 3); +// Returns: [] + +// 음수 처리 +const result5 = take(numbers, -1); +// Returns: [] +``` + +#### 파라미터 + +- `array` (`T[]`): 요소를 가져올 배열이에요. +- `count` (`number`): 가져올 요소의 개수예요. 기본값은 1이에요. + +#### 반환 값 + +(`T[]`): 앞에서부터 지정된 개수만큼의 요소를 포함하는 새로운 배열이에요. diff --git a/docs/ko/compat/reference/array/takeRight.md b/docs/ko/compat/reference/array/takeRight.md new file mode 100644 index 000000000..0df29e97a --- /dev/null +++ b/docs/ko/compat/reference/array/takeRight.md @@ -0,0 +1,63 @@ +# takeRight (Lodash 호환성) + +::: warning `es-toolkit`의 [takeRight](../../../reference/array/takeRight.md)를 사용하세요 + +이 `takeRight` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [takeRight](../../../reference/array/takeRight.md)를 사용하세요. + +::: + +배열의 뒤에서부터 지정된 개수만큼의 요소를 가져와요. + +```typescript +const result = takeRight(array, count); +``` + +## 사용법 + +### `takeRight(array, count)` + +배열의 뒤에서부터 지정된 개수만큼의 요소를 가져와서 새로운 배열을 만들고 싶을 때 `takeRight`를 사용하세요. 요청한 개수가 배열의 길이보다 크다면 전체 배열을 반환해요. + +```typescript +import { takeRight } from 'es-toolkit/compat'; + +// 숫자 배열에서 뒤의 2개 요소를 가져와요. +takeRight([1, 2, 3, 4, 5], 2); +// Returns: [4, 5] + +// 문자열 배열에서 뒤의 3개 요소를 가져와요. +takeRight(['a', 'b', 'c'], 2); +// Returns: ['b', 'c'] + +// 요청한 개수가 배열 길이보다 클 때 +takeRight([1, 2, 3], 5); +// Returns: [1, 2, 3] + +// 0개 요청 +takeRight([1, 2, 3], 0); +// Returns: [] + +// 음수 요청 +takeRight([1, 2, 3], -1); +// Returns: [] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { takeRight } from 'es-toolkit/compat'; + +takeRight(null, 2); // [] +takeRight(undefined, 2); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 요소를 가져올 배열이에요. +- `count` (`number`, 선택): 가져올 요소의 개수예요. 기본값은 `1`이에요. + +#### 반환 값 + +(`T[]`): 뒤에서부터 지정된 개수만큼의 요소를 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/takeRightWhile.md b/docs/ko/compat/reference/array/takeRightWhile.md new file mode 100644 index 000000000..adb995b1c --- /dev/null +++ b/docs/ko/compat/reference/array/takeRightWhile.md @@ -0,0 +1,71 @@ +# takeRightWhile (Lodash 호환성) + +::: warning `es-toolkit`의 [takeRightWhile](../../../reference/array/takeRightWhile.md)를 사용하세요 + +이 `takeRightWhile` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [takeRightWhile](../../../reference/array/takeRightWhile.md)를 사용하세요. + +::: + +조건을 만족하는 동안 배열의 뒤에서부터 요소들을 가져와요. + +```typescript +const result = takeRightWhile(array, predicate); +``` + +## 사용법 + +### `takeRightWhile(array, predicate)` + +배열의 끝에서부터 시작해서 조건을 만족하는 동안 요소들을 가져와서 새로운 배열을 만들고 싶을 때 `takeRightWhile`를 사용하세요. 조건이 거짓으로 평가되면 멈춰요. + +```typescript +import { takeRightWhile } from 'es-toolkit/compat'; + +// 함수 조건 사용 +const numbers = [1, 2, 3, 4, 5]; +takeRightWhile(numbers, x => x > 3); +// Returns: [4, 5] + +// 객체 속성 조건 사용 +const users = [ + { user: 'barney', active: true }, + { user: 'fred', active: false }, + { user: 'pebbles', active: false }, +]; + +takeRightWhile(users, o => !o.active); +// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] + +// 부분 객체로 조건 매칭 +takeRightWhile(users, { active: false }); +// Returns: [{ user: 'pebbles', active: false }] + +// 속성-값 배열로 조건 매칭 +takeRightWhile(users, ['active', false]); +// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] + +// 속성명으로 참으로 평가되는 값 확인 +const items = [{ active: false }, { active: true }, { active: true }]; +takeRightWhile(items, 'active'); +// Returns: [{ active: true }, { active: true }] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { takeRightWhile } from 'es-toolkit/compat'; + +takeRightWhile(null, x => x > 0); // [] +takeRightWhile(undefined, x => x > 0); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 처리할 배열이에요. +- `predicate` (`ListIteratee`, 선택): 각 요소에 대해 실행할 조건이에요. 함수, 부분 객체, 속성-값 배열, 속성명을 사용할 수 있어요. 기본값은 항등 함수예요. + +#### 반환 값 + +(`T[]`): 조건을 만족하는 동안 배열의 뒤에서부터 가져온 요소들의 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/takeWhile.md b/docs/ko/compat/reference/array/takeWhile.md new file mode 100644 index 000000000..aadb5a04c --- /dev/null +++ b/docs/ko/compat/reference/array/takeWhile.md @@ -0,0 +1,71 @@ +# takeWhile (Lodash 호환성) + +::: warning `es-toolkit`의 [takeWhile](../../../reference/array/takeWhile.md)를 사용하세요 + +이 `takeWhile` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [takeWhile](../../../reference/array/takeWhile.md)를 사용하세요. + +::: + +조건을 만족하는 동안 배열의 앞에서부터 요소들을 가져와요. + +```typescript +const result = takeWhile(array, predicate); +``` + +## 사용법 + +### `takeWhile(array, predicate)` + +배열의 시작에서부터 조건을 만족하는 동안 요소들을 가져와서 새로운 배열을 만들고 싶을 때 `takeWhile`을 사용하세요. 조건이 거짓으로 평가되면 멈춰요. + +```typescript +import { takeWhile } from 'es-toolkit/compat'; + +// 함수 조건 사용 +const numbers = [1, 2, 3, 4, 5]; +takeWhile(numbers, x => x < 3); +// Returns: [1, 2] + +// 객체 속성 조건 사용 +const users = [ + { user: 'barney', active: false }, + { user: 'fred', active: false }, + { user: 'pebbles', active: true }, +]; + +takeWhile(users, o => !o.active); +// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] + +// 부분 객체로 조건 매칭 +takeWhile(users, { active: false }); +// Returns: [{ user: 'barney', active: false }] + +// 속성-값 배열로 조건 매칭 +takeWhile(users, ['active', false]); +// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] + +// 속성명으로 참으로 평가되는 값 확인 +const items = [{ active: true }, { active: true }, { active: false }]; +takeWhile(items, 'active'); +// Returns: [{ active: true }, { active: true }] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { takeWhile } from 'es-toolkit/compat'; + +takeWhile(null, x => x > 0); // [] +takeWhile(undefined, x => x > 0); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 처리할 배열이에요. +- `predicate` (`ListIteratee`, 선택): 각 요소에 대해 실행할 조건이에요. 함수, 부분 객체, 속성-값 배열, 속성명을 사용할 수 있어요. 기본값은 항등 함수예요. + +#### 반환 값 + +(`T[]`): 조건을 만족하는 동안 배열의 앞에서부터 가져온 요소들의 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/union.md b/docs/ko/compat/reference/array/union.md new file mode 100644 index 000000000..4a84b3f0a --- /dev/null +++ b/docs/ko/compat/reference/array/union.md @@ -0,0 +1,62 @@ +# union (Lodash 호환성) + +::: warning `es-toolkit`의 [union](../../../reference/array/union.md)을 사용하세요 + +이 `union` 함수는 복잡한 배열 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [union](../../../reference/array/union.md)을 사용하세요. + +::: + +여러 배열에서 고유한 값들만 모아서 새로운 배열을 만들어요. + +```typescript +const result = union(...arrays); +``` + +## 사용법 + +### `union(...arrays)` + +여러 배열들을 합치고 중복을 제거해서 고유한 값들만 포함하는 새로운 배열을 만들고 싶을 때 `union`을 사용하세요. 각 값이 처음 나타나는 순서를 유지해요. + +```typescript +import { union } from 'es-toolkit/compat'; + +// 숫자 배열들 합치기 +union([2], [1, 2]); +// Returns: [2, 1] + +// 여러 배열 합치기 +union([2], [1, 2], [2, 3]); +// Returns: [2, 1, 3] + +// 중첩된 배열은 평평하게 하지 않아요 +union([1, 3, 2], [1, [5]], [2, [4]]); +// Returns: [1, 3, 2, [5], [4]] + +// 배열이 아닌 값은 무시해요 +union([0], 3, { '0': 1 }, null, [2, 1]); +// Returns: [0, 2, 1] + +// 배열과 유사한 객체도 처리해요 +union([0], { 0: 'a', length: 1 }, [2, 1]); +// Returns: [0, 'a', 2, 1] +``` + +`null`이나 `undefined`는 무시해요. + +```typescript +import { union } from 'es-toolkit/compat'; + +union([1, 2], null, undefined, [3, 4]); +// Returns: [1, 2, 3, 4] +``` + +#### 파라미터 + +- `...arrays` (`Array | null | undefined>`): 합칠 배열들이에요. 배열이 아닌 값들은 무시돼요. + +#### 반환 값 + +(`T[]`): 모든 배열의 고유한 값들을 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/unionBy.md b/docs/ko/compat/reference/array/unionBy.md new file mode 100644 index 000000000..5e6f3441d --- /dev/null +++ b/docs/ko/compat/reference/array/unionBy.md @@ -0,0 +1,66 @@ +# unionBy (Lodash 호환성) + +::: warning `es-toolkit`의 [unionBy](../../../reference/array/unionBy.md)를 사용하세요 + +이 `unionBy` 함수는 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [unionBy](../../../reference/array/unionBy.md)를 사용하세요. + +::: + +여러 배열을 합치고 지정한 기준으로 고유한 값들만 남겨요. + +```typescript +const result = unionBy(...arrays, iteratee); +``` + +## 사용법 + +### `unionBy(...arrays, iteratee)` + +여러 배열들을 합치고 주어진 기준 함수로 중복을 제거해서 고유한 값들만 포함하는 새로운 배열을 만들고 싶을 때 `unionBy`를 사용하세요. 각 값이 처음 나타나는 순서를 유지해요. + +```typescript +import { unionBy } from 'es-toolkit/compat'; + +// 소수점을 내림해서 비교 +unionBy([2.1], [1.2, 2.3], Math.floor); +// Returns: [2.1, 1.2] + +// 객체의 속성으로 비교 +unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); +// Returns: [{ x: 1 }, { x: 2 }] + +// 함수로 비교 +unionBy( + [{ id: 1, name: 'a' }], + [ + { id: 2, name: 'b' }, + { id: 1, name: 'c' }, + ], + item => item.id +); +// Returns: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }] + +// 부분 객체로 비교 +unionBy([{ x: 1, y: 1 }], [{ x: 1, y: 2 }], { x: 1 }); +// Returns: [{ x: 1, y: 1 }] +``` + +`null`이나 `undefined` 배열은 무시해요. + +```typescript +import { unionBy } from 'es-toolkit/compat'; + +unionBy([1, 2], null, undefined, [3, 4], x => x); +// Returns: [1, 2, 3, 4] +``` + +#### 파라미터 + +- `...arrays` (`Array | null | undefined>`): 합칠 배열들이에요. +- `iteratee` (`ValueIteratee`): 고유성을 결정할 기준이에요. 함수, 속성 이름, 부분 객체, 속성-값 배열을 사용할 수 있어요. + +#### 반환 값 + +(`T[]`): 지정한 기준으로 중복을 제거한 고유한 값들을 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/unionWith.md b/docs/ko/compat/reference/array/unionWith.md new file mode 100644 index 000000000..62a1826e3 --- /dev/null +++ b/docs/ko/compat/reference/array/unionWith.md @@ -0,0 +1,64 @@ +# unionWith (Lodash 호환성) + +::: warning `es-toolkit`의 [unionWith](../../../reference/array/unionWith.md)를 사용하세요 + +이 `unionWith` 함수는 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [unionWith](../../../reference/array/unionWith.md)를 사용하세요. + +::: + +여러 배열을 합치고 비교 함수로 고유한 값들만 남겨요. + +```typescript +const result = unionWith(...arrays, comparator); +``` + +## 사용법 + +### `unionWith(...arrays, comparator)` + +여러 배열들을 합치고 커스텀 비교 함수로 중복을 제거해서 고유한 값들만 포함하는 새로운 배열을 만들고 싶을 때 `unionWith`를 사용하세요. 각 값이 처음 나타나는 순서를 유지해요. + +```typescript +import { unionWith } from 'es-toolkit/compat'; + +// 커스텀 비교 함수 사용 +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, +]; +const others = [ + { x: 1, y: 1 }, + { x: 1, y: 2 }, +]; + +unionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); +// Returns: [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 1, y: 1 }] + +// 간단한 동등성 비교 +unionWith([1, 2], [2, 3], (a, b) => a === b); +// Returns: [1, 2, 3] + +// 문자열 길이로 비교 +unionWith(['ab', 'cd'], ['ef', 'gh', 'ab'], (a, b) => a.length === b.length); +// Returns: ['ab'] +``` + +`null`이나 `undefined` 배열은 무시해요. + +```typescript +import { unionWith } from 'es-toolkit/compat'; + +unionWith([1, 2], null, undefined, [3, 4], (a, b) => a === b); +// Returns: [1, 2, 3, 4] +``` + +#### 파라미터 + +- `...arrays` (`Array | null | undefined>`): 합칠 배열들이에요. +- `comparator` (`(a: T, b: T) => boolean`): 두 값이 같은지 판단하는 비교 함수예요. + +#### 반환 값 + +(`T[]`): 비교 함수로 중복을 제거한 고유한 값들을 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/uniq.md b/docs/ko/compat/reference/array/uniq.md new file mode 100644 index 000000000..36ef7aa17 --- /dev/null +++ b/docs/ko/compat/reference/array/uniq.md @@ -0,0 +1,51 @@ +# uniq (Lodash 호환성) + +::: warning `es-toolkit`의 [uniq](../../../reference/array/uniq.md)를 사용하세요 + +이 `uniq` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [uniq](../../../reference/array/uniq.md)를 사용하세요. + +::: + +배열에서 중복된 요소를 제거하여 고유한 요소만 남긴 새로운 배열을 만들어요. + +```typescript +const result = uniq([1, 2, 2, 3, 3, 4]); +// result는 [1, 2, 3, 4]가 돼요. +``` + +## 사용법 + +### `uniq(array)` + +배열에서 중복된 요소를 제거하고 고유한 요소만 포함하는 새로운 배열을 반환해요. 첫 번째로 나타나는 요소만 유지되고 순서는 보존돼요. + +```typescript +import { uniq } from 'es-toolkit/compat'; + +// 숫자 배열에서 중복 제거 +const numbers = [1, 2, 2, 3, 3, 4, 1]; +const result1 = uniq(numbers); +// Returns: [1, 2, 3, 4] + +// 문자열 배열에서 중복 제거 +const strings = ['a', 'b', 'b', 'c', 'a']; +const result2 = uniq(strings); +// Returns: ['a', 'b', 'c'] + +// 객체 배열에서 중복 제거 (참조값 비교) +const obj1 = { id: 1 }; +const obj2 = { id: 2 }; +const objects = [obj1, obj2, obj1]; +const result3 = uniq(objects); +// Returns: [{ id: 1 }, { id: 2 }] +``` + +#### 파라미터 + +- `array` (`T[]`): 처리할 배열이에요. + +#### 반환 값 + +(`T[]`): 중복이 제거된 새로운 배열이에요. diff --git a/docs/ko/compat/reference/array/uniqBy.md b/docs/ko/compat/reference/array/uniqBy.md new file mode 100644 index 000000000..e05adc772 --- /dev/null +++ b/docs/ko/compat/reference/array/uniqBy.md @@ -0,0 +1,55 @@ +# uniqBy (Lodash 호환성) + +::: warning `es-toolkit`의 [uniqBy](../../../reference/array/uniqBy.md)를 사용하세요 + +이 `uniqBy` 함수는 `null`이나 `undefined` 처리, 복잡한 인자 타입 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [uniqBy](../../../reference/array/uniqBy.md)를 사용하세요. + +::: + +배열에서 변환 함수가 반환하는 값으로 중복을 제거하여 유일한 요소들로 구성된 새 배열을 만들어요. + +```typescript +const result = uniqBy(array, iteratee); +``` + +## 사용법 + +### `uniqBy(array, iteratee)` + +배열의 각 요소에 변환 함수를 적용하여, 변환 결과가 같은 요소들 중에서 첫 번째 요소만 유지해요. 객체 배열에서 특정 속성을 기준으로 중복을 제거하거나, 숫자 배열에서 특정 계산 결과를 기준으로 중복을 제거할 때 유용해요. + +```typescript +import { uniqBy } from 'es-toolkit/compat'; + +// 숫자 배열에서 Math.floor 결과로 중복 제거 +uniqBy([2.1, 1.2, 2.3], Math.floor); +// Returns: [2.1, 1.2] + +// 객체 배열에서 속성으로 중복 제거 +uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); +// Returns: [{ x: 1 }, { x: 2 }] + +// 함수로 중복 제거 +uniqBy([{ name: 'John' }, { name: 'Jane' }, { name: 'John' }], obj => obj.name); +// Returns: [{ name: 'John' }, { name: 'Jane' }] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { uniqBy } from 'es-toolkit/compat'; + +uniqBy(null, Math.floor); // [] +uniqBy(undefined, 'x'); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 중복을 제거할 배열이에요. +- `iteratee` (`ValueIteratee`): 각 요소에 적용할 변환 함수예요. 함수, 속성 이름, 부분 객체 등을 사용할 수 있어요. + +#### 반환 값 + +(`T[]`): 변환 함수 결과를 기준으로 중복이 제거된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/uniqWith.md b/docs/ko/compat/reference/array/uniqWith.md new file mode 100644 index 000000000..f9f31c446 --- /dev/null +++ b/docs/ko/compat/reference/array/uniqWith.md @@ -0,0 +1,60 @@ +# uniqWith (Lodash 호환성) + +::: warning `es-toolkit`의 [uniqWith](../../../reference/array/uniqWith.md)를 사용하세요 + +이 `uniqWith` 함수는 `null`이나 `undefined` 처리, 복잡한 인자 타입 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [uniqWith](../../../reference/array/uniqWith.md)를 사용하세요. + +::: + +배열에서 비교 함수를 사용하여 중복을 제거하고 유일한 요소들로 구성된 새 배열을 만들어요. + +```typescript +const result = uniqWith(array, comparator); +``` + +## 사용법 + +### `uniqWith(array, comparator)` + +배열의 각 요소를 비교 함수로 비교하여 중복을 제거해요. 비교 함수가 `true`를 반환하면 두 요소를 같다고 판단하고, 첫 번째로 나타나는 요소만 유지해요. 비교 함수를 제공하지 않으면 기본적으로 얕은 동등성 비교를 사용해요. + +```typescript +import { uniqWith } from 'es-toolkit/compat'; + +// 비교 함수 없이 사용 (얕은 동등성 비교) +uniqWith([1, 2, 2, 3]); +// Returns: [1, 2, 3] + +// 사용자 정의 비교 함수로 홀수/짝수 기준 중복 제거 +uniqWith([1, 2, 3, 4], (a, b) => a % 2 === b % 2); +// Returns: [1, 2] + +// 객체 배열에서 속성 기준 중복 제거 +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 1, y: 2 }, +]; +uniqWith(objects, (a, b) => a.x === b.x && a.y === b.y); +// Returns: [{ x: 1, y: 2 }, { x: 2, y: 1 }] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { uniqWith } from 'es-toolkit/compat'; + +uniqWith(null); // [] +uniqWith(undefined); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 중복을 제거할 배열이에요. +- `comparator` (`(a: T, b: T) => boolean`, 선택): 두 요소가 같은지 비교할 함수예요. `true`를 반환하면 같다고 판단해요. 기본값은 얕은 동등성 비교예요. + +#### 반환 값 + +(`T[]`): 비교 함수 결과를 기준으로 중복이 제거된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/unzip.md b/docs/ko/compat/reference/array/unzip.md new file mode 100644 index 000000000..bf01e4f39 --- /dev/null +++ b/docs/ko/compat/reference/array/unzip.md @@ -0,0 +1,68 @@ +# unzip (Lodash 호환성) + +::: warning `es-toolkit`의 [unzip](../../../reference/array/unzip.md)를 사용하세요 + +이 `unzip` 함수는 `null`이나 `undefined` 처리, 배열이 아닌 값 필터링 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [unzip](../../../reference/array/unzip.md)를 사용하세요. + +::: + +묶여있는 배열의 같은 위치에 있는 요소들을 모아서 새 배열로 만들어요. + +```typescript +const result = unzip(array); +``` + +## 사용법 + +### `unzip(array)` + +중첩된 배열에서 같은 인덱스에 있는 요소들을 모아서 새로운 배열로 반환해요. `zip` 함수의 반대 동작을 수행해요. 행렬을 전치하거나 구조화된 데이터를 재정렬할 때 유용해요. + +```typescript +import { unzip } from 'es-toolkit/compat'; + +// 문자열과 불린, 숫자가 섞인 배열 언집 +const zipped = [ + ['a', true, 1], + ['b', false, 2], +]; +const result = unzip(zipped); +// Returns: [['a', 'b'], [true, false], [1, 2]] + +// 숫자 배열들 언집 +const numbers = [ + [1, 4], + [2, 5], + [3, 6], +]; +unzip(numbers); +// Returns: [[1, 2, 3], [4, 5, 6]] + +// 길이가 다른 배열들도 처리 +const uneven = [ + ['a', 1], + ['b', 2, true], +]; +unzip(uneven); +// Returns: [['a', 'b'], [1, 2], [undefined, true]] +``` + +`null`이나 `undefined`, 빈 배열은 빈 배열로 처리해요. + +```typescript +import { unzip } from 'es-toolkit/compat'; + +unzip(null); // [] +unzip(undefined); // [] +unzip([]); // [] +``` + +#### 파라미터 + +- `array` (`T[][] | ArrayLike> | null | undefined`): 언집할 중첩 배열이에요. 각 내부 배열의 같은 위치 요소들이 모여요. + +#### 반환 값 + +(`T[][]`): 같은 위치의 요소들이 모인 새로운 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/unzipWith.md b/docs/ko/compat/reference/array/unzipWith.md new file mode 100644 index 000000000..3eb048f37 --- /dev/null +++ b/docs/ko/compat/reference/array/unzipWith.md @@ -0,0 +1,84 @@ +# unzipWith (Lodash 호환성) + +::: warning `es-toolkit`의 `unzipWith`를 사용하세요 + +이 `unzipWith` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [unzipWith](../../../reference/array/unzipWith.md)를 사용하세요. + +::: + +묶여있는 배열의 같은 위치에 있는 요소들을 모아서 변환 함수를 적용한 새 배열을 만들어요. + +```typescript +const result = unzipWith(array, iteratee); +``` + +## 사용법 + +### `unzipWith(array, iteratee)` + +중첩된 배열에서 같은 인덱스에 있는 요소들을 모아서 변환 함수를 적용해요. `unzip` 함수와 비슷하지만, 각 그룹에 변환 함수를 적용할 수 있어요. 변환 함수를 제공하지 않으면 기본 `unzip` 동작을 수행해요. + +```typescript +import { unzipWith } from 'es-toolkit/compat'; + +// 같은 위치의 요소들을 더하기 +unzipWith( + [ + [1, 10, 100], + [2, 20, 200], + ], + (a, b) => a + b +); +// Returns: [3, 30, 300] + +// 변환 함수 없이 사용 (기본 unzip 동작) +unzipWith([ + [1, 4], + [2, 5], + [3, 6], +]); +// Returns: [[1, 2, 3], [4, 5, 6]] + +// 문자열 연결 +unzipWith( + [ + ['a', 'x'], + ['b', 'y'], + ['c', 'z'], + ], + (a, b) => a + b +); +// Returns: ['abc', 'xyz'] + +// 최대값 찾기 +unzipWith( + [ + [1, 10], + [2, 20], + [3, 5], + ], + Math.max +); +// Returns: [3, 20] +``` + +`null`이나 `undefined`, 빈 배열은 빈 배열로 처리해요. + +```typescript +import { unzipWith } from 'es-toolkit/compat'; + +unzipWith(null, (a, b) => a + b); // [] +unzipWith(undefined, (a, b) => a + b); // [] +unzipWith([], (a, b) => a + b); // [] +``` + +#### 파라미터 + +- `array` (`ArrayLike> | null | undefined`): 언집할 중첩 배열이에요. +- `iteratee` (`(...values: T[]) => R`, 선택): 각 그룹의 요소들에 적용할 변환 함수예요. 제공하지 않으면 기본 `unzip` 동작을 수행해요. + +#### 반환 값 + +(`R[]` 또는 `T[][]`): 변환 함수가 있으면 변환된 결과 배열을, 없으면 언집된 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/without.md b/docs/ko/compat/reference/array/without.md new file mode 100644 index 000000000..f02d288e8 --- /dev/null +++ b/docs/ko/compat/reference/array/without.md @@ -0,0 +1,49 @@ +# without (Lodash 호환성) + +::: warning `es-toolkit`의 [without](../../../reference/array/without.md)을 사용하세요 + +이 `without` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [without](../../../reference/array/without.md)을 사용하세요. + +::: + +배열에서 지정된 값들을 제외한 새로운 배열을 만들어요. + +```typescript +const result = without([1, 2, 3, 4, 5], 2, 4); +// result는 [1, 3, 5]가 돼요. +``` + +## 사용법 + +### `without(array, ...values)` + +배열에서 지정된 값들을 제거한 새로운 배열을 반환해요. 원본 배열은 변경되지 않아요. + +```typescript +import { without } from 'es-toolkit/compat'; + +// 숫자 배열에서 여러 값 제거 +const numbers = [1, 2, 3, 4, 5, 2, 4]; +const result1 = without(numbers, 2, 4); +// Returns: [1, 3, 5] + +// 문자열 배열에서 값 제거 +const fruits = ['apple', 'banana', 'cherry', 'banana']; +const result2 = without(fruits, 'banana'); +// Returns: ['apple', 'cherry'] + +// 빈 배열 처리 +const result3 = without([], 1, 2, 3); +// Returns: [] +``` + +#### 파라미터 + +- `array` (`T[]`): 처리할 원본 배열이에요. +- `...values` (`T[]`): 제거할 값들이에요. + +#### 반환 값 + +(`T[]`): 지정된 값들을 제거한 새로운 배열이에요. diff --git a/docs/ko/compat/reference/array/xor.md b/docs/ko/compat/reference/array/xor.md new file mode 100644 index 000000000..c940a5ff6 --- /dev/null +++ b/docs/ko/compat/reference/array/xor.md @@ -0,0 +1,61 @@ +# xor (Lodash 호환성) + +::: warning `es-toolkit`의 [xor](../../../reference/array/xor.md)을 사용하세요 + +이 `xor` 함수는 `null`이나 `undefined` 처리, 복잡한 중복 계산 로직 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [xor](../../../reference/array/xor.md)를 사용하세요. + +::: + +여러 배열들에서 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 만들어요. + +```typescript +const result = xor(...arrays); +``` + +## 사용법 + +### `xor(...arrays)` + +여러 배열의 대칭 차집합을 계산해요. 즉, 주어진 배열들 중 정확히 하나의 배열에만 존재하는 요소들을 반환해요. 두 개 이상의 배열을 비교할 때 겹치지 않는 고유한 요소들을 찾고 싶을 때 유용해요. + +```typescript +import { xor } from 'es-toolkit/compat'; + +// 두 배열의 대칭 차집합 +xor([1, 2, 3, 4], [3, 4, 5, 6]); +// Returns: [1, 2, 5, 6] + +// 세 배열의 대칭 차집합 +xor([1, 2], [2, 3], [4, 5]); +// Returns: [1, 3, 4, 5] + +// 문자열 배열 +xor(['a', 'b'], ['b', 'c']); +// Returns: ['a', 'c'] + +// 하나의 배열만 제공 +xor([1, 2, 3]); +// Returns: [1, 2, 3] +``` + +`null`이나 `undefined`, 빈 배열은 무시되고 유효한 배열만 처리해요. + +```typescript +import { xor } from 'es-toolkit/compat'; + +xor([1, 2], null, [2, 3]); +// Returns: [1, 3] + +xor([], [1, 2], [2, 3]); +// Returns: [1, 3] +``` + +#### 파라미터 + +- `...arrays` (`Array | null | undefined>`): 대칭 차집합을 계산할 배열들이에요. `null`이나 `undefined`는 무시돼요. + +#### 반환 값 + +(`T[]`): 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/xorBy.md b/docs/ko/compat/reference/array/xorBy.md new file mode 100644 index 000000000..89bb9fa27 --- /dev/null +++ b/docs/ko/compat/reference/array/xorBy.md @@ -0,0 +1,63 @@ +# xorBy (Lodash 호환성) + +::: warning `es-toolkit`의 [xorBy](../../../reference/array/xorBy.md)을 사용하세요 + +이 `xorBy` 함수는 `null`이나 `undefined` 처리, 복잡한 중복 계산 로직 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [xorBy](../../../reference/array/xorBy.md)를 사용하세요. + +::: + +여러 배열들에서 변환 함수를 기준으로 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 만들어요. + +```typescript +const result = xorBy(...arrays, iteratee); +``` + +## 사용법 + +### `xorBy(...arrays, iteratee)` + +여러 배열의 대칭 차집합을 변환 함수를 기준으로 계산해요. 각 요소에 변환 함수를 적용한 결과가 정확히 하나의 배열에만 존재하는 요소들을 반환해요. 객체 배열에서 특정 속성을 기준으로 비교하거나, 숫자 배열에서 특정 계산 결과를 기준으로 비교할 때 유용해요. + +```typescript +import { xorBy } from 'es-toolkit/compat'; + +// Math.floor 결과로 대칭 차집합 계산 +xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); +// Returns: [1.2, 4.3] + +// 객체 속성으로 대칭 차집합 계산 +xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); +// Returns: [{ x: 2 }] + +// 함수로 대칭 차집합 계산 +const users1 = [{ name: 'John', age: 30 }]; +const users2 = [ + { name: 'Jane', age: 25 }, + { name: 'John', age: 30 }, +]; +xorBy(users1, users2, user => user.name); +// Returns: [{ name: 'Jane', age: 25 }] + +// 세 배열의 대칭 차집합 +xorBy([1.2, 2.3], [3.4, 4.5], [5.6, 6.7], Math.floor); +// Returns: [1.2, 2.3, 3.4, 4.5, 5.6, 6.7] +``` + +`null`이나 `undefined`는 무시돼요. + +```typescript +import { xorBy } from 'es-toolkit/compat'; + +xorBy([2.1, 1.2], null, [4.3, 2.4], Math.floor); +// Returns: [1.2, 4.3] +``` + +#### 파라미터 + +- `...arrays` (`Array | null | undefined | ValueIteratee>`): 대칭 차집합을 계산할 배열들과 마지막에 변환 함수예요. 함수, 속성 이름, 부분 객체 등을 사용할 수 있어요. + +#### 반환 값 + +(`T[]`): 변환 함수 결과를 기준으로 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/xorWith.md b/docs/ko/compat/reference/array/xorWith.md new file mode 100644 index 000000000..0f33b2591 --- /dev/null +++ b/docs/ko/compat/reference/array/xorWith.md @@ -0,0 +1,66 @@ +# xorWith (Lodash 호환성) + +::: warning `es-toolkit`의 [xorWith](../../../reference/array/xorWith.md)을 사용하세요 + +이 `xorWith` 함수는 `null`이나 `undefined` 처리, 복잡한 중복 계산 로직 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [xorWith](../../../reference/array/xorWith.md)를 사용하세요. + +::: + +여러 배열들에서 비교 함수를 사용하여 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 만들어요. + +```typescript +const result = xorWith(...arrays, comparator); +``` + +## 사용법 + +### `xorWith(...arrays, comparator)` + +여러 배열의 대칭 차집합을 비교 함수를 사용하여 계산해요. 비교 함수가 `true`를 반환하면 두 요소를 같다고 판단하고, 정확히 하나의 배열에만 존재하는 요소들을 반환해요. 복잡한 객체나 사용자 정의 비교 로직이 필요할 때 유용해요. + +```typescript +import { xorWith } from 'es-toolkit/compat'; + +// 간단한 숫자 비교 +xorWith([1, 2], [2, 3], (a, b) => a === b); +// Returns: [1, 3] + +// 객체의 속성 비교 +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, +]; +const others = [ + { x: 1, y: 1 }, + { x: 1, y: 2 }, +]; +xorWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); +// Returns: [{ x: 2, y: 1 }, { x: 1, y: 1 }] + +// 세 배열의 대칭 차집합 +xorWith([1], [2], [3], (a, b) => a === b); +// Returns: [1, 2, 3] + +// 문자열 길이로 비교 +xorWith(['hello'], ['world', 'hi'], (a, b) => a.length === b.length); +// Returns: ['hi'] +``` + +비교 함수를 제공하지 않으면 기본적으로 얕은 동등성 비교를 사용해요. + +```typescript +import { xorWith } from 'es-toolkit/compat'; + +xorWith([1, 2], [2, 3]); +// Returns: [1, 3] +``` + +#### 파라미터 + +- `...arrays` (`Array | null | undefined | ((a: T, b: T) => boolean)>`): 대칭 차집합을 계산할 배열들과 마지막에 비교 함수예요. 비교 함수는 두 요소가 같으면 `true`를 반환해야 해요. + +#### 반환 값 + +(`T[]`): 비교 함수 결과를 기준으로 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 반환해요. diff --git a/docs/ko/compat/reference/array/zip.md b/docs/ko/compat/reference/array/zip.md new file mode 100644 index 000000000..faedce2b8 --- /dev/null +++ b/docs/ko/compat/reference/array/zip.md @@ -0,0 +1,48 @@ +# zip (Lodash 호환성) + +::: warning `es-toolkit`의 [zip](../../../reference/array/zip.md)을 사용하세요 + +이 `zip` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [zip](../../../reference/array/zip.md)을 사용하세요. + +::: + +여러 배열을 튜플의 단일 배열로 결합해요. + +```typescript +const result = zip([1, 2], ['a', 'b']); +// result는 [[1, 'a'], [2, 'b']]가 돼요. +``` + +## 사용법 + +### `zip(...arrs)` + +여러 배열을 받아서 각 인덱스의 요소들을 하나의 튜플로 묶어 새로운 배열을 만들어요. 입력 배열의 길이가 다를 경우, 결과 배열의 길이는 가장 긴 입력 배열의 길이를 가지며, 누락된 요소는 `undefined`로 채워져요. + +```typescript +import { zip } from 'es-toolkit/compat'; + +const arr1 = [1, 2, 3]; +const arr2 = ['a', 'b', 'c']; +const result = zip(arr1, arr2); +// Returns: [[1, 'a'], [2, 'b'], [3, 'c']] + +// 길이가 다른 배열들 +const arr3 = [true, false]; +const result2 = zip(arr1, arr2, arr3); +// Returns: [[1, 'a', true], [2, 'b', false], [3, 'c', undefined]] + +// 빈 배열이 포함된 경우 +zip([1, 2], [], ['a', 'b']); +// Returns: [[1, undefined, 'a'], [2, undefined, 'b']] +``` + +#### 파라미터 + +- `...arrs` (`any[][]`): 결합할 배열들이에요. + +#### 반환 값 + +(`any[][]`): 입력 배열들의 각 인덱스 요소들을 포함하는 튜플로 이루어진 새로운 배열이에요. diff --git a/docs/ko/compat/reference/array/zipObject.md b/docs/ko/compat/reference/array/zipObject.md new file mode 100644 index 000000000..8bded3741 --- /dev/null +++ b/docs/ko/compat/reference/array/zipObject.md @@ -0,0 +1,50 @@ +# zipObject (Lodash 호환성) + +::: warning `es-toolkit`의 [zipObject](../../../reference/array/zipObject.md)를 사용하세요 + +이 `zipObject` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [zipObject](../../../reference/array/zipObject.md)를 사용하세요. + +::: + +두 배열을 사용해서 객체를 만들어요. 첫 번째 배열은 버전망을 프로퍼티 이름으로, 두 번째 배열은 해당 값으로 사용해요. + +```typescript +const result = zipObject(keys, values); +``` + +## 사용법 + +### `zipObject(keys, values)` + +키 배열과 값 배열을 받아서 하나의 객체로 만들고 싶을 때 `zipObject`를 사용하세요. 첫 번째 배열의 요소들을 프로퍼티 이름으로, 두 번째 배열의 요소들을 해당 값으로 사용해서 객체를 만들어요. API 응답을 처리하거나 데이터를 변환할 때 특히 유용해요. + +```typescript +import { zipObject } from 'es-toolkit/compat'; + +// 기본 사용법 +const keys = ['a', 'b', 'c']; +const values = [1, 2, 3]; +const result = zipObject(keys, values); +// Returns: { a: 1, b: 2, c: 3 } + +// 길이가 다른 배열들 +const keys2 = ['x', 'y', 'z']; +const values2 = [10, 20]; +const result2 = zipObject(keys2, values2); +// Returns: { x: 10, y: 20, z: undefined } + +// 빈 배열이 전달된 경우 +const result3 = zipObject([], []); +// Returns: {} +``` + +#### 파라미터 + +- `keys` (`PropertyKey[]`): 프로퍼티 이름으로 사용할 배열이에요. +- `values` (`T[]`): 프로퍼티 값으로 사용할 배열이에요. + +#### 반환 값 + +(`Record`): 만들어진 객체예요. diff --git a/docs/ko/reference/compat/array/zipObjectDeep.md b/docs/ko/compat/reference/array/zipObjectDeep.md similarity index 100% rename from docs/ko/reference/compat/array/zipObjectDeep.md rename to docs/ko/compat/reference/array/zipObjectDeep.md diff --git a/docs/ko/compat/reference/array/zipWith.md b/docs/ko/compat/reference/array/zipWith.md new file mode 100644 index 000000000..8713870ce --- /dev/null +++ b/docs/ko/compat/reference/array/zipWith.md @@ -0,0 +1,47 @@ +# zipWith (Lodash 호환성) + +::: warning `es-toolkit`의 [zipWith](../../../reference/array/zipWith.md)을 사용하세요 + +이 `zipWith` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [zipWith](../../../reference/array/zipWith.md)을 사용하세요. + +::: + +여러 배열의 요소를 결합 함수를 사용해서 새로운 배열로 결합해요. + +```typescript +const result = zipWith([1, 2], [3, 4], (a, b) => a + b); +// result는 [4, 6]이 돼요. +``` + +## 사용법 + +### `zipWith(...arrs, iteratee)` + +여러 배열을 받아서 각 인덱스의 요소들을 제공된 함수로 결합하여 새로운 배열을 만들어요. 배열의 길이가 다를 경우, 가장 긴 배열의 길이까지 처리하며 누락된 값은 `undefined`로 전달돼요. + +```typescript +import { zipWith } from 'es-toolkit/compat'; + +// 두 배열의 요소를 더하기 +const result1 = zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b); +// Returns: [5, 7, 9] + +// 세 배열의 요소를 결합 +const result2 = zipWith([1, 2], [3, 4], [5, 6], (a, b, c) => a + b + c); +// Returns: [9, 12] + +// 길이가 다른 배열들 +const result3 = zipWith([1, 2, 3], [4, 5], (a, b) => (a || 0) + (b || 0)); +// Returns: [5, 7, 3] +``` + +#### 파라미터 + +- `...arrs` (`any[][]`): 결합할 배열들이에요. +- `iteratee` (`Function`): 각 인덱스의 요소들을 결합하는 함수예요. + +#### 반환 값 + +(`any[]`): 결합 함수를 적용한 결과로 이루어진 새로운 배열이에요. diff --git a/docs/ko/compat/reference/function/after.md b/docs/ko/compat/reference/function/after.md new file mode 100644 index 000000000..a6bbafca4 --- /dev/null +++ b/docs/ko/compat/reference/function/after.md @@ -0,0 +1,75 @@ +# after (Lodash 호환성) + +::: warning `es-toolkit`의 [`after`](../../../reference/function/after.md)를 사용하세요 + +이 `after` 함수는 복잡한 타입 검증과 정수 변환 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [after](../../../reference/function/after.md)를 사용하세요. + +::: + +함수가 지정된 호출 횟수 이후에만 실행되도록 하는 함수를 만들어요. + +```typescript +const restrictedFunction = after(n, func); +``` + +## 사용법 + +### `after(n, func)` + +함수가 특정 횟수만큼 호출된 후에야 실행되도록 제한하고 싶을 때 `after`를 사용하세요. 여러 비동기 작업이 완료된 후 콜백을 실행하거나, 초기화 단계를 거친 후 함수를 활성화할 때 유용해요. + +```typescript +import { after } from 'es-toolkit/compat'; + +// 기본 사용법 +const logAfterThree = after(3, () => { + console.log('3번째 호출부터 실행돼요!'); +}); + +logAfterThree(); // 실행되지 않음 +logAfterThree(); // 실행되지 않음 +logAfterThree(); // "3번째 호출부터 실행돼요!" 출력 +logAfterThree(); // "3번째 호출부터 실행돼요!" 출력 (계속 실행됨) +``` + +여러 비동기 작업이 모두 완료된 후에 특정 콜백을 실행할 때도 사용할 수 있어요. + +```typescript +import { after } from 'es-toolkit/compat'; + +const tasks = ['task1', 'task2', 'task3']; +const allTasksComplete = after(tasks.length, () => { + console.log('모든 작업이 완료되었습니다!'); +}); + +// 각 작업이 완료될 때마다 호출 +tasks.forEach(task => { + performAsyncTask(task, () => { + console.log(`${task} 완료`); + allTasksComplete(); // 3번째 호출에서 "모든 작업이 완료되었습니다!" 출력 + }); +}); +``` + +0이나 음수를 전달하면 첫 번째 호출부터 바로 실행돼요. + +```typescript +import { after } from 'es-toolkit/compat'; + +const immediate = after(0, () => console.log('즉시 실행')); +immediate(); // "즉시 실행" + +const negative = after(-1, () => console.log('즉시 실행')); +negative(); // "즉시 실행" +``` + +#### 파라미터 + +- `n` (`number`): 함수가 실행되기 전에 필요한 호출 횟수예요. +- `func` (`TFunc`): 제한할 함수예요. + +#### 반환 값 + +(`TFunc`): n번째 호출부터 원본 함수를 실행하는 새로운 제한된 함수를 반환해요. diff --git a/docs/ko/compat/reference/function/ary.md b/docs/ko/compat/reference/function/ary.md new file mode 100644 index 000000000..3389f6b6b --- /dev/null +++ b/docs/ko/compat/reference/function/ary.md @@ -0,0 +1,90 @@ +# ary (Lodash 호환성) + +::: warning `es-toolkit`의 [`ary`](../../../reference/function/ary.md)를 사용하세요 + +이 `ary` 함수는 파라미터를 복잡하게 검증하고 있어서 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [ary](../../../reference/function/ary.md)를 사용하세요. + +::: + +함수가 받을 수 있는 인수의 개수를 제한하는 함수를 만들어요. + +```typescript +const cappedFunction = ary(func, n); +``` + +## 사용법 + +### `ary(func, n)` + +함수가 받는 인수의 개수를 제한하고 싶을 때 `ary`를 사용하세요. 너무 많은 인수를 받는 함수를 안전하게 사용하거나, 콜백 함수에서 불필요한 인수를 무시할 때 유용해요. + +```typescript +import { ary } from 'es-toolkit/compat'; + +// 기본 사용법 +function greet(name, age, city) { + return `안녕하세요, ${name}님! ${age}세, ${city}에서 오셨군요.`; +} + +const limitedGreet = ary(greet, 2); +console.log(limitedGreet('김철수', 30, '서울', '추가인수')); +// "안녕하세요, 김철수님! 30세, undefined에서 오셨군요." +// 3번째 인수부터는 무시됨 +``` + +배열 메서드와 함께 사용할 때 콜백 함수에 불필요한 인자가 전달되지 않도록 할 수 있어요. + +```typescript +import { ary } from 'es-toolkit/compat'; + +// parseInt는 두 번째 인수(기수)를 받지만, map의 콜백은 3개 인수를 전달함 +const numbers = ['1', '2', '3', '4', '5']; + +// 잘못된 사용 - parseInt가 인덱스를 기수로 받음 +console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] + +// ary를 사용해서 첫 번째 인수만 전달 +console.log(numbers.map(ary(parseInt, 1))); // [1, 2, 3, 4, 5] +``` + +함수가 원하는 파라미터 인자 숫자만 받도록 제한할 수 있어요. + +```typescript +import { ary } from 'es-toolkit/compat'; + +function sum(...args) { + return args.reduce((total, num) => total + num, 0); +} + +const sum0 = ary(sum, 0); +const sum1 = ary(sum, 1); +const sum2 = ary(sum, 2); +const sum3 = ary(sum, 3); + +console.log(sum0(1, 2, 3, 4, 5)); // 0 (인수 없음) +console.log(sum1(1, 2, 3, 4, 5)); // 1 (첫 번째 인수만) +console.log(sum2(1, 2, 3, 4, 5)); // 3 (첫 두 인수만) +console.log(sum3(1, 2, 3, 4, 5)); // 6 (첫 세 인수만) +``` + +음수나 `NaN`을 전달하면 0으로 처리되어 모든 인수가 무시돼요. + +```typescript +import { ary } from 'es-toolkit/compat'; + +const func = (a, b, c) => [a, b, c]; + +console.log(ary(func, -1)(1, 2, 3)); // [] (음수는 0으로 처리) +console.log(ary(func, NaN)(1, 2, 3)); // [] (NaN은 0으로 처리) +``` + +#### 파라미터 + +- `func` (`Function`): 인수 개수를 제한할 함수예요. +- `n` (`number`, 선택): 허용할 최대 인수 개수예요. 생략하면 함수의 `length` 속성을 사용해요. + +#### 반환 값 + +(`Function`): 최대 `n`개의 인수만 받는 새로운 함수를 반환해요. diff --git a/docs/ko/compat/reference/function/attempt.md b/docs/ko/compat/reference/function/attempt.md new file mode 100644 index 000000000..aaeb3bb1e --- /dev/null +++ b/docs/ko/compat/reference/function/attempt.md @@ -0,0 +1,66 @@ +# attempt (Lodash 호환성) + +::: warning `es-toolkit`의 [`attempt`](../../../reference/util/attempt.md) 함수나 try-catch 블록을 사용하세요 + +이 `attempt` 함수는 에러와 반환 값을 구분하지 않고 반환해서 사용할 때 혼란이 있을 수 있어요. + +대신 더 직접적이고 명확한 [`attempt`](../../../reference/util/attempt.md) 함수나 try-catch 블록을 사용하세요. + +::: + +함수를 실행하고 에러가 발생하면 에러 객체를 반환하는 함수예요. + +```typescript +const result = attempt(func, ...args); +``` + +## 사용법 + +### `attempt(func, ...args)` + +함수를 안전하게 실행하고 싶을 때 `attempt`를 사용하세요. 에러가 발생할 수 있는 함수를 실행할 때 프로그램이 중단되지 않도록 하고, 에러를 반환값으로 처리할 때 유용해요. + +```typescript +import { attempt } from 'es-toolkit/compat'; + +// 기본 사용법 - 성공하는 경우 +const result = attempt((x, y) => x + y, 2, 3); +console.log(result); // 5 + +// 에러가 발생하는 경우 +const errorResult = attempt(() => { + throw new Error('뭔가 잘못됐어요'); +}); +console.log(errorResult); // Error: 뭔가 잘못됐어요 +``` + +try-catch 블록 사용과의 차이점을 살펴보면 다음과 같아요. + +```typescript +// attempt 사용 +import { attempt } from 'es-toolkit/compat'; + +const result = attempt(riskyFunction, arg1, arg2); +if (result instanceof Error) { + console.log('에러 발생:', result.message); +} else { + console.log('결과:', result); +} + +// try-catch 사용 (더 직접적) +try { + const result = riskyFunction(arg1, arg2); + console.log('결과:', result); +} catch (error) { + console.log('에러 발생:', error.message); +} +``` + +#### 파라미터 + +- `func` (`Function`): 실행할 함수예요. +- `args` (`...any[]`): 함수에 전달할 인수들이에요. + +#### 반환 값 + +(`ReturnType | Error`): 함수가 성공하면 반환값을, 에러가 발생하면 Error 객체를 반환해요. diff --git a/docs/ko/compat/reference/function/before.md b/docs/ko/compat/reference/function/before.md new file mode 100644 index 000000000..7a91c4b3a --- /dev/null +++ b/docs/ko/compat/reference/function/before.md @@ -0,0 +1,186 @@ +# before (Lodash 호환성) + +::: warning `es-toolkit`의 [`before`](../../../reference/function/before.md)를 사용하세요 + +이 `before` 함수는 복잡한 타입 검증과 정수 변환 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [before](../../../reference/function/before.md)를 사용하세요. + +::: + +함수를 지정된 횟수까지만 실행하고, 그 이후엔 마지막 결과를 반환하는 함수를 만들어요. + +```typescript +const limitedFunction = before(n, func); +``` + +## 사용법 + +### `before(n, func)` + +함수가 특정 횟수까지만 실행되도록 제한하고 싶을 때 `before`를 사용하세요. 함수 호출 횟수를 제한하거나, 초기 설정 단계에서만 함수를 실행하고 싶을 때 유용해요. + +```typescript +import { before } from 'es-toolkit/compat'; + +// 기본 사용법 +let count = 0; +const beforeThree = before(3, () => ++count); + +console.log(beforeThree()); // 1 (첫 번째 호출) +console.log(beforeThree()); // 2 (두 번째 호출) +console.log(beforeThree()); // 2 (세 번째 호출부터는 마지막 결과 반환) +console.log(beforeThree()); // 2 (계속 마지막 결과만 반환) +``` + +클로저를 사용한 대안: + +```typescript +// before 사용 +const beforeThree = before(3, myFunction); + +// 클로저 사용 (더 간단하고 빠름) +function createBefore(limit, callback) { + let callCount = 0; + let lastResult; + + return function (...args) { + if (callCount < limit - 1) { + lastResult = callback.apply(this, args); + callCount++; + } + return lastResult; + }; +} + +const beforeThreeAlternative = createBefore(3, myFunction); +``` + +초기화 함수로 활용: + +```typescript +import { before } from 'es-toolkit/compat'; + +class Database { + constructor() { + this.isInitialized = false; + + // 초기화는 한 번만 실행 + this.initialize = before(2, () => { + console.log('데이터베이스 초기화 중...'); + this.setupConnection(); + this.isInitialized = true; + return '초기화 완료'; + }); + } + + setupConnection() { + // 실제 연결 설정 로직 + } + + query(sql) { + const initResult = this.initialize(); + console.log(initResult); // 첫 번째 호출: "초기화 완료", 이후: 동일 결과 + + // 쿼리 실행 로직 + return `쿼리 실행: ${sql}`; + } +} + +const db = new Database(); +db.query('SELECT * FROM users'); // 초기화 실행됨 +db.query('SELECT * FROM products'); // 초기화는 실행되지 않음 +``` + +API 호출 제한: + +```typescript +import { before } from 'es-toolkit/compat'; + +// API 호출을 최대 5번까지만 허용 +const limitedApiCall = before(6, endpoint => { + console.log(`API 호출: ${endpoint}`); + return fetch(endpoint).then(res => res.json()); +}); + +// 처음 5번은 실제 API 호출 +limitedApiCall('/api/data1'); // 실제 호출 +limitedApiCall('/api/data2'); // 실제 호출 +limitedApiCall('/api/data3'); // 실제 호출 +limitedApiCall('/api/data4'); // 실제 호출 +limitedApiCall('/api/data5'); // 실제 호출 +limitedApiCall('/api/data6'); // 마지막 결과 반환 (API 호출 안 함) +``` + +이벤트 리스너 제한: + +```typescript +import { before } from 'es-toolkit/compat'; + +// 클릭 이벤트를 3번까지만 처리 +const limitedClickHandler = before(4, event => { + console.log('클릭 처리됨:', event.target.id); + return `처리 완료: ${Date.now()}`; +}); + +document.getElementById('button').addEventListener('click', limitedClickHandler); +// 처음 3번 클릭만 처리되고, 그 이후엔 마지막 결과만 반환 +``` + +파라미터와 반환값 처리: + +```typescript +import { before } from 'es-toolkit/compat'; + +const limitedCalculator = before(3, (operation, a, b) => { + const result = operation === 'add' ? a + b : a - b; + console.log(`계산: ${a} ${operation} ${b} = ${result}`); + return result; +}); + +console.log(limitedCalculator('add', 5, 3)); // "계산: 5 add 3 = 8", 반환: 8 +console.log(limitedCalculator('subtract', 10, 4)); // "계산: 10 subtract 4 = 6", 반환: 6 +console.log(limitedCalculator('multiply', 7, 2)); // 계산 안 함, 반환: 6 (마지막 결과) +``` + +0 또는 1을 전달하면 함수가 실행되지 않아요: + +```typescript +import { before } from 'es-toolkit/compat'; + +const neverCalled = before(0, () => { + console.log('이 함수는 실행되지 않아요'); + return '결과'; +}); + +const onceOnly = before(1, () => { + console.log('이 함수도 실행되지 않아요'); + return '결과'; +}); + +console.log(neverCalled()); // undefined +console.log(onceOnly()); // undefined +``` + +리소스 정리 최적화: + +```typescript +import { before } from 'es-toolkit/compat'; + +// 함수 참조가 자동으로 정리되어 메모리 누수 방지 +const limitedProcessor = before(2, data => { + // 복잡한 데이터 처리 + return processComplexData(data); +}); + +// 2번째 호출 이후에는 원본 함수 참조가 제거됨 (가비지 컬렉션) +``` + +#### 파라미터 + +- `n` (`number`): 함수를 실행할 최대 횟수예요. n-1번째까지 실행되고, n번째부터는 마지막 결과를 반환해요. +- `func` (`Function`): 제한할 함수예요. + +#### 반환 값 + +(`Function`): 지정된 횟수까지만 원본 함수를 실행하고, 그 이후엔 마지막 결과를 반환하는 새로운 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/bind.md b/docs/ko/compat/reference/function/bind.md similarity index 100% rename from docs/ko/reference/compat/function/bind.md rename to docs/ko/compat/reference/function/bind.md diff --git a/docs/ko/reference/compat/function/bindKey.md b/docs/ko/compat/reference/function/bindKey.md similarity index 100% rename from docs/ko/reference/compat/function/bindKey.md rename to docs/ko/compat/reference/function/bindKey.md diff --git a/docs/ko/compat/reference/function/curry.md b/docs/ko/compat/reference/function/curry.md new file mode 100644 index 000000000..bc9b3f316 --- /dev/null +++ b/docs/ko/compat/reference/function/curry.md @@ -0,0 +1,224 @@ +# curry (Lodash 호환성) + +::: warning `es-toolkit`의 `curry`나 수동 클로저를 사용하세요 + +이 `curry` 함수는 복잡한 placeholder 처리, arity 검증, 인수 합성 로직으로 인해 느리게 동작해요. + +placeholder가 필요하지 않다면 대신 더 빠른 `es-toolkit`의 [`curry`](../../../reference/function/curry.md)나 간단한 클로저를 사용하세요. + +::: + +함수를 커링해서 인수를 하나씩 받거나 여러 개씩 받을 수 있는 함수를 만들어요. + +```typescript +const curriedFunction = curry(func, arity); +``` + +## 사용법 + +### `curry(func, arity)` + +함수를 커링해서 부분 적용을 쉽게 하고 싶을 때 `curry`를 사용하세요. 인수를 단계적으로 제공하거나 placeholder를 사용해서 특정 위치의 인수를 나중에 제공할 때 유용해요. + +```typescript +import { curry } from 'es-toolkit/compat'; + +// 기본 사용법 +function add(a, b, c) { + return a + b + c; +} + +const curriedAdd = curry(add); + +// 다양한 방식으로 호출 가능 +console.log(curriedAdd(1)(2)(3)); // 6 +console.log(curriedAdd(1, 2)(3)); // 6 +console.log(curriedAdd(1)(2, 3)); // 6 +console.log(curriedAdd(1, 2, 3)); // 6 +``` + +메인 라이브러리 curry와 비교: + +```typescript +// compat 버전 (유연함, 하지만 느림) +import { curry } from 'es-toolkit/compat'; +const curriedCompat = curry(add); +curriedCompat(1, 2)(3); // 지원됨 +curriedCompat(1)(curry.placeholder, 3)(2); // placeholder 지원 + +// 메인 라이브러리 버전 (더 빠름, 하지만 한 번에 하나씩만) +import { curry } from 'es-toolkit'; +const curriedMain = curry(add); +curriedMain(1)(2)(3); // 지원됨 +curriedMain(1, 2)(3); // 지원되지 않음 +``` + +placeholder 기능 사용: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function greet(greeting, name, punctuation) { + return `${greeting}, ${name}${punctuation}`; +} + +const curriedGreet = curry(greet); + +// placeholder로 중간 인수 건너뛰기 +const greetWithExclamation = curriedGreet(curry.placeholder, curry.placeholder, '!'); +console.log(greetWithExclamation('Hello', '김철수')); // "Hello, 김철수!" + +const sayHello = curriedGreet('Hello'); +console.log(sayHello(curry.placeholder, '~')('이영희')); // "Hello, 이영희~" +``` + +함수형 프로그래밍에서 활용: + +```typescript +import { curry } from 'es-toolkit/compat'; + +// 맵핑 함수 만들기 +const map = curry((fn, array) => array.map(fn)); +const filter = curry((predicate, array) => array.filter(predicate)); + +const numbers = [1, 2, 3, 4, 5]; + +// 재사용 가능한 함수들 생성 +const double = x => x * 2; +const isEven = x => x % 2 === 0; + +const mapDouble = map(double); +const filterEven = filter(isEven); + +console.log(mapDouble(numbers)); // [2, 4, 6, 8, 10] +console.log(filterEven(numbers)); // [2, 4] + +// 함수 합성 +const processNumbers = nums => mapDouble(filterEven(nums)); +console.log(processNumbers(numbers)); // [4, 8] +``` + +API 클라이언트 구성: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function apiRequest(method, baseUrl, endpoint, options) { + return fetch(`${baseUrl}${endpoint}`, { + method, + ...options, + }); +} + +const curriedApiRequest = curry(apiRequest); + +// 기본 설정으로 특화된 함수들 생성 +const apiGet = curriedApiRequest('GET', 'https://api.example.com'); +const apiPost = curriedApiRequest('POST', 'https://api.example.com'); + +// 인증 헤더 포함 +const authenticatedPost = apiPost(curry.placeholder, { + headers: { Authorization: 'Bearer token123' }, +}); + +// 사용 +apiGet('/users'); // GET https://api.example.com/users +authenticatedPost('/users'); // POST with auth headers +``` + +수학 연산 함수: + +```typescript +import { curry } from 'es-toolkit/compat'; + +const calculate = curry((operation, a, b) => { + switch (operation) { + case '+': + return a + b; + case '-': + return a - b; + case '*': + return a * b; + case '/': + return a / b; + default: + throw new Error('지원하지 않는 연산'); + } +}); + +// 특화된 연산 함수들 +const add = calculate('+'); +const subtract = calculate('-'); +const multiply = calculate('*'); + +console.log(add(5, 3)); // 8 +console.log(subtract(10)(4)); // 6 +console.log(multiply(3, 4)); // 12 + +// placeholder로 두 번째 피연산자 고정 +const addFive = calculate('+', curry.placeholder, 5); +console.log(addFive(10)); // 15 +``` + +Arity 지정: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function variableArgsFunction(a, b, c, ...rest) { + return [a, b, c, rest]; +} + +// arity를 3으로 제한 +const curriedFixed = curry(variableArgsFunction, 3); + +console.log(curriedFixed(1)(2)(3)); // [1, 2, 3, []] +console.log(curriedFixed(1, 2)(3)); // [1, 2, 3, []] + +// arity 없이 사용 (기본값: function.length) +const curriedDefault = curry(variableArgsFunction); // arity = 3 +``` + +간단한 커링 대안: + +```typescript +// curry 사용 +const curriedAdd = curry((a, b, c) => a + b + c); + +// 수동 클로저 (더 빠름) +const manualCurry = a => b => c => a + b + c; + +// 둘 다 같은 결과 +console.log(curriedAdd(1)(2)(3)); // 6 +console.log(manualCurry(1)(2)(3)); // 6 +``` + +생성자 함수도 지원: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function Person(name, age, city) { + this.name = name; + this.age = age; + this.city = city; +} + +const CurriedPerson = curry(Person); +const SeoulPerson = CurriedPerson(curry.placeholder, curry.placeholder, '서울'); + +const person1 = new SeoulPerson('김철수', 30); +const person2 = new SeoulPerson('이영희', 25); + +console.log(person1.city); // "서울" +console.log(person2.city); // "서울" +``` + +#### 파라미터 + +- `func` (`Function`): 커링할 함수예요. +- `arity` (`number`, 선택): 함수의 arity(인수 개수)예요. 생략하면 `func.length`를 사용해요. + +#### 반환 값 + +(`Function & { placeholder: symbol }`): 커링된 함수를 반환해요. `placeholder` 속성으로 인수 위치를 제어할 수 있어요. diff --git a/docs/ko/compat/reference/function/curryRight.md b/docs/ko/compat/reference/function/curryRight.md new file mode 100644 index 000000000..cbdca845a --- /dev/null +++ b/docs/ko/compat/reference/function/curryRight.md @@ -0,0 +1,242 @@ +# curryRight (Lodash 호환성) + +::: warning `es-toolkit`의 [`curryRight`](../../../reference/function/curryRight.md)나 수동 클로저를 사용하세요 + +이 `curryRight` 함수는 복잡한 placeholder 처리, arity 검증, 인수 합성 로직으로 인해 느리게 동작해요. + +placeholder가 필요하지 않다면 대신 더 빠른 `es-toolkit`의 [`curryRight`](../../../reference/function/curryRight.md)나 간단한 클로저를 사용하세요. + +::: + +함수를 오른쪽부터 커링해서 마지막 인수부터 하나씩 받거나 여러 개씩 받을 수 있는 함수를 만들어요. + +```typescript +const curriedFunction = curryRight(func, arity); +``` + +## 사용법 + +### `curryRight(func, arity)` + +함수를 오른쪽부터 커링해서 마지막 인수부터 부분 적용하고 싶을 때 `curryRight`를 사용하세요. 일반적인 `curry`와 달리 마지막 인수부터 먼저 받아서 처리해요. + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 기본 사용법 +function subtract(a, b, c) { + return a - b - c; +} + +const curriedSubtract = curryRight(subtract); + +// 오른쪽부터(마지막 인수부터) 커링 +console.log(curriedSubtract(1)(2)(5)); // 5 - 2 - 1 = 2 +console.log(curriedSubtract(1, 2)(5)); // 5 - 2 - 1 = 2 +console.log(curriedSubtract(1)(2, 5)); // 2 - 5 - 1 = -4 +console.log(curriedSubtract(1, 2, 5)); // 1 - 2 - 5 = -6 +``` + +`curry`와 `curryRight` 차이점: + +```typescript +import { curry, curryRight } from 'es-toolkit/compat'; + +function divide(a, b, c) { + return a / b / c; +} + +// 일반 curry (왼쪽부터) +const leftCurried = curry(divide); +console.log(leftCurried(12)(3)(2)); // ((12 / 3) / 2) = 2 + +// curryRight (오른쪽부터) +const rightCurried = curryRight(divide); +console.log(rightCurried(2)(3)(12)); // ((12 / 3) / 2) = 2 +// 마지막에 전달한 12가 첫 번째 인수(a)가 됨 +``` + +메인 라이브러리와 비교: + +```typescript +// compat 버전 (유연함, 하지만 느림) +import { curryRight } from 'es-toolkit/compat'; +const curriedCompat = curryRight(subtract); +curriedCompat(1, 2)(3); // 지원됨 +curriedCompat(1)(curryRight.placeholder, 3)(2); // placeholder 지원 + +// 메인 라이브러리 버전 (더 빠름, 하지만 한 번에 하나씩만) +import { curryRight } from 'es-toolkit'; +const curriedMain = curryRight(subtract); +curriedMain(1)(2)(3); // 지원됨 +curriedMain(1, 2)(3); // 지원되지 않음 +``` + +placeholder 기능 사용: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function formatMessage(name, action, time) { + return `${name}님이 ${action}을 ${time}에 했습니다`; +} + +const curriedFormat = curryRight(formatMessage); + +// placeholder로 특정 위치 건너뛰기 +const todayAction = curriedFormat('오늘'); +const todayLoginAction = todayAction(curryRight.placeholder, '로그인'); + +console.log(todayLoginAction('김철수')); +// "김철수님이 로그인을 오늘에 했습니다" + +// 시간을 먼저 고정 +const morningFormat = curriedFormat('아침 9시'); +console.log(morningFormat('댓글 작성', '이영희')); +// "이영희님이 댓글 작성을 아침 9시에 했습니다" +``` + +배열 처리에서 활용: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 배열에서 특정 개수만큼 뒤에서 자르기 +function takeFromEnd(array, count, separator = ', ') { + return array.slice(-count).join(separator); +} + +const curriedTake = curryRight(takeFromEnd); + +// 쉼표로 구분하는 함수 생성 +const takeWithComma = curriedTake(', '); + +// 마지막 3개 가져오기 +const takeLast3 = takeWithComma(3); + +const fruits = ['사과', '바나나', '오렌지', '포도', '키위']; +console.log(takeLast3(fruits)); // "오렌지, 포도, 키위" + +// 다른 구분자 사용 +const takeWithDash = curriedTake(' - '); +console.log(takeWithDash(2, fruits)); // "포도 - 키위" +``` + +함수 합성에서 활용: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 로그 출력 함수 +function logWithPrefix(message, level, timestamp) { + return `[${timestamp}] ${level}: ${message}`; +} + +const curriedLog = curryRight(logWithPrefix); + +// 현재 시간으로 고정 +const currentTimeLog = curriedLog(new Date().toISOString()); + +// 레벨별 로거 생성 +const errorLog = currentTimeLog('ERROR'); +const infoLog = currentTimeLog('INFO'); +const debugLog = currentTimeLog('DEBUG'); + +// 사용 +console.log(errorLog('데이터베이스 연결 실패')); +console.log(infoLog('서버 시작됨')); +console.log(debugLog('사용자 요청 처리 중')); +``` + +함수형 프로그래밍 파이프라인: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 데이터 변환 함수들 +const mapWith = curryRight((array, fn) => array.map(fn)); +const filterWith = curryRight((array, predicate) => array.filter(predicate)); +const reduceWith = curryRight((array, reducer, initial) => array.reduce(reducer, initial)); + +const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + +// 변환 함수들 정의 +const double = x => x * 2; +const isEven = x => x % 2 === 0; +const sum = (acc, val) => acc + val; + +// 파이프라인 구성 (오른쪽 먼저) +const processNumbers = nums => { + return reduceWith(filterWith(mapWith(nums, double), isEven), sum, 0); +}; + +console.log(processNumbers(numbers)); // 모든 수를 2배 후 짝수만 필터링해서 합계 +``` + +API 요청 빌더: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function makeRequest(url, method, headers, body) { + return fetch(url, { method, headers, body }); +} + +const curriedRequest = curryRight(makeRequest); + +// body부터 설정 +const withJsonBody = curriedRequest(JSON.stringify({ data: 'test' })); + +// headers 추가 +const withHeaders = withJsonBody({ + 'Content-Type': 'application/json', + Authorization: 'Bearer token123', +}); + +// POST 메서드 설정 +const postRequest = withHeaders('POST'); + +// 최종 사용 +postRequest('/api/data') + .then(response => response.json()) + .then(data => console.log(data)); +``` + +수동 커링 대안: + +```typescript +// curryRight 사용 +const curriedSubtract = curryRight((a, b, c) => a - b - c); + +// 수동 클로저 (더 빠름, 오른쪽부터) +const manualCurryRight = c => b => a => a - b - c; + +// 둘 다 같은 결과 +console.log(curriedSubtract(1)(2)(5)); // 2 +console.log(manualCurryRight(1)(2)(5)); // 2 +``` + +Arity 지정: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function variableArgsFunction(a, b, c, ...rest) { + return { a, b, c, rest }; +} + +// arity를 3으로 제한 (뒤의 rest는 무시) +const curriedFixed = curryRight(variableArgsFunction, 3); + +// 오른쪽부터 c, b, a 순서로 받음 +console.log(curriedFixed(3)(2)(1)); // { a: 1, b: 2, c: 3, rest: [] } +``` + +#### 파라미터 + +- `func` (`Function`): 오른쪽부터 커링할 함수예요. +- `arity` (`number`, 선택): 함수의 arity(인수 개수)예요. 생략하면 `func.length`를 사용해요. + +#### 반환 값 + +(`Function & { placeholder: symbol }`): 오른쪽부터 커링된 함수를 반환해요. `placeholder` 속성으로 인수 위치를 제어할 수 있어요. diff --git a/docs/ko/compat/reference/function/debounce.md b/docs/ko/compat/reference/function/debounce.md new file mode 100644 index 000000000..b5331d197 --- /dev/null +++ b/docs/ko/compat/reference/function/debounce.md @@ -0,0 +1,264 @@ +# debounce (Lodash 호환성) + +::: warning `es-toolkit`의 [`debounce`](../../../reference/function/debounce.md)를 사용하세요 + +이 `debounce` 함수는 복잡한 `maxWait` 처리와 Lodash 호환 옵션 구조로 인해 오버헤드가 있어요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [`debounce`](../../../reference/function/debounce.md)를 사용하세요. + +::: + +함수 호출을 지연시키고, 마지막 호출 후 지정된 시간이 경과한 후에만 실행되도록 하는 디바운스 함수를 만들어요. + +```typescript +const debouncedFunction = debounce(func, wait, options); +``` + +## 사용법 + +### `debounce(func, wait, options)` + +함수 호출을 지연시키고 싶을 때 `debounce`를 사용하세요. 검색 입력, 스크롤 이벤트, 버튼 클릭 등에서 과도한 호출을 방지할 때 유용해요. + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// 기본 사용법 +const searchFunction = debounce(query => { + console.log('검색:', query); +}, 300); + +// 300ms 내에 다시 호출되지 않으면 실행 +searchFunction('리액트'); // 실행 안됨 +searchFunction('뷰'); // 실행 안됨 +searchFunction('앵귤러'); // 300ms 후에 "검색: 앵귤러" 출력 +``` + +메인 라이브러리 debounce와 비교: + +```typescript +// compat 버전 (Lodash 호환, maxWait 등 추가 옵션) +import { debounce } from 'es-toolkit/compat'; +const debouncedCompat = debounce(func, 300, { + leading: true, + trailing: false, + maxWait: 1000 +}); + +// 메인 라이브러리 버전 (더 빠름, 간단함) +import { debounce } from 'es-toolkit'; +const debouncedMain = debounce(func, 300, { + edges: ['leading'] // leading/trailing 대신 edges 사용 +}); +``` + +leading과 trailing 옵션: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const func = () => console.log('실행됨'); + +// leading: true - 첫 호출 시 즉시 실행 +const leadingDebounce = debounce(func, 1000, { leading: true }); +leadingDebounce(); // 즉시 "실행됨" 출력 +leadingDebounce(); // 1초 대기 +// 1초 후 추가 실행 없음 + +// trailing: true (기본값) - 마지막 호출 후 지연 시간 뒤 실행 +const trailingDebounce = debounce(func, 1000, { trailing: true }); +trailingDebounce(); // 1초 대기 +trailingDebounce(); // 1초 대기 (이전 타이머 취소) +// 1초 후 "실행됨" 출력 + +// 둘 다 true - 시작과 끝에서 실행 +const bothDebounce = debounce(func, 1000, { + leading: true, + trailing: true, +}); +bothDebounce(); // 즉시 "실행됨" 출력 +bothDebounce(); // 1초 대기 +// 1초 후 "실행됨" 출력 (trailing) +``` + +maxWait 옵션: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// 최대 2초마다는 반드시 실행 +const debouncedWithMaxWait = debounce(() => console.log('저장됨'), 500, { maxWait: 2000 }); + +// 빠르게 연속 호출해도 최대 2초마다는 실행됨 +setInterval(() => { + debouncedWithMaxWait(); +}, 100); // 100ms마다 호출하지만 2초마다 "저장됨" 출력 +``` + +실제 검색 예제: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +class SearchComponent { + constructor() { + this.searchInput = document.getElementById('search'); + + // 사용자 입력을 300ms 디바운스 + this.debouncedSearch = debounce(this.performSearch.bind(this), 300, { + leading: false, // 입력 시작시 즉시 검색하지 않음 + trailing: true, // 입력 멈춘 후 검색 + }); + + this.searchInput.addEventListener('input', e => { + this.debouncedSearch(e.target.value); + }); + } + + performSearch(query) { + if (query.length < 2) return; + + console.log('API 호출:', query); + // fetch(`/api/search?q=${query}`)... + } +} +``` + +스크롤 이벤트 최적화: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// 스크롤 이벤트를 100ms 디바운스하되, 최대 500ms마다는 실행 +const optimizedScrollHandler = debounce( + () => { + const scrollTop = window.pageYOffset; + console.log('스크롤 위치:', scrollTop); + + // 헤더 숨김/표시 로직 + if (scrollTop > 100) { + document.header.classList.add('hidden'); + } else { + document.header.classList.remove('hidden'); + } + }, + 100, + { maxWait: 500 } +); + +window.addEventListener('scroll', optimizedScrollHandler); +``` + +API 호출 제한: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +class AutoSave { + constructor() { + // 500ms 디바운스, 최대 5초마다는 저장 + this.debouncedSave = debounce(this.saveToServer.bind(this), 500, { maxWait: 5000 }); + } + + onTextChange(content) { + this.pendingContent = content; + this.debouncedSave(); + } + + saveToServer() { + if (!this.pendingContent) return; + + console.log('서버에 저장:', this.pendingContent); + // fetch('/api/save', { ... }) + + this.pendingContent = null; + } +} +``` + +cancel과 flush 메서드: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const debouncedFunc = debounce(() => { + console.log('실행됨'); +}, 1000); + +debouncedFunc(); // 1초 대기 중 + +// 대기 중인 실행을 취소 +debouncedFunc.cancel(); + +// 또는 즉시 실행 +debouncedFunc(); // 1초 대기 시작 +debouncedFunc.flush(); // 즉시 "실행됨" 출력하고 타이머 취소 +``` + +버튼 클릭 중복 방지: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const handleSubmit = debounce( + async formData => { + console.log('폼 제출 중...'); + try { + const response = await fetch('/api/submit', { + method: 'POST', + body: formData, + }); + console.log('제출 완료'); + } catch (error) { + console.error('제출 실패:', error); + } + }, + 1000, + { leading: true, trailing: false } // 첫 클릭만 처리 +); + +document.getElementById('submit-btn').addEventListener('click', e => { + const formData = new FormData(e.target.form); + handleSubmit(formData); +}); +``` + +리사이즈 이벤트 처리: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const handleResize = debounce( + () => { + const width = window.innerWidth; + const height = window.innerHeight; + + console.log('창 크기 변경:', { width, height }); + + // 레이아웃 재계산 + recalculateLayout(); + }, + 250, + { leading: false, trailing: true } +); + +window.addEventListener('resize', handleResize); + +// 페이지 종료 시 정리 +window.addEventListener('beforeunload', () => { + handleResize.cancel(); +}); +``` + +#### 파라미터 + +- `func` (`Function`): 디바운스할 함수예요. +- `wait` (`number`, 선택): 지연할 밀리초 수예요. 기본값은 `0`이에요. +- `options` (`DebounceSettings`, 선택): 옵션 객체예요. + - `leading` (`boolean`): `true`이면 지연 시작 시점에 함수를 실행해요. 기본값은 `false`예요. + - `trailing` (`boolean`): `true`이면 지연 종료 시점에 함수를 실행해요. 기본값은 `true`예요. + - `maxWait` (`number`): 함수 실행이 지연될 수 있는 최대 시간이에요. 기본값은 `Infinity`예요. + +#### 반환 값 + +(`DebouncedFunc`): 디바운스된 함수를 반환해요. `cancel()`과 `flush()` 메서드가 포함되어 있어요. diff --git a/docs/ko/reference/compat/function/defer.md b/docs/ko/compat/reference/function/defer.md similarity index 100% rename from docs/ko/reference/compat/function/defer.md rename to docs/ko/compat/reference/function/defer.md diff --git a/docs/ko/reference/compat/function/delay.md b/docs/ko/compat/reference/function/delay.md similarity index 100% rename from docs/ko/reference/compat/function/delay.md rename to docs/ko/compat/reference/function/delay.md diff --git a/docs/ko/reference/compat/function/flip.md b/docs/ko/compat/reference/function/flip.md similarity index 100% rename from docs/ko/reference/compat/function/flip.md rename to docs/ko/compat/reference/function/flip.md diff --git a/docs/ko/compat/reference/function/flow.md b/docs/ko/compat/reference/function/flow.md new file mode 100644 index 000000000..ddd64b9b4 --- /dev/null +++ b/docs/ko/compat/reference/function/flow.md @@ -0,0 +1,89 @@ +# flow (Lodash 호환성) + +::: warning `es-toolkit`의 `flow`를 사용하세요 + +이 `flow` 함수는 Lodash 호환성을 위해 배열 평탄화 처리가 추가되어 복잡해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [flow](../../../reference/function/flow.md)를 사용하세요. + +::: + +주어진 함수들을 왼쪽부터 오른쪽으로 순차적으로 실행하는 새로운 함수를 만들어요. + +```typescript +const combinedFunc = flow(...functions); +``` + +## 사용법 + +### `flow(...functions)` + +여러 함수를 왼쪽부터 오른쪽으로 순차적으로 실행하는 하나의 합성 함수를 만들고 싶을 때 `flow`를 사용하세요. 데이터 변환 파이프라인을 만들 때 유용해요. + +```typescript +import { flow } from 'es-toolkit/compat'; + +// 기본 사용법 +function add(x, y) { + return x + y; +} + +function square(n) { + return n * n; +} + +function double(n) { + return n * 2; +} + +// 왼쪽부터 오른쪽으로 실행: double(square(add(x, y))) +const calculate = flow(add, square, double); +console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 + +// 배열로 함수 전달 +const calculate2 = flow([add, square], double); +console.log(calculate2(2, 3)); // 50 + +// 현대적인 대안 (권장) +const modernCalculate = (x, y) => double(square(add(x, y))); +console.log(modernCalculate(1, 2)); // 18 + +// 파이프 연산자 사용 (미래 JavaScript) +const pipeCalculate = (x, y) => add(x, y) |> square |> double; + +// 또는 체이닝 패턴 +class Calculator { + constructor(value) { + this.value = value; + } + + add(n) { + this.value += n; + return this; + } + + square() { + this.value *= this.value; + return this; + } + + double() { + this.value *= 2; + return this; + } + + valueOf() { + return this.value; + } +} + +const chainedResult = new Calculator(3).square().double().valueOf(); // 18 +``` + +#### 파라미터 + +- `...functions` (`Array`): 왼쪽부터 오른쪽으로 실행할 함수들이에요. 배열로 전달할 수도 있어요. + +#### 반환 값 + +(`Function`): 모든 함수를 왼쪽부터 오른쪽으로 순차적으로 실행하는 새로운 합성 함수를 반환해요. diff --git a/docs/ko/compat/reference/function/flowRight.md b/docs/ko/compat/reference/function/flowRight.md new file mode 100644 index 000000000..9555b37a8 --- /dev/null +++ b/docs/ko/compat/reference/function/flowRight.md @@ -0,0 +1,67 @@ +# flowRight (Lodash 호환성) + +::: warning `es-toolkit`의 `flowRight`를 사용하세요 + +이 `flowRight` 함수는 Lodash 호환성을 위해 배열 평탄화 처리가 추가되어 복잡해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [flowRight](../../../reference/function/flowRight.md)를 사용하세요. + +::: + +주어진 함수들을 오른쪽부터 왼쪽으로 순차적으로 실행하는 새로운 함수를 만들어요. + +```typescript +const combinedFunc = flowRight(...functions); +``` + +## 사용법 + +### `flowRight(...functions)` + +여러 함수를 오른쪽부터 왼쪽으로 순차적으로 실행하는 하나의 합성 함수를 만들고 싶을 때 `flowRight`를 사용하세요. 데이터 변환 파이프라인을 만들 때 유용해요. + +```typescript +import { flowRight } from 'es-toolkit/compat'; + +// 기본 사용법 +function add(x, y) { + return x + y; +} + +function square(n) { + return n * n; +} + +function double(n) { + return n * 2; +} + +// 오른쪽부터 왼쪽으로 실행: double(square(add(x, y))) +const calculate = flowRight(double, square, add); +console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 + +// 배열로 함수 전달 +const calculate2 = flowRight([double, square], add); +console.log(calculate2(2, 3)); // 50 + +// 현대적인 대안 (권장) +const modernCalculate = (x, y) => double(square(add(x, y))); +console.log(modernCalculate(1, 2)); // 18 + +// 또는 함수 체이닝 사용 +const chainedCalculate = (x, y) => [x, y] + .reduce((acc, val, idx) => idx === 0 ? val : acc + val) + .valueOf() + |> (n => n * n) + |> (n => n * 2); +``` + +일반적으로 `flow`와 반대 순서로 동작해요. 합성 함수와 비슷한 방식으로 동작하여 직관적입니다. + +#### 파라미터 + +- `...functions` (`Array`): 오른쪽부터 왼쪽으로 실행할 함수들이에요. 배열로 전달할 수도 있어요. + +#### 반환 값 + +(`Function`): 모든 함수를 오른쪽부터 왼쪽으로 순차적으로 실행하는 새로운 합성 함수를 반환해요. diff --git a/docs/ko/compat/reference/function/identity.md b/docs/ko/compat/reference/function/identity.md new file mode 100644 index 000000000..35584cce2 --- /dev/null +++ b/docs/ko/compat/reference/function/identity.md @@ -0,0 +1,64 @@ +# identity (Lodash 호환성) + +::: warning `es-toolkit`의 `identity`를 사용하세요 + +이 `identity` 함수는 `es-toolkit`의 메인 라이브러리에도 동일한 기능의 함수가 있어요. 단순히 입력값을 그대로 반환하는 기능이에요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [identity](../../../reference/function/identity.md)를 사용하세요. + +::: + +입력받은 값을 그대로 반환해요. + +```typescript +const result = identity(value); +``` + +## 사용법 + +### `identity(value)` + +입력받은 값을 그대로 반환하고 싶을 때 `identity`를 사용하세요. 주로 기본값이나 플레이스홀더 함수로 사용되며, 함수형 프로그래밍에서 자주 사용돼요. + +```typescript +import { identity } from 'es-toolkit/compat'; + +// 기본 사용법 +console.log(identity(5)); // 5 +console.log(identity('hello')); // 'hello' +console.log(identity({ key: 'value' })); // { key: 'value' } + +// 배열의 map과 함께 사용 (값 복사) +const numbers = [1, 2, 3, 4, 5]; +const copied = numbers.map(identity); +console.log(copied); // [1, 2, 3, 4, 5] + +// 필터링에서 기본값으로 사용 +const values = [1, 0, '', 'hello', null, undefined, false, true]; +const filtered = values.filter(identity); // 참으로 평가되는 값들만 남김 +console.log(filtered); // [1, 'hello', true] + +// 기본 변환 함수로 사용 +function processData(data, transform = identity) { + return transform(data); +} + +console.log(processData('hello')); // 'hello' +console.log(processData('hello', x => x.toUpperCase())); // 'HELLO' +``` + +대부분의 경우 더 간단한 화살표 함수 `x => x`로 대체할 수 있어요: + +```typescript +// identity 대신 화살표 함수 사용 (권장) +const copied = numbers.map(x => x); +const filtered = values.filter(x => x); +``` + +#### 파라미터 + +- `value` (`T`): 반환할 값이에요. + +#### 반환 값 + +(`T`): 입력받은 값을 그대로 반환해요. diff --git a/docs/ko/compat/reference/function/memoize.md b/docs/ko/compat/reference/function/memoize.md new file mode 100644 index 000000000..6610456b1 --- /dev/null +++ b/docs/ko/compat/reference/function/memoize.md @@ -0,0 +1,68 @@ +# memoize (Lodash 호환성) + +::: warning `es-toolkit`의 `memoize`를 사용하세요 + +이 `memoize` 함수는 `resolver` 함수의 `null` 체크, `MapCache` 인터페이스의 복잡한 타입 처리, 그리고 Lodash 호환성을 위한 추가적인 오버헤드로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [memoize](../../../reference/function/memoize.md)를 사용하세요. + +::: + +함수의 결과를 캐시하여 동일한 인수로 호출할 때 성능을 향상시켜요. + +```typescript +const memoizedFunc = memoize(func, resolver); +``` + +## 사용법 + +### `memoize(func, resolver)` + +함수의 결과를 메모이제이션하여 동일한 인수로 호출할 때 이전 결과를 재사용하고 싶을 때 `memoize`를 사용하세요. 비용이 많이 드는 계산이나 API 호출에 유용해요. + +```typescript +import { memoize } from 'es-toolkit/compat'; + +// 기본 사용법 +function expensiveCalculation(n) { + console.log('계산 중...', n); + return n * n; +} + +const memoizedCalc = memoize(expensiveCalculation); + +console.log(memoizedCalc(5)); // '계산 중... 5', 25 +console.log(memoizedCalc(5)); // 25 (캐시된 결과, 계산하지 않음) +console.log(memoizedCalc(10)); // '계산 중... 10', 100 + +// 커스텀 리졸버 사용 +function fetchUserData(userId, includeProfile) { + console.log('사용자 데이터 가져오는 중...', userId, includeProfile); + return { id: userId, profile: includeProfile ? '프로필 데이터' : null }; +} + +// 모든 인수를 고려한 캐시 키 생성 +const memoizedFetch = memoize(fetchUserData, (userId, includeProfile) => { + return `${userId}_${includeProfile}`; +}); + +memoizedFetch(1, true); // '사용자 데이터 가져오는 중... 1 true' +memoizedFetch(1, true); // 캐시된 결과 사용 +memoizedFetch(1, false); // '사용자 데이터 가져오는 중... 1 false' (다른 캐시 키) + +// 캐시 접근 및 수정 +console.log(memoizedCalc.cache.get(5)); // 25 +memoizedCalc.cache.set(7, 49); // 수동으로 캐시 설정 +console.log(memoizedCalc(7)); // 49 (계산하지 않고 캐시된 값 사용) +``` + +대부분의 경우 기본 해시 맵을 사용하지만, 필요에 따라 커스텀 캐시 구현체를 사용할 수도 있어요. + +#### 파라미터 + +- `func` (`Function`): 메모이제이션할 함수예요. +- `resolver` (`Function`, 선택): 캐시 키를 결정하는 함수예요. 제공되지 않으면 첫 번째 인수를 키로 사용해요. + +#### 반환 값 + +(`Function & { cache: MapCache }`): 메모이제이션된 함수를 반환해요. 반환된 함수에는 `cache` 프로퍼티가 있어서 캐시에 직접 접근할 수 있어요. diff --git a/docs/ko/reference/compat/function/negate.md b/docs/ko/compat/reference/function/negate.md similarity index 100% rename from docs/ko/reference/compat/function/negate.md rename to docs/ko/compat/reference/function/negate.md diff --git a/docs/ko/compat/reference/function/noop.md b/docs/ko/compat/reference/function/noop.md new file mode 100644 index 000000000..eb1b4429b --- /dev/null +++ b/docs/ko/compat/reference/function/noop.md @@ -0,0 +1,60 @@ +# noop (Lodash 호환성) + +::: warning `es-toolkit`의 `noop`을 사용하세요 + +`es-toolkit`에도 동일한 동작을 하는 [noop](../../../reference/function/noop.md) 함수가 있어요. + +::: + +아무것도 하지 않는 빈 함수예요. + +```typescript +noop(); +``` + +## 사용법 + +### `noop(...args)` + +아무것도 하지 않는 플레이스홀더 함수가 필요할 때 `noop`을 사용하세요. 기본값이나 콜백 함수로 자주 사용돼요. + +```typescript +import { noop } from 'es-toolkit/compat'; + +// 기본 사용법 +noop(); // 아무것도 하지 않음 +noop(1, 2, 3); // 인수를 받지만 아무것도 하지 않음 + +// 기본 콜백으로 사용 +function processData(data, callback = noop) { + // 데이터 처리 + console.log('데이터 처리 중...', data); + + // 콜백 호출 (제공되지 않았다면 noop) + callback(data); +} + +processData('테스트'); // 콜백이 제공되지 않았지만 오류 없이 동작 + +// 현대적인 대안 (권장) +function modernProcessData(data, callback = () => {}) { + console.log('데이터 처리 중...', data); + callback(data); +} + +// 또는 선택적 콜백 사용 +function processDataOptional(data, callback) { + console.log('데이터 처리 중...', data); + callback?.(data); // 콜백이 제공된 경우만 호출 +} +``` + +기본값이나 플레이스홀더가 필요한 상황에서 유용하지만, 현대 JavaScript에서는 선택적 체이닝(`?.`)이나 기본 매개변수를 사용하는 것이 더 일반적이에요. + +#### 파라미터 + +- `...args` (`any[]`): 어떤 인수들이든 받을 수 있지만 모두 무시돼요. + +#### 반환 값 + +(`void`): 아무것도 반환하지 않아요. diff --git a/docs/ko/reference/compat/function/nthArg.md b/docs/ko/compat/reference/function/nthArg.md similarity index 100% rename from docs/ko/reference/compat/function/nthArg.md rename to docs/ko/compat/reference/function/nthArg.md diff --git a/docs/ko/compat/reference/function/once.md b/docs/ko/compat/reference/function/once.md new file mode 100644 index 000000000..516bb6e7e --- /dev/null +++ b/docs/ko/compat/reference/function/once.md @@ -0,0 +1,56 @@ +# once (Lodash 호환성) + +::: warning `es-toolkit`의 `once`를 사용하세요 + +이 `once` 함수는 `es-toolkit`의 메인 라이브러리 [once](../../../reference/function/once.md) 함수와 동일한 기능을 가지고 있어요. + +::: + +함수가 한 번만 호출되도록 제한해요. + +```typescript +const limitedFunc = once(func); +``` + +## 사용법 + +### `once(func)` + +함수가 한 번만 호출되도록 제한하고 싶을 때 `once`를 사용하세요. 첫 번째 호출 후에는 결과가 캐시되어 동일한 값을 반환해요. + +```typescript +import { once } from 'es-toolkit/compat'; + +// 기본 사용법 +let count = 0; +const increment = once(() => { + count++; + console.log('카운터 증가:', count); + return count; +}); + +increment(); // '카운터 증가: 1' 출력, 1 반환 +increment(); // 아무것도 출력하지 않음, 1 반환 +increment(); // 아무것도 출력하지 않음, 1 반환 + +// 실용 예시 - 초기화 함수 +const initialize = once(() => { + console.log('애플리케이션 초기화 중...'); + // 비용 많은 초기화 작업 + return '초기화 완료'; +}); + +// 여러 번 호출해도 초기화는 한 번만 실행됨 +initialize(); // '애플리케이션 초기화 중...' 출력 +initialize(); // 아무것도 출력하지 않음 +``` + +비용이 많이 드는 초기화 작업이나 설정 함수를 만들 때 유용해요. 예를 들어 데이터베이스 연결, API 토큰 초기화 등에 사용할 수 있어요. + +#### 파라미터 + +- `func` (`Function`): 한 번만 호출되도록 제한할 함수예요. + +#### 반환 값 + +(`Function`): 한 번만 호출되는 새로운 함수를 반환해요. 두 번째 호출부터는 첫 번째 호출의 결과를 반환해요. diff --git a/docs/ko/reference/compat/function/overArgs.md b/docs/ko/compat/reference/function/overArgs.md similarity index 100% rename from docs/ko/reference/compat/function/overArgs.md rename to docs/ko/compat/reference/function/overArgs.md diff --git a/docs/ko/compat/reference/function/partial.md b/docs/ko/compat/reference/function/partial.md new file mode 100644 index 000000000..aab9e8713 --- /dev/null +++ b/docs/ko/compat/reference/function/partial.md @@ -0,0 +1,59 @@ +# partial (Lodash 호환성) + +::: warning `es-toolkit`의 `partial`을 사용하세요 + +이 `partial` 함수는 많은 오버로드와 공용체 타입 처리로 인해 비효율적이에요. 또한 대부분의 경우 더 간단한 화살표 함수로 대체할 수 있어요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [partial](../../../reference/function/partial.md)을 사용하세요. + +::: + +함수의 인수를 미리 채워서 부분 적용된 함수를 만들어요. + +```typescript +const partialFunc = partial(func, ...args); +``` + +## 사용법 + +### `partial(func, ...args)` + +함수의 인수를 미리 채워서 부분 적용된 함수를 만들고 싶을 때 `partial`을 사용하세요. 주로 인수 순서가 중요한 함수에서 첫 번째 인수들을 고정할 때 유용해요. + +```typescript +import { partial } from 'es-toolkit/compat'; + +// 기본 사용법 +function greet(greeting, name, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// 첫 번째 인수를 미리 설정 +const sayHello = partial(greet, 'Hello'); +sayHello('Alice', '!'); // 'Hello Alice!' + +// 여러 인수를 미리 설정 +const greetAlice = partial(greet, 'Hello', 'Alice'); +greetAlice('!'); // 'Hello Alice!' + +// placeholder를 사용하여 인수 순서 조절 +const greetWithExclamation = partial(greet, partial.placeholder, 'Alice', '!'); +greetWithExclamation('Hi'); // 'Hi Alice!' +``` + +대부분의 경우 화살표 함수로 대체할 수 있어요: + +```typescript +// partial 대신 화살표 함수 사용 (권장) +const sayHello = (name, punctuation) => greet('Hello', name, punctuation); +const greetAlice = punctuation => greet('Hello', 'Alice', punctuation); +``` + +#### 파라미터 + +- `func` (`Function`): 부분 적용할 함수예요. +- `...args` (`any[]`): 미리 채울 인수들이에요. `partial.placeholder`를 사용해서 인수 순서를 조절할 수 있어요. + +#### 반환 값 + +(`Function`): 인수가 미리 채워진 새로운 함수를 반환해요. diff --git a/docs/ko/compat/reference/function/partialRight.md b/docs/ko/compat/reference/function/partialRight.md new file mode 100644 index 000000000..77d55f413 --- /dev/null +++ b/docs/ko/compat/reference/function/partialRight.md @@ -0,0 +1,59 @@ +# partialRight (Lodash 호환성) + +::: warning `es-toolkit`의 `partialRight`를 사용하세요 + +이 `partialRight` 함수는 많은 오버로드와 공용체 타입 처리로 인해 비효율적이에요. 또한 대부분의 경우 더 간단한 냄자마 함수로 대체할 수 있어요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [partialRight](../../../reference/function/partialRight.md)를 사용하세요. + +::: + +함수의 오른쪽부터 인수를 미리 채워서 부분 적용된 함수를 만들어요. + +```typescript +const partialFunc = partialRight(func, ...args); +``` + +## 사용법 + +### `partialRight(func, ...args)` + +함수의 오른쪽부터 인수를 미리 채워서 부분 적용된 함수를 만들고 싶을 때 `partialRight`를 사용하세요. 주로 인수 순서가 중요한 함수에서 마지막 인수들을 고정할 때 유용해요. + +```typescript +import { partialRight } from 'es-toolkit/compat'; + +// 기본 사용법 +function greet(greeting, name, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// 마지막 인수를 미리 설정 +const greetWithExclamation = partialRight(greet, '!'); +greetWithExclamation('Hello', 'Alice'); // 'Hello Alice!' + +// 여러 인수를 미리 설정 +const sayHiToAlice = partialRight(greet, 'Alice', '!'); +sayHiToAlice('Hi'); // 'Hi Alice!' + +// placeholder를 사용하여 인수 순서 조절 +const greetAliceWithCustom = partialRight(greet, 'Alice', partialRight.placeholder); +greetAliceWithCustom('Hello', '?'); // 'Hello Alice?' +``` + +대부분의 경우 화살표 함수로 대체할 수 있어요: + +```typescript +// partialRight 대신 화살표 함수 사용 (권장) +const greetWithExclamation = (greeting, name) => greet(greeting, name, '!'); +const sayHiToAlice = greeting => greet(greeting, 'Alice', '!'); +``` + +#### 파라미터 + +- `func` (`Function`): 부분 적용할 함수예요. +- `...args` (`any[]`): 미리 채울 인수들이에요. `partialRight.placeholder`를 사용해서 인수 순서를 조절할 수 있어요. + +#### 반환 값 + +(`Function`): 오른쪽부터 인수가 미리 채워진 새로운 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/rearg.md b/docs/ko/compat/reference/function/rearg.md similarity index 100% rename from docs/ko/reference/compat/function/rearg.md rename to docs/ko/compat/reference/function/rearg.md diff --git a/docs/ko/compat/reference/function/rest.md b/docs/ko/compat/reference/function/rest.md new file mode 100644 index 000000000..35581cdda --- /dev/null +++ b/docs/ko/compat/reference/function/rest.md @@ -0,0 +1,54 @@ +# rest (Lodash 호환성) + +::: warning `es-toolkit`의 `rest`를 사용하세요 + +이 `rest` 함수는 기본값 처리나 인덱스 유효성 검사 등의 추가 로직으로 인해 성능이 떨어질 수 있어요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [rest](../../../reference/function/rest.md)를 사용하세요. + +::: + +지정된 인덱스부터 나머지 인수들을 배열로 그룹화하는 함수를 만들어요. + +```typescript +const restFunc = rest(func, start); +``` + +## 사용법 + +### `rest(func, start)` + +함수의 인수들을 변환하여 지정된 인덱스부터 나머지 인수들을 배열로 그룹화하고 싶을 때 `rest`를 사용하세요. 가변 인수를 받는 함수를 만들 때 유용해요. + +```typescript +import { rest } from 'es-toolkit/compat'; + +// 기본 사용법 - 마지막 인수들을 배열로 그룹화 +function logMessage(level, message, ...details) { + console.log(`[${level}] ${message}`, details); +} + +const restLogger = rest(logMessage, 2); +restLogger('ERROR', '오류 발생', '상세정보 1', '상세정보 2'); +// 내부적으로 logMessage('ERROR', '오류 발생', [['상세정보 1', '상세정보 2']])로 호출 + +// 다른 인덱스 예시 +function process(action, target, ...args) { + return { action, target, args }; +} + +const restProcess = rest(process, 1); +restProcess('update', 'user', 'name', 'John', 'age', 25); +// { action: 'update', target: ['user', 'name', 'John', 'age', 25], args: [] } +``` + +함수의 마지막 인수들을 배열로 받고 싶을 때 사용하면 됩니다. 현대 JavaScript에서는 나머지 매개변수 문법(`...args`)을 사용하는 것이 더 일반적이에요. + +#### 파라미터 + +- `func` (`Function`): 변환할 함수예요. +- `start` (`number`, 선택): 배열로 그룹화를 시작할 인덱스예요. 기본값은 `func.length - 1`이에요. + +#### 반환 값 + +(`Function`): 지정된 인덱스부터 나머지 인수들을 배열로 그룹화하는 새로운 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/spread.md b/docs/ko/compat/reference/function/spread.md similarity index 100% rename from docs/ko/reference/compat/function/spread.md rename to docs/ko/compat/reference/function/spread.md diff --git a/docs/ko/compat/reference/function/throttle.md b/docs/ko/compat/reference/function/throttle.md new file mode 100644 index 000000000..880823119 --- /dev/null +++ b/docs/ko/compat/reference/function/throttle.md @@ -0,0 +1,52 @@ +# throttle (Lodash 호환성) + +::: warning `es-toolkit`의 `throttle`을 사용하세요 + +이 `throttle` 함수는 Lodash 호환성을 위해 debounce 함수를 내부적으로 사용해서 방식이 조금 복잡해요. 또한 기본값 처리나 옵션 처리 등이 더 복잡해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [throttle](../../../reference/function/throttle.md)을 사용하세요. + +::: + +함수 호출을 지정된 시간 간격마다 최대 한 번만 실행되도록 제한해요. + +```typescript +const throttledFunc = throttle(func, wait, options); +``` + +## 사용법 + +### `throttle(func, wait, options)` + +함수 호출을 지정된 시간 간격마다 최대 한 번만 실행되도록 제한하고 싶을 때 `throttle`을 사용하세요. 이벤트 핸들러나 API 호출 빈도를 제한할 때 유용해요. + +```typescript +import { throttle } from 'es-toolkit/compat'; + +// 기본 사용법 - 1초마다 최대 한 번 실행 +const throttledLog = throttle(() => { + console.log('이벤트 발생!'); +}, 1000); + +// 옵션을 사용한 예시 +const throttledScroll = throttle(handleScroll, 100, { + leading: true, // 처음에 바로 실행 + trailing: false, // 마지막에 실행하지 않음 +}); + +window.addEventListener('scroll', throttledScroll); +``` + +스크롤 이벤트나 리사이즈 이벤트처럼 빠르게 발생하는 이벤트를 처리할 때 성능을 위해 필수적이에요. + +#### 파라미터 + +- `func` (`Function`): 스로틀링할 함수예요. +- `wait` (`number`, 선택): 밀리세컨드 단위의 대기 시간이에요. 기본값은 `0`이에요. +- `options` (`ThrottleSettings`, 선택): 스로틀링 옵션이에요. + - `leading` (`boolean`): 첫 번째 호출에서 바로 실행할지 여부예요. 기본값은 `true`예요. + - `trailing` (`boolean`): 마지막 호출 후에 실행할지 여부예요. 기본값은 `true`예요. + +#### 반환 값 + +(`DebouncedFunc`): 스로틀링된 함수를 반환해요. `cancel()` 메소드로 대기 중인 실행을 취소할 수 있어요. diff --git a/docs/ko/compat/reference/function/unary.md b/docs/ko/compat/reference/function/unary.md new file mode 100644 index 000000000..47daefafb --- /dev/null +++ b/docs/ko/compat/reference/function/unary.md @@ -0,0 +1,47 @@ +# unary (Lodash 호환성) + +::: warning `es-toolkit`의 `ary`를 사용하세요 + +이 `unary` 함수는 `ary` 함수의 특수한 경우로 구현되어 있어요. 더 많은 제어가 필요하다면 `es-toolkit`의 [ary](../../../reference/function/ary.md)를 직접 사용하는 것이 더 효율적이에요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [ary](../../../reference/function/ary.md)를 사용하세요. + +::: + +함수가 최대 하나의 인수만 받도록 제한해요. + +```typescript +const limitedFunc = unary(func); +``` + +## 사용법 + +### `unary(func)` + +함수가 최대 하나의 인수만 받도록 제한하고 싶을 때 `unary`를 사용하세요. 추가로 전달되는 인수들은 모두 무시돼요. + +```typescript +import { unary } from 'es-toolkit/compat'; + +function greet(name, greeting, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// 첫 번째 인수만 받는 함수로 변환 +const greetOne = unary(greet); +greetOne('Alice', 'Hello', '!'); // greet('Alice')와 동일하게 동작 + +// 배열의 map 함수와 함께 사용할 때 유용해요 +const numbers = ['1', '2', '3']; +numbers.map(parseInt); // [1, NaN, NaN] - 예상치 못한 결과 +numbers.map(unary(parseInt)); // [1, 2, 3] - 올바른 결과 +``` + +#### 파라미터 + +- `func` (`(...args: any[]) => any`): 인수를 제한할 함수예요. + +#### 반환 값 + +(`(...args: any[]) => any`): 최대 하나의 인수만 받는 새로운 함수를 반환해요. +ㅇ깆 diff --git a/docs/ko/reference/compat/function/wrap.md b/docs/ko/compat/reference/function/wrap.md similarity index 100% rename from docs/ko/reference/compat/function/wrap.md rename to docs/ko/compat/reference/function/wrap.md diff --git a/docs/ko/reference/compat/math/add.md b/docs/ko/compat/reference/math/add.md similarity index 100% rename from docs/ko/reference/compat/math/add.md rename to docs/ko/compat/reference/math/add.md diff --git a/docs/ko/reference/compat/math/ceil.md b/docs/ko/compat/reference/math/ceil.md similarity index 100% rename from docs/ko/reference/compat/math/ceil.md rename to docs/ko/compat/reference/math/ceil.md diff --git a/docs/ko/compat/reference/math/clamp.md b/docs/ko/compat/reference/math/clamp.md new file mode 100644 index 000000000..c1f667c2b --- /dev/null +++ b/docs/ko/compat/reference/math/clamp.md @@ -0,0 +1,82 @@ +# clamp (Lodash 호환성) + +::: warning `es-toolkit`의 [clamp](../../../reference/math/clamp.md)를 사용하세요 + +이 `clamp` 함수는 NaN 검증과 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [clamp](../../../reference/math/clamp.md)를 사용하세요. + +::: + +숫자를 지정된 범위 내로 제한해요. + +```typescript +const clamped = clamp(number, lower, upper); +``` + +## 사용법 + +### `clamp(number, lower, upper)` + +숫자를 지정된 최솟값과 최댓값 사이로 제한하고 싶을 때 `clamp`를 사용하세요. + +```typescript +import { clamp } from 'es-toolkit/compat'; + +// 기본 사용법 +clamp(3, 2, 4); +// Returns: 3 (범위 안에 있음) + +clamp(0, 5, 10); +// Returns: 5 (최솟값으로 제한) + +clamp(15, 5, 10); +// Returns: 10 (최댓값으로 제한) + +// 음수도 처리 +clamp(-5, -10, -1); +// Returns: -5 + +clamp(-15, -10, -1); +// Returns: -10 (최솟값으로 제한) +``` + +### `clamp(number, upper)` + +하나의 인수만 제공하면 그 값을 최댓값으로 사용해요. + +```typescript +import { clamp } from 'es-toolkit/compat'; + +// 최댓값만 지정 +clamp(5, 3); +// Returns: 3 (최댓값으로 제한) + +clamp(2, 3); +// Returns: 2 (범위 안에 있음) + +clamp(1, 5); +// Returns: 1 +``` + +NaN 값은 0으로 처리해요. + +```typescript +import { clamp } from 'es-toolkit/compat'; + +clamp(5, NaN, 10); +// Returns: 5 (NaN이 0으로 처리되어 범위는 0~10) + +clamp(5, 2, NaN); +// Returns: 2 (NaN이 0으로 처리되어 범위는 0~2) +``` + +#### 파라미터 + +- `number` (`number`): 제한할 숫자예요. +- `lower` (`number`): 최솟값이에요. 두 번째 파라미터만 있으면 최댓값이 돼요. +- `upper` (`number`, 선택): 최댓값이에요. + +#### 반환 값 + +(`number`): 지정된 범위 내로 제한된 숫자를 반환해요. diff --git a/docs/ko/reference/compat/math/divide.md b/docs/ko/compat/reference/math/divide.md similarity index 100% rename from docs/ko/reference/compat/math/divide.md rename to docs/ko/compat/reference/math/divide.md diff --git a/docs/ko/reference/compat/math/floor.md b/docs/ko/compat/reference/math/floor.md similarity index 100% rename from docs/ko/reference/compat/math/floor.md rename to docs/ko/compat/reference/math/floor.md diff --git a/docs/ko/compat/reference/math/inRange.md b/docs/ko/compat/reference/math/inRange.md new file mode 100644 index 000000000..2d357c3bf --- /dev/null +++ b/docs/ko/compat/reference/math/inRange.md @@ -0,0 +1,101 @@ +# inRange (Lodash 호환성) + +::: warning `es-toolkit`의 [inRange](../../../reference/math/inRange.md)을 사용하세요 + +이 `inRange` 함수는 복잡한 타입 변환과 null/undefined 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [inRange](../../../reference/math/inRange.md)을 사용하세요. + +::: + +숫자가 지정된 범위 내에 있는지 확인해요. + +```typescript +const result = inRange(value, minimum, maximum); +``` + +## 사용법 + +### `inRange(value, minimum, maximum?)` + +숫자가 특정 범위 안에 있는지 확인하고 싶을 때 `inRange`을 사용하세요. 최솟값은 포함되고 최댓값은 포함되지 않아요. + +```typescript +import { inRange } from 'es-toolkit/compat'; + +// 기본 사용법 +inRange(3, 2, 4); +// Returns: true (2 ≤ 3 < 4) + +inRange(1, 2, 5); +// Returns: false (1 < 2) + +inRange(5, 2, 5); +// Returns: false (5는 포함되지 않음) + +// 범위 경계값 +inRange(2, 2, 4); +// Returns: true (최솟값은 포함) + +inRange(4, 2, 4); +// Returns: false (최댓값은 포함되지 않음) +``` + +### `inRange(value, maximum)` + +두 개의 인수만 제공하면 0부터 maximum까지의 범위로 처리해요. + +```typescript +import { inRange } from 'es-toolkit/compat'; + +inRange(3, 5); +// Returns: true (0 ≤ 3 < 5) + +inRange(-1, 5); +// Returns: false (-1 < 0) + +inRange(0, 5); +// Returns: true (0 ≤ 0 < 5) + +inRange(5, 5); +// Returns: false (5는 포함되지 않음) +``` + +최솟값이 최댓값보다 크면 자동으로 교체해요. + +```typescript +import { inRange } from 'es-toolkit/compat'; + +inRange(3, 5, 2); +// Returns: true (범위가 2~5로 바뀌고, 2 ≤ 3 < 5) + +inRange(1, 5, 2); +// Returns: false (1 < 2) +``` + +잘못된 값들은 적절히 변환해요. + +```typescript +import { inRange } from 'es-toolkit/compat'; + +// 문자열 숫자 변환 +inRange(3, '2', '4'); +// Returns: true + +// falsy 값은 0으로 처리 +inRange(1, null, 5); +// Returns: true (null이 0으로 처리되어 0~5 범위) + +inRange(3, false, 5); +// Returns: true (false가 0으로 처리) +``` + +#### 파라미터 + +- `value` (`number`): 범위 안에 있는지 확인할 숫자예요. +- `minimum` (`number`): 범위의 최솟값이에요 (포함). `maximum`이 없으면 이 값이 최댓값이 돼요. +- `maximum` (`number`, 선택): 범위의 최댓값이에요 (포함되지 않음). + +#### 반환 값 + +(`boolean`): 값이 지정된 범위 안에 있으면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/math/max.md b/docs/ko/compat/reference/math/max.md similarity index 100% rename from docs/ko/reference/compat/math/max.md rename to docs/ko/compat/reference/math/max.md diff --git a/docs/ko/compat/reference/math/maxBy.md b/docs/ko/compat/reference/math/maxBy.md new file mode 100644 index 000000000..846ad9166 --- /dev/null +++ b/docs/ko/compat/reference/math/maxBy.md @@ -0,0 +1,114 @@ +# maxBy (Lodash 호환성) + +::: warning es-toolkit의 [maxBy](../../../reference/array/maxBy.md)를 사용하세요 + +이 `maxBy` 함수는 iteratee 함수 처리와 타입 변환으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [maxBy](../../../reference/array/maxBy.md)를 사용하세요. + +::: + +조건에 맞는 값 중에서 최댓값 요소를 찾아요. + +```typescript +const maxItem = maxBy(array, iteratee); +``` + +## 사용법 + +### `maxBy(array, iteratee)` + +배열에서 함수로 계산한 값이 가장 큰 요소를 찾아요. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +// 객체 배열에서 특정 속성이 최대인 요소 +const people = [ + { name: '홍길동', age: 25 }, + { name: '김철수', age: 30 }, + { name: '이영희', age: 35 }, +]; + +maxBy(people, person => person.age); +// Returns: { name: '이영희', age: 35 } + +// 속성명으로도 가능 +maxBy(people, 'age'); +// Returns: { name: '이영희', age: 35 } +``` + +함수로 값을 변환해서 최댓값을 찾아요. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +maxBy(items, x => x.a); +// Returns: { a: 3 } + +const numbers = [-1, -2, -3]; +maxBy(numbers, x => Math.abs(x)); +// Returns: -3 (절댓값이 가장 큰 요소) +``` + +배열 요소로 접근해요. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const arrays = [ + [1, 2], + [3, 4], + [0, 5], +]; +maxBy(arrays, 0); // 첫 번째 요소가 최대인 배열 +// Returns: [3, 4] + +maxBy(arrays, 1); // 두 번째 요소가 최대인 배열 +// Returns: [0, 5] +``` + +객체의 특정 속성과 값이 일치하는 경우를 찾아요. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const users = [ + { name: '홍길동', age: 25, active: true }, + { name: '김철수', age: 30, active: false }, + { name: '이영희', age: 35, active: true }, +]; + +// active가 true인 요소들 중에서 첫 번째 +maxBy(users, ['active', true]); +// Returns: { name: '홍길동', age: 25, active: true } + +// 객체로 조건 지정 +maxBy(users, { active: true }); +// Returns: { name: '홍길동', age: 25, active: true } +``` + +빈 배열은 undefined를 반환해요. + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +maxBy([], x => x.a); +// Returns: undefined + +maxBy(null); +// Returns: undefined + +maxBy(undefined); +// Returns: undefined +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 검색할 배열이에요. +- `iteratee` (`ValueIteratee`, 선택): 각 요소에 적용할 함수, 속성명, 또는 조건이에요. + +#### 반환 값 + +(`T | undefined`): 조건에 맞는 값이 가장 큰 요소를 반환해요. 빈 배열이면 `undefined`를 반환해요. diff --git a/docs/ko/compat/reference/math/mean.md b/docs/ko/compat/reference/math/mean.md new file mode 100644 index 000000000..2b74c78f1 --- /dev/null +++ b/docs/ko/compat/reference/math/mean.md @@ -0,0 +1,76 @@ +# mean (Lodash 호환성) + +::: warning es-toolkit의 [mean](../../../reference/math/mean.md)를 사용하세요 + +이 `mean` 함수는 타입 변환과 null/undefined 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [mean](../../../reference/math/mean.md)를 사용하세요. + +::: + +배열의 평균값을 구해요. + +```typescript +const average = mean(array); +``` + +## 사용법 + +### `mean(array)` + +숫자 배열의 평균값을 계산해요. + +```typescript +import { mean } from 'es-toolkit/compat'; + +// 숫자 배열 +mean([1, 2, 3, 4, 5]); +// Returns: 3 + +mean([10, 20, 30]); +// Returns: 20 + +mean([1.5, 2.5, 3.5]); +// Returns: 2.5 +``` + +빈 배열은 NaN을 반환해요. + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean([]); +// Returns: NaN + +mean(null); +// Returns: NaN + +mean(undefined); +// Returns: NaN +``` + +유효하지 않은 값은 0으로 간주되어 계산에 포함돼요. + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean([1, undefined, 2, null, 3]); +// Returns: 1.2 (1 + 2 + 3) / 5 = 1.2 +``` + +문자열 숫자도 처리돼요. + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean(['1', '2', '3']); +// Returns: 41 (123 / 3 = 41) +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 평균을 구할 숫자들이 있는 배열이에요. + +#### 반환 값 + +(`number`): 배열의 평균값을 반환해요. 빈 배열이면 `NaN`을 반환해요. diff --git a/docs/ko/compat/reference/math/meanBy.md b/docs/ko/compat/reference/math/meanBy.md new file mode 100644 index 000000000..e7985d15d --- /dev/null +++ b/docs/ko/compat/reference/math/meanBy.md @@ -0,0 +1,103 @@ +# meanBy (Lodash 호환성) + +::: warning es-toolkit의 [meanBy](../../../reference/math/meanBy.md)를 사용하세요 + +이 `meanBy` 함수는 iteratee 함수 처리와 타입 변환으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [meanBy](../../../reference/math/meanBy.md)를 사용하세요. + +::: + +조건에 맞는 값들의 평균을 구해요. + +```typescript +const average = meanBy(array, iteratee); +``` + +## 사용법 + +### `meanBy(array, iteratee)` + +배열의 각 요소에 함수를 적용한 결과의 평균을 계산해요. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +// 객체 배열에서 특정 속성의 평균 +const people = [ + { name: '홍길동', age: 25 }, + { name: '김철수', age: 30 }, + { name: '이영희', age: 35 }, +]; + +meanBy(people, person => person.age); +// Returns: 30 + +// 속성명으로도 가능 +meanBy(people, 'age'); +// Returns: 30 +``` + +함수로 값을 변환해서 평균을 구해요. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const numbers = [1.5, 2.7, 3.2, 4.8]; +meanBy(numbers, x => Math.floor(x)); +// Returns: 2.5 (1 + 2 + 3 + 4) / 4 + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +meanBy(items, x => x.a); +// Returns: 2 +``` + +배열 요소로 접근해요. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const arrays = [[2], [3], [1]]; +meanBy(arrays, 0); // 첫 번째 요소들의 평균 +// Returns: 2 +``` + +객체의 특정 속성과 값이 일치하는 경우만 계산해요. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const users = [ + { name: '홍길동', age: 25, active: true }, + { name: '김철수', age: 30, active: false }, + { name: '이영희', age: 35, active: true }, +]; + +// active가 true인 사람들만 +meanBy(users, { active: true }); +// Returns: 0.6666666 (active 가 true 인 사람의 비율) +``` + +빈 배열은 NaN을 반환해요. + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +meanBy([], x => x.a); +// Returns: NaN + +meanBy(null); +// Returns: NaN + +meanBy(undefined); +// Returns: NaN +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 처리할 배열이에요. +- `iteratee` (`ValueIteratee`, 선택): 각 요소에 적용할 함수, 속성명, 또는 조건이에요. + +#### 반환 값 + +(`number`): 조건에 맞는 값들의 평균을 반환해요. 빈 배열이면 `NaN`을 반환해요. diff --git a/docs/ko/reference/compat/math/min.md b/docs/ko/compat/reference/math/min.md similarity index 100% rename from docs/ko/reference/compat/math/min.md rename to docs/ko/compat/reference/math/min.md diff --git a/docs/ko/compat/reference/math/minBy.md b/docs/ko/compat/reference/math/minBy.md new file mode 100644 index 000000000..4b4ab5fcf --- /dev/null +++ b/docs/ko/compat/reference/math/minBy.md @@ -0,0 +1,114 @@ +# minBy (Lodash 호환성) + +::: warning es-toolkit의 [minBy](../../../reference/array/minBy.md)를 사용하세요 + +이 `minBy` 함수는 iteratee 함수 처리와 타입 변환으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [minBy](../../../reference/array/minBy.md)를 사용하세요. + +::: + +조건에 맞는 값 중에서 최솟값 요소를 찾아요. + +```typescript +const minItem = minBy(array, iteratee); +``` + +## 사용법 + +### `minBy(array, iteratee)` + +배열에서 함수로 계산한 값이 가장 작은 요소를 찾아요. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +// 객체 배열에서 특정 속성이 최소인 요소 +const people = [ + { name: '홍길동', age: 25 }, + { name: '김철수', age: 30 }, + { name: '이영희', age: 35 }, +]; + +minBy(people, person => person.age); +// Returns: { name: '홍길동', age: 25 } + +// 속성명으로도 가능 +minBy(people, 'age'); +// Returns: { name: '홍길동', age: 25 } +``` + +함수로 값을 변환해서 최솟값을 찾아요. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +minBy(items, x => x.a); +// Returns: { a: 1 } + +const numbers = [-1, -2, -3]; +minBy(numbers, x => Math.abs(x)); +// Returns: -1 (절댓값이 가장 작은 요소) +``` + +배열 요소로 접근해요. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const arrays = [ + [1, 2], + [3, 4], + [0, 5], +]; +minBy(arrays, 0); // 첫 번째 요소가 최소인 배열 +// Returns: [0, 5] + +minBy(arrays, 1); // 두 번째 요소가 최소인 배열 +// Returns: [1, 2] +``` + +객체의 특정 속성과 값이 일치하는 경우를 찾아요. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const users = [ + { name: '홍길동', age: 25, active: true }, + { name: '김철수', age: 30, active: false }, + { name: '이영희', age: 35, active: true }, +]; + +// active가 true인 요소들 중에서 첫 번째가 아닌 것을 찾음 +minBy(users, ['active', true]); +// Returns: { name: '김철수', age: 30, active: false } + +// 객체로 조건 지정 +minBy(users, { active: true }); +// Returns: { name: '김철수', age: 30, active: false } +``` + +빈 배열은 undefined를 반환해요. + +```typescript +import { minBy } from 'es-toolkit/compat'; + +minBy([], x => x.a); +// Returns: undefined + +minBy(null); +// Returns: undefined + +minBy(undefined); +// Returns: undefined +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 검색할 배열이에요. +- `iteratee` (`ValueIteratee`, 선택): 각 요소에 적용할 함수, 속성명, 또는 조건이에요. + +#### 반환 값 + +(`T | undefined`): 조건에 맞는 값이 가장 작은 요소를 반환해요. 빈 배열이면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/math/multiply.md b/docs/ko/compat/reference/math/multiply.md similarity index 100% rename from docs/ko/reference/compat/math/multiply.md rename to docs/ko/compat/reference/math/multiply.md diff --git a/docs/ko/reference/compat/math/parseInt.md b/docs/ko/compat/reference/math/parseInt.md similarity index 100% rename from docs/ko/reference/compat/math/parseInt.md rename to docs/ko/compat/reference/math/parseInt.md diff --git a/docs/ko/reference/compat/math/random.md b/docs/ko/compat/reference/math/random.md similarity index 100% rename from docs/ko/reference/compat/math/random.md rename to docs/ko/compat/reference/math/random.md diff --git a/docs/ko/compat/reference/math/range.md b/docs/ko/compat/reference/math/range.md new file mode 100644 index 000000000..2293c1ff6 --- /dev/null +++ b/docs/ko/compat/reference/math/range.md @@ -0,0 +1,99 @@ +# range (Lodash 호환성) + +::: warning es-toolkit의 [range](../../../reference/math/range.md)를 사용하세요 + +이 `range` 함수는 복잡한 인수 처리와 타입 변환으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [range](../../../reference/math/range.md)를 사용하세요. + +::: + +숫자 범위 배열을 만들어요. + +```typescript +const numbers = range(start, end, step); +``` + +## 사용법 + +### `range(end)` + +0부터 end까지 1씩 증가하는 배열을 만들어요. + +```typescript +import { range } from 'es-toolkit/compat'; + +range(4); +// Returns: [0, 1, 2, 3] + +range(0); +// Returns: [] + +range(-4); +// Returns: [0, -1, -2, -3] +``` + +### `range(start, end)` + +start부터 end까지 1씩 증가하는 배열을 만들어요. + +```typescript +import { range } from 'es-toolkit/compat'; + +range(1, 5); +// Returns: [1, 2, 3, 4] + +range(5, 1); +// Returns: [5, 4, 3, 2] (자동으로 -1씩 감소) + +range(-2, 3); +// Returns: [-2, -1, 0, 1, 2] +``` + +### `range(start, end, step)` + +start부터 end까지 step만큼 증가하는 배열을 만들어요. + +```typescript +import { range } from 'es-toolkit/compat'; + +range(0, 20, 5); +// Returns: [0, 5, 10, 15] + +range(0, -4, -1); +// Returns: [0, -1, -2, -3] + +range(1, 4, 0); +// Returns: [1, 1, 1] +``` + +소수 step도 가능해요. + +```typescript +import { range } from 'es-toolkit/compat'; + +range(0, 1, 0.2); +// Returns: [0, 0.2, 0.4, 0.6, 0.8] + +range(1, 0, -0.25); +// Returns: [1, 0.75, 0.5, 0.25] +``` + +iteratee로 사용할 때는 guard 객체로 처리해요. + +```typescript +import { range } from 'es-toolkit/compat'; + +[1, 2, 3].map(range); +// Returns: [[0], [0, 1], [0, 1, 2]] +``` + +#### 파라미터 + +- `start` (`number`): 범위의 시작값이에요 (포함). `end`가 없으면 이 값이 end가 돼요. +- `end` (`number`, 선택): 범위의 끝값이에요 (포함되지 않음). +- `step` (`number`, 선택): 증가폭이에요. 기본값은 1 또는 -1이에요. + +#### 반환 값 + +(`number[]`): 지정된 범위의 숫자 배열을 반환해요. diff --git a/docs/ko/compat/reference/math/rangeRight.md b/docs/ko/compat/reference/math/rangeRight.md new file mode 100644 index 000000000..73bbb0f14 --- /dev/null +++ b/docs/ko/compat/reference/math/rangeRight.md @@ -0,0 +1,99 @@ +# rangeRight (Lodash 호환성) + +::: warning es-toolkit의 [rangeRight](../../../reference/math/rangeRight.md)를 사용하세요 + +이 `rangeRight` 함수는 복잡한 인수 처리와 타입 변환으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [rangeRight](../../../reference/math/rangeRight.md)를 사용하세요. + +::: + +숫자 범위 배열을 역순으로 만들어요. + +```typescript +const numbers = rangeRight(start, end, step); +``` + +## 사용법 + +### `rangeRight(end)` + +0부터 end까지 1씩 증가한 뒤 역순으로 배열을 만들어요. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(4); +// Returns: [3, 2, 1, 0] + +rangeRight(0); +// Returns: [] + +rangeRight(-4); +// Returns: [-3, -2, -1, 0] +``` + +### `rangeRight(start, end)` + +start부터 end까지 1씩 증가한 뒤 역순으로 배열을 만들어요. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(1, 5); +// Returns: [4, 3, 2, 1] + +rangeRight(5, 1); +// Returns: [2, 3, 4, 5] (자동으로 -1씩 감소했다가 역순) + +rangeRight(-2, 3); +// Returns: [2, 1, 0, -1, -2] +``` + +### `rangeRight(start, end, step)` + +start부터 end까지 step만큼 증가한 뒤 역순으로 배열을 만들어요. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(0, 8, 2); +// Returns: [6, 4, 2, 0] + +rangeRight(0, -4, -1); +// Returns: [-3, -2, -1, 0] + +rangeRight(1, 4, 0); +// Returns: [1, 1, 1] +``` + +소수 step도 가능해요. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(0, 1, 0.2); +// Returns: [0.8, 0.6, 0.4, 0.2, 0] + +rangeRight(1, 0, -0.25); +// Returns: [0.25, 0.5, 0.75, 1] +``` + +iteratee로 사용할 때는 guard 객체로 처리해요. + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +[1, 2, 3].map(rangeRight); +// Returns: [[0], [1, 0], [2, 1, 0]] +``` + +#### 파라미터 + +- `start` (`number`): 범위의 시작값이에요 (포함). `end`가 없으면 이 값이 end가 돼요. +- `end` (`number`, 선택): 범위의 끝값이에요 (포함되지 않음). +- `step` (`number`, 선택): 증가폭이에요. 기본값은 1 또는 -1이에요. + +#### 반환 값 + +(`number[]`): 지정된 범위의 숫자 배열을 역순으로 반환해요. diff --git a/docs/ko/reference/compat/math/round.md b/docs/ko/compat/reference/math/round.md similarity index 100% rename from docs/ko/reference/compat/math/round.md rename to docs/ko/compat/reference/math/round.md diff --git a/docs/ko/reference/compat/math/subtract.md b/docs/ko/compat/reference/math/subtract.md similarity index 100% rename from docs/ko/reference/compat/math/subtract.md rename to docs/ko/compat/reference/math/subtract.md diff --git a/docs/ko/compat/reference/math/sum.md b/docs/ko/compat/reference/math/sum.md new file mode 100644 index 000000000..4c70f2510 --- /dev/null +++ b/docs/ko/compat/reference/math/sum.md @@ -0,0 +1,73 @@ +# sum (Lodash 호환성) + +::: warning es-toolkit의 [sum](../../../reference/math/sum.md)를 사용하세요 + +이 `sum` 함수는 타입 변환과 null/undefined 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [sum](../../../reference/math/sum.md)를 사용하세요. + +::: + +배열의 모든 값을 더해요. + +```typescript +const total = sum(array); +``` + +## 사용법 + +### `sum(array)` + +배열 안의 모든 숫자를 더해서 총합을 구해요. + +```typescript +import { sum } from 'es-toolkit/compat'; + +// 숫자 배열 +sum([1, 2, 3]); +// Returns: 6 + +sum([1.5, 2.5, 3]); +// Returns: 7 + +// 빈 배열 +sum([]); +// Returns: 0 +``` + +BigInt와 문자열도 처리해요. + +```typescript +import { sum } from 'es-toolkit/compat'; + +// BigInt 배열 +sum([1n, 2n, 3n]); +// Returns: 6n + +// 문자열 배열 (연결됨) +sum(['1', '2']); +// Returns: '12' +``` + +잘못된 값들은 무시해요. + +```typescript +import { sum } from 'es-toolkit/compat'; + +sum([1, undefined, 2]); +// Returns: 3 (undefined 무시) + +sum(null); +// Returns: 0 + +sum(undefined); +// Returns: 0 +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 더할 값들이 있는 배열이에요. + +#### 반환 값 + +(`number`): 모든 값을 더한 총합을 반환해요. diff --git a/docs/ko/compat/reference/math/sumBy.md b/docs/ko/compat/reference/math/sumBy.md new file mode 100644 index 000000000..0f3dfe563 --- /dev/null +++ b/docs/ko/compat/reference/math/sumBy.md @@ -0,0 +1,103 @@ +# sumBy (Lodash 호환성) + +::: warning es-toolkit의 [sumBy](../../../reference/math/sumBy.md)를 사용하세요 + +이 `sumBy` 함수는 iteratee 함수 처리와 타입 변환으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [sumBy](../../../reference/math/sumBy.md)를 사용하세요. + +::: + +조건에 맞는 값들을 더해요. + +```typescript +const total = sumBy(array, iteratee); +``` + +## 사용법 + +### `sumBy(array, iteratee)` + +배열의 각 요소에 함수를 적용한 결과를 더해요. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +// 숫자 배열 +sumBy([1, 2, 3], value => value); +// Returns: 6 + +sumBy([1.5, 2.5, 3.5], value => Math.floor(value)); +// Returns: 6 (1 + 2 + 3) + +// 빈 배열 +sumBy([], value => value); +// Returns: 0 +``` + +### `sumBy(array)` + +함수를 주지 않으면 배열 값을 그대로 더해요. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +sumBy([1, 2, 3]); +// Returns: 6 + +sumBy([1n, 2n, 3n]); +// Returns: 6n +``` + +객체 배열에서 특정 속성을 더해요. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +const people = [ + { name: '홍길동', age: 25 }, + { name: '김철수', age: 30 }, + { name: '이영희', age: 35 }, +]; + +sumBy(people, person => person.age); +// Returns: 90 + +// 속성명으로도 가능 +sumBy(people, 'age'); +// Returns: 90 +``` + +문자열도 연결해요. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +const items = [{ a: '1' }, { a: '2' }]; +sumBy(items, obj => obj.a); +// Returns: '12' +``` + +잘못된 값들은 무시해요. + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +sumBy([1, undefined, 2], value => value); +// Returns: 3 (undefined 무시) + +sumBy(null); +// Returns: 0 + +sumBy(undefined); +// Returns: 0 +``` + +#### 파라미터 + +- `array` (`ArrayLike | null | undefined`): 처리할 배열이에요. +- `iteratee` (`((value: T) => number) | string`, 선택): 각 요소에 적용할 함수나 속성명이에요. + +#### 반환 값 + +(`number`): 조건에 맞는 값들을 더한 총합을 반환해요. diff --git a/docs/ko/reference/compat/object/assign.md b/docs/ko/compat/reference/object/assign.md similarity index 100% rename from docs/ko/reference/compat/object/assign.md rename to docs/ko/compat/reference/object/assign.md diff --git a/docs/ko/reference/compat/object/assignIn.md b/docs/ko/compat/reference/object/assignIn.md similarity index 100% rename from docs/ko/reference/compat/object/assignIn.md rename to docs/ko/compat/reference/object/assignIn.md diff --git a/docs/ko/reference/compat/object/assignInWith.md b/docs/ko/compat/reference/object/assignInWith.md similarity index 100% rename from docs/ko/reference/compat/object/assignInWith.md rename to docs/ko/compat/reference/object/assignInWith.md diff --git a/docs/ko/reference/compat/object/assignWith.md b/docs/ko/compat/reference/object/assignWith.md similarity index 100% rename from docs/ko/reference/compat/object/assignWith.md rename to docs/ko/compat/reference/object/assignWith.md diff --git a/docs/ko/reference/compat/object/at.md b/docs/ko/compat/reference/object/at.md similarity index 100% rename from docs/ko/reference/compat/object/at.md rename to docs/ko/compat/reference/object/at.md diff --git a/docs/ko/compat/reference/object/clone.md b/docs/ko/compat/reference/object/clone.md new file mode 100644 index 000000000..a15138935 --- /dev/null +++ b/docs/ko/compat/reference/object/clone.md @@ -0,0 +1,89 @@ +# clone (Lodash 호환성) + +::: warning `es-toolkit`의 `clone`을 사용하세요 + +이 `clone` 함수는 특수한 객체 타입들을 처리하는 복잡한 로직으로 인해 상대적으로 느려요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [clone](../../../reference/object/clone.md)을 사용하세요. + +::: + +객체의 얕은 복사본을 만들어요. + +```typescript +const cloned = clone(value); +``` + +## 사용법 + +### `clone(value)` + +값의 얕은 복사본을 만들고 싶을 때 `clone`을 사용하세요. 다양한 타입의 객체와 원시값을 복사할 수 있어요. + +```typescript +import { clone } from 'es-toolkit/compat'; + +// 원시 값 복사 +const num = 42; +const clonedNum = clone(num); +// Returns: 42 (같은 값) + +// 배열 복사 +const arr = [1, 2, 3]; +const clonedArr = clone(arr); +// Returns: [1, 2, 3] (새로운 배열 인스턴스) + +// 객체 복사 +const obj = { a: 1, b: 'hello' }; +const clonedObj = clone(obj); +// Returns: { a: 1, b: 'hello' } (새로운 객체 인스턴스) + +// Date 객체 복사 +const date = new Date('2023-01-01'); +const clonedDate = clone(date); +// Returns: new Date('2023-01-01') (새로운 Date 인스턴스) + +// 정규 표현식 복사 +const regex = /hello/gi; +regex.lastIndex = 3; +const clonedRegex = clone(regex); +// Returns: /hello/gi with lastIndex = 3 + +// Map 복사 +const map = new Map([ + ['a', 1], + ['b', 2], +]); +const clonedMap = clone(map); +// Returns: new Map([['a', 1], ['b', 2]]) + +// Set 복사 +const set = new Set([1, 2, 3]); +const clonedSet = clone(set); +// Returns: new Set([1, 2, 3]) +``` + +중첩된 객체는 얕은 복사만 수행해요. + +```typescript +import { clone } from 'es-toolkit/compat'; + +const nested = { + a: 1, + b: { + c: 2, + }, +}; +const clonedNested = clone(nested); + +console.log(clonedNested !== nested); // true (다른 객체) +console.log(clonedNested.b === nested.b); // true (중첩 객체는 같은 참조) +``` + +#### 파라미터 + +- `value` (`T`): 복사할 값이에요. + +#### 반환 값 + +(`T`): 복사된 값을 반환해요. diff --git a/docs/ko/compat/reference/object/cloneDeep.md b/docs/ko/compat/reference/object/cloneDeep.md new file mode 100644 index 000000000..f7ed22b37 --- /dev/null +++ b/docs/ko/compat/reference/object/cloneDeep.md @@ -0,0 +1,88 @@ +# cloneDeep (Lodash 호환성) + +::: warning `es-toolkit`의 `cloneDeep`을 사용하세요 + +이 `cloneDeep` 함수는 특수한 객체 타입들을 처리하는 복잡한 로직으로 인해 상대적으로 느려요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [cloneDeep](../../../reference/object/cloneDeep.md)을 사용하세요. + +::: + +객체의 깊은 복사본을 만들어요. + +```typescript +const cloned = cloneDeep(value); +``` + +## 사용법 + +### `cloneDeep(value)` + +값의 깊은 복사본을 만들고 싶을 때 `cloneDeep`을 사용하세요. 중첩된 객체와 배열까지 완전히 새로운 인스턴스로 복사해요. + +```typescript +import { cloneDeep } from 'es-toolkit/compat'; + +// 원시 값 복사 +const num = 42; +const clonedNum = cloneDeep(num); +// Returns: 42 (같은 값) + +// 배열 깊은 복사 +const arr = [1, [2, 3], { a: 4 }]; +const clonedArr = cloneDeep(arr); +clonedArr[1][0] = 99; +console.log(arr[1][0]); // 2 (원본은 변경되지 않음) +console.log(clonedArr[1][0]); // 99 + +// 객체 깊은 복사 +const obj = { + a: 1, + b: { + c: 2, + d: { + e: 3, + }, + }, +}; +const clonedObj = cloneDeep(obj); +clonedObj.b.d.e = 99; +console.log(obj.b.d.e); // 3 (원본은 변경되지 않음) +console.log(clonedObj.b.d.e); // 99 + +// Date 객체 깊은 복사 +const date = new Date('2023-01-01'); +const clonedDate = cloneDeep(date); +// Returns: new Date('2023-01-01') (새로운 Date 인스턴스) + +// 복잡한 중첩 구조 +const complex = { + arr: [1, { nested: true }], + map: new Map([['key', { value: 1 }]]), + set: new Set([{ item: 1 }]), + date: new Date(), +}; +const clonedComplex = cloneDeep(complex); +// 모든 중첩된 객체들이 완전히 새로운 인스턴스로 복사됨 +``` + +순환 참조도 올바르게 처리해요. + +```typescript +import { cloneDeep } from 'es-toolkit/compat'; + +const obj = { a: 1 }; +obj.self = obj; // 순환 참조 + +const cloned = cloneDeep(obj); +console.log(cloned !== obj); // true +console.log(cloned.self === cloned); // true (순환 참조 유지) +``` + +#### 파라미터 + +- `value` (`T`): 깊은 복사할 값이에요. + +#### 반환 값 + +(`T`): 깊은 복사된 값을 반환해요. diff --git a/docs/ko/reference/compat/object/cloneDeepWith.md b/docs/ko/compat/reference/object/cloneDeepWith.md similarity index 100% rename from docs/ko/reference/compat/object/cloneDeepWith.md rename to docs/ko/compat/reference/object/cloneDeepWith.md diff --git a/docs/ko/reference/compat/object/cloneWith.md b/docs/ko/compat/reference/object/cloneWith.md similarity index 100% rename from docs/ko/reference/compat/object/cloneWith.md rename to docs/ko/compat/reference/object/cloneWith.md diff --git a/docs/ko/reference/compat/object/create.md b/docs/ko/compat/reference/object/create.md similarity index 100% rename from docs/ko/reference/compat/object/create.md rename to docs/ko/compat/reference/object/create.md diff --git a/docs/ko/reference/compat/object/defaults.md b/docs/ko/compat/reference/object/defaults.md similarity index 100% rename from docs/ko/reference/compat/object/defaults.md rename to docs/ko/compat/reference/object/defaults.md diff --git a/docs/ko/reference/compat/object/defaultsDeep.md b/docs/ko/compat/reference/object/defaultsDeep.md similarity index 100% rename from docs/ko/reference/compat/object/defaultsDeep.md rename to docs/ko/compat/reference/object/defaultsDeep.md diff --git a/docs/ko/reference/compat/object/extend.md b/docs/ko/compat/reference/object/extend.md similarity index 100% rename from docs/ko/reference/compat/object/extend.md rename to docs/ko/compat/reference/object/extend.md diff --git a/docs/ko/reference/compat/object/extendWith.md b/docs/ko/compat/reference/object/extendWith.md similarity index 100% rename from docs/ko/reference/compat/object/extendWith.md rename to docs/ko/compat/reference/object/extendWith.md diff --git a/docs/ko/compat/reference/object/findKey.md b/docs/ko/compat/reference/object/findKey.md new file mode 100644 index 000000000..33b7ae2cb --- /dev/null +++ b/docs/ko/compat/reference/object/findKey.md @@ -0,0 +1,61 @@ +# findKey (Lodash 호환성) + +::: warning `es-toolkit`의 `findKey`를 사용하세요 + +이 `findKey` 함수는 다양한 조건 타입 처리와 호환성 로직으로 인해 복잡하게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [findKey](../../../reference/object/findKey.md)를 사용하세요. + +::: + +조건에 맞는 첫 번째 요소의 키를 찾아요. + +```typescript +const key = findKey(obj, predicate); +``` + +## 사용법 + +### `findKey(obj, predicate)` + +객체에서 조건에 맞는 첫 번째 요소의 키를 찾을 때 `findKey`를 사용하세요. 함수, 객체, 배열, 문자열 등 다양한 형태의 조건을 사용할 수 있어요. + +```typescript +import { findKey } from 'es-toolkit/compat'; + +// 함수 조건으로 키 찾기 +const users = { + alice: { age: 25, active: true }, + bob: { age: 30, active: false }, + charlie: { age: 35, active: true }, +}; + +findKey(users, user => user.age > 30); +// 반환값: 'charlie' + +// 객체 조건으로 키 찾기 +findKey(users, { active: false }); +// 반환값: 'bob' + +// 속성 경로로 키 찾기 +findKey(users, 'active'); +// 반환값: 'alice' +``` + +조건에 맞는 요소가 없으면 `undefined`를 반환해요. + +```typescript +import { findKey } from 'es-toolkit/compat'; + +findKey({ a: 1, b: 2 }, value => value > 5); +// 반환값: undefined +``` + +#### 파라미터 + +- `obj` (`T | null | undefined`): 검색할 객체예요. +- `predicate` (`ObjectIteratee`, 선택): 각 요소에 적용할 조건이에요. 함수, 객체, 배열, 문자열이 될 수 있어요. + +#### 반환 값 + +(`string | undefined`): 조건에 맞는 첫 번째 요소의 키를 반환해요. 없으면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/object/findLastKey.md b/docs/ko/compat/reference/object/findLastKey.md similarity index 100% rename from docs/ko/reference/compat/object/findLastKey.md rename to docs/ko/compat/reference/object/findLastKey.md diff --git a/docs/ko/reference/compat/object/forIn.md b/docs/ko/compat/reference/object/forIn.md similarity index 100% rename from docs/ko/reference/compat/object/forIn.md rename to docs/ko/compat/reference/object/forIn.md diff --git a/docs/ko/reference/compat/object/forInRight.md b/docs/ko/compat/reference/object/forInRight.md similarity index 100% rename from docs/ko/reference/compat/object/forInRight.md rename to docs/ko/compat/reference/object/forInRight.md diff --git a/docs/ko/reference/compat/object/forOwn.md b/docs/ko/compat/reference/object/forOwn.md similarity index 100% rename from docs/ko/reference/compat/object/forOwn.md rename to docs/ko/compat/reference/object/forOwn.md diff --git a/docs/ko/reference/compat/object/forOwnRight.md b/docs/ko/compat/reference/object/forOwnRight.md similarity index 100% rename from docs/ko/reference/compat/object/forOwnRight.md rename to docs/ko/compat/reference/object/forOwnRight.md diff --git a/docs/ko/reference/compat/object/fromPairs.md b/docs/ko/compat/reference/object/fromPairs.md similarity index 100% rename from docs/ko/reference/compat/object/fromPairs.md rename to docs/ko/compat/reference/object/fromPairs.md diff --git a/docs/ko/reference/compat/object/functions.md b/docs/ko/compat/reference/object/functions.md similarity index 100% rename from docs/ko/reference/compat/object/functions.md rename to docs/ko/compat/reference/object/functions.md diff --git a/docs/ko/reference/compat/object/functionsIn.md b/docs/ko/compat/reference/object/functionsIn.md similarity index 100% rename from docs/ko/reference/compat/object/functionsIn.md rename to docs/ko/compat/reference/object/functionsIn.md diff --git a/docs/ko/reference/compat/object/get.md b/docs/ko/compat/reference/object/get.md similarity index 100% rename from docs/ko/reference/compat/object/get.md rename to docs/ko/compat/reference/object/get.md diff --git a/docs/ko/reference/compat/object/has.md b/docs/ko/compat/reference/object/has.md similarity index 100% rename from docs/ko/reference/compat/object/has.md rename to docs/ko/compat/reference/object/has.md diff --git a/docs/ko/reference/compat/object/hasIn.md b/docs/ko/compat/reference/object/hasIn.md similarity index 100% rename from docs/ko/reference/compat/object/hasIn.md rename to docs/ko/compat/reference/object/hasIn.md diff --git a/docs/ko/compat/reference/object/invert.md b/docs/ko/compat/reference/object/invert.md new file mode 100644 index 000000000..870f207d0 --- /dev/null +++ b/docs/ko/compat/reference/object/invert.md @@ -0,0 +1,60 @@ +# invert (Lodash 호환성) + +::: warning `es-toolkit`의 `invert`를 사용하세요 + +이 `invert` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [invert](../../../reference/object/invert.md)를 사용하세요. + +::: + +객체의 키와 값을 뒤바꿔요. + +```typescript +const inverted = invert(object); +``` + +## 사용법 + +### `invert(object)` + +객체의 키와 값을 서로 바꾸고 싶을 때 `invert`를 사용하세요. 원래 객체의 키는 새 객체의 값이 되고, 원래 객체의 값은 새 객체의 키가 돼요. + +```typescript +import { invert } from 'es-toolkit/compat'; + +// 기본 키-값 뒤바꾸기 +const object = { a: 1, b: 2, c: 3 }; +invert(object); +// => { '1': 'a', '2': 'b', '3': 'c' } + +// 문자열 값들 뒤바꾸기 +const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' }; +invert(colors); +// => { '#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue' } + +// 혼합된 키와 값 타입 +const mixed = { a: 1, 2: 'b', c: 3, 4: 'd' }; +invert(mixed); +// => { '1': 'a', 'b': '2', '3': 'c', 'd': '4' } +``` + +중복된 값이 있을 때는 마지막 키가 사용돼요. + +```typescript +import { invert } from 'es-toolkit/compat'; + +// 중복된 값이 있는 경우 +const object = { a: 1, b: 1, c: 2 }; +invert(object); +// => { '1': 'b', '2': 'c' } +// 'a'는 덮어쓰여져서 사라져요 +``` + +#### 파라미터 + +- `object` (`object`): 뒤바꿀 객체예요. + +#### 반환 값 + +(`Record`): 키와 값이 뒤바뀐 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/invertBy.md b/docs/ko/compat/reference/object/invertBy.md similarity index 100% rename from docs/ko/reference/compat/object/invertBy.md rename to docs/ko/compat/reference/object/invertBy.md diff --git a/docs/ko/reference/compat/object/keys.md b/docs/ko/compat/reference/object/keys.md similarity index 100% rename from docs/ko/reference/compat/object/keys.md rename to docs/ko/compat/reference/object/keys.md diff --git a/docs/ko/reference/compat/object/keysIn.md b/docs/ko/compat/reference/object/keysIn.md similarity index 100% rename from docs/ko/reference/compat/object/keysIn.md rename to docs/ko/compat/reference/object/keysIn.md diff --git a/docs/ko/compat/reference/object/mapKeys.md b/docs/ko/compat/reference/object/mapKeys.md new file mode 100644 index 000000000..a52930d73 --- /dev/null +++ b/docs/ko/compat/reference/object/mapKeys.md @@ -0,0 +1,63 @@ +# mapKeys (Lodash 호환성) + +::: warning `es-toolkit`의 `mapKeys`를 사용하세요 + +이 `mapKeys` 함수는 `null`이나 `undefined` 처리, `iteratee` 변환 과정 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [mapKeys](../../../reference/object/mapKeys.md)를 사용하세요. + +::: + +객체의 값은 그대로 두고 키를 변환해서 새로운 객체를 만들어요. + +```typescript +const result = mapKeys(obj, iteratee); +``` + +## 사용법 + +### `mapKeys(object, iteratee)` + +객체의 각 키를 `iteratee` 함수로 변환해서 새로운 객체를 만들어요. 값은 원래대로 유지되고 키만 변경돼요. 객체의 키를 변환하거나 정규화할 때 유용해요. + +```typescript +import { mapKeys } from 'es-toolkit/compat'; + +// 키에 접두사 추가 +const obj = { a: 1, b: 2, c: 3 }; +const result = mapKeys(obj, (value, key) => 'prefix_' + key); +// 결과: { prefix_a: 1, prefix_b: 2, prefix_c: 3 } + +// 키를 대문자로 변환 +const data = { name: 'John', age: 30 }; +const uppercased = mapKeys(data, (value, key) => key.toUpperCase()); +// 결과: { NAME: 'John', AGE: 30 } + +// 배열 인덱스를 키로 변환 +const arr = ['apple', 'banana', 'orange']; +const indexed = mapKeys(arr, (value, index) => `item_${index}`); +// 결과: { item_0: 'apple', item_1: 'banana', item_2: 'orange' } + +// 키와 값을 조합해서 새로운 키 생성 +const scores = { math: 90, science: 85, english: 92 }; +const detailed = mapKeys(scores, (value, key) => `${key}_score_${value}`); +// 결과: { math_score_90: 90, science_score_85: 85, english_score_92: 92 } +``` + +`null`이나 `undefined`는 빈 객체로 처리해요. + +```typescript +import { mapKeys } from 'es-toolkit/compat'; + +mapKeys(null, iteratee); // {} +mapKeys(undefined, iteratee); // {} +``` + +#### 파라미터 + +- `object` (`ArrayLike | T | null | undefined`): 키를 변환할 객체나 배열이에요. +- `iteratee` (`ListIteratee | ObjectIteratee`, 선택): 각 키를 변환할 함수예요. 기본값은 `identity` 함수예요. + +#### 반환 값 + +(`Record | Record`): 변환된 키를 가진 새로운 객체를 반환해요. diff --git a/docs/ko/compat/reference/object/mapValues.md b/docs/ko/compat/reference/object/mapValues.md new file mode 100644 index 000000000..2189f84a3 --- /dev/null +++ b/docs/ko/compat/reference/object/mapValues.md @@ -0,0 +1,71 @@ +# mapValues (Lodash 호환성) + +::: warning `es-toolkit`의 `mapValues`를 사용하세요 + +이 `mapValues` 함수는 `null`이나 `undefined` 처리, `iteratee` 변환 과정 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [mapValues](../../../reference/object/mapValues.md)를 사용하세요. + +::: + +객체의 키는 그대로 두고 값을 변환해서 새로운 객체를 만들어요. + +```typescript +const result = mapValues(obj, iteratee); +``` + +## 사용법 + +### `mapValues(object, iteratee)` + +객체의 각 값을 `iteratee` 함수로 변환해서 새로운 객체를 만들어요. 키는 원래대로 유지되고 값만 변경돼요. 문자열, 배열, 객체 모두 처리할 수 있어요. 데이터를 변환하거나 계산할 때 유용해요. + +```typescript +import { mapValues } from 'es-toolkit/compat'; + +// 객체의 값을 변환 +const obj = { a: 1, b: 2, c: 3 }; +const doubled = mapValues(obj, value => value * 2); +// 결과: { a: 2, b: 4, c: 6 } + +// 문자열을 대문자로 변환 +const names = { first: 'john', last: 'doe' }; +const uppercased = mapValues(names, value => value.toUpperCase()); +// 결과: { first: 'JOHN', last: 'DOE' } + +// 문자열의 각 문자 변환 +const str = 'abc'; +const charMap = mapValues(str, char => char.toUpperCase()); +// 결과: { '0': 'A', '1': 'B', '2': 'C' } + +// 배열을 객체로 변환 +const arr = [10, 20, 30]; +const arrMap = mapValues(arr, (value, index) => value + index); +// 결과: { '0': 10, '1': 21, '2': 32 } + +// 속성 경로로 값 추출 +const users = { + user1: { profile: { name: 'Alice' } }, + user2: { profile: { name: 'Bob' } }, +}; +const userNames = mapValues(users, 'profile.name'); +// 결과: { user1: 'Alice', user2: 'Bob' } +``` + +`null`이나 `undefined`는 빈 객체로 처리해요. + +```typescript +import { mapValues } from 'es-toolkit/compat'; + +mapValues(null, iteratee); // {} +mapValues(undefined, iteratee); // {} +``` + +#### 파라미터 + +- `object` (`string | T[] | T | null | undefined`): 값을 변환할 객체, 배열, 또는 문자열이에요. +- `iteratee` (`ValueIteratee`, 선택): 각 값을 변환할 함수, 속성 경로, 또는 매칭 객체예요. 기본값은 `identity` 함수예요. + +#### 반환 값 + +(`Record | { [P in keyof T]: U } | Record | Record | Partial`): 변환된 값을 가진 새로운 객체를 반환해요. diff --git a/docs/ko/compat/reference/object/merge.md b/docs/ko/compat/reference/object/merge.md new file mode 100644 index 000000000..7b4e6b150 --- /dev/null +++ b/docs/ko/compat/reference/object/merge.md @@ -0,0 +1,82 @@ +# merge (Lodash 호환성) + +::: warning `es-toolkit`의 `merge`를 사용하세요 + +이 `merge` 함수는 내부적으로 복잡한 `mergeWith` 함수를 호출하여 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [merge](../../../reference/object/merge.md)를 사용하세요. + +::: + +여러 객체를 깊게 병합해서 하나의 객체로 만들어요. + +```typescript +const result = merge(target, ...sources); +``` + +## 사용법 + +### `merge(object, ...sources)` + +대상 객체에 하나 이상의 소스 객체를 깊게 병합해요. 중첩된 객체와 배열도 재귀적으로 병합돼요. 소스 객체의 속성이 `undefined`이면 대상 객체의 기존 값을 덮어쓰지 않아요. 객체 설정 병합이나 기본값 적용에 유용해요. + +```typescript +import { merge } from 'es-toolkit/compat'; + +// 기본 객체 병합 +const target = { a: 1, b: { x: 1, y: 2 } }; +const source = { b: { y: 3, z: 4 }, c: 5 }; +const result = merge(target, source); +// 결과: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } + +// 배열 병합 +const obj1 = { arr: [1, 2] }; +const obj2 = { arr: [3, 4] }; +const merged = merge(obj1, obj2); +// 결과: { arr: [3, 4] } (배열은 교체됨) + +// 여러 객체 병합 +const base = { a: 1 }; +const ext1 = { b: 2 }; +const ext2 = { c: 3 }; +const ext3 = { d: 4 }; +const combined = merge(base, ext1, ext2, ext3); +// 결과: { a: 1, b: 2, c: 3, d: 4 } + +// 중첩된 객체 병합 +const config = { + api: { url: 'https://api.example.com', timeout: 5000 }, + features: { auth: true }, +}; +const overrides = { + api: { timeout: 10000, retries: 3 }, + features: { analytics: true }, +}; +const finalConfig = merge(config, overrides); +// 결과: { +// api: { url: 'https://api.example.com', timeout: 10000, retries: 3 }, +// features: { auth: true, analytics: true } +// } +``` + +대상 객체가 수정되므로 원본을 보존하려면 빈 객체를 사용하세요. + +```typescript +import { merge } from 'es-toolkit/compat'; + +const original = { a: 1, b: { x: 1 } }; +const source = { b: { y: 2 } }; + +// 원본 보존 +const result = merge({}, original, source); +// original은 변경되지 않음 +``` + +#### 파라미터 + +- `object` (`any`): 병합 대상이 되는 객체예요. 이 객체가 수정돼요. +- `...sources` (`any[]`): 병합할 소스 객체들이에요. + +#### 반환 값 + +(`any`): 병합된 대상 객체를 반환해요. diff --git a/docs/ko/compat/reference/object/mergeWith.md b/docs/ko/compat/reference/object/mergeWith.md new file mode 100644 index 000000000..1ca37cfd0 --- /dev/null +++ b/docs/ko/compat/reference/object/mergeWith.md @@ -0,0 +1,94 @@ +# mergeWith (Lodash 호환성) + +::: warning `es-toolkit`의 `mergeWith`를 사용하세요 + +이 `mergeWith` 함수는 복잡한 타입 체크와 순환 참조 처리, 특수 객체 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [mergeWith](../../../reference/object/mergeWith.md)를 사용하세요. + +::: + +사용자 정의 함수로 병합 방식을 제어하면서 여러 객체를 깊게 병합해요. + +```typescript +const result = mergeWith(target, ...sources, customizer); +``` + +## 사용법 + +### `mergeWith(object, ...sources, customizer)` + +대상 객체에 하나 이상의 소스 객체를 깊게 병합하되, 커스터마이저 함수로 병합 방식을 제어해요. 커스터마이저 함수가 `undefined`를 반환하면 기본 병합 로직이 사용돼요. 배열 합치기나 특별한 병합 규칙이 필요할 때 유용해요. + +```typescript +import { mergeWith } from 'es-toolkit/compat'; + +// 숫자 더하기 +const obj1 = { a: 1, b: 2 }; +const obj2 = { b: 3, c: 4 }; +const result = mergeWith(obj1, obj2, (objValue, srcValue) => { + if (typeof objValue === 'number' && typeof srcValue === 'number') { + return objValue + srcValue; + } +}); +// 결과: { a: 1, b: 5, c: 4 } + +// 배열 합치기 +const arr1 = { items: [1, 2] }; +const arr2 = { items: [3, 4] }; +const merged = mergeWith(arr1, arr2, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return objValue.concat(srcValue); + } +}); +// 결과: { items: [1, 2, 3, 4] } + +// 문자열 연결 +const str1 = { message: 'Hello' }; +const str2 = { message: 'World' }; +const combined = mergeWith(str1, str2, (objValue, srcValue, key) => { + if (key === 'message' && typeof objValue === 'string') { + return objValue + ' ' + srcValue; + } +}); +// 결과: { message: 'Hello World' } + +// 여러 소스 객체와 커스터마이저 +const base = { scores: [80] }; +const quiz1 = { scores: [90] }; +const quiz2 = { scores: [85] }; +const final = mergeWith(base, quiz1, quiz2, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return objValue.concat(srcValue); + } +}); +// 결과: { scores: [80, 90, 85] } +``` + +커스터마이저 함수는 다양한 매개변수를 받아요. + +```typescript +import { mergeWith } from 'es-toolkit/compat'; + +const customizer = (objValue, srcValue, key, object, source, stack) => { + console.log('병합 중:', key, objValue, '->', srcValue); + + // 특정 키에 대해서만 커스터마이징 + if (key === 'specialField') { + return `${objValue}_${srcValue}`; + } + + // undefined를 반환하면 기본 병합 로직 사용 + return undefined; +}; +``` + +#### 파라미터 + +- `object` (`any`): 병합 대상이 되는 객체예요. 이 객체가 수정돼요. +- `...sources` (`any[]`): 병합할 소스 객체들이에요. +- `customizer` (`MergeWithCustomizer`): 값 할당을 커스터마이즈하는 함수예요. `(objValue, srcValue, key, object, source, stack) => any` 형태예요. + +#### 반환 값 + +(`any`): 병합된 대상 객체를 반환해요. diff --git a/docs/ko/compat/reference/object/omit.md b/docs/ko/compat/reference/object/omit.md new file mode 100644 index 000000000..5b037b4f3 --- /dev/null +++ b/docs/ko/compat/reference/object/omit.md @@ -0,0 +1,82 @@ +# omit (Lodash 호환성) + +::: warning `es-toolkit`의 `omit`를 사용하세요 + +이 `omit` 함수는 깊은 복사와 `unset` 함수 호출 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [omit](../../../reference/object/omit.md)를 사용하세요. + +::: + +객체에서 지정된 키들을 제외한 새로운 객체를 만들어요. + +```typescript +const result = omit(obj, ...keys); +``` + +## 사용법 + +### `omit(object, ...paths)` + +객체에서 지정된 키들을 제외한 새로운 객체를 생성해요. 깊은 키 경로도 지원하며, 배열로 여러 키를 한 번에 지정할 수도 있어요. 객체에서 민감한 정보를 제거하거나 필요한 속성만 선택할 때 유용해요. + +```typescript +import { omit } from 'es-toolkit/compat'; + +// 기본 키 제거 +const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }; +const publicUser = omit(user, 'password', 'email'); +// 결과: { id: 1, name: 'John' } + +// 배열로 여러 키 제거 +const data = { a: 1, b: 2, c: 3, d: 4 }; +const filtered = omit(data, ['a', 'c']); +// 결과: { b: 2, d: 4 } + +// 깊은 키 경로 제거 +const nested = { + user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, + admin: true, +}; +const result = omit(nested, 'user.profile.age', 'admin'); +// 결과: { user: { profile: { name: 'John' }, settings: { theme: 'dark' } } } + +// 중첩된 배열과 키 조합 +const complex = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; +const simplified = omit(complex, 'a', ['b', 'c'], 'd.f'); +// 결과: { d: { e: 4 } } +``` + +배열이나 문자열, 키 경로를 자유롭게 조합할 수 있어요. + +```typescript +import { omit } from 'es-toolkit/compat'; + +const config = { + api: { url: 'https://api.example.com', key: 'secret', timeout: 5000 }, + ui: { theme: 'dark', language: 'en' }, + debug: true, +}; + +// 여러 방식으로 키 지정 +const cleaned = omit(config, 'api.key', ['debug'], 'ui.language'); +// 결과: { api: { url: 'https://api.example.com', timeout: 5000 }, ui: { theme: 'dark' } } +``` + +`null`이나 `undefined`는 빈 객체로 처리해요. + +```typescript +import { omit } from 'es-toolkit/compat'; + +omit(null, 'key'); // {} +omit(undefined, 'key'); // {} +``` + +#### 파라미터 + +- `object` (`T | null | undefined`): 키를 제거할 원본 객체예요. +- `...paths` (`Array>`): 제거할 키들이에요. 단일 키, 키 배열, 또는 깊은 키 경로를 지정할 수 있어요. + +#### 반환 값 + +(`Partial`): 지정된 키들이 제거된 새로운 객체를 반환해요. diff --git a/docs/ko/compat/reference/object/omitBy.md b/docs/ko/compat/reference/object/omitBy.md new file mode 100644 index 000000000..915950b94 --- /dev/null +++ b/docs/ko/compat/reference/object/omitBy.md @@ -0,0 +1,76 @@ +# omitBy (Lodash 호환성) + +::: warning `es-toolkit`의 `omitBy`를 사용하세요 + +이 `omitBy` 함수는 배열 유사 객체 체크, `iteratee` 변환, 키 변환 과정 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [omitBy](../../../reference/object/omitBy.md)를 사용하세요. + +::: + +조건 함수가 참을 반환하는 속성들을 제외한 새로운 객체를 만들어요. + +```typescript +const result = omitBy(obj, predicate); +``` + +## 사용법 + +### `omitBy(object, predicate)` + +객체의 각 속성에 대해 조건 함수를 실행하고, 조건 함수가 참을 반환하는 속성들을 제외한 새로운 객체를 생성해요. 조건에 따라 동적으로 속성을 필터링할 때 유용해요. + +```typescript +import { omitBy } from 'es-toolkit/compat'; + +// 특정 타입의 값 제거 +const data = { a: 1, b: 'remove', c: 3, d: 'keep' }; +const numbers = omitBy(data, value => typeof value === 'string'); +// 결과: { a: 1, c: 3 } + +// 조건에 따른 속성 제거 +const user = { id: 1, name: 'John', age: 0, active: false, email: '' }; +const validData = omitBy(user, value => !value); +// 결과: { id: 1, name: 'John' } (falsy 값들 제거) + +// 키 이름으로 필터링 +const settings = { userSetting: true, adminSetting: false, debugMode: true }; +const userOnly = omitBy(settings, (value, key) => key.startsWith('admin')); +// 결과: { userSetting: true, debugMode: true } + +// 숫자 속성만 제거 +const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; +const noNumbers = omitBy(mixed, value => typeof value === 'number'); +// 결과: { str: 'hello', bool: true, obj: {} } + +// 배열에서도 사용 가능 +const arr = [1, 2, 3, 4, 5]; +const filtered = omitBy(arr, value => value % 2 === 0); +// 결과: { '0': 1, '2': 3, '4': 5 } (짝수 인덱스의 홀수 값들) + +// 객체와 키, 원본 객체 모두 활용 +const scores = { math: 90, science: 75, english: 85, art: 60 }; +const passingGrades = omitBy(scores, (value, key, obj) => { + console.log(`${key}: ${value} (평균: ${Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length})`); + return value < 80; +}); +// 결과: { math: 90, english: 85 } +``` + +`null`이나 `undefined`는 빈 객체로 처리해요. + +```typescript +import { omitBy } from 'es-toolkit/compat'; + +omitBy(null, () => true); // {} +omitBy(undefined, () => true); // {} +``` + +#### 파라미터 + +- `object` (`Record | Record | object | null | undefined`): 필터링할 원본 객체예요. +- `predicate` (`ValueKeyIteratee | ValueKeyIteratee`, 선택): 각 속성에 대해 실행할 조건 함수예요. 참을 반환하면 해당 속성이 제거돼요. 기본값은 `identity` 함수예요. + +#### 반환 값 + +(`Record | Record | Partial`): 조건에 맞지 않는 속성들로 구성된 새로운 객체를 반환해요. diff --git a/docs/ko/compat/reference/object/pick.md b/docs/ko/compat/reference/object/pick.md new file mode 100644 index 000000000..c4ec0b42a --- /dev/null +++ b/docs/ko/compat/reference/object/pick.md @@ -0,0 +1,73 @@ +# pick (Lodash 호환성) + +::: warning `es-toolkit`의 `pick`을 사용하세요 + +이 `pick` 함수는 복잡한 경로 처리, `get`/`set` 함수 호출, `null`/`undefined` 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [pick](../../../reference/object/pick.md)을 사용하세요. + +::: + +객체에서 지정한 속성들만 선택해서 새로운 객체를 만들어요. + +```typescript +const result = pick(obj, ...keys); +``` + +## 사용법 + +### `pick(object, ...props)` + +객체에서 원하는 속성들만 골라서 새로운 객체를 만들고 싶을 때 `pick`을 사용하세요. 배열로 여러 키를 한번에 전달하거나, 개별 인수로 하나씩 전달할 수 있어요. 깊은 키 경로도 지원하므로 중첩된 속성도 선택할 수 있어요. + +```typescript +import { pick } from 'es-toolkit/compat'; + +// 기본 사용법 +const obj = { a: 1, b: 2, c: 3, d: 4 }; +const result = pick(obj, ['a', 'c']); +// 결과: { a: 1, c: 3 } + +// 개별 인수로 전달 +const result2 = pick(obj, 'a', 'c'); +// 결과: { a: 1, c: 3 } + +// 깊은 경로 선택 +const nested = { + user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, + admin: true, +}; +const userInfo = pick(nested, 'user.profile.name', 'admin'); +// 결과: { user: { profile: { name: 'John' } }, admin: true } + +// 배열과 개별 키 혼합 +const mixed = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; +const selected = pick(mixed, ['a', 'b'], 'c', 'd.e'); +// 결과: { a: 1, b: 2, c: 3, d: { e: 4 } } + +// 점 표기법 키와 실제 점이 있는 키 구분 +const ambiguous = { + 'a.b': 1, // 실제로 'a.b'라는 키 + a: { b: 2, c: 3 }, // 중첩된 객체 +}; +const dotKey = pick(ambiguous, 'a.b'); +// 결과: { 'a.b': 1 } (실제 키를 우선 선택) +``` + +`null`이나 `undefined`는 빈 객체로 처리해요. + +```typescript +import { pick } from 'es-toolkit/compat'; + +pick(null, ['a', 'b']); // {} +pick(undefined, ['a', 'b']); // {} +``` + +#### 파라미터 + +- `object` (`T | null | undefined`): 속성을 선택할 객체예요. +- `...props` (`Array>`): 선택할 속성의 키들이에요. 단일 키, 키 배열, 또는 깊은 키 경로를 지정할 수 있어요. + +#### 반환 값 + +(`Pick | Partial`): 지정한 속성들만 포함하는 새로운 객체를 반환해요. diff --git a/docs/ko/compat/reference/object/pickBy.md b/docs/ko/compat/reference/object/pickBy.md new file mode 100644 index 000000000..4d7f538e7 --- /dev/null +++ b/docs/ko/compat/reference/object/pickBy.md @@ -0,0 +1,86 @@ +# pickBy (Lodash 호환성) + +::: warning `es-toolkit`의 `pickBy`를 사용하세요 + +이 `pickBy` 함수는 배열 유사 객체 체크, `iteratee` 변환, 키 변환 과정 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [pickBy](../../../reference/object/pickBy.md)를 사용하세요. + +::: + +조건 함수가 참을 반환하는 속성들만 선택해서 새로운 객체를 만들어요. + +```typescript +const result = pickBy(obj, predicate); +``` + +## 사용법 + +### `pickBy(object, predicate)` + +객체의 각 속성에 대해 조건 함수를 실행하고, 조건 함수가 참을 반환하는 속성들만 포함한 새로운 객체를 생성해요. 조건에 따라 동적으로 속성을 선택할 때 유용해요. + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +// 특정 타입의 값만 선택 +const data = { a: 1, b: 'keep', c: 3, d: 'select' }; +const strings = pickBy(data, value => typeof value === 'string'); +// 결과: { b: 'keep', d: 'select' } + +// 조건에 따른 속성 선택 +const user = { id: 1, name: 'John', age: 0, active: true, email: '' }; +const validData = pickBy(user, value => Boolean(value)); +// 결과: { id: 1, name: 'John', active: true } (참으로 평가되는 값들만) + +// 키 이름으로 필터링 +const settings = { userSetting: true, adminSetting: false, debugMode: true }; +const userOnly = pickBy(settings, (value, key) => key.startsWith('user')); +// 결과: { userSetting: true } + +// 숫자 속성만 선택 +const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; +const numbersOnly = pickBy(mixed, value => typeof value === 'number'); +// 결과: { num1: 42, num2: 0 } + +// 배열에서도 사용 가능 +const arr = [1, 2, 3, 4, 5]; +const evens = pickBy(arr, value => value % 2 === 0); +// 결과: { '1': 2, '3': 4 } (짝수 값들의 인덱스와 값) + +// 객체와 키, 원본 객체 모두 활용 +const scores = { math: 90, science: 75, english: 85, art: 60 }; +const highScores = pickBy(scores, (value, key, obj) => { + const average = Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length; + return value > average; +}); +// 결과: { math: 90, english: 85 } +``` + +조건 함수 없이 호출하면 참으로 평가되는 값들만 선택해요. + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +const data = { a: 1, b: '', c: 0, d: 'hello', e: null, f: true }; +const truthyValues = pickBy(data); +// 결과: { a: 1, d: 'hello', f: true } +``` + +`null`이나 `undefined`는 빈 객체로 처리해요. + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +pickBy(null, () => true); // {} +pickBy(undefined, () => true); // {} +``` + +#### 파라미터 + +- `object` (`Record | Record | object | null | undefined`): 필터링할 원본 객체예요. +- `predicate` (`ValueKeyIterateeTypeGuard | ValueKeyIteratee | ValueKeyIteratee`, 선택): 각 속성에 대해 실행할 조건 함수예요. 참을 반환하면 해당 속성이 선택돼요. 기본값은 `identity` 함수예요. + +#### 반환 값 + +(`Record | Record | Partial`): 조건에 맞는 속성들로 구성된 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/property.md b/docs/ko/compat/reference/object/property.md similarity index 100% rename from docs/ko/reference/compat/object/property.md rename to docs/ko/compat/reference/object/property.md diff --git a/docs/ko/reference/compat/object/propertyOf.md b/docs/ko/compat/reference/object/propertyOf.md similarity index 100% rename from docs/ko/reference/compat/object/propertyOf.md rename to docs/ko/compat/reference/object/propertyOf.md diff --git a/docs/ko/reference/compat/object/result.md b/docs/ko/compat/reference/object/result.md similarity index 100% rename from docs/ko/reference/compat/object/result.md rename to docs/ko/compat/reference/object/result.md diff --git a/docs/ko/reference/compat/object/set.md b/docs/ko/compat/reference/object/set.md similarity index 100% rename from docs/ko/reference/compat/object/set.md rename to docs/ko/compat/reference/object/set.md diff --git a/docs/ko/reference/compat/object/setWith.md b/docs/ko/compat/reference/object/setWith.md similarity index 100% rename from docs/ko/reference/compat/object/setWith.md rename to docs/ko/compat/reference/object/setWith.md diff --git a/docs/ko/reference/compat/object/toDefaulted.md b/docs/ko/compat/reference/object/toDefaulted.md similarity index 100% rename from docs/ko/reference/compat/object/toDefaulted.md rename to docs/ko/compat/reference/object/toDefaulted.md diff --git a/docs/ko/reference/compat/object/toPairs.md b/docs/ko/compat/reference/object/toPairs.md similarity index 100% rename from docs/ko/reference/compat/object/toPairs.md rename to docs/ko/compat/reference/object/toPairs.md diff --git a/docs/ko/reference/compat/object/toPairsIn.md b/docs/ko/compat/reference/object/toPairsIn.md similarity index 100% rename from docs/ko/reference/compat/object/toPairsIn.md rename to docs/ko/compat/reference/object/toPairsIn.md diff --git a/docs/ko/reference/compat/object/transform.md b/docs/ko/compat/reference/object/transform.md similarity index 100% rename from docs/ko/reference/compat/object/transform.md rename to docs/ko/compat/reference/object/transform.md diff --git a/docs/ko/reference/compat/object/unset.md b/docs/ko/compat/reference/object/unset.md similarity index 100% rename from docs/ko/reference/compat/object/unset.md rename to docs/ko/compat/reference/object/unset.md diff --git a/docs/ko/reference/compat/object/update.md b/docs/ko/compat/reference/object/update.md similarity index 100% rename from docs/ko/reference/compat/object/update.md rename to docs/ko/compat/reference/object/update.md diff --git a/docs/ko/reference/compat/object/updateWith.md b/docs/ko/compat/reference/object/updateWith.md similarity index 100% rename from docs/ko/reference/compat/object/updateWith.md rename to docs/ko/compat/reference/object/updateWith.md diff --git a/docs/ko/reference/compat/object/values.md b/docs/ko/compat/reference/object/values.md similarity index 100% rename from docs/ko/reference/compat/object/values.md rename to docs/ko/compat/reference/object/values.md diff --git a/docs/ko/reference/compat/object/valuesIn.md b/docs/ko/compat/reference/object/valuesIn.md similarity index 100% rename from docs/ko/reference/compat/object/valuesIn.md rename to docs/ko/compat/reference/object/valuesIn.md diff --git a/docs/ko/reference/compat/predicate/conforms.md b/docs/ko/compat/reference/predicate/conforms.md similarity index 100% rename from docs/ko/reference/compat/predicate/conforms.md rename to docs/ko/compat/reference/predicate/conforms.md diff --git a/docs/ko/reference/compat/predicate/conformsTo.md b/docs/ko/compat/reference/predicate/conformsTo.md similarity index 100% rename from docs/ko/reference/compat/predicate/conformsTo.md rename to docs/ko/compat/reference/predicate/conformsTo.md diff --git a/docs/ko/reference/compat/predicate/isArguments.md b/docs/ko/compat/reference/predicate/isArguments.md similarity index 100% rename from docs/ko/reference/compat/predicate/isArguments.md rename to docs/ko/compat/reference/predicate/isArguments.md diff --git a/docs/ko/reference/compat/predicate/isArray.md b/docs/ko/compat/reference/predicate/isArray.md similarity index 100% rename from docs/ko/reference/compat/predicate/isArray.md rename to docs/ko/compat/reference/predicate/isArray.md diff --git a/docs/ko/compat/reference/predicate/isArrayBuffer.md b/docs/ko/compat/reference/predicate/isArrayBuffer.md new file mode 100644 index 000000000..11c2a4645 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isArrayBuffer.md @@ -0,0 +1,44 @@ +# isArrayBuffer (Lodash 호환성) + +::: warning es-toolkit의 [isArrayBuffer](../../../reference/predicate/isArrayBuffer.md)를 사용하세요 +이 `isArrayBuffer` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isArrayBuffer](../../../reference/predicate/isArrayBuffer.md)를 사용하세요. +::: + +값이 ArrayBuffer인지 확인해요. + +```typescript +const result = isArrayBuffer(value); +``` + +## 사용법 + +### `isArrayBuffer(value)` + +값이 ArrayBuffer인지 타입 안전하게 확인하고 싶을 때 `isArrayBuffer`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isArrayBuffer } from 'es-toolkit/compat'; + +// ArrayBuffer 확인 +const buffer = new ArrayBuffer(16); +isArrayBuffer(buffer); // true + +// 다른 타입들은 false +isArrayBuffer(new Array()); // false +isArrayBuffer(new Map()); // false +isArrayBuffer({}); // false +isArrayBuffer('hello'); // false +isArrayBuffer(123); // false +isArrayBuffer(null); // false +isArrayBuffer(undefined); // false +``` + +#### 파라미터 + +- `value` (`unknown`): ArrayBuffer인지 확인할 값이에요. + +#### 반환 값 + +(`value is ArrayBuffer`): 값이 ArrayBuffer이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isArrayLike.md b/docs/ko/compat/reference/predicate/isArrayLike.md similarity index 100% rename from docs/ko/reference/compat/predicate/isArrayLike.md rename to docs/ko/compat/reference/predicate/isArrayLike.md diff --git a/docs/ko/reference/compat/predicate/isArrayLikeObject.md b/docs/ko/compat/reference/predicate/isArrayLikeObject.md similarity index 100% rename from docs/ko/reference/compat/predicate/isArrayLikeObject.md rename to docs/ko/compat/reference/predicate/isArrayLikeObject.md diff --git a/docs/ko/reference/compat/predicate/isBoolean.md b/docs/ko/compat/reference/predicate/isBoolean.md similarity index 100% rename from docs/ko/reference/compat/predicate/isBoolean.md rename to docs/ko/compat/reference/predicate/isBoolean.md diff --git a/docs/ko/compat/reference/predicate/isBuffer.md b/docs/ko/compat/reference/predicate/isBuffer.md new file mode 100644 index 000000000..ba4068f67 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isBuffer.md @@ -0,0 +1,43 @@ +# isBuffer (Lodash 호환성) + +::: warning es-toolkit의 [isBuffer](../../../reference/predicate/isBuffer.md)를 사용하세요 +이 `isBuffer` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isBuffer](../../../reference/predicate/isBuffer.md)를 사용하세요. +::: + +값이 Buffer 인스턴스인지 확인해요. + +```typescript +const result = isBuffer(value); +``` + +## 사용법 + +### `isBuffer(value)` + +값이 Buffer 인스턴스인지 타입 안전하게 확인하고 싶을 때 `isBuffer`를 사용하세요. Node.js 환경에서 Buffer 객체를 다룰 때 유용해요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isBuffer } from 'es-toolkit/compat'; + +// Buffer 인스턴스 확인 +const buffer = Buffer.from('hello'); +isBuffer(buffer); // true + +// 다른 타입들은 false +isBuffer('hello'); // false +isBuffer([1, 2, 3]); // false +isBuffer(new Uint8Array([1, 2, 3])); // false +isBuffer({}); // false +isBuffer(null); // false +isBuffer(undefined); // false +``` + +#### 파라미터 + +- `value` (`unknown`): Buffer 인스턴스인지 확인할 값이에요. + +#### 반환 값 + +(`boolean`): 값이 Buffer 인스턴스면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/compat/reference/predicate/isDate.md b/docs/ko/compat/reference/predicate/isDate.md new file mode 100644 index 000000000..5093dc56f --- /dev/null +++ b/docs/ko/compat/reference/predicate/isDate.md @@ -0,0 +1,46 @@ +# isDate (Lodash 호환성) + +::: warning es-toolkit의 [isDate](../../../reference/predicate/isDate.md)를 사용하세요 +이 `isDate` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isDate](../../../reference/predicate/isDate.md)를 사용하세요. +::: + +값이 Date 객체인지 확인해요. + +```typescript +const result = isDate(value); +``` + +## 사용법 + +### `isDate(value)` + +값이 Date 객체인지 타입 안전하게 확인하고 싶을 때 `isDate`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isDate } from 'es-toolkit/compat'; + +// Date 객체 확인 +const date = new Date(); +isDate(date); // true + +// 유효하지 않은 Date도 Date 객체로 인식해요 +const invalidDate = new Date('invalid'); +isDate(invalidDate); // true + +// 다른 타입들은 false +isDate('2024-01-01'); // false +isDate(1640995200000); // false +isDate({}); // false +isDate(null); // false +isDate(undefined); // false +``` + +#### 파라미터 + +- `value` (`unknown`): Date 객체인지 확인할 값이에요. + +#### 반환 값 + +(`value is Date`): 값이 Date 객체이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isElement.md b/docs/ko/compat/reference/predicate/isElement.md similarity index 100% rename from docs/ko/reference/compat/predicate/isElement.md rename to docs/ko/compat/reference/predicate/isElement.md diff --git a/docs/ko/reference/compat/predicate/isEmpty.md b/docs/ko/compat/reference/predicate/isEmpty.md similarity index 100% rename from docs/ko/reference/compat/predicate/isEmpty.md rename to docs/ko/compat/reference/predicate/isEmpty.md diff --git a/docs/ko/compat/reference/predicate/isEqual.md b/docs/ko/compat/reference/predicate/isEqual.md new file mode 100644 index 000000000..ac07bae85 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isEqual.md @@ -0,0 +1,82 @@ +# isEqual (Lodash 호환성) + +::: warning `es-toolkit`의 [isEqual](../../../reference/predicate/isEqual.md)를 사용하세요 +이 `isEqual` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isEqual](../../../reference/predicate/isEqual.md)를 사용하세요. +::: + +두 값이 같은지 깊이 비교해서 확인해요. + +```typescript +const result = isEqual(value1, value2); +``` + +## 사용법 + +### `isEqual(a, b)` + +두 값이 같은지 깊이 비교해서 확인하고 싶을 때 `isEqual`를 사용하세요. Date, RegExp, 객체, 배열 등 복잡한 타입도 내용까지 비교해요. + +```typescript +import { isEqual } from 'es-toolkit/compat'; + +// 기본 타입 비교 +isEqual(1, 1); // true +isEqual('hello', 'hello'); // true +isEqual(true, true); // true + +// 객체 깊이 비교 +isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true +isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true +isEqual({ a: 1 }, { a: 1, b: undefined }); // false + +// 배열 깊이 비교 +isEqual([1, 2, 3], [1, 2, 3]); // true +isEqual([1, [2, 3]], [1, [2, 3]]); // true + +// Date 객체 비교 +isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true +isEqual(new Date('2020-01-01'), new Date('2020-01-02')); // false + +// RegExp 객체 비교 +isEqual(/abc/g, /abc/g); // true +isEqual(/abc/g, /abc/i); // false +``` + +중첩된 객체나 배열도 재귀적으로 비교해요. + +```typescript +import { isEqual } from 'es-toolkit/compat'; + +const obj1 = { + user: { + name: 'John', + details: { + age: 30, + hobbies: ['reading', 'gaming'], + }, + }, +}; + +const obj2 = { + user: { + name: 'John', + details: { + age: 30, + hobbies: ['reading', 'gaming'], + }, + }, +}; + +isEqual(obj1, obj2); // true +``` + +#### 파라미터 + +- `a` (`unknown`): 비교할 첫 번째 값이에요. +- `b` (`unknown`): 비교할 두 번째 값이에요. + +#### 반환 값 + +(`boolean`): 두 값이 같으면 `true`, 다르면 `false`를 반환해요. diff --git a/docs/ko/compat/reference/predicate/isEqualWith.md b/docs/ko/compat/reference/predicate/isEqualWith.md new file mode 100644 index 000000000..10ec8c930 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isEqualWith.md @@ -0,0 +1,92 @@ +# isEqualWith (Lodash 호환성) + +::: warning es-toolkit의 [isEqualWith](../../../reference/predicate/isEqualWith.md)를 사용하세요 +이 `isEqualWith` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isEqualWith](../../../reference/predicate/isEqualWith.md)를 사용하세요. +::: + +사용자 정의 비교 함수를 사용해서 두 값이 같은지 확인해요. + +```typescript +const result = isEqualWith(a, b, customizer); +``` + +## 사용법 + +### `isEqualWith(a, b, areValuesEqual?)` + +사용자 정의 비교 함수를 사용해서 두 값을 깊게 비교해요. 사용자 정의 함수가 불린 값을 반환하면 그 결과를 사용하고, `undefined`를 반환하면 기본 동등성 비교를 사용해요. + +사용자 정의 비교 함수는 객체, 배열, Map, Set 등의 복잡한 구조 내부의 값들을 비교할 때도 사용되어서 깊은 비교를 보장해요. + +```typescript +import { isEqualWith } from 'es-toolkit/compat'; + +// 대소문자 무시하는 문자열 비교 +const customizer = (a: any, b: any) => { + if (typeof a === 'string' && typeof b === 'string') { + return a.toLowerCase() === b.toLowerCase(); + } +}; + +isEqualWith('Hello', 'hello', customizer); // true +isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true + +// 숫자의 절댓값으로 비교 +const absCustomizer = (a: any, b: any) => { + if (typeof a === 'number' && typeof b === 'number') { + return Math.abs(a) === Math.abs(b); + } +}; + +isEqualWith([-1, 2], [1, -2], absCustomizer); // true + +// 복잡한 객체 비교 +const obj1 = { + name: 'JOHN', + details: { age: 30, city: 'NYC' }, +}; +const obj2 = { + name: 'john', + details: { age: 30, city: 'nyc' }, +}; + +isEqualWith(obj1, obj2, customizer); // true +``` + +Map과 Set에 대해서는 특별한 처리를 해요. + +```typescript +import { isEqualWith } from 'es-toolkit/compat'; + +const customizer = (a: any, b: any) => { + if (typeof a === 'string' && typeof b === 'string') { + return a.toLowerCase() === b.toLowerCase(); + } +}; + +const map1 = new Map([['KEY', 'value']]); +const map2 = new Map([['key', 'value']]); +isEqualWith(map1, map2, customizer); // true + +const set1 = new Set(['HELLO']); +const set2 = new Set(['hello']); +isEqualWith(set1, set2, customizer); // true +``` + +#### 파라미터 + +- `a` (`any`): 비교할 첫 번째 값이에요. +- `b` (`any`): 비교할 두 번째 값이에요. +- `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): 사용자 정의 비교 함수예요. + - `x`: 첫 번째 객체 `a`에서 온 값 + - `y`: 두 번째 객체 `b`에서 온 값 + - `property`: `x`와 `y`를 가져올 때 사용한 속성 키 + - `xParent`: 첫 번째 값 `x`의 부모 객체 + - `yParent`: 두 번째 값 `y`의 부모 객체 + - `stack`: 순환 참조를 처리하는 내부 스택 (Map) + +#### 반환 값 + +(`boolean`): 사용자 정의 함수에 따라 두 값이 같으면 `true`, 다르면 `false`를 반환해요. diff --git a/docs/ko/compat/reference/predicate/isError.md b/docs/ko/compat/reference/predicate/isError.md new file mode 100644 index 000000000..51f4aa8c2 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isError.md @@ -0,0 +1,47 @@ +# isError (Lodash 호환성) + +::: warning es-toolkit의 [isError](../../../reference/predicate/isError.md)를 사용하세요 +이 `isError` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isError](../../../reference/predicate/isError.md)를 사용하세요. +::: + +값이 Error 객체인지 확인해요. + +```typescript +const result = isError(value); +``` + +## 사용법 + +### `isError(value)` + +값이 Error 객체인지 타입 안전하게 확인하고 싶을 때 `isError`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isError } from 'es-toolkit/compat'; + +// Error 객체 확인 +isError(new Error()); // true +isError(new TypeError('Type error')); // true +isError(new ReferenceError('Reference error')); // true + +// Error를 상속한 사용자 정의 에러 +class CustomError extends Error {} +isError(new CustomError()); // true + +// 다른 타입들은 false +isError('Error'); // false +isError({ name: 'Error', message: 'Something went wrong' }); // false +isError({}); // false +isError(null); // false +isError(undefined); // false +``` + +#### 파라미터 + +- `value` (`unknown`): Error 객체인지 확인할 값이에요. + +#### 반환 값 + +(`value is Error`): 값이 Error 객체이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isFinite.md b/docs/ko/compat/reference/predicate/isFinite.md similarity index 100% rename from docs/ko/reference/compat/predicate/isFinite.md rename to docs/ko/compat/reference/predicate/isFinite.md diff --git a/docs/ko/compat/reference/predicate/isFunction.md b/docs/ko/compat/reference/predicate/isFunction.md new file mode 100644 index 000000000..63d3325fc --- /dev/null +++ b/docs/ko/compat/reference/predicate/isFunction.md @@ -0,0 +1,52 @@ +# isFunction (Lodash 호환성) + +::: warning es-toolkit의 [isFunction](../../../reference/predicate/isFunction.md)를 사용하세요 +이 `isFunction` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isFunction](../../../reference/predicate/isFunction.md)를 사용하세요. +::: + +값이 함수인지 확인해요. + +```typescript +const result = isFunction(value); +``` + +## 사용법 + +### `isFunction(value)` + +값이 함수인지 타입 안전하게 확인하고 싶을 때 `isFunction`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isFunction } from 'es-toolkit/compat'; + +// 일반 함수 +isFunction(function () {}); // true +isFunction(() => {}); // true + +// 내장 함수와 생성자 +isFunction(Array.prototype.slice); // true +isFunction(Proxy); // true +isFunction(Int8Array); // true + +// 비동기 함수와 제너레이터 함수 +isFunction(async function () {}); // true +isFunction(function* () {}); // true + +// 다른 타입들은 false +isFunction('function'); // false +isFunction({}); // false +isFunction([]); // false +isFunction(null); // false +isFunction(undefined); // false +isFunction(123); // false +``` + +#### 파라미터 + +- `value` (`unknown`): 함수인지 확인할 값이에요. + +#### 반환 값 + +(`value is (...args: any[]) => any`): 값이 함수이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isInteger.md b/docs/ko/compat/reference/predicate/isInteger.md similarity index 100% rename from docs/ko/reference/compat/predicate/isInteger.md rename to docs/ko/compat/reference/predicate/isInteger.md diff --git a/docs/ko/compat/reference/predicate/isLength.md b/docs/ko/compat/reference/predicate/isLength.md new file mode 100644 index 000000000..b9a28b378 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isLength.md @@ -0,0 +1,63 @@ +# isLength (Lodash 호환성) + +::: warning es-toolkit의 [isLength](../../../reference/predicate/isLength.md)를 사용하세요 +이 `isLength` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isLength](../../../reference/predicate/isLength.md)를 사용하세요. +::: + +값이 유효한 길이인지 확인해요. + +```typescript +const result = isLength(value); +``` + +## 사용법 + +### `isLength(value)` + +값이 유효한 길이인지 확인하고 싶을 때 `isLength`를 사용하세요. 유효한 길이는 숫자 타입이고, 음이 아닌 정수이며, JavaScript의 최대 안전 정수(`Number.MAX_SAFE_INTEGER`) 이하여야 해요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isLength } from 'es-toolkit/compat'; + +// 유효한 길이들 +isLength(0); // true +isLength(42); // true +isLength(100); // true +isLength(Number.MAX_SAFE_INTEGER); // true + +// 유효하지 않은 길이들 +isLength(-1); // false (음수) +isLength(1.5); // false (정수가 아님) +isLength(Number.MAX_SAFE_INTEGER + 1); // false (안전 범위 초과) +isLength('3'); // false (문자열) +isLength(null); // false +isLength(undefined); // false +isLength({}); // false +isLength([]); // false +``` + +배열이나 문자열의 length 속성이 유효한지 확인할 때 유용해요. + +```typescript +import { isLength } from 'es-toolkit/compat'; + +function validateArrayLength(arr: any[]) { + if (isLength(arr.length)) { + console.log(`배열의 길이 ${arr.length}는 유효해요`); + return true; + } + return false; +} + +validateArrayLength([1, 2, 3]); // "배열의 길이 3는 유효해요" +``` + +#### 파라미터 + +- `value` (`any`): 유효한 길이인지 확인할 값이에요. + +#### 반환 값 + +(`boolean`): 값이 유효한 길이이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/compat/reference/predicate/isMap.md b/docs/ko/compat/reference/predicate/isMap.md new file mode 100644 index 000000000..d1f649320 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isMap.md @@ -0,0 +1,63 @@ +# isMap (Lodash 호환성) + +::: warning es-toolkit의 [isMap](../../../reference/predicate/isMap.md)를 사용하세요 + +이 `isMap` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isMap](../../../reference/predicate/isMap.md)를 사용하세요. + +::: + +값이 Map인지 확인해요. + +```typescript +const result = isMap(value); +``` + +## 사용법 + +### `isMap(value)` + +값이 Map인지 타입 안전하게 확인하고 싶을 때 `isMap`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isMap } from 'es-toolkit/compat'; + +// Map 확인 +const map = new Map(); +isMap(map); // true + +// 다른 타입들은 false +isMap(new Set()); // false +isMap(new WeakMap()); // false +isMap({}); // false +isMap([]); // false +isMap('map'); // false +isMap(123); // false +isMap(null); // false +isMap(undefined); // false +``` + +Map과 비슷한 다른 컬렉션들과도 구분해요. + +```typescript +import { isMap } from 'es-toolkit/compat'; + +// Map vs Set vs WeakMap +isMap(new Map([['key', 'value']])); // true +isMap(new Set(['value'])); // false +isMap(new WeakMap()); // false + +// Map vs 일반 객체 +isMap({}); // false +isMap({ key: 'value' }); // false +isMap(Object.create(null)); // false +``` + +#### 파라미터 + +- `value` (`unknown`): Map인지 확인할 값이에요. + +#### 반환 값 + +(`value is Map`): 값이 Map이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isMatch.md b/docs/ko/compat/reference/predicate/isMatch.md similarity index 100% rename from docs/ko/reference/compat/predicate/isMatch.md rename to docs/ko/compat/reference/predicate/isMatch.md diff --git a/docs/ko/reference/compat/predicate/isMatchWith.md b/docs/ko/compat/reference/predicate/isMatchWith.md similarity index 100% rename from docs/ko/reference/compat/predicate/isMatchWith.md rename to docs/ko/compat/reference/predicate/isMatchWith.md diff --git a/docs/ko/reference/compat/predicate/isNaN.md b/docs/ko/compat/reference/predicate/isNaN.md similarity index 100% rename from docs/ko/reference/compat/predicate/isNaN.md rename to docs/ko/compat/reference/predicate/isNaN.md diff --git a/docs/ko/reference/compat/predicate/isNative.md b/docs/ko/compat/reference/predicate/isNative.md similarity index 100% rename from docs/ko/reference/compat/predicate/isNative.md rename to docs/ko/compat/reference/predicate/isNative.md diff --git a/docs/ko/compat/reference/predicate/isNil.md b/docs/ko/compat/reference/predicate/isNil.md new file mode 100644 index 000000000..4ec43fe27 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isNil.md @@ -0,0 +1,62 @@ +# isNil (Lodash 호환성) + +::: warning es-toolkit의 [isNil](../../../reference/predicate/isNil.md)를 사용하세요 + +이 `isNil` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isNil](../../../reference/predicate/isNil.md)를 사용하세요. + +::: + +값이 `null` 또는 `undefined`인지 확인해요. + +```typescript +const result = isNil(value); +``` + +## 사용법 + +### `isNil(x)` + +값이 `null` 또는 `undefined`인지 타입 안전하게 확인하고 싶을 때 `isNil`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isNil } from 'es-toolkit/compat'; + +// null과 undefined는 true +isNil(null); // true +isNil(undefined); // true + +// 다른 모든 값들은 false +isNil(0); // false +isNil(''); // false +isNil(false); // false +isNil([]); // false +isNil({}); // false +isNil('hello'); // false +isNil(42); // false +``` + +참으로 평가되지만 `null`이나 `undefined`가 아닌 값들과 구분해요. + +```typescript +import { isNil } from 'es-toolkit/compat'; + +// 거짓으로 평가되지만 null/undefined가 아닌 값들 +isNil(0); // false +isNil(''); // false +isNil(false); // false +isNil(NaN); // false + +// null과 undefined만 true +isNil(null); // true +isNil(undefined); // true +``` + +#### 파라미터 + +- `x` (`any`): `null` 또는 `undefined`인지 확인할 값이에요. + +#### 반환 값 + +(`x is null | undefined`): 값이 `null` 또는 `undefined`이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/compat/reference/predicate/isNull.md b/docs/ko/compat/reference/predicate/isNull.md new file mode 100644 index 000000000..3e9d7b7e0 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isNull.md @@ -0,0 +1,68 @@ +# isNull (Lodash 호환성) + +::: warning es-toolkit의 [isNull](../../../reference/predicate/isNull.md)를 사용하세요 + +이 `isNull` 함수는 Lodash 호환성을 위한 함수이지만, 메인 라이브러리와 같은 구현이에요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isNull](../../../reference/predicate/isNull.md)를 사용하세요. + +::: + +값이 `null`인지 확인해요. + +```typescript +const result = isNull(value); +``` + +## 사용법 + +### `isNull(value)` + +값이 정확히 `null`인지 타입 안전하게 확인하고 싶을 때 `isNull`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isNull } from 'es-toolkit/compat'; + +// null만 true +isNull(null); // true + +// undefined도 false +isNull(undefined); // false + +// 다른 모든 값들도 false +isNull(0); // false +isNull(''); // false +isNull(false); // false +isNull([]); // false +isNull({}); // false +isNull('null'); // false +isNull(NaN); // false +``` + +`null`과 `undefined`를 구분해서 확인할 수 있어요. + +```typescript +import { isNull } from 'es-toolkit/compat'; + +function handleValue(value: string | null | undefined) { + if (isNull(value)) { + console.log('값이 명시적으로 null이에요'); + } else if (value === undefined) { + console.log('값이 undefined에요'); + } else { + console.log(`값이 있어요: ${value}`); + } +} + +handleValue(null); // "값이 명시적으로 null이에요" +handleValue(undefined); // "값이 undefined에요" +handleValue('hello'); // "값이 있어요: hello" +``` + +#### 파라미터 + +- `value` (`any`): `null`인지 확인할 값이에요. + +#### 반환 값 + +(`value is null`): 값이 `null`이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isNumber.md b/docs/ko/compat/reference/predicate/isNumber.md similarity index 100% rename from docs/ko/reference/compat/predicate/isNumber.md rename to docs/ko/compat/reference/predicate/isNumber.md diff --git a/docs/ko/reference/compat/predicate/isObject.md b/docs/ko/compat/reference/predicate/isObject.md similarity index 100% rename from docs/ko/reference/compat/predicate/isObject.md rename to docs/ko/compat/reference/predicate/isObject.md diff --git a/docs/ko/reference/compat/predicate/isObjectLike.md b/docs/ko/compat/reference/predicate/isObjectLike.md similarity index 100% rename from docs/ko/reference/compat/predicate/isObjectLike.md rename to docs/ko/compat/reference/predicate/isObjectLike.md diff --git a/docs/ko/compat/reference/predicate/isPlainObject.md b/docs/ko/compat/reference/predicate/isPlainObject.md new file mode 100644 index 000000000..3f8292463 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isPlainObject.md @@ -0,0 +1,85 @@ +# isPlainObject (Lodash 호환성) + +::: warning es-toolkit의 [isPlainObject](../../../reference/predicate/isPlainObject.md)를 사용하세요 + +이 `isPlainObject` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isPlainObject](../../../reference/predicate/isPlainObject.md)를 사용하세요. + +::: + +값이 순수 객체인지 확인해요. + +```typescript +const result = isPlainObject(object); +``` + +## 사용법 + +### `isPlainObject(object)` + +값이 순수 객체인지 확인하고 싶을 때 `isPlainObject`를 사용하세요. 순수 객체는 `{}` 리터럴, `new Object()`, 또는 `Object.create(null)`로 생성된 객체예요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +// 순수 객체들 +isPlainObject({}); // true +isPlainObject(new Object()); // true +isPlainObject(Object.create(null)); // true +isPlainObject({ name: 'John', age: 30 }); // true + +// 순수 객체가 아닌 값들 +isPlainObject([]); // false (배열) +isPlainObject(new Date()); // false (Date 인스턴스) +isPlainObject(new Map()); // false (Map 인스턴스) +isPlainObject(new Set()); // false (Set 인스턴스) +isPlainObject(/regex/); // false (정규식) +isPlainObject(function () {}); // false (함수) +isPlainObject(null); // false +isPlainObject(undefined); // false +isPlainObject('object'); // false (문자열) +isPlainObject(42); // false (숫자) +``` + +클래스 인스턴스와 순수 객체를 구분해요. + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +class Person { + name: string; + constructor(name: string) { + this.name = name; + } +} + +const person = new Person('John'); +const plainObj = { name: 'John' }; + +isPlainObject(person); // false (클래스 인스턴스) +isPlainObject(plainObj); // true (순수 객체) +``` + +커스텀 `Symbol.toStringTag` 속성도 올바르게 처리해요. + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +// 쓰기 가능한 Symbol.toStringTag +const obj1 = {}; +obj1[Symbol.toStringTag] = 'CustomObject'; +isPlainObject(obj1); // true + +// 읽기 전용 Symbol.toStringTag (내장 객체들) +const date = new Date(); +isPlainObject(date); // false +``` + +#### 파라미터 + +- `object` (`any`): 순수 객체인지 확인할 값이에요. + +#### 반환 값 + +(`boolean`): 값이 순수 객체이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/compat/reference/predicate/isRegExp.md b/docs/ko/compat/reference/predicate/isRegExp.md new file mode 100644 index 000000000..98ed1cab8 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isRegExp.md @@ -0,0 +1,82 @@ +# isRegExp (Lodash 호환성) + +::: warning es-toolkit의 [isRegExp](../../../reference/predicate/isRegExp.md)를 사용하세요 + +이 `isRegExp` 함수는 Lodash 호환성을 위한 함수이지만, 단순한 타입 확인이에요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isRegExp](../../../reference/predicate/isRegExp.md)를 사용하세요. + +::: + +값이 정규식인지 확인해요. + +```typescript +const result = isRegExp(value); +``` + +## 사용법 + +### `isRegExp(value)` + +값이 정규식인지 타입 안전하게 확인하고 싶을 때 `isRegExp`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// 정규식들 +isRegExp(/abc/); // true +isRegExp(new RegExp('abc')); // true +isRegExp(/[a-z]+/g); // true +isRegExp(/pattern/gi); // true + +// 다른 타입들은 false +isRegExp('/abc/'); // false (문자열) +isRegExp('pattern'); // false (문자열) +isRegExp({}); // false (객체) +isRegExp([]); // false (배열) +isRegExp(null); // false +isRegExp(undefined); // false +isRegExp(123); // false (숫자) +``` + +정규식 문자열과 실제 정규식 객체를 구분해요. + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// 정규식 vs 정규식 문자열 +isRegExp(/test/); // true +isRegExp('/test/'); // false +isRegExp('\\d+'); // false +isRegExp('/\\d+/g'); // false + +// 다양한 정규식 플래그들 +isRegExp(/test/i); // true (대소문자 무시) +isRegExp(/test/g); // true (전역 검색) +isRegExp(/test/m); // true (다중행) +isRegExp(/test/gim); // true (모든 플래그 조합) +``` + +동적으로 생성된 정규식도 인식해요. + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// RegExp 생성자로 만든 정규식 +const dynamicRegex = new RegExp('\\d{3}-\\d{4}', 'g'); +isRegExp(dynamicRegex); // true + +// 문자열을 통해 생성한 정규식 +const pattern = 'hello'; +const flags = 'gi'; +const regex = new RegExp(pattern, flags); +isRegExp(regex); // true +``` + +#### 파라미터 + +- `value` (`any`): 정규식인지 확인할 값이에요. + +#### 반환 값 + +(`value is RegExp`): 값이 정규식이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isSafeInteger.md b/docs/ko/compat/reference/predicate/isSafeInteger.md similarity index 100% rename from docs/ko/reference/compat/predicate/isSafeInteger.md rename to docs/ko/compat/reference/predicate/isSafeInteger.md diff --git a/docs/ko/compat/reference/predicate/isSet.md b/docs/ko/compat/reference/predicate/isSet.md new file mode 100644 index 000000000..088e92a9b --- /dev/null +++ b/docs/ko/compat/reference/predicate/isSet.md @@ -0,0 +1,67 @@ +# isSet (Lodash 호환성) + +::: warning `es-toolkit`의 [isSet](../../../reference/predicate/isSet.md)를 사용하세요 + +이 `isSet` 함수는 Lodash 호환성을 위한 함수이지만, 메인 라이브러리와 같은 구현이에요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isSet](../../../reference/predicate/isSet.md)를 사용하세요. + +::: + +값이 Set인지 확인해요. + +```typescript +const result = isSet(value); +``` + +## 사용법 + +### `isSet(value)` + +값이 Set인지 타입 안전하게 확인하고 싶을 때 `isSet`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isSet } from 'es-toolkit/compat'; + +// Set 확인 +const set = new Set(); +isSet(set); // true + +// 다른 타입들은 false +isSet(new Map()); // false +isSet(new WeakSet()); // false +isSet([]); // false +isSet({}); // false +isSet('set'); // false +isSet(123); // false +isSet(null); // false +isSet(undefined); // false +``` + +Set과 비슷한 다른 컬렉션들과도 구분해요. + +```typescript +import { isSet } from 'es-toolkit/compat'; + +// Set vs Map vs WeakSet +isSet(new Set([1, 2, 3])); // true +isSet(new Map([['key', 'value']])); // false +isSet(new WeakSet()); // false + +// Set vs 배열 +isSet(new Set([1, 2, 3])); // true +isSet([1, 2, 3]); // false + +// Set vs 일반 객체 +isSet(new Set()); // true +isSet({}); // false +isSet(Object.create(null)); // false +``` + +#### 파라미터 + +- `value` (`unknown`): Set인지 확인할 값이에요. + +#### 반환 값 + +(`value is Set`): 값이 Set이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isString.md b/docs/ko/compat/reference/predicate/isString.md similarity index 100% rename from docs/ko/reference/compat/predicate/isString.md rename to docs/ko/compat/reference/predicate/isString.md diff --git a/docs/ko/reference/compat/predicate/isSymbol.md b/docs/ko/compat/reference/predicate/isSymbol.md similarity index 100% rename from docs/ko/reference/compat/predicate/isSymbol.md rename to docs/ko/compat/reference/predicate/isSymbol.md diff --git a/docs/ko/reference/compat/predicate/isTypedArray.md b/docs/ko/compat/reference/predicate/isTypedArray.md similarity index 100% rename from docs/ko/reference/compat/predicate/isTypedArray.md rename to docs/ko/compat/reference/predicate/isTypedArray.md diff --git a/docs/ko/compat/reference/predicate/isUndefined.md b/docs/ko/compat/reference/predicate/isUndefined.md new file mode 100644 index 000000000..fdfb8ad45 --- /dev/null +++ b/docs/ko/compat/reference/predicate/isUndefined.md @@ -0,0 +1,92 @@ +# isUndefined (Lodash 호환성) + +::: warning es-toolkit의 [ isUndefined](../../../reference/predicate/isUndefined.md)를 사용하세요 + +이 `isUndefined` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [isUndefined](../../../reference/predicate/isUndefined.md)를 사용하세요. + +::: + +값이 `undefined`인지 확인해요. + +```typescript +const result = isUndefined(value); +``` + +## 사용법 + +### `isUndefined(x)` + +값이 정확히 `undefined`인지 타입 안전하게 확인하고 싶을 때 `isUndefined`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +// undefined만 true +isUndefined(undefined); // true + +// null도 false +isUndefined(null); // false + +// 다른 모든 값들도 false +isUndefined(0); // false +isUndefined(''); // false +isUndefined(false); // false +isUndefined([]); // false +isUndefined({}); // false +isUndefined('undefined'); // false +isUndefined(NaN); // false +``` + +`undefined`와 `null`을 구분해서 확인할 수 있어요. + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +function handleValue(value: string | null | undefined) { + if (isUndefined(value)) { + console.log('값이 undefined에요'); + } else if (value === null) { + console.log('값이 명시적으로 null이에요'); + } else { + console.log(`값이 있어요: ${value}`); + } +} + +handleValue(undefined); // "값이 undefined에요" +handleValue(null); // "값이 명시적으로 null이에요" +handleValue('hello'); // "값이 있어요: hello" +``` + +선언되지 않은 변수나 초기화되지 않은 속성을 확인할 때 유용해요. + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +const obj: { name?: string; age?: number } = { name: 'John' }; + +if (isUndefined(obj.age)) { + console.log('나이가 설정되지 않았어요'); + obj.age = 25; // 기본값 설정 +} + +// 함수 매개변수의 기본값 처리 +function greet(name: string, title?: string) { + if (isUndefined(title)) { + title = '님'; + } + console.log(`안녕하세요, ${name}${title}!`); +} + +greet('김철수'); // "안녕하세요, 김철수님!" +greet('김철수', '선생'); // "안녕하세요, 김철수선생!" +``` + +#### 파라미터 + +- `x` (`any`): `undefined`인지 확인할 값이에요. + +#### 반환 값 + +(`x is undefined`): 값이 `undefined`이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isWeakMap.md b/docs/ko/compat/reference/predicate/isWeakMap.md similarity index 100% rename from docs/ko/reference/compat/predicate/isWeakMap.md rename to docs/ko/compat/reference/predicate/isWeakMap.md diff --git a/docs/ko/reference/compat/predicate/isWeakSet.md b/docs/ko/compat/reference/predicate/isWeakSet.md similarity index 100% rename from docs/ko/reference/compat/predicate/isWeakSet.md rename to docs/ko/compat/reference/predicate/isWeakSet.md diff --git a/docs/ko/reference/compat/predicate/matches.md b/docs/ko/compat/reference/predicate/matches.md similarity index 100% rename from docs/ko/reference/compat/predicate/matches.md rename to docs/ko/compat/reference/predicate/matches.md diff --git a/docs/ko/reference/compat/predicate/matchesProperty.md b/docs/ko/compat/reference/predicate/matchesProperty.md similarity index 100% rename from docs/ko/reference/compat/predicate/matchesProperty.md rename to docs/ko/compat/reference/predicate/matchesProperty.md diff --git a/docs/ko/compat/reference/string/camelCase.md b/docs/ko/compat/reference/string/camelCase.md new file mode 100644 index 000000000..a7e0afa90 --- /dev/null +++ b/docs/ko/compat/reference/string/camelCase.md @@ -0,0 +1,48 @@ +# camelCase (Lodash 호환성) + +::: warning `es-toolkit`의 `camelCase`를 사용하세요 + +이 `camelCase` 함수는 문자열이 아닌 입력값 처리와 축약 아포스트로피 제거 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [camelCase](../../../reference/string/camelCase.md)를 사용하세요. + +::: + +문자열을 카멜 케이스로 변환해요. + +```typescript +const result = camelCase(str); +``` + +## 사용법 + +### `camelCase(str)` + +문자열을 카멜 케이스로 변환해요. 카멜 케이스는 첫 번째 단어는 소문자로 시작하고, 이후 단어들의 첫 글자는 대문자로 하여 공백 없이 연결하는 명명 규칙이에요. + +```typescript +import { camelCase } from 'es-toolkit/compat'; + +camelCase('camelCase'); // 'camelCase' +camelCase('some whitespace'); // 'someWhitespace' +camelCase('hyphen-text'); // 'hyphenText' +camelCase('HTTPRequest'); // 'httpRequest' +``` + +문자열이 아닌 값도 문자열로 변환해서 처리해요. + +```typescript +import { camelCase } from 'es-toolkit/compat'; + +camelCase(123); // '123' +camelCase(null); // '' +camelCase(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string | object`, 선택): 카멜 케이스로 변환할 값이에요. + +#### 반환 값 + +(`string`): 카멜 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/capitalize.md b/docs/ko/compat/reference/string/capitalize.md new file mode 100644 index 000000000..0b68aac05 --- /dev/null +++ b/docs/ko/compat/reference/string/capitalize.md @@ -0,0 +1,48 @@ +# capitalize (Lodash 호환성) + +::: warning `es-toolkit`의 `capitalize`를 사용하세요 + +이 `capitalize` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [capitalize](../../../reference/string/capitalize.md)를 사용하세요. + +::: + +문자열의 첫 글자를 대문자로, 나머지 글자는 소문자로 변환해요. + +```typescript +const result = capitalize(str); +``` + +## 사용법 + +### `capitalize(str)` + +문자열의 첫 글자를 대문자로, 나머지 글자는 소문자로 변환해요. 단어의 첫 인상을 좋게 하거나 제목 형태로 만들 때 유용해요. + +```typescript +import { capitalize } from 'es-toolkit/compat'; + +capitalize('fred'); // 'Fred' +capitalize('FRED'); // 'Fred' +capitalize('fRED'); // 'Fred' +``` + +빈 문자열이나 문자열이 아닌 값도 처리할 수 있어요. + +```typescript +import { capitalize } from 'es-toolkit/compat'; + +capitalize(''); // '' +capitalize(123); // '123' +capitalize(null); // '' +capitalize(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 첫 글자를 대문자로 변환할 문자열이에요. + +#### 반환 값 + +(`string`): 첫 글자가 대문자이고 나머지가 소문자인 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/deburr.md b/docs/ko/compat/reference/string/deburr.md new file mode 100644 index 000000000..132cf2be6 --- /dev/null +++ b/docs/ko/compat/reference/string/deburr.md @@ -0,0 +1,47 @@ +# deburr (Lodash 호환성) + +::: warning `es-toolkit`의 `deburr`를 사용하세요 + +이 `deburr` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [deburr](../../../reference/string/deburr.md)를 사용하세요. + +::: + +문자열에서 특수 문자와 발음 구별 기호를 ASCII 문자로 변환해요. + +```typescript +const result = deburr(str); +``` + +## 사용법 + +### `deburr(str)` + +문자열에서 특수 문자와 발음 구별 기호를 ASCII 문자로 변환해요. 다국어 텍스트를 검색이나 정렬에 사용하기 쉽게 만들 때 유용해요. + +```typescript +import { deburr } from 'es-toolkit/compat'; + +deburr('Æthelred'); // 'Aethelred' +deburr('München'); // 'Munchen' +deburr('Crème brûlée'); // 'Creme brulee' +``` + +문자열이 아닌 값도 문자열로 변환해서 처리해요. + +```typescript +import { deburr } from 'es-toolkit/compat'; + +deburr(123); // '123' +deburr(null); // '' +deburr(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 특수 문자를 제거할 문자열이에요. + +#### 반환 값 + +(`string`): 특수 문자와 발음 구별 기호가 ASCII 문자로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/endsWith.md b/docs/ko/compat/reference/string/endsWith.md similarity index 100% rename from docs/ko/reference/compat/string/endsWith.md rename to docs/ko/compat/reference/string/endsWith.md diff --git a/docs/ko/compat/reference/string/escape.md b/docs/ko/compat/reference/string/escape.md new file mode 100644 index 000000000..c382a8956 --- /dev/null +++ b/docs/ko/compat/reference/string/escape.md @@ -0,0 +1,48 @@ +# escape (Lodash 호환성) + +::: warning `es-toolkit`의 `escape`를 사용하세요 + +이 `escape` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [escape](../../../reference/string/escape.md)를 사용하세요. + +::: + +문자열에서 HTML 특수 문자를 HTML 엔티티로 변환해요. + +```typescript +const result = escape(str); +``` + +## 사용법 + +### `escape(str)` + +문자열에서 `&`, `<`, `>`, `"`, `'` 문자를 해당하는 HTML 엔티티로 변환해요. HTML 문서에 텍스트를 안전하게 삽입할 때 XSS 공격을 방지하는 데 유용해요. + +```typescript +import { escape } from 'es-toolkit/compat'; + +escape('This is a
element.'); // 'This is a <div> element.' +escape('This is a "quote"'); // 'This is a "quote"' +escape("This is a 'quote'"); // 'This is a 'quote'' +escape('This is a & symbol'); // 'This is a & symbol' +``` + +문자열이 아닌 값도 문자열로 변환해서 처리해요. + +```typescript +import { escape } from 'es-toolkit/compat'; + +escape(123); // '123' +escape(null); // '' +escape(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): HTML 특수 문자를 이스케이프할 문자열이에요. + +#### 반환 값 + +(`string`): HTML 특수 문자가 엔티티로 변환된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/escapeRegExp.md b/docs/ko/compat/reference/string/escapeRegExp.md new file mode 100644 index 000000000..1266f4d07 --- /dev/null +++ b/docs/ko/compat/reference/string/escapeRegExp.md @@ -0,0 +1,49 @@ +# escapeRegExp (Lodash 호환성) + +::: warning `es-toolkit`의 `escapeRegExp`를 사용하세요 + +이 `escapeRegExp` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [escapeRegExp](../../../reference/string/escapeRegExp.md)를 사용하세요. + +::: + +문자열에서 정규 표현식 특수 문자를 이스케이프해요. + +```typescript +const result = escapeRegExp(str); +``` + +## 사용법 + +### `escapeRegExp(str)` + +문자열에서 정규 표현식 특수 문자 `^`, `$`, `\`, `.`, `*`, `+`, `?`, `(`, `)`, `[`, `]`, `{`, `}`, `|`를 이스케이프해요. 동적으로 정규 표현식을 생성할 때 문자열을 문자 그대로 처리하고 싶을 때 유용해요. + +```typescript +import { escapeRegExp } from 'es-toolkit/compat'; + +escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); +// '\\[es-toolkit\\]\\(https://es-toolkit\\.dev/\\)' + +escapeRegExp('$^{}.+*?()[]|\\'); +// '\\$\\^\\{\\}\\.\\+\\*\\?\\(\\)\\[\\]\\|\\\\' +``` + +문자열이 아닌 값도 문자열로 변환해서 처리해요. + +```typescript +import { escapeRegExp } from 'es-toolkit/compat'; + +escapeRegExp(123); // '123' +escapeRegExp(null); // '' +escapeRegExp(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 정규 표현식 특수 문자를 이스케이프할 문자열이에요. + +#### 반환 값 + +(`string`): 정규 표현식 특수 문자가 이스케이프된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/kebabCase.md b/docs/ko/compat/reference/string/kebabCase.md new file mode 100644 index 000000000..5e98b7908 --- /dev/null +++ b/docs/ko/compat/reference/string/kebabCase.md @@ -0,0 +1,48 @@ +# kebabCase (Lodash 호환성) + +::: warning `es-toolkit`의 `kebabCase`를 사용하세요 + +이 `kebabCase` 함수는 문자열이 아닌 입력값 처리와 축약 아포스트로피 제거 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [kebabCase](../../../reference/string/kebabCase.md)를 사용하세요. + +::: + +문자열을 케밥 케이스로 변환해요. + +```typescript +const result = kebabCase(str); +``` + +## 사용법 + +### `kebabCase(str)` + +문자열을 케밥 케이스로 변환해요. 케밥 케이스는 각 단어를 소문자로 쓰고 대시(-) 문자로 연결하는 명명 규칙이에요. URL이나 CSS 클래스 이름에서 주로 사용돼요. + +```typescript +import { kebabCase } from 'es-toolkit/compat'; + +kebabCase('camelCase'); // 'camel-case' +kebabCase('some whitespace'); // 'some-whitespace' +kebabCase('hyphen-text'); // 'hyphen-text' +kebabCase('HTTPRequest'); // 'http-request' +``` + +문자열이 아닌 값도 문자열로 변환해서 처리해요. + +```typescript +import { kebabCase } from 'es-toolkit/compat'; + +kebabCase(123); // '123' +kebabCase(null); // '' +kebabCase(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string | object`, 선택): 케밥 케이스로 변환할 값이에요. + +#### 반환 값 + +(`string`): 케밥 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/lowerCase.md b/docs/ko/compat/reference/string/lowerCase.md new file mode 100644 index 000000000..5f948eeb5 --- /dev/null +++ b/docs/ko/compat/reference/string/lowerCase.md @@ -0,0 +1,48 @@ +# lowerCase (Lodash 호환성) + +::: warning `es-toolkit`의 `lowerCase`를 사용하세요 + +이 `lowerCase` 함수는 문자열이 아닌 입력값 처리와 축약 아포스트로피 제거 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [lowerCase](../../../reference/string/lowerCase.md)를 사용하세요. + +::: + +문자열을 소문자로 된 단어들을 공백으로 분리한 형태로 변환해요. + +```typescript +const result = lowerCase(str); +``` + +## 사용법 + +### `lowerCase(str)` + +문자열을 소문자로 된 단어들을 공백으로 분리한 형태로 변환해요. 각 단어는 소문자로 변환되고 공백 문자로 연결돼요. 사람이 읽기 쉬운 텍스트 형태로 만들 때 유용해요. + +```typescript +import { lowerCase } from 'es-toolkit/compat'; + +lowerCase('camelCase'); // 'camel case' +lowerCase('some whitespace'); // 'some whitespace' +lowerCase('hyphen-text'); // 'hyphen text' +lowerCase('HTTPRequest'); // 'http request' +``` + +문자열이 아닌 값도 문자열로 변환해서 처리해요. + +```typescript +import { lowerCase } from 'es-toolkit/compat'; + +lowerCase(123); // '123' +lowerCase(null); // '' +lowerCase(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string | object`, 선택): 소문자 형태로 변환할 값이에요. + +#### 반환 값 + +(`string`): 소문자로 된 단어들이 공백으로 분리된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/lowerFirst.md b/docs/ko/compat/reference/string/lowerFirst.md new file mode 100644 index 000000000..ccc6d90c7 --- /dev/null +++ b/docs/ko/compat/reference/string/lowerFirst.md @@ -0,0 +1,48 @@ +# lowerFirst (Lodash 호환성) + +::: warning `es-toolkit`의 `lowerFirst`를 사용하세요 + +이 `lowerFirst` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [lowerFirst](../../../reference/string/lowerFirst.md)를 사용하세요. + +::: + +문자열의 첫 글자를 소문자로 변환해요. + +```typescript +const result = lowerFirst(str); +``` + +## 사용법 + +### `lowerFirst(str)` + +문자열의 첫 글자를 소문자로 변환해요. 나머지 글자들은 그대로 유지돼요. 변수명을 camelCase로 만들거나 첫 글자만 소문자로 바꾸고 싶을 때 유용해요. + +```typescript +import { lowerFirst } from 'es-toolkit/compat'; + +lowerFirst('fred'); // 'fred' +lowerFirst('Fred'); // 'fred' +lowerFirst('FRED'); // 'fRED' +lowerFirst(''); // '' +``` + +문자열이 아닌 값도 문자열로 변환해서 처리해요. + +```typescript +import { lowerFirst } from 'es-toolkit/compat'; + +lowerFirst(123); // '123' +lowerFirst(null); // '' +lowerFirst(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 첫 글자를 소문자로 변환할 문자열이에요. + +#### 반환 값 + +(`string`): 첫 글자가 소문자로 변환된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/pad.md b/docs/ko/compat/reference/string/pad.md new file mode 100644 index 000000000..addc2eaad --- /dev/null +++ b/docs/ko/compat/reference/string/pad.md @@ -0,0 +1,60 @@ +# pad (Lodash 호환성) + +::: warning `es-toolkit`의 `pad`를 사용하세요 + +이 `pad` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [pad](../../../reference/string/pad.md)를 사용하세요. + +::: + +문자열의 앞뒤로 패딩 문자를 추가해서 지정된 길이만큼 맞춰요. + +```typescript +const padded = pad(str, length, chars); +``` + +## 사용법 + +### `pad(str, length, chars)` + +문자열이 원하는 길이보다 짧을 때 앞뒤로 패딩 문자를 추가해서 길이를 맞추고 싶을 때 `pad`를 사용하세요. 패딩 문자가 균등하게 나누어 떨어지지 않으면, 추가 문자는 오른쪽에 배치돼요. + +```typescript +import { pad } from 'es-toolkit/compat'; + +// 기본 공백으로 패딩 +pad('abc', 8); +// Returns: ' abc ' + +// 지정된 문자로 패딩 +pad('abc', 8, '_-'); +// Returns: '_-abc_-_' + +// 이미 충분한 길이이면 그대로 반환 +pad('abc', 3); +// Returns: 'abc' + +// 길이가 더 짧으면 그대로 반환 +pad('abc', 2); +// Returns: 'abc' +``` + +`null`이나 `undefined`는 빈 문자열로 처리해요. + +```typescript +import { pad } from 'es-toolkit/compat'; + +pad(null, 5); // ' ' +pad(undefined, 3, '*'); // '***' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 패딩할 문자열이에요. +- `length` (`number`, 선택): 목표 길이예요. 기본값은 `0`이에요. +- `chars` (`string`, 선택): 패딩에 사용할 문자들이에요. 기본값은 공백 `' '`이에요. + +#### 반환 값 + +(`string`): 지정된 길이만큼 패딩된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/padEnd.md b/docs/ko/compat/reference/string/padEnd.md similarity index 100% rename from docs/ko/reference/compat/string/padEnd.md rename to docs/ko/compat/reference/string/padEnd.md diff --git a/docs/ko/reference/compat/string/padStart.md b/docs/ko/compat/reference/string/padStart.md similarity index 100% rename from docs/ko/reference/compat/string/padStart.md rename to docs/ko/compat/reference/string/padStart.md diff --git a/docs/ko/reference/compat/string/repeat.md b/docs/ko/compat/reference/string/repeat.md similarity index 100% rename from docs/ko/reference/compat/string/repeat.md rename to docs/ko/compat/reference/string/repeat.md diff --git a/docs/ko/reference/compat/string/replace.md b/docs/ko/compat/reference/string/replace.md similarity index 100% rename from docs/ko/reference/compat/string/replace.md rename to docs/ko/compat/reference/string/replace.md diff --git a/docs/ko/compat/reference/string/snakeCase.md b/docs/ko/compat/reference/string/snakeCase.md new file mode 100644 index 000000000..89008b8b1 --- /dev/null +++ b/docs/ko/compat/reference/string/snakeCase.md @@ -0,0 +1,58 @@ +# snakeCase (Lodash 호환성) + +::: warning `es-toolkit`의 `snakeCase`를 사용하세요 + +이 `snakeCase` 함수는 `null`이나 `undefined` 처리를 위한 정규화 로직으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [snakeCase](../../../reference/string/snakeCase.md)를 사용하세요. + +::: + +문자열을 스네이크 케이스로 변환해요. + +```typescript +const snakeCased = snakeCase(str); +``` + +## 사용법 + +### `snakeCase(str)` + +문자열을 스네이크 케이스(snake*case)로 변환하고 싶을 때 `snakeCase`를 사용하세요. 스네이크 케이스는 각 단어를 소문자로 쓰고 밑줄(*)로 연결하는 명명 규칙이에요. + +```typescript +import { snakeCase } from 'es-toolkit/compat'; + +// 카멜 케이스 변환 +snakeCase('camelCase'); +// Returns: 'camel_case' + +// 공백으로 구분된 문자열 변환 +snakeCase('some whitespace'); +// Returns: 'some_whitespace' + +// 하이픈으로 구분된 문자열 변환 +snakeCase('hyphen-text'); +// Returns: 'hyphen_text' + +// 대문자가 연속으로 나타나는 경우 +snakeCase('HTTPRequest'); +// Returns: 'http_request' +``` + +`null`이나 `undefined`는 빈 문자열로 처리해요. + +```typescript +import { snakeCase } from 'es-toolkit/compat'; + +snakeCase(null); // '' +snakeCase(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 스네이크 케이스로 변환할 문자열이에요. + +#### 반환 값 + +(`string`): 스네이크 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/split.md b/docs/ko/compat/reference/string/split.md similarity index 100% rename from docs/ko/reference/compat/string/split.md rename to docs/ko/compat/reference/string/split.md diff --git a/docs/ko/compat/reference/string/startCase.md b/docs/ko/compat/reference/string/startCase.md new file mode 100644 index 000000000..d6231bac1 --- /dev/null +++ b/docs/ko/compat/reference/string/startCase.md @@ -0,0 +1,58 @@ +# startCase (Lodash 호환성) + +::: warning `es-toolkit`의 `startCase`를 사용하세요 + +이 `startCase` 함수는 `null`이나 `undefined` 처리를 위한 정규화 로직으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [startCase](../../../reference/string/startCase.md)를 사용하세요. + +::: + +문자열을 스타트 케이스로 변환해요. + +```typescript +const startCased = startCase(str); +``` + +## 사용법 + +### `startCase(str)` + +문자열을 스타트 케이스(Start Case)로 변환하고 싶을 때 `startCase`를 사용하세요. 스타트 케이스는 각 단어의 첫 글자를 대문자로 쓰고 공백으로 구분하는 명명 규칙이에요. + +```typescript +import { startCase } from 'es-toolkit/compat'; + +// 일반 문자열 변환 +startCase('hello world'); +// Returns: 'Hello World' + +// 이미 대문자인 단어는 그대로 유지 +startCase('HELLO WORLD'); +// Returns: 'HELLO WORLD' + +// 하이픈으로 구분된 문자열 변환 +startCase('hello-world'); +// Returns: 'Hello World' + +// 밑줄로 구분된 문자열 변환 +startCase('hello_world'); +// Returns: 'Hello World' +``` + +`null`이나 `undefined`는 빈 문자열로 처리해요. + +```typescript +import { startCase } from 'es-toolkit/compat'; + +startCase(null); // '' +startCase(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 스타트 케이스로 변환할 문자열이에요. + +#### 반환 값 + +(`string`): 스타트 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/startsWith.md b/docs/ko/compat/reference/string/startsWith.md similarity index 100% rename from docs/ko/reference/compat/string/startsWith.md rename to docs/ko/compat/reference/string/startsWith.md diff --git a/docs/ko/reference/compat/string/template.md b/docs/ko/compat/reference/string/template.md similarity index 100% rename from docs/ko/reference/compat/string/template.md rename to docs/ko/compat/reference/string/template.md diff --git a/docs/ko/reference/compat/string/toLower.md b/docs/ko/compat/reference/string/toLower.md similarity index 100% rename from docs/ko/reference/compat/string/toLower.md rename to docs/ko/compat/reference/string/toLower.md diff --git a/docs/ko/reference/compat/string/toUpper.md b/docs/ko/compat/reference/string/toUpper.md similarity index 100% rename from docs/ko/reference/compat/string/toUpper.md rename to docs/ko/compat/reference/string/toUpper.md diff --git a/docs/ko/compat/reference/string/trim.md b/docs/ko/compat/reference/string/trim.md new file mode 100644 index 000000000..513632a73 --- /dev/null +++ b/docs/ko/compat/reference/string/trim.md @@ -0,0 +1,55 @@ +# trim (Lodash 호환성) + +::: warning `es-toolkit`의 `trim`을 사용하세요 + +이 `trim` 함수는 `null`이나 `undefined` 처리, 배열 형태의 `chars` 처리 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [trim](../../../reference/string/trim.md)을 사용하세요. + +::: + +문자열의 앞뒤 공백이나 지정된 문자들을 제거해요. + +```typescript +const trimmed = trim(str, chars); +``` + +## 사용법 + +### `trim(str, chars)` + +문자열의 앞뒤에서 공백이나 특정 문자들을 제거하고 싶을 때 `trim`을 사용하세요. `chars`를 지정하지 않으면 앞뒤 공백만 제거해요. + +```typescript +import { trim } from 'es-toolkit/compat'; + +// 앞뒤 공백 제거 +trim(' hello '); +// Returns: 'hello' + +// 지정된 문자 제거 +trim('--hello--', '-'); +// Returns: 'hello' + +// 배열로 여러 문자 제거 +trim('##hello##', ['#', 'o']); +// Returns: 'hell' +``` + +`null`이나 `undefined`는 빈 문자열로 처리해요. + +```typescript +import { trim } from 'es-toolkit/compat'; + +trim(null); // '' +trim(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 정리할 문자열이에요. +- `chars` (`string`, 선택): 제거할 문자들이에요. 지정하지 않으면 공백을 제거해요. + +#### 반환 값 + +(`string`): 앞뒤의 지정된 문자들이 제거된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/trimEnd.md b/docs/ko/compat/reference/string/trimEnd.md new file mode 100644 index 000000000..203540bef --- /dev/null +++ b/docs/ko/compat/reference/string/trimEnd.md @@ -0,0 +1,55 @@ +# trimEnd (Lodash 호환성) + +::: warning `es-toolkit`의 `trimEnd`를 사용하세요 + +이 `trimEnd` 함수는 `null`이나 `undefined` 처리, 파라미터 순서 변경 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [trimEnd](../../../reference/string/trimEnd.md)를 사용하세요. + +::: + +문자열의 뒤쪽 공백이나 지정된 문자들을 제거해요. + +```typescript +const trimmed = trimEnd(str, chars); +``` + +## 사용법 + +### `trimEnd(str, chars)` + +문자열의 뒤쪽에서 공백이나 특정 문자들을 제거하고 싶을 때 `trimEnd`를 사용하세요. `chars`를 지정하지 않으면 뒤쪽 공백만 제거해요. + +```typescript +import { trimEnd } from 'es-toolkit/compat'; + +// 뒤쪽 공백 제거 +trimEnd(' abc '); +// Returns: ' abc' + +// 지정된 문자 제거 +trimEnd('-_-abc-_-', '_-'); +// Returns: '-_-abc' + +// 문자열의 뒤쪽에만 적용 +trimEnd('abc', 'a'); +// Returns: 'abc' +``` + +`null`이나 `undefined`는 빈 문자열로 처리해요. + +```typescript +import { trimEnd } from 'es-toolkit/compat'; + +trimEnd(null); // '' +trimEnd(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 뒤쪽을 정리할 문자열이에요. +- `chars` (`string`, 선택): 제거할 문자들이에요. 지정하지 않으면 공백을 제거해요. + +#### 반환 값 + +(`string`): 뒤쪽의 지정된 문자들이 제거된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/trimStart.md b/docs/ko/compat/reference/string/trimStart.md new file mode 100644 index 000000000..575ecffd9 --- /dev/null +++ b/docs/ko/compat/reference/string/trimStart.md @@ -0,0 +1,55 @@ +# trimStart (Lodash 호환성) + +::: warning `es-toolkit`의 `trimStart`를 사용하세요 + +이 `trimStart` 함수는 `null`이나 `undefined` 처리, 파라미터 순서 변경 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [trimStart](../../../reference/string/trimStart.md)를 사용하세요. + +::: + +문자열의 앞쪽 공백이나 지정된 문자들을 제거해요. + +```typescript +const trimmed = trimStart(str, chars); +``` + +## 사용법 + +### `trimStart(str, chars)` + +문자열의 앞쪽에서 공백이나 특정 문자들을 제거하고 싶을 때 `trimStart`를 사용하세요. `chars`를 지정하지 않으면 앞쪽 공백만 제거해요. + +```typescript +import { trimStart } from 'es-toolkit/compat'; + +// 앞쪽 공백 제거 +trimStart(' abc '); +// Returns: 'abc ' + +// 지정된 문자 제거 +trimStart('-_-abc-_-', '_-'); +// Returns: 'abc-_-' + +// 문자열의 앞쪽에만 적용 +trimStart('abc', 'c'); +// Returns: 'abc' +``` + +`null`이나 `undefined`는 빈 문자열로 처리해요. + +```typescript +import { trimStart } from 'es-toolkit/compat'; + +trimStart(null); // '' +trimStart(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 앞쪽을 정리할 문자열이에요. +- `chars` (`string`, 선택): 제거할 문자들이에요. 지정하지 않으면 공백을 제거해요. + +#### 반환 값 + +(`string`): 앞쪽의 지정된 문자들이 제거된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/truncate.md b/docs/ko/compat/reference/string/truncate.md similarity index 100% rename from docs/ko/reference/compat/string/truncate.md rename to docs/ko/compat/reference/string/truncate.md diff --git a/docs/ko/compat/reference/string/unescape.md b/docs/ko/compat/reference/string/unescape.md new file mode 100644 index 000000000..dcd8444e3 --- /dev/null +++ b/docs/ko/compat/reference/string/unescape.md @@ -0,0 +1,58 @@ +# unescape (Lodash 호환성) + +::: warning `es-toolkit`의 `unescape`를 사용하세요 + +이 `unescape` 함수는 `null`이나 `undefined` 처리를 위한 변환 로직으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [unescape](../../../reference/string/unescape.md)를 사용하세요. + +::: + +HTML 엔터티를 원래 문자로 변환해요. + +```typescript +const unescaped = unescape(str); +``` + +## 사용법 + +### `unescape(str)` + +HTML 엔터티 `&`, `<`, `>`, `"`, `'`를 원래 문자로 되돌리고 싶을 때 `unescape`를 사용하세요. 이는 `escape` 함수의 반대 동작을 해요. + +```typescript +import { unescape } from 'es-toolkit/compat'; + +// HTML 태그 언이스케이프 +unescape('This is a <div> element.'); +// Returns: 'This is a
element.' + +// 따옴표 언이스케이프 +unescape('This is a "quote"'); +// Returns: 'This is a "quote"' + +// 작은따옴표 언이스케이프 +unescape('This is a 'quote''); +// Returns: 'This is a 'quote'' + +// 앰퍼샌드 언이스케이프 +unescape('This is a & symbol'); +// Returns: 'This is a & symbol' +``` + +`null`이나 `undefined`는 빈 문자열로 처리해요. + +```typescript +import { unescape } from 'es-toolkit/compat'; + +unescape(null); // '' +unescape(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 언이스케이프할 문자열이에요. + +#### 반환 값 + +(`string`): HTML 엔터티가 원래 문자로 변환된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/upperCase.md b/docs/ko/compat/reference/string/upperCase.md new file mode 100644 index 000000000..00893b196 --- /dev/null +++ b/docs/ko/compat/reference/string/upperCase.md @@ -0,0 +1,58 @@ +# upperCase (Lodash 호환성) + +::: warning `es-toolkit`의 `upperCase`를 사용하세요 + +이 `upperCase` 함수는 `null`이나 `undefined` 처리를 위한 정규화 로직으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [upperCase](../../../reference/string/upperCase.md)를 사용하세요. + +::: + +문자열을 대문자 케이스로 변환해요. + +```typescript +const upperCased = upperCase(str); +``` + +## 사용법 + +### `upperCase(str)` + +문자열을 대문자 케이스(UPPER CASE)로 변환하고 싶을 때 `upperCase`를 사용하세요. 대문자 케이스는 각 단어를 대문자로 쓰고 공백으로 연결하는 명명 규칙이에요. + +```typescript +import { upperCase } from 'es-toolkit/compat'; + +// 카멜 케이스 변환 +upperCase('camelCase'); +// Returns: 'CAMEL CASE' + +// 공백으로 구분된 문자열 변환 +upperCase('some whitespace'); +// Returns: 'SOME WHITESPACE' + +// 하이픈으로 구분된 문자열 변환 +upperCase('hyphen-text'); +// Returns: 'HYPHEN TEXT' + +// 대문자가 연속으로 나타나는 경우 +upperCase('HTTPRequest'); +// Returns: 'HTTP REQUEST' +``` + +`null`이나 `undefined`는 빈 문자열로 처리해요. + +```typescript +import { upperCase } from 'es-toolkit/compat'; + +upperCase(null); // '' +upperCase(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 대문자 케이스로 변환할 문자열이에요. + +#### 반환 값 + +(`string`): 대문자 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/upperFirst.md b/docs/ko/compat/reference/string/upperFirst.md new file mode 100644 index 000000000..24418b82f --- /dev/null +++ b/docs/ko/compat/reference/string/upperFirst.md @@ -0,0 +1,54 @@ +# upperFirst (Lodash 호환성) + +::: warning `es-toolkit`의 `upperFirst`를 사용하세요 + +이 `upperFirst` 함수는 `null`이나 `undefined` 처리를 위한 변환 로직으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [upperFirst](../../../reference/string/upperFirst.md)를 사용하세요. + +::: + +문자열의 첫 번째 문자를 대문자로 변환해요. + +```typescript +const upperCased = upperFirst(str); +``` + +## 사용법 + +### `upperFirst(str)` + +문자열의 첫 번째 문자만 대문자로 만들고 싶을 때 `upperFirst`를 사용하세요. 나머지 문자들은 그대로 유지돼요. + +```typescript +import { upperFirst } from 'es-toolkit/compat'; + +// 소문자로 시작하는 문자열 +upperFirst('fred'); +// Returns: 'Fred' + +// 이미 대문자로 시작하는 문자열 +upperFirst('Fred'); +// Returns: 'Fred' + +// 모두 대문자인 문자열 +upperFirst('FRED'); +// Returns: 'FRED' +``` + +`null`이나 `undefined`는 빈 문자열로 처리해요. + +```typescript +import { upperFirst } from 'es-toolkit/compat'; + +upperFirst(null); // '' +upperFirst(undefined); // '' +``` + +#### 파라미터 + +- `str` (`string`, 선택): 첫 문자를 대문자로 변환할 문자열이에요. + +#### 반환 값 + +(`string`): 첫 문자가 대문자로 변환된 문자열을 반환해요. diff --git a/docs/ko/compat/reference/string/words.md b/docs/ko/compat/reference/string/words.md new file mode 100644 index 000000000..5204aa8e7 --- /dev/null +++ b/docs/ko/compat/reference/string/words.md @@ -0,0 +1,69 @@ +# words (Lodash 호환성) + +::: warning `es-toolkit`의 `words`를 사용하세요 + +이 `words` 함수는 `null`이나 `undefined` 처리, 복잡한 유니코드 지원 등으로 인해 느리게 동작해요. + +대신 더 빠르고 현대적인 `es-toolkit`의 [words](../../../reference/string/words.md)를 사용하세요. + +::: + +문자열을 단어들로 나누어요. + +```typescript +const wordArray = words(str, pattern); +``` + +## 사용법 + +### `words(str, pattern)` + +문자열을 단어 단위로 나누고 싶을 때 `words`를 사용하세요. 기본적으로 영문자, 숫자, 이모지 등을 인식하여 단어를 추출해요. + +```typescript +import { words } from 'es-toolkit/compat'; + +// 기본 단어 추출 +words('fred, barney, & pebbles'); +// Returns: ['fred', 'barney', 'pebbles'] + +// 카멜 케이스에서 단어 추출 +words('camelCaseWord'); +// Returns: ['camel', 'Case', 'Word'] + +// 숫자가 포함된 문자열 +words('hello123world'); +// Returns: ['hello', '123', 'world'] +``` + +사용자 정의 패턴을 사용하여 단어를 추출할 수도 있어요. + +```typescript +import { words } from 'es-toolkit/compat'; + +// 정규식을 사용한 단어 추출 +words('hello world', /\w+/g); +// Returns: ['hello', 'world'] + +// 문자열 패턴 사용 +words('one-two-three', '-'); +// Returns: ['-'] +``` + +`null`이나 `undefined`는 빈 배열로 처리해요. + +```typescript +import { words } from 'es-toolkit/compat'; + +words(null); // [] +words(undefined); // [] +``` + +#### 파라미터 + +- `str` (`string`, 선택): 단어로 나눌 문자열이에요. +- `pattern` (`RegExp | string`, 선택): 단어를 매치할 패턴이에요. 기본값은 내장 유니코드 단어 패턴이에요. + +#### 반환 값 + +(`string[]`): 추출된 단어들의 배열을 반환해요. diff --git a/docs/ko/reference/compat/util/bindAll.md b/docs/ko/compat/reference/util/bindAll.md similarity index 100% rename from docs/ko/reference/compat/util/bindAll.md rename to docs/ko/compat/reference/util/bindAll.md diff --git a/docs/ko/reference/compat/util/cond.md b/docs/ko/compat/reference/util/cond.md similarity index 100% rename from docs/ko/reference/compat/util/cond.md rename to docs/ko/compat/reference/util/cond.md diff --git a/docs/ko/reference/compat/util/constant.md b/docs/ko/compat/reference/util/constant.md similarity index 100% rename from docs/ko/reference/compat/util/constant.md rename to docs/ko/compat/reference/util/constant.md diff --git a/docs/ko/reference/compat/util/defaultTo.md b/docs/ko/compat/reference/util/defaultTo.md similarity index 100% rename from docs/ko/reference/compat/util/defaultTo.md rename to docs/ko/compat/reference/util/defaultTo.md diff --git a/docs/ko/reference/compat/util/eq.md b/docs/ko/compat/reference/util/eq.md similarity index 100% rename from docs/ko/reference/compat/util/eq.md rename to docs/ko/compat/reference/util/eq.md diff --git a/docs/ko/reference/compat/util/gt.md b/docs/ko/compat/reference/util/gt.md similarity index 100% rename from docs/ko/reference/compat/util/gt.md rename to docs/ko/compat/reference/util/gt.md diff --git a/docs/ko/reference/compat/util/gte.md b/docs/ko/compat/reference/util/gte.md similarity index 100% rename from docs/ko/reference/compat/util/gte.md rename to docs/ko/compat/reference/util/gte.md diff --git a/docs/ko/reference/compat/util/invoke.md b/docs/ko/compat/reference/util/invoke.md similarity index 100% rename from docs/ko/reference/compat/util/invoke.md rename to docs/ko/compat/reference/util/invoke.md diff --git a/docs/ko/reference/compat/util/iteratee.md b/docs/ko/compat/reference/util/iteratee.md similarity index 100% rename from docs/ko/reference/compat/util/iteratee.md rename to docs/ko/compat/reference/util/iteratee.md diff --git a/docs/ko/reference/compat/util/lt.md b/docs/ko/compat/reference/util/lt.md similarity index 100% rename from docs/ko/reference/compat/util/lt.md rename to docs/ko/compat/reference/util/lt.md diff --git a/docs/ko/reference/compat/util/lte.md b/docs/ko/compat/reference/util/lte.md similarity index 100% rename from docs/ko/reference/compat/util/lte.md rename to docs/ko/compat/reference/util/lte.md diff --git a/docs/ko/reference/compat/util/method.md b/docs/ko/compat/reference/util/method.md similarity index 100% rename from docs/ko/reference/compat/util/method.md rename to docs/ko/compat/reference/util/method.md diff --git a/docs/ko/reference/compat/util/methodOf.md b/docs/ko/compat/reference/util/methodOf.md similarity index 100% rename from docs/ko/reference/compat/util/methodOf.md rename to docs/ko/compat/reference/util/methodOf.md diff --git a/docs/ko/reference/compat/util/now.md b/docs/ko/compat/reference/util/now.md similarity index 100% rename from docs/ko/reference/compat/util/now.md rename to docs/ko/compat/reference/util/now.md diff --git a/docs/ko/reference/compat/util/over.md b/docs/ko/compat/reference/util/over.md similarity index 100% rename from docs/ko/reference/compat/util/over.md rename to docs/ko/compat/reference/util/over.md diff --git a/docs/ko/reference/compat/util/overEvery.md b/docs/ko/compat/reference/util/overEvery.md similarity index 100% rename from docs/ko/reference/compat/util/overEvery.md rename to docs/ko/compat/reference/util/overEvery.md diff --git a/docs/ko/reference/compat/util/overSome.md b/docs/ko/compat/reference/util/overSome.md similarity index 100% rename from docs/ko/reference/compat/util/overSome.md rename to docs/ko/compat/reference/util/overSome.md diff --git a/docs/ko/reference/compat/util/stubArray.md b/docs/ko/compat/reference/util/stubArray.md similarity index 100% rename from docs/ko/reference/compat/util/stubArray.md rename to docs/ko/compat/reference/util/stubArray.md diff --git a/docs/ko/reference/compat/util/stubFalse.md b/docs/ko/compat/reference/util/stubFalse.md similarity index 100% rename from docs/ko/reference/compat/util/stubFalse.md rename to docs/ko/compat/reference/util/stubFalse.md diff --git a/docs/ko/reference/compat/util/stubObject.md b/docs/ko/compat/reference/util/stubObject.md similarity index 100% rename from docs/ko/reference/compat/util/stubObject.md rename to docs/ko/compat/reference/util/stubObject.md diff --git a/docs/ko/reference/compat/util/stubString.md b/docs/ko/compat/reference/util/stubString.md similarity index 100% rename from docs/ko/reference/compat/util/stubString.md rename to docs/ko/compat/reference/util/stubString.md diff --git a/docs/ko/reference/compat/util/stubTrue.md b/docs/ko/compat/reference/util/stubTrue.md similarity index 100% rename from docs/ko/reference/compat/util/stubTrue.md rename to docs/ko/compat/reference/util/stubTrue.md diff --git a/docs/ko/reference/compat/util/times.md b/docs/ko/compat/reference/util/times.md similarity index 100% rename from docs/ko/reference/compat/util/times.md rename to docs/ko/compat/reference/util/times.md diff --git a/docs/ko/reference/compat/util/toArray.md b/docs/ko/compat/reference/util/toArray.md similarity index 100% rename from docs/ko/reference/compat/util/toArray.md rename to docs/ko/compat/reference/util/toArray.md diff --git a/docs/ko/reference/compat/util/toFinite.md b/docs/ko/compat/reference/util/toFinite.md similarity index 100% rename from docs/ko/reference/compat/util/toFinite.md rename to docs/ko/compat/reference/util/toFinite.md diff --git a/docs/ko/reference/compat/util/toInteger.md b/docs/ko/compat/reference/util/toInteger.md similarity index 100% rename from docs/ko/reference/compat/util/toInteger.md rename to docs/ko/compat/reference/util/toInteger.md diff --git a/docs/ko/reference/compat/util/toLength.md b/docs/ko/compat/reference/util/toLength.md similarity index 100% rename from docs/ko/reference/compat/util/toLength.md rename to docs/ko/compat/reference/util/toLength.md diff --git a/docs/ko/reference/compat/util/toNumber.md b/docs/ko/compat/reference/util/toNumber.md similarity index 100% rename from docs/ko/reference/compat/util/toNumber.md rename to docs/ko/compat/reference/util/toNumber.md diff --git a/docs/ko/reference/compat/util/toPath.md b/docs/ko/compat/reference/util/toPath.md similarity index 100% rename from docs/ko/reference/compat/util/toPath.md rename to docs/ko/compat/reference/util/toPath.md diff --git a/docs/ko/reference/compat/util/toPlainObject.md b/docs/ko/compat/reference/util/toPlainObject.md similarity index 100% rename from docs/ko/reference/compat/util/toPlainObject.md rename to docs/ko/compat/reference/util/toPlainObject.md diff --git a/docs/ko/reference/compat/util/toSafeInteger.md b/docs/ko/compat/reference/util/toSafeInteger.md similarity index 100% rename from docs/ko/reference/compat/util/toSafeInteger.md rename to docs/ko/compat/reference/util/toSafeInteger.md diff --git a/docs/ko/reference/compat/util/toString.md b/docs/ko/compat/reference/util/toString.md similarity index 100% rename from docs/ko/reference/compat/util/toString.md rename to docs/ko/compat/reference/util/toString.md diff --git a/docs/ko/reference/compat/util/uniqueId.md b/docs/ko/compat/reference/util/uniqueId.md similarity index 100% rename from docs/ko/reference/compat/util/uniqueId.md rename to docs/ko/compat/reference/util/uniqueId.md diff --git a/docs/ko/compatibility.md b/docs/ko/compatibility.md deleted file mode 100644 index 63b04cbd8..000000000 --- a/docs/ko/compatibility.md +++ /dev/null @@ -1,63 +0,0 @@ -# Lodash와의 호환성 - -::: tip ✅ 1.39.3 버전부터 Lodash와 100% 호환성을 보장해요 - -`es-toolkit/compat`은 Lodash의 모든 함수에 대해서 똑같이 동작하면서 더 가볍고 빨라요. - -- Lodash의 실제 테스트 코드로 동일하게 동작하는 것을 보장해요. -- Storybook, Recharts, CKEditor 등 유명 오픈소스 라이브러리들이 사용하고 있고, Nuxt에서도 추천하고 있어요. - -모든 호환성 함수들의 자세한 문서는 [호환성 레퍼런스](/ko/reference/compat/array/castArray)에서 확인할 수 있어요. - -::: - -```tsx -// es-toolkit/compat은 lodash와 100% 동일한 동작을 제공하도록 목표하고 있어요 -import { chunk } from 'es-toolkit/compat'; - -// es-toolkit은 원래 chunk의 size로 0을 지원하지 않았어요 -chunk([1, 2, 3, 4], 0); -// es-toolkit/compat은 lodash와 같은 []을 반환해요 -``` - -`lodash`와 최대 호환성을 위해서는 `es-toolkit/compat` 라이브러리를 사용하세요. - -`es-toolkit`은 매끄러운 마이그레이션을 보장하기 위해, 두 라이브러리 사이의 동작 차이가 없는 `es-toolkit/compat` 라이브러리를 개발하고 있어요. `lodash`와 동일한 API와 기능을 제공하여, 수월하게 마이그레이션을 할 수 있도록 도와줄 예정이에요. - -`es-toolkit/compat`은 실제 `lodash` 테스트 코드를 이용해서 테스트돼요. - -`es-toolkit/compat`은 원래 `es-toolkit`에 비해 런타임 퍼포먼스나 번들 크기가 최적은 아닐 수 있어요. 마이그레이션 중에 사용하는 도구로 생각해 주시고, 새로운 기능은 `es-toolkit`로 개발해주세요. - -## 설계 원칙 - -::: info -`es-toolkit/compat` 설계 원칙의 방향성은 변경될 수 있어요. -::: - -`es-toolkit/compat`은 다음과 같은 기능들에 대해서 `lodash`와 100% 동일한 기능을 제공하는 것을 목표로 해요. - -- `lodash`의 테스트 케이스로 작성된 기능 -- `@types/lodash` 또는 `@types/lodash-es`의 타입에서 추론할 수 있는 기능 -- `lodash`에서 `es-toolkit`으로 코드를 마이그레이션하는 동안 발견된 기능 차이점 ([이슈 페이지](https://github.com/toss/es-toolkit/issues)에 제보해 주세요.) - -아래와 같은 기능은 `es-toolkit/compat`에서 지원하지 않아요. - -- 암시적 타입 변환: 빈 문자열을 0 또는 false로 변환하는 것과 같은 동작 -- 어떤 경우에 특화된 구현: [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq)와 같이 정렬된 배열만 받는 함수 -- `Array.prototype`과 같은 JavaScript 내장 객체의 프로토타입이 수정된 경우에 대한 처리 -- JavaScript Realm에 대응하는 코드 -- 메서드 체이닝: `_(arr).map(...).filter(...)`와 같은 메서드 체이닝 - -## 구현 상태 - -::: info -아래 이모지로 현재 구현 상태를 나타내고 있어요. - -- ✅: 완료 (구현됐고, lodash 테스트 코드를 모두 통과해요.) -- 📝: 리뷰 중 (구현됐지만, lodash 테스트 코드로 테스트되지는 않았어요.) -- ❌: 아직 구현되지 않음 - -"리뷰 중"으로 표시되었더라고 하더라도, 이미 lodash와 100% 동일한 기능을 제공하고 있을 수도 있어요. -::: - - diff --git a/docs/ko/index.md b/docs/ko/index.md index 3d7e0bde7..65c9b880b 100644 --- a/docs/ko/index.md +++ b/docs/ko/index.md @@ -29,7 +29,7 @@ features: details: 같은 기능의 함수들을 기준으로, 최대 97% 작은 JavaScript 크기를 가져요. - title: 쉬운 Lodash 대체 details: es-toolkit은 Lodash를 손쉽게 대체할 수 있는 완전한 호환성 레이어를 제공해요. - link: /ko/compatibility + link: /ko/compat/intro - title: 현대적인 구현 details: 최신 JavaScript API를 사용하여, 구현이 직관적이고 간단해요. - title: 견고한 타입 diff --git a/docs/ko/reference/compat/array/chunk.md b/docs/ko/reference/compat/array/chunk.md deleted file mode 100644 index 69e7f1931..000000000 --- a/docs/ko/reference/compat/array/chunk.md +++ /dev/null @@ -1,70 +0,0 @@ -# chunk (Lodash 호환성) - -::: warning `es-toolkit`의 [`chunk`](../../array/chunk.md)를 사용하세요 - -이 `chunk` 함수는 `null`이나 `undefined` 처리, `size` 기본값 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [chunk](../../array/chunk.md)를 사용하세요. - -::: - -배열을 정해진 크기의 작은 배열들로 나눠요. - -```typescript -const chunked = chunk(arr, size); -``` - -## 사용법 - -### `chunk(arr, size?)` - -긴 배열을 같은 크기의 여러 작은 배열로 나누고 싶을 때 `chunk`를 사용하세요. 배열을 똑같이 나눌 수 없다면, 마지막 배열이 남은 요소들을 포함해요. - -```typescript -import { chunk } from 'es-toolkit/compat'; - -// 숫자 배열을 크기 2로 나눠요. -chunk([1, 2, 3, 4], 2); -// Returns: [[1, 2], [3, 4]] - -// 문자열 배열을 크기 3으로 나눠요. -chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); -// Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] - -// 나누어떨어지지 않는 경우 -chunk([1, 2, 3, 4, 5], 2); -// Returns: [[1, 2], [3, 4], [5]] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { chunk } from 'es-toolkit/compat'; - -chunk(null, 2); -// Returns: [] - -chunk(undefined, 2); -// Returns: [] -``` - -크기가 0이거나 음수면 빈 배열을 반환해요. - -```typescript -import { chunk } from 'es-toolkit/compat'; - -chunk([1, 2, 3], 0); -// Returns: [] - -chunk([1, 2, 3], -1); -// Returns: [] -``` - -#### 파라미터 - -- `arr` (`ArrayLike | null | undefined`): 나눌 배열이에요. -- `size` (`number`, 선택): 각 작은 배열의 크기예요. 기본값은 `1`이에요. - -#### 반환 값 - -(`T[][]`): 크기 `size`로 나눠진 2차원 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/compact.md b/docs/ko/reference/compat/array/compact.md deleted file mode 100644 index 8ce6395f2..000000000 --- a/docs/ko/reference/compat/array/compact.md +++ /dev/null @@ -1,77 +0,0 @@ -# compact (Lodash 호환성) - -::: warning `es-toolkit`의 [`compact`](../../array/compact.md)를 사용하세요 - -이 `compact` 함수는 `null`이나 `undefined` 처리, `size` 기본값 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [compact](../../array/compact.md)를 사용하세요. - -::: - -배열에서 거짓으로 평가되는 값들을 제거해요. - -```typescript -const compacted = compact(arr); -``` - -## 사용법 - -### `compact(arr)` - -배열에서 `false`, `null`, `0`, `""`, `undefined`, `NaN` 같은 거짓으로 평가되는 값들을 제거하고 싶을 때 `compact`를 사용하세요. - -```typescript -import { compact } from 'es-toolkit/compat'; - -// 거짓으로 평가되는 값들 제거 -compact([0, 1, false, 2, '', 3]); -// Returns: [1, 2, 3] - -compact(['a', null, 'b', undefined, 'c', NaN]); -// Returns: ['a', 'b', 'c'] - -// 빅인트 0도 제거 -compact([0n, 1n, false, 2n]); -// Returns: [1n, 2n] - -// 빈 배열도 처리 -compact([]); -// Returns: [] - -// 모든 값이 거짓으로 평가되는 경우 -compact([false, null, 0, '', undefined, NaN]); -// Returns: [] -``` - -참으로 평가되는 값들은 그대로 유지돼요. - -```typescript -import { compact } from 'es-toolkit/compat'; - -compact([1, 'hello', true, {}, []]); -// Returns: [1, 'hello', true, {}, []] - -// 0이 아닌 숫자들 -compact([0, -1, 2, -3]); -// Returns: [-1, 2, -3] -``` - -`null`이나 `undefined` 배열은 빈 배열로 처리해요. - -```typescript -import { compact } from 'es-toolkit/compat'; - -compact(null); -// Returns: [] - -compact(undefined); -// Returns: [] -``` - -#### 파라미터 - -- `arr` (`ArrayLike | null | undefined`): 압축할 배열이에요. - -#### 반환 값 - -(`T[]`): 거짓으로 평가되는 값들이 제거된 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/countBy.md b/docs/ko/reference/compat/array/countBy.md deleted file mode 100644 index ae89d7202..000000000 --- a/docs/ko/reference/compat/array/countBy.md +++ /dev/null @@ -1,88 +0,0 @@ -# countBy (Lodash 호환성) - -::: warning `es-toolkit`의 `countBy`를 사용하세요 - -이 `countBy` 함수는 복잡한 변환 함수 처리와 타입 변환으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [countBy](../../array/countBy.md)를 사용하세요. - -::: - -배열이나 객체의 요소들을 조건에 따라 분류해서 각 분류의 개수를 세어요. - -```typescript -const counts = countBy(collection, iteratee); -``` - -## 사용법 - -### `countBy(collection, iteratee?)` - -배열이나 객체의 각 요소를 어떤 기준으로 그룹화하고, 각 그룹에 몇 개의 요소가 있는지 세고 싶을 때 `countBy`를 사용하세요. 반복자 함수가 반환하는 값이 키가 되고, 그 키에 해당하는 요소들의 개수가 값이 돼요. - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// 숫자를 소수점 아래 버림으로 그룹화 -countBy([6.1, 4.2, 6.3], Math.floor); -// Returns: { '4': 1, '6': 2 } - -// 문자열을 길이로 그룹화 -countBy(['one', 'two', 'three'], 'length'); -// Returns: { '3': 2, '5': 1 } - -// 사용자를 나이대로 그룹화 -const users = [ - { name: 'Alice', age: 25 }, - { name: 'Bob', age: 35 }, - { name: 'Charlie', age: 25 }, -]; -countBy(users, user => Math.floor(user.age / 10) * 10); -// Returns: { '20': 2, '30': 1 } -``` - -객체도 처리할 수 있어요. - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// 객체의 값들을 타입으로 분류 -const obj = { a: 1, b: 'string', c: 2, d: 'text' }; -countBy(obj, value => typeof value); -// Returns: { 'number': 2, 'string': 2 } -``` - -반복자 함수 없이 사용하면 값 자체로 그룹화해요. - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// 값 자체로 그룹화 -countBy([1, 2, 1, 3, 2, 1]); -// Returns: { '1': 3, '2': 2, '3': 1 } - -// 불린 값으로 그룹화 -countBy([true, false, true, true]); -// Returns: { 'true': 3, 'false': 1 } -``` - -`null`이나 `undefined` 컬렉션은 빈 객체를 반환해요. - -```typescript -import { countBy } from 'es-toolkit/compat'; - -countBy(null); -// Returns: {} - -countBy(undefined); -// Returns: {} -``` - -#### 파라미터 - -- `collection` (`ArrayLike | object | null | undefined`): 처리할 배열이나 객체예요. -- `iteratee` (`ValueIteratee`, 선택): 각 요소를 그룹화할 기준을 정하는 함수예요. 함수, 프로퍼티 이름, 또는 부분 객체를 사용할 수 있어요. - -#### 반환 값 - -(`Record`): 각 그룹의 키와 해당 그룹의 요소 개수를 가진 객체를 반환해요. diff --git a/docs/ko/reference/compat/array/difference.md b/docs/ko/reference/compat/array/difference.md deleted file mode 100644 index 21d5ebc60..000000000 --- a/docs/ko/reference/compat/array/difference.md +++ /dev/null @@ -1,94 +0,0 @@ -# difference (Lodash 호환성) - -::: warning `es-toolkit`의 `difference`를 사용하세요 - -이 `difference` 함수는 `null`이나 `undefined` 처리, 여러 배열 인자 처리로 인해 복잡하게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [difference](../../array/difference.md)를 사용하세요. - -::: - -첫 번째 배열에서 다른 배열들의 값들을 제외한 차집합을 구해요. - -```typescript -const result = difference(arr, ...values); -``` - -## 사용법 - -### `difference(arr, ...values)` - -첫 번째 배열에서 나머지 배열들에 포함된 값들을 모두 제거하고 싶을 때 `difference`를 사용하세요. 순서는 첫 번째 배열의 순서를 유지해요. - -```typescript -import { difference } from 'es-toolkit/compat'; - -// 기본 사용법 -const array1 = [1, 2, 3, 4, 5]; -const array2 = [2, 4]; -const array3 = [5, 6]; -difference(array1, array2, array3); -// Returns: [1, 3] - -// 문자열 배열 -difference(['a', 'b', 'c'], ['b'], ['c', 'd']); -// Returns: ['a'] - -// 중복된 값 처리 -difference([1, 2, 2, 3], [2]); -// Returns: [1, 3] -``` - -빈 배열이나 빈 차집합도 처리해요. - -```typescript -import { difference } from 'es-toolkit/compat'; - -// 빈 배열과의 차집합 -difference([1, 2, 3], []); -// Returns: [1, 2, 3] - -// 모든 값이 제외되는 경우 -difference([1, 2, 3], [1, 2, 3]); -// Returns: [] - -// 겹치는 값이 없는 경우 -difference([1, 2], [3, 4]); -// Returns: [1, 2] -``` - -`null`이나 `undefined` 배열은 빈 배열로 처리해요. - -```typescript -import { difference } from 'es-toolkit/compat'; - -difference(null, [1, 2]); -// Returns: [] - -difference(undefined, [1, 2]); -// Returns: [] - -difference([1, 2, 3], null, undefined); -// Returns: [1, 2, 3] (null과 undefined는 무시됨) -``` - -유사 배열 객체도 지원해요. - -```typescript -import { difference } from 'es-toolkit/compat'; - -// 유사 배열 객체 -const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; -const arrayLike2 = { 0: 2, 1: 4, length: 2 }; -difference(arrayLike1, arrayLike2); -// Returns: [1, 3] -``` - -#### 파라미터 - -- `arr` (`ArrayLike | null | undefined`): 차집합을 구할 기준 배열이에요. -- `values` (`...ArrayLike[]`): 제외할 값들을 포함한 배열들이에요. - -#### 반환 값 - -(`T[]`): 첫 번째 배열에서 다른 배열들의 값들을 제외한 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/differenceBy.md b/docs/ko/reference/compat/array/differenceBy.md deleted file mode 100644 index 842fc5036..000000000 --- a/docs/ko/reference/compat/array/differenceBy.md +++ /dev/null @@ -1,88 +0,0 @@ -# differenceBy (Lodash 호환성) - -::: warning `es-toolkit`의 `differenceBy`를 사용하세요 - -이 `differenceBy` 함수는 복잡한 인자 처리와 반복자 변환으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [differenceBy](../../array/differenceBy.md)를 사용하세요. - -::: - -반복자 함수로 변환한 값들을 기준으로 첫 번째 배열에서 다른 배열들의 요소를 제외한 차집합을 구해요. - -```typescript -const result = differenceBy(array, ...values, iteratee); -``` - -## 사용법 - -### `differenceBy(array, ...values, iteratee)` - -첫 번째 배열의 각 요소와 제외할 배열들의 요소들을 반복자 함수로 변환한 후, 같은 값이 나오는 요소들을 제거하고 싶을 때 `differenceBy`를 사용하세요. 객체 배열에서 특정 프로퍼티 값이나 변환된 값을 기준으로 비교할 때 유용해요. - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// 소수점 버림으로 비교 -differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); -// Returns: [1.2] (Math.floor(2.1) === Math.floor(2.3)이므로 2.1 제외) - -// 문자열 길이로 비교 -differenceBy(['one', 'two', 'three'], ['four', 'eight'], 'length'); -// Returns: ['one', 'two'] (three와 eight은 길이가 같으므로 three 제외) - -// 객체의 프로퍼티로 비교 -const users1 = [ - { id: 1, name: 'Alice' }, - { id: 2, name: 'Bob' }, -]; -const users2 = [{ id: 1, name: 'Different Alice' }]; -differenceBy(users1, users2, 'id'); -// Returns: [{ id: 2, name: 'Bob' }] (id가 1인 객체 제외) -``` - -여러 배열을 한 번에 제외할 수 있어요. - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// 여러 배열에서 제외 -differenceBy([2.1, 1.2, 3.5], [2.3], [1.4], [3.2], Math.floor); -// Returns: [] (모든 요소가 제외됨) - -// 문자열 배열에서 길이로 비교 -differenceBy(['a', 'bb', 'ccc'], ['x'], ['yy'], ['zzz'], 'length'); -// Returns: [] (길이 1, 2, 3 모두 제외됨) -``` - -반복자 함수가 없으면 일반 `difference`처럼 동작해요. - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// 반복자 함수 없이 사용 -differenceBy([1, 2, 3], [2, 4]); -// Returns: [1, 3] -``` - -`null`이나 `undefined` 배열은 빈 배열로 처리해요. - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -differenceBy(null, [1, 2], Math.floor); -// Returns: [] - -differenceBy(undefined, [1, 2], x => x); -// Returns: [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 차집합을 구할 기준 배열이에요. -- `values` (`...ArrayLike[]`): 제외할 값들을 포함한 배열들이에요. -- `iteratee` (`ValueIteratee`): 각 요소를 비교할 값으로 변환하는 함수예요. 함수, 프로퍼티 이름, 또는 부분 객체를 사용할 수 있어요. - -#### 반환 값 - -(`T[]`): 반복자 함수로 변환한 값들을 기준으로 제외된 요소들을 뺀 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/differenceWith.md b/docs/ko/reference/compat/array/differenceWith.md deleted file mode 100644 index cbb4fd361..000000000 --- a/docs/ko/reference/compat/array/differenceWith.md +++ /dev/null @@ -1,79 +0,0 @@ -# differenceWith (Lodash 호환성) - -::: warning `es-toolkit`의 `differenceWith`를 사용하세요 - -이 `differenceWith` 함수는 `null`이나 `undefined` 처리, 여러 배열 처리, `ArrayLike` 타입 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [differenceWith](../../array/differenceWith.md)를 사용하세요. - -::: - -비교 함수를 사용해서 첫 번째 배열에서 다른 배열들에 포함된 요소들을 제거해요. - -```typescript -const result = differenceWith(array, ...values, comparator); -``` - -## 사용법 - -### `differenceWith(array, ...values, comparator)` - -각 요소를 비교 함수로 비교해서 차이를 구하고 싶을 때 `differenceWith`를 사용하세요. 마지막 인수가 비교 함수가 돼요. - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -// 객체를 id로 비교해요. -const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; -const others = [{ id: 2 }]; -const comparator = (a, b) => a.id === b.id; - -differenceWith(objects, others, comparator); -// Returns: [{ id: 1 }, { id: 3 }] - -// 여러 배열을 한 번에 제외해요. -const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]; -const values1 = [{ id: 2 }]; -const values2 = [{ id: 3 }]; - -differenceWith(array, values1, values2, comparator); -// Returns: [{ id: 1 }, { id: 4 }] -``` - -비교 함수를 제공하지 않으면 일반적인 `difference`처럼 동작해요. - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -// 비교 함수 없이 사용하면 일반적인 비교를 해요. -differenceWith([1, 2, 3], [2], [3]); -// Returns: [1] -``` - -복잡한 비교 로직도 사용할 수 있어요. - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -const users = [ - { name: 'alice', age: 25 }, - { name: 'bob', age: 30 }, - { name: 'charlie', age: 35 }, -]; -const excludeUsers = [{ name: 'bob', age: 25 }]; // 다른 나이 - -// 이름만으로 비교해요. -const compareByName = (a, b) => a.name === b.name; -differenceWith(users, excludeUsers, compareByName); -// Returns: [{ name: 'alice', age: 25 }, { name: 'charlie', age: 35 }] -// bob이 제외돼요 (나이는 달라도 이름이 같아서) -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 차이를 구할 기준 배열이에요. -- `...values` (`Array>` + `(a: T, b: T) => boolean`): 제외할 요소들이 포함된 배열들과 마지막에 비교 함수예요. - -#### 반환 값 - -(`T[]`): 비교 함수를 사용해서 첫 번째 배열에서 나머지 배열들의 요소를 제거한 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/drop.md b/docs/ko/reference/compat/array/drop.md deleted file mode 100644 index 84832e37c..000000000 --- a/docs/ko/reference/compat/array/drop.md +++ /dev/null @@ -1,97 +0,0 @@ -# drop (Lodash 호환성) - -::: warning `es-toolkit`의 `drop`을 사용하세요 - -이 `drop` 함수는 `null`이나 `undefined` 처리, `toInteger` 변환 등으로 인해 복잡하게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [drop](../../array/drop.md)을 사용하세요. - -::: - -배열의 앞에서부터 지정된 개수만큼 요소들을 제거해요. - -```typescript -const result = drop(array, n); -``` - -## 사용법 - -### `drop(array, n?)` - -배열의 처음 부분에서 몇 개의 요소를 제거하고 나머지를 얻고 싶을 때 `drop`을 사용하세요. 기본적으로 첫 번째 요소 하나를 제거해요. - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 기본 사용법 (첫 번째 요소 제거) -drop([1, 2, 3, 4, 5]); -// Returns: [2, 3, 4, 5] - -// 처음 2개 요소 제거 -drop([1, 2, 3, 4, 5], 2); -// Returns: [3, 4, 5] - -// 처음 3개 요소 제거 -drop(['a', 'b', 'c', 'd'], 3); -// Returns: ['d'] -``` - -0이나 음수를 지정하면 원본 배열을 그대로 반환해요. - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 0개 제거 -drop([1, 2, 3], 0); -// Returns: [1, 2, 3] - -// 음수 지정 -drop([1, 2, 3], -1); -// Returns: [1, 2, 3] -``` - -배열보다 큰 수를 지정하면 빈 배열을 반환해요. - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 배열 크기보다 큰 수 지정 -drop([1, 2, 3], 5); -// Returns: [] - -// 빈 배열에서 제거 -drop([], 1); -// Returns: [] -``` - -`null`이나 `undefined` 배열은 빈 배열로 처리해요. - -```typescript -import { drop } from 'es-toolkit/compat'; - -drop(null, 1); -// Returns: [] - -drop(undefined, 2); -// Returns: [] -``` - -유사 배열 객체도 지원해요. - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 유사 배열 객체 -const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; -drop(arrayLike, 1); -// Returns: ['b', 'c'] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 요소를 제거할 배열이에요. -- `n` (`number`, 선택): 제거할 요소의 개수예요. 기본값은 `1`이에요. - -#### 반환 값 - -(`T[]`): 앞에서 지정된 개수만큼 제거된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/dropRight.md b/docs/ko/reference/compat/array/dropRight.md deleted file mode 100644 index 563ead111..000000000 --- a/docs/ko/reference/compat/array/dropRight.md +++ /dev/null @@ -1,55 +0,0 @@ -# dropRight (Lodash 호환성) - -::: warning `es-toolkit`의 `dropRight`를 사용하세요 - -이 `dropRight` 함수는 `null`이나 `undefined` 처리, `guard` 파라미터 처리, `toInteger` 변환 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [dropRight](../../array/dropRight.md)를 사용하세요. - -::: - -배열의 끝에서부터 지정된 개수만큼 요소를 제거한 새로운 배열을 반환해요. - -```typescript -const result = dropRight(array, itemsCount); -``` - -## 사용법 - -### `dropRight(array, itemsCount)` - -배열의 끝부터 특정 개수의 요소를 제거하고 나머지 요소들로 새로운 배열을 만들고 싶을 때 `dropRight`를 사용하세요. - -```typescript -import { dropRight } from 'es-toolkit/compat'; - -// 숫자 배열에서 끝의 2개 요소를 제거해요. -dropRight([1, 2, 3, 4, 5], 2); -// Returns: [1, 2, 3] - -// 문자열 배열에서 끝의 1개 요소를 제거해요. -dropRight(['a', 'b', 'c'], 1); -// Returns: ['a', 'b'] - -// 제거할 개수를 지정하지 않으면 기본값 1을 사용해요. -dropRight([1, 2, 3]); -// Returns: [1, 2] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { dropRight } from 'es-toolkit/compat'; - -dropRight(null, 2); // [] -dropRight(undefined, 2); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 요소를 제거할 배열이에요. -- `itemsCount` (`number`, 선택): 배열의 끝에서부터 제거할 요소의 개수예요. 기본값은 `1`이에요. - -#### 반환 값 - -(`T[]`): 끝에서부터 `itemsCount`개의 요소가 제거된 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/dropRightWhile.md b/docs/ko/reference/compat/array/dropRightWhile.md deleted file mode 100644 index d6b5ea19f..000000000 --- a/docs/ko/reference/compat/array/dropRightWhile.md +++ /dev/null @@ -1,65 +0,0 @@ -# dropRightWhile (Lodash 호환성) - -::: warning `es-toolkit`의 `dropRightWhile`을 사용하세요 - -이 `dropRightWhile` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [dropRightWhile](../../array/dropRightWhile.md)을 사용하세요. - -::: - -조건 함수에 따라 배열의 끝에서부터 요소를 제거해요. - -```typescript -const result = dropRightWhile(array, predicate); -``` - -## 사용법 - -### `dropRightWhile(array, predicate)` - -배열의 끝에서부터 특정 조건을 만족하는 요소들을 연속으로 제거하고 싶을 때 `dropRightWhile`을 사용하세요. 조건 함수가 `false`를 반환하면 제거를 중단해요. - -```typescript -import { dropRightWhile } from 'es-toolkit/compat'; - -// 함수를 조건으로 사용해요. -const users = [ - { user: 'barney', active: true }, - { user: 'fred', active: false }, - { user: 'pebbles', active: false }, -]; - -dropRightWhile(users, user => !user.active); -// Returns: [{ user: 'barney', active: true }] - -// 객체 패턴으로 매칭해요. -dropRightWhile(users, { user: 'pebbles', active: false }); -// Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }] - -// 배열 형태로 속성과 값을 지정해요. -dropRightWhile(users, ['active', false]); -// Returns: [{ user: 'barney', active: true }] - -// 속성 이름으로 조건을 확인해요. -dropRightWhile(users, 'active'); -// Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { dropRightWhile } from 'es-toolkit/compat'; - -dropRightWhile(null, x => x > 0); // [] -dropRightWhile(undefined, x => x > 0); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 요소를 제거할 배열이에요. -- `predicate` (`ListIteratee`, 선택): 각 요소에 적용할 조건 함수예요. 함수, 객체 패턴, 배열 패턴, 또는 속성 이름을 받을 수 있어요. - -#### 반환 값 - -(`T[]`): 조건을 만족하지 않는 첫 번째 요소부터의 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/dropWhile.md b/docs/ko/reference/compat/array/dropWhile.md deleted file mode 100644 index 11be7599d..000000000 --- a/docs/ko/reference/compat/array/dropWhile.md +++ /dev/null @@ -1,67 +0,0 @@ -# dropWhile (Lodash 호환성) - -::: warning `es-toolkit`의 `dropWhile`을 사용하세요 - -이 `dropWhile` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [dropWhile](../../array/dropWhile.md)을 사용하세요. - -::: - -조건 함수에 따라 배열의 시작에서부터 요소를 제거해요. - -```typescript -const result = dropWhile(array, predicate); -``` - -## 사용법 - -### `dropWhile(array, predicate)` - -배열의 시작에서부터 특정 조건을 만족하는 요소들을 연속으로 제거하고 싶을 때 `dropWhile`을 사용하세요. 조건 함수가 `false`를 반환하면 제거를 중단해요. - -```typescript -import { dropWhile } from 'es-toolkit/compat'; - -// 함수를 조건으로 사용해요. -dropWhile([1, 2, 3, 4, 5], n => n < 3); -// Returns: [3, 4, 5] - -// 객체 패턴으로 매칭해요. -const users = [ - { name: 'alice', active: false }, - { name: 'bob', active: false }, - { name: 'charlie', active: true }, -]; - -dropWhile(users, { active: false }); -// Returns: [{ name: 'charlie', active: true }] - -// 배열 형태로 속성과 값을 지정해요. -dropWhile(users, ['active', false]); -// Returns: [{ name: 'charlie', active: true }] - -// 속성 이름으로 조건을 확인해요. -const items = [{ visible: false }, { visible: false }, { visible: true }]; - -dropWhile(items, 'visible'); -// Returns: [{ visible: false }, { visible: false }, { visible: true }] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { dropWhile } from 'es-toolkit/compat'; - -dropWhile(null, x => x > 0); // [] -dropWhile(undefined, x => x > 0); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 요소를 제거할 배열이에요. -- `predicate` (`ListIteratee`, 선택): 각 요소에 적용할 조건 함수예요. 함수, 객체 패턴, 배열 패턴, 또는 속성 이름을 받을 수 있어요. 기본값은 `identity`예요. - -#### 반환 값 - -(`T[]`): 조건을 만족하지 않는 첫 번째 요소부터의 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/eachRight.md b/docs/ko/reference/compat/array/eachRight.md deleted file mode 100644 index 16ded6d60..000000000 --- a/docs/ko/reference/compat/array/eachRight.md +++ /dev/null @@ -1,58 +0,0 @@ -# eachRight (Lodash 호환성) - -::: warning `es-toolkit`의 `forEachRight`을 사용하세요 - -이 `eachRight` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [forEachRight](../../array/forEachRight.md)을 사용하세요. - -::: - -배열이나 객체의 각 요소에 대해 오른쪽부터 왼쪽으로 반복 작업을 수행해요. - -```typescript -const result = eachRight(collection, iteratee); -``` - -## 사용법 - -### `eachRight(collection, iteratee)` - -배열, 객체, 문자열의 각 요소를 오른쪽부터 왼쪽으로 순회하면서 주어진 함수를 실행해요. 배열의 경우 마지막 인덱스부터 역순으로, 객체의 경우 열거 가능한 속성들을 역순으로 순회해요. - -```typescript -import { eachRight } from 'es-toolkit/compat'; - -// 배열 역순 순회 -eachRight([1, 2, 3], (value, index) => console.log(value, index)); -// 로그: 3 2, 2 1, 1 0 - -// 객체 역순 순회 -eachRight({ a: 1, b: 2 }, (value, key) => console.log(key, value)); -// 로그: 'b' 2, 'a' 1 - -// 문자열 역순 순회 -eachRight('hello', (char, index) => console.log(char, index)); -// 로그: 'o' 4, 'l' 3, 'l' 2, 'e' 1, 'h' 0 -``` - -함수가 `false`를 반환하면 순회를 중단해요. - -```typescript -import { eachRight } from 'es-toolkit/compat'; - -eachRight([1, 2, 3, 4], value => { - console.log(value); - return value !== 2; // 2에서 중단 -}); -// 로그: 4, 3, 2 -``` - -#### 파라미터 - -- `collection` (`ArrayLike | Record | string | null | undefined`): 순회할 컬렉션이에요. -- `iteratee` (`(item: any, index: any, collection: any) => unknown`, 선택): 각 요소에 대해 실행할 함수예요. 기본값은 `identity` 함수예요. - -#### 반환 값 - -(`ArrayLike | Record | string | null | undefined`): 원본 컬렉션을 반환해요. diff --git a/docs/ko/reference/compat/array/fill.md b/docs/ko/reference/compat/array/fill.md deleted file mode 100644 index f63fe3f1e..000000000 --- a/docs/ko/reference/compat/array/fill.md +++ /dev/null @@ -1,82 +0,0 @@ -# fill (Lodash 호환성) - -::: warning `es-toolkit`의 `fill`을 사용하세요 - -이 `fill` 함수는 `null`이나 `undefined` 처리, 유사 배열 객체 지원 등으로 인해 복잡하게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [fill](../../array/fill.md)을 사용하세요. - -::: - -배열의 요소들을 지정된 값으로 채워요. - -```typescript -const result = fill(array, value, start, end); -``` - -## 사용법 - -### `fill(array, value, start?, end?)` - -배열의 특정 범위나 전체를 동일한 값으로 채우고 싶을 때 `fill`을 사용하세요. 원본 배열을 직접 수정해요. - -```typescript -import { fill } from 'es-toolkit/compat'; - -// 전체 배열 채우기 -const arr1 = [1, 2, 3]; -fill(arr1, 'a'); -// Returns: ['a', 'a', 'a'] - -// 특정 범위 채우기 -const arr2 = [1, 2, 3, 4, 5]; -fill(arr2, '*', 1, 4); -// Returns: [1, '*', '*', '*', 5] - -// 음수 인덱스 사용 -const arr3 = [1, 2, 3, 4, 5]; -fill(arr3, 'x', -3, -1); -// Returns: [1, 2, 'x', 'x', 5] -``` - -유사 배열 객체도 지원해요. - -```typescript -import { fill } from 'es-toolkit/compat'; - -const arrayLike = { 0: 1, 1: 2, 2: 3, length: 3 }; -fill(arrayLike, 'a', 1, 2); -// Returns: { 0: 1, 1: 'a', 2: 3, length: 3 } -``` - -`null`이나 `undefined` 배열은 빈 배열로 처리해요. - -```typescript -import { fill } from 'es-toolkit/compat'; - -fill(null, 'a'); -// Returns: [] - -fill(undefined, 'a'); -// Returns: [] -``` - -문자열은 읽기 전용이므로 그대로 반환해요. - -```typescript -import { fill } from 'es-toolkit/compat'; - -fill('abc', 'x'); -// Returns: 'abc' (변경되지 않음) -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 채울 배열이에요. -- `value` (`U`): 배열을 채울 값이에요. -- `start` (`number`, 선택): 시작 위치예요. 기본값은 `0`이에요. -- `end` (`number`, 선택): 끝 위치예요 (포함되지 않음). 기본값은 `array.length`예요. - -#### 반환 값 - -(`ArrayLike`): 값으로 채워진 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/first.md b/docs/ko/reference/compat/array/first.md deleted file mode 100644 index 48018ff41..000000000 --- a/docs/ko/reference/compat/array/first.md +++ /dev/null @@ -1,78 +0,0 @@ -# first (Lodash 호환성) - -::: warning `es-toolkit`의 `head`를 사용하세요 - -이 `first` 함수는 `null`이나 `undefined` 처리와 배열 형태의 객체 변환으로 인해 느리게 동작해요. `es-toolkit`의 `head` 함수는 이러한 추가 처리 없이 더 빠르고 간단하게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [head](../../array/head.md)를 사용하세요. - -::: - -배열의 첫 번째 요소를 반환해요. - -```typescript -const firstElement = first(array); -``` - -## 사용법 - -### `first(array)` - -배열의 첫 번째 요소를 가져오고 싶을 때 `first`를 사용하세요. 배열이 비어있거나 `null`, `undefined`인 경우 `undefined`를 반환해요. - -```typescript -import { first } from 'es-toolkit/compat'; - -// 일반 배열에서 첫 번째 요소 가져오기 -first([1, 2, 3]); -// Returns: 1 - -// 문자열 배열에서 첫 번째 요소 가져오기 -first(['a', 'b', 'c']); -// Returns: 'a' - -// 빈 배열 -first([]); -// Returns: undefined -``` - -`null`이나 `undefined`는 `undefined`를 반환해요. - -```typescript -import { first } from 'es-toolkit/compat'; - -first(null); // undefined -first(undefined); // undefined -``` - -배열 형태의 객체에서도 사용할 수 있어요. - -```typescript -import { first } from 'es-toolkit/compat'; - -const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; -first(arrayLike); -// Returns: 'a' - -// 문자열도 배열처럼 처리됨 -first('hello'); -// Returns: 'h' -``` - -타입이 보장된 튜플에서는 정확한 타입을 반환해요. - -```typescript -import { first } from 'es-toolkit/compat'; - -const tuple = [1, 'two', true] as const; -first(tuple); -// Returns: 1 (타입이 1로 추론됨) -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 첫 번째 요소를 가져올 배열이에요. - -#### 반환 값 - -(`T | undefined`): 배열의 첫 번째 요소를 반환해요. 배열이 비어있거나 유효하지 않으면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/array/flatMap.md b/docs/ko/reference/compat/array/flatMap.md deleted file mode 100644 index a36a38766..000000000 --- a/docs/ko/reference/compat/array/flatMap.md +++ /dev/null @@ -1,77 +0,0 @@ -# flatMap (Lodash 호환성) - -::: warning `es-toolkit`의 `flatMap`을 사용하세요 - -이 `flatMap` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [flatMap](../../array/flatMap.md)을 사용하세요. - -::: - -각 요소에 함수를 적용한 후 결과를 평탄화해요. - -```typescript -const result = flatMap(collection, iteratee); -``` - -## 사용법 - -### `flatMap(collection, iteratee)` - -컬렉션의 각 요소에 반복자 함수를 적용한 후 한 단계 평탄화한 배열을 반환해요. 배열, 객체, 문자열을 지원하며 다양한 형태의 반복자를 사용할 수 있어요. - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -// 배열에 함수 적용 -function duplicate(n) { - return [n, n]; -} -flatMap([1, 2], duplicate); -// 결과: [1, 1, 2, 2] - -// 객체에 함수 적용 -const obj = { a: 1, b: 2 }; -flatMap(obj, (value, key) => [key, value]); -// 결과: ['a', 1, 'b', 2] - -// 문자열 속성으로 매핑 -const users = [ - { user: 'barney', hobbies: ['hiking', 'coding'] }, - { user: 'fred', hobbies: ['reading'] }, -]; -flatMap(users, 'hobbies'); -// 결과: ['hiking', 'coding', 'reading'] -``` - -반복자 없이 사용하면 값들을 한 단계 평탄화해요. - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -const obj = { a: [1, 2], b: [3, 4] }; -flatMap(obj); -// 결과: [1, 2, 3, 4] -``` - -부분 객체로 조건 매핑도 가능해요. - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -const users = [ - { user: 'barney', age: 36, active: true }, - { user: 'fred', age: 40, active: false }, -]; -flatMap(users, { active: false }); -// 결과: [false, true] (active가 false인 요소들의 매칭 결과) -``` - -#### 파라미터 - -- `collection` (`object | null | undefined`): 순회할 컬렉션이에요. 배열, 객체, 문자열이 될 수 있어요. -- `iteratee` (`ListIterator | ObjectIterator | string | object`, 선택): 각 요소에 적용할 반복자예요. 함수, 속성 이름, 또는 부분 객체가 될 수 있어요. - -#### 반환 값 - -(`any[]`): 매핑 후 한 단계 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/flatMapDeep.md b/docs/ko/reference/compat/array/flatMapDeep.md deleted file mode 100644 index 476395fdf..000000000 --- a/docs/ko/reference/compat/array/flatMapDeep.md +++ /dev/null @@ -1,77 +0,0 @@ -# flatMapDeep (Lodash 호환성) - -::: warning `es-toolkit`의 [`flatMapDeep`](../../array/flatMapDeep.md)를 사용하세요 - -이 `flatMapDeep` 함수는 복잡한 컬렉션 타입 처리와 깊은 평탄화 로직으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [flatMapDeep](../../array/flatMapDeep.md)를 사용하세요. - -::: - -각 요소에 함수를 적용한 후 결과를 재귀적으로 평탄화해요. - -```typescript -const result = flatMapDeep(collection, iteratee); -``` - -## 사용법 - -### `flatMapDeep(collection, iteratee)` - -컬렉션의 각 요소에 반복자 함수를 적용한 후 무한 깊이로 평탄화한 배열을 반환해요. 중첩된 배열 구조가 모두 평탄화되어 1차원 배열이 됩니다. - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -// 배열에 함수 적용 후 깊은 평탄화 -function duplicate(n) { - return [[[n, n]]]; -} -flatMapDeep([1, 2], duplicate); -// 결과: [1, 1, 2, 2] - -// 객체에 함수 적용 후 깊은 평탄화 -const obj = { a: 1, b: 2 }; -flatMapDeep(obj, (value, key) => [[[key, value]]]); -// 결과: ['a', 1, 'b', 2] - -// 문자열 속성으로 매핑 후 깊은 평탄화 -const users = [ - { user: 'barney', hobbies: [['hiking', 'coding']] }, - { user: 'fred', hobbies: [['reading']] }, -]; -flatMapDeep(users, 'hobbies'); -// 결과: ['hiking', 'coding', 'reading'] -``` - -반복자 없이 사용하면 값들을 재귀적으로 평탄화해요. - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -const obj = { a: [[1, 2]], b: [[[3]]] }; -flatMapDeep(obj); -// 결과: [1, 2, 3] -``` - -부분 객체로 조건 매핑도 가능해요. - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -const users = [ - { user: 'barney', active: [true, false] }, - { user: 'fred', active: [false] }, -]; -flatMapDeep(users, { active: [false] }); -// 결과: [true, true] (active 배열에 [false]가 포함된 요소들의 매칭 결과) -``` - -#### 파라미터 - -- `collection` (`object | null | undefined`): 순회할 컬렉션이에요. 배열, 객체, 문자열이 될 수 있어요. -- `iteratee` (`ListIterator | ObjectIterator | string | object`, 선택): 각 요소에 적용할 반복자예요. 함수, 속성 이름, 또는 부분 객체가 될 수 있어요. - -#### 반환 값 - -(`any[]`): 매핑 후 재귀적으로 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/flatMapDepth.md b/docs/ko/reference/compat/array/flatMapDepth.md deleted file mode 100644 index f161839c3..000000000 --- a/docs/ko/reference/compat/array/flatMapDepth.md +++ /dev/null @@ -1,79 +0,0 @@ -# flatMapDepth (Lodash 호환성) - -::: warning `es-toolkit`의 [flatMap](../../array/flatMap.md)을 사용하세요 - -이 `flatMapDepth` 함수는 Lodash와의 호환성을 위해 여러 형태의 iteratee를 지원하고 `null`이나 `undefined` 처리 등으로 인해 복잡하게 구현되어 있어요. 메인 라이브러리의 `flatMap` 함수는 간단한 함수 iteratee만 지원하므로 더 빠르게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [flatMap](../../array/flatMap.md)를 사용하세요. - -::: - -배열의 각 요소를 iteratee 함수로 변환한 후 지정된 깊이까지 평탄화해요. - -```typescript -const result = flatMapDepth(collection, iteratee, depth); -``` - -## 사용법 - -### `flatMapDepth(collection, iteratee, depth)` - -배열이나 객체의 각 요소를 주어진 함수로 변환한 후, 결과를 지정된 깊이까지 평탄화해서 새 배열로 반환해요. 중첩된 배열 구조를 원하는 깊이까지만 평탄화할 때 유용해요. - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -// 배열을 변환하고 깊이 2까지 평탄화 -flatMapDepth([1, 2], n => [[n, n]], 2); -// => [1, 1, 2, 2] - -// 깊이 1로 제한하면 완전히 평탄화되지 않아요 -flatMapDepth([1, 2], n => [[n, n]], 1); -// => [[1, 1], [2, 2]] - -// 객체에서 값을 추출하고 평탄화 -const users = [ - { user: 'barney', hobbies: [['hiking'], ['coding']] }, - { user: 'fred', hobbies: [['reading']] }, -]; -flatMapDepth(users, 'hobbies', 2); -// => ['hiking', 'coding', 'reading'] -``` - -이 함수는 다양한 형태의 iteratee를 지원해요. - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -// 함수를 사용한 변환 -flatMapDepth([1, 2, 3], n => [[n, n]], 2); - -// 속성명으로 값 추출 -const objects = [{ items: [['a'], ['b']] }, { items: [['c']] }]; -flatMapDepth(objects, 'items', 2); -// => ['a', 'b', 'c'] - -// 객체의 부분 매칭 -const users = [{ active: [[true], [false]] }, { active: [[false]] }]; -flatMapDepth(users, { active: [[false]] }, 2); -// => [true, true] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -flatMapDepth(null, n => [n], 1); // => [] -flatMapDepth(undefined, n => [n], 1); // => [] -``` - -#### 파라미터 - -- `collection` (`ArrayLike | Record | Record | object | null | undefined`): 순회할 배열이나 객체예요. -- `iteratee` (`((value: T, index: number, collection: any) => any) | string | object`, 선택): 각 요소에 대해 실행할 변환 함수나 속성명이에요. 기본값은 `identity`예요. -- `depth` (`number`, 선택): 평탄화할 최대 깊이예요. 기본값은 `1`이에요. - -#### 반환 값 - -(`T[]`): iteratee로 변환된 후 지정된 깊이까지 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/flatten.md b/docs/ko/reference/compat/array/flatten.md deleted file mode 100644 index 69ec3c2f9..000000000 --- a/docs/ko/reference/compat/array/flatten.md +++ /dev/null @@ -1,69 +0,0 @@ -# flatten (Lodash 호환성) - -::: warning `es-toolkit`의 `flatten`을 사용하세요 - -이 `flatten` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [flatten](../../array/flatten.md)을 사용하세요. - -::: - -배열을 한 단계 평탄화해요. - -```typescript -const result = flatten(array, depth); -``` - -## 사용법 - -### `flatten(value, depth)` - -중첩 배열을 지정된 깊이만큼 평탄화해요. 기본적으로 한 단계만 평탄화하며, Arguments 객체나 Symbol.isConcatSpreadable을 가진 객체도 지원해요. - -```typescript -import { flatten } from 'es-toolkit/compat'; - -// 기본 평탄화 (한 단계) -flatten([1, [2, [3, [4]], 5]]); -// 결과: [1, 2, [3, [4]], 5] - -// 깊이 지정 -flatten([1, [2, [3, [4]], 5]], 2); -// 결과: [1, 2, 3, [4], 5] - -// Arguments 객체 지원 -function example() { - return flatten(arguments); -} -example(1, [2, 3], [[4]]); -// 결과: [1, 2, 3, [4]] -``` - -빈 배열이나 null, undefined는 빈 배열을 반환해요. - -```typescript -import { flatten } from 'es-toolkit/compat'; - -flatten(null); // [] -flatten(undefined); // [] -flatten([]); // [] -``` - -Symbol.isConcatSpreadable을 가진 객체도 배열처럼 평탄화돼요. - -```typescript -import { flatten } from 'es-toolkit/compat'; - -const spreadable = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true }; -flatten([1, spreadable, 3]); -// 결과: [1, 'a', 'b', 3] -``` - -#### 파라미터 - -- `value` (`ArrayLike | null | undefined`): 평탄화할 배열이에요. -- `depth` (`number`, 선택): 평탄화할 최대 깊이예요. 기본값은 `1`이에요. - -#### 반환 값 - -(`T[]`): 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/flattenDeep.md b/docs/ko/reference/compat/array/flattenDeep.md deleted file mode 100644 index 32d0d5d02..000000000 --- a/docs/ko/reference/compat/array/flattenDeep.md +++ /dev/null @@ -1,64 +0,0 @@ -# flattenDeep (Lodash 호환성) - -::: warning `es-toolkit`의 `flattenDeep`을 사용하세요 - -이 `flattenDeep` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [flattenDeep](../../array/flattenDeep.md)을 사용하세요. - -::: - -배열을 완전히 평탄화해요. - -```typescript -const result = flattenDeep(array); -``` - -## 사용법 - -### `flattenDeep(value)` - -중첩 배열을 모든 깊이에서 재귀적으로 평탄화해요. 모든 중첩 수준이 제거되어 완전히 평탄화된 1차원 배열을 반환해요. - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -// 깊이 중첩된 배열 완전 평탄화 -flattenDeep([1, [2, [3, [4]], 5]]); -// 결과: [1, 2, 3, 4, 5] - -// 복잡한 중첩 구조도 완전 평탄화 -flattenDeep([1, [2, [3, [[[[4]]]]], 5]]); -// 결과: [1, 2, 3, 4, 5] - -// 혼합된 타입도 지원 -flattenDeep(['a', ['b', ['c', [['d']]]]]); -// 결과: ['a', 'b', 'c', 'd'] -``` - -빈 배열이나 null, undefined는 빈 배열을 반환해요. - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -flattenDeep(null); // [] -flattenDeep(undefined); // [] -flattenDeep([]); // [] -``` - -이미 평탄화된 배열은 그대로 복사돼요. - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -flattenDeep([1, 2, 3, 4, 5]); -// 결과: [1, 2, 3, 4, 5] -``` - -#### 파라미터 - -- `value` (`ListOfRecursiveArraysOrValues | null | undefined`): 완전히 평탄화할 배열이에요. - -#### 반환 값 - -(`Array`): 모든 중첩이 제거된 완전히 평탄화된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/flattenDepth.md b/docs/ko/reference/compat/array/flattenDepth.md deleted file mode 100644 index f970b8bf5..000000000 --- a/docs/ko/reference/compat/array/flattenDepth.md +++ /dev/null @@ -1,55 +0,0 @@ -# flattenDepth (Lodash 호환성) - -::: warning `es-toolkit`의 `flatten`를 사용하세요 - -이 `flattenDepth` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. `es-toolkit`의 `flatten` 함수는 이러한 추가 처리 없이 더 빠르고 간단하게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [flatten](../../array/flatten.md)를 사용하세요. - -::: - -배열을 지정한 깊이까지 평탄화해요. - -```typescript -const flattened = flattenDepth(array, depth); -``` - -## 사용법 - -### `flattenDepth(array, depth)` - -중첩된 배열을 원하는 깊이까지 평탄화하고 싶을 때 `flattenDepth`를 사용하세요. 깊이를 지정하면 그 깊이까지만 중첩된 배열을 평탄화해요. - -```typescript -import { flattenDepth } from 'es-toolkit/compat'; - -// 깊이 1까지 평탄화해요. -flattenDepth([1, [2, [3, [4]], 5]], 1); -// Returns: [1, 2, [3, [4]], 5] - -// 깊이 2까지 평탄화해요. -flattenDepth([1, [2, [3, [4]], 5]], 2); -// Returns: [1, 2, 3, [4], 5] - -// 깊이를 지정하지 않으면 기본값 1로 평탄화해요. -flattenDepth([1, [2, [3, [4]], 5]]); -// Returns: [1, 2, [3, [4]], 5] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { flattenDepth } from 'es-toolkit/compat'; - -flattenDepth(null, 2); // [] -flattenDepth(undefined, 2); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 평탄화할 배열이에요. -- `depth` (`number`, 선택): 평탄화할 최대 깊이예요. 기본값은 `1`이에요. - -#### 반환 값 - -(`T[]`): 지정한 깊이까지 평탄화된 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/forEachRight.md b/docs/ko/reference/compat/array/forEachRight.md deleted file mode 100644 index df57a7642..000000000 --- a/docs/ko/reference/compat/array/forEachRight.md +++ /dev/null @@ -1,75 +0,0 @@ -# forEachRight (Lodash 호환성) - -::: warning `es-toolkit`의 `forEachRight`을 사용하세요 - -이 `forEachRight` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [forEachRight](../../array/forEachRight.md)을 사용하세요. - -::: - -배열이나 객체의 요소들을 오른쪽에서 왼쪽으로 순회하면서 각 요소에 대해 함수를 실행해요. - -```typescript -forEachRight(collection, callback); -``` - -## 사용법 - -### `forEachRight(collection, callback)` - -배열, 객체, 문자열을 오른쪽에서 왼쪽 순서로 순회하면서 각 요소에 대해 콜백 함수를 실행해요. 콜백이 `false`를 반환하면 순회를 중단해요. - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -// 배열을 역순으로 순회해요 -forEachRight([1, 2, 3], (value, index) => { - console.log(value, index); -}); -// 출력: 3 2, 2 1, 1 0 - -// 문자열을 역순으로 순회해요 -forEachRight('abc', (char, index) => { - console.log(char, index); -}); -// 출력: 'c' 2, 'b' 1, 'a' 0 - -// 객체를 역순으로 순회해요 -forEachRight({ a: 1, b: 2, c: 3 }, (value, key) => { - console.log(value, key); -}); -// 출력: 3 'c', 2 'b', 1 'a' -``` - -`null`이나 `undefined`는 그대로 반환해요. - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -forEachRight(null, value => console.log(value)); // null -forEachRight(undefined, value => console.log(value)); // undefined -``` - -콜백이 `false`를 반환하면 순회를 중단해요. - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -forEachRight([1, 2, 3, 4], value => { - console.log(value); - if (value === 2) { - return false; // 순회 중단 - } -}); -// 출력: 4, 3, 2 -``` - -#### 파라미터 - -- `collection` (`ArrayLike | Record | string | null | undefined`): 순회할 컬렉션이에요. 배열, 객체, 문자열, 또는 null/undefined일 수 있어요. -- `callback` (`(item: any, index: any, arr: any) => unknown`, 선택): 각 요소에 대해 실행할 함수예요. `false`를 반환하면 순회를 중단해요. 기본값은 `identity` 함수예요. - -#### 반환 값 - -(`ArrayLike | Record | string | null | undefined`): 원본 컬렉션을 그대로 반환해요. diff --git a/docs/ko/reference/compat/array/groupBy.md b/docs/ko/reference/compat/array/groupBy.md deleted file mode 100644 index e19765dd6..000000000 --- a/docs/ko/reference/compat/array/groupBy.md +++ /dev/null @@ -1,79 +0,0 @@ -# groupBy (Lodash 호환성) - -::: warning `es-toolkit`의 [groupBy](../../array/groupBy.md)를 사용하세요 - -이 `groupBy` 함수는 `null`이나 `undefined` 처리, 객체 지원, 복잡한 타입 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [groupBy](../../array/groupBy.md)를 사용하세요. - -::: - -배열이나 객체의 요소들을 주어진 조건에 따라 그룹으로 나눠요. - -```typescript -const grouped = groupBy(collection, iteratee); -``` - -## 사용법 - -### `groupBy(collection, iteratee)` - -배열이나 객체의 각 요소를 주어진 조건 함수에 따라 그룹으로 나누고, 그룹별로 분류된 객체를 반환해요. 조건은 함수, 프로퍼티 이름, 부분 객체 등 다양한 형태로 제공할 수 있어요. - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -// 함수로 그룹 나누기 -const array = [6.1, 4.2, 6.3]; -const result = groupBy(array, Math.floor); -// result는 { '4': [4.2], '6': [6.1, 6.3] } - -// 프로퍼티 이름으로 그룹 나누기 -const users = [ - { name: 'john', age: 30 }, - { name: 'jane', age: 25 }, - { name: 'bob', age: 30 }, -]; -const byAge = groupBy(users, 'age'); -// byAge는 { '25': [{ name: 'jane', age: 25 }], '30': [{ name: 'john', age: 30 }, { name: 'bob', age: 30 }] } - -// 객체에서 그룹 나누기 -const obj = { a: 6.1, b: 4.2, c: 6.3 }; -const groupedObj = groupBy(obj, Math.floor); -// groupedObj는 { '4': [4.2], '6': [6.1, 6.3] } -``` - -`null`이나 `undefined`는 빈 객체로 처리해요. - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -groupBy(null, x => x); // {} -groupBy(undefined, x => x); // {} -``` - -부분 객체나 프로퍼티-값 쌍으로도 그룹을 나눌 수 있어요. - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -const products = [ - { category: 'fruit', name: 'apple' }, - { category: 'fruit', name: 'banana' }, - { category: 'vegetable', name: 'carrot' }, -]; - -// 부분 객체로 그룹 나누기 -const byCategory = groupBy(products, { category: 'fruit' }); -// 프로퍼티-값 쌍으로 그룹 나누기 -const byName = groupBy(products, ['name', 'apple']); -``` - -#### 파라미터 - -- `collection` (`ArrayLike | Record | null | undefined`): 그룹으로 나눌 배열이나 객체예요. -- `iteratee` (`Function | PropertyKey | Array | Object`, 선택): 그룹을 나누는 조건이에요. 함수, 프로퍼티 이름, 프로퍼티-값 쌍, 또는 부분 객체일 수 있어요. 기본값은 `identity` 함수예요. - -#### 반환 값 - -(`Record`): 각 키가 그룹의 조건값이고, 값이 해당 그룹에 속하는 요소들의 배열인 객체를 반환해요. diff --git a/docs/ko/reference/compat/array/head.md b/docs/ko/reference/compat/array/head.md deleted file mode 100644 index 4fc8530fb..000000000 --- a/docs/ko/reference/compat/array/head.md +++ /dev/null @@ -1,61 +0,0 @@ -# head (Lodash 호환성) - -::: warning `es-toolkit`의 [head](../../array/head.md)를 사용하세요 - -이 `head` 함수는 `ArrayLike` 객체 처리와 배열 변환 과정으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [head](../../array/head.md)를 사용하세요. - -::: - -배열의 첫 번째 요소를 반환해요. - -```typescript -const firstElement = head(array); -``` - -## 사용법 - -### `head(array)` - -배열이나 배열 형태 객체의 첫 번째 요소를 반환해요. 배열이 비어있거나 유효하지 않으면 `undefined`를 반환해요. - -```typescript -import { head } from 'es-toolkit/compat'; - -// 숫자 배열의 첫 번째 요소 -const numbers = [1, 2, 3, 4]; -const first = head(numbers); -// first는 1 - -// 문자열 배열의 첫 번째 요소 -const strings = ['a', 'b', 'c']; -const firstChar = head(strings); -// firstChar는 'a' - -// 배열 형태 객체 -const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; -const firstItem = head(arrayLike); -// firstItem은 'x' -``` - -빈 배열이나 유효하지 않은 입력은 `undefined`를 반환해요. - -```typescript -import { head } from 'es-toolkit/compat'; - -const emptyArray: number[] = []; -const noElement = head(emptyArray); -// noElement는 undefined - -head(null); // undefined -head(undefined); // undefined -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 첫 번째 요소를 가져올 배열이나 배열 형태 객체예요. - -#### 반환 값 - -(`T | undefined`): 배열의 첫 번째 요소를 반환하고, 배열이 비어있거나 유효하지 않으면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/array/initial.md b/docs/ko/reference/compat/array/initial.md deleted file mode 100644 index 549565835..000000000 --- a/docs/ko/reference/compat/array/initial.md +++ /dev/null @@ -1,65 +0,0 @@ -# initial (Lodash 호환성) - -::: warning `es-toolkit`의 [initial](../../array/initial.md)을 사용하세요 - -이 `initial` 함수는 `ArrayLike` 객체 처리와 배열 변환 과정으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [initial](../../array/initial.md)을 사용하세요. - -::: - -배열에서 마지막 요소를 제외한 모든 요소를 새 배열로 반환해요. - -```typescript -const result = initial(array); -``` - -## 사용법 - -### `initial(array)` - -배열이나 배열 형태 객체에서 마지막 요소를 제외한 모든 요소를 포함하는 새 배열을 반환해요. 배열이 비어있거나 요소가 하나뿐이면 빈 배열을 반환해요. - -```typescript -import { initial } from 'es-toolkit/compat'; - -// 숫자 배열에서 마지막 요소 제외 -const numbers = [1, 2, 3, 4]; -const result = initial(numbers); -// result는 [1, 2, 3] - -// 문자열 배열에서 마지막 요소 제외 -const strings = ['a', 'b', 'c', 'd']; -const withoutLast = initial(strings); -// withoutLast는 ['a', 'b', 'c'] - -// 배열 형태 객체 -const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; -const items = initial(arrayLike); -// items는 ['x', 'y'] -``` - -빈 배열이나 유효하지 않은 입력은 빈 배열을 반환해요. - -```typescript -import { initial } from 'es-toolkit/compat'; - -const emptyArray: number[] = []; -const result = initial(emptyArray); -// result는 [] - -const singleItem = [42]; -const onlyOne = initial(singleItem); -// onlyOne은 [] - -initial(null); // [] -initial(undefined); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 마지막 요소를 제외할 배열이나 배열 형태 객체예요. - -#### 반환 값 - -(`T[]`): 마지막 요소를 제외한 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/intersection.md b/docs/ko/reference/compat/array/intersection.md deleted file mode 100644 index dbc5ab452..000000000 --- a/docs/ko/reference/compat/array/intersection.md +++ /dev/null @@ -1,80 +0,0 @@ -# intersection (Lodash 호환성) - -::: warning `es-toolkit`의 [intersection](../../array/intersection.md)을 사용하세요 - -이 `intersection` 함수는 `null`이나 `undefined` 처리, 다중 배열 지원, 중복 제거 과정으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [intersection](../../array/intersection.md)을 사용하세요. - -::: - -여러 배열의 교집합을 구해요. - -```typescript -const result = intersection(...arrays); -``` - -## 사용법 - -### `intersection(...arrays)` - -여러 배열에서 공통으로 존재하는 요소들을 찾아서 새 배열로 반환해요. 결과는 중복이 제거되고 첫 번째 배열의 순서를 유지해요. - -```typescript -import { intersection } from 'es-toolkit/compat'; - -// 두 배열의 교집합 -const array1 = [1, 2, 3, 4]; -const array2 = [2, 3, 5, 6]; -const result = intersection(array1, array2); -// result는 [2, 3] - -// 세 개 배열의 교집합 -const array3 = [3, 4, 7, 8]; -const multiResult = intersection(array1, array2, array3); -// multiResult는 [3] - -// 문자열 배열 -const strings1 = ['a', 'b', 'c']; -const strings2 = ['b', 'c', 'd']; -const stringResult = intersection(strings1, strings2); -// stringResult는 ['b', 'c'] - -// 배열 형태 객체 -const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; -const arrayLike2 = { 0: 2, 1: 3, 2: 4, length: 3 }; -const likeResult = intersection(arrayLike1, arrayLike2); -// likeResult는 [2, 3] -``` - -`null`이나 `undefined` 배열은 빈 배열로 처리해요. - -```typescript -import { intersection } from 'es-toolkit/compat'; - -const array1 = [1, 2, 3]; -const result1 = intersection(array1, null); -// result1는 [] - -const result2 = intersection(null, undefined); -// result2는 [] -``` - -중복된 요소가 있어도 결과에서는 제거돼요. - -```typescript -import { intersection } from 'es-toolkit/compat'; - -const array1 = [1, 1, 2, 3]; -const array2 = [1, 2, 2, 4]; -const result = intersection(array1, array2); -// result는 [1, 2] (중복 제거됨) -``` - -#### 파라미터 - -- `...arrays` (`Array | null | undefined>`): 교집합을 구할 배열들이에요. 배열 형태 객체나 null/undefined도 허용해요. - -#### 반환 값 - -(`T[]`): 모든 배열에 공통으로 존재하는 요소들의 새 배열을 반환해요. 중복은 제거되고 첫 번째 배열의 순서를 따라요. diff --git a/docs/ko/reference/compat/array/intersectionBy.md b/docs/ko/reference/compat/array/intersectionBy.md deleted file mode 100644 index 0024123a7..000000000 --- a/docs/ko/reference/compat/array/intersectionBy.md +++ /dev/null @@ -1,93 +0,0 @@ -# intersectionBy (Lodash 호환성) - -::: warning `es-toolkit`의 [intersectionBy](../../array/intersectionBy.md)를 사용하세요 - -이 `intersectionBy` 함수는 복잡한 조건 처리, 다중 배열 지원, 프로퍼티 경로 해석 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [intersectionBy](../../array/intersectionBy.md)를 사용하세요. - -::: - -주어진 조건 함수를 사용해서 여러 배열의 교집합을 구해요. - -```typescript -const result = intersectionBy(...arrays, iteratee); -``` - -## 사용법 - -### `intersectionBy(...arrays, iteratee)` - -여러 배열에서 각 요소를 주어진 조건 함수로 변환한 값을 기준으로 교집합을 구해요. 조건은 함수, 프로퍼티 이름, 부분 객체 등 다양한 형태로 제공할 수 있어요. - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -// 함수로 교집합 구하기 -const array1 = [2.1, 1.2]; -const array2 = [2.3, 3.4]; -const result = intersectionBy(array1, array2, Math.floor); -// result는 [2.1] (Math.floor 기준으로 2가 공통) - -// 프로퍼티로 교집합 구하기 -const users1 = [ - { id: 1, name: 'john' }, - { id: 2, name: 'jane' }, -]; -const users2 = [ - { id: 2, name: 'jane' }, - { id: 3, name: 'bob' }, -]; -const byId = intersectionBy(users1, users2, 'id'); -// byId는 [{ id: 2, name: 'jane' }] - -// 세 개 배열의 교집합 -const array3 = [2.5, 4.1]; -const multiResult = intersectionBy(array1, array2, array3, Math.floor); -// multiResult는 [2.1] - -// 배열 형태 객체 -const arrayLike1 = { 0: { x: 1 }, 1: { x: 2 }, length: 2 }; -const arrayLike2 = { 0: { x: 2 }, 1: { x: 3 }, length: 2 }; -const byProperty = intersectionBy(arrayLike1, arrayLike2, 'x'); -// byProperty는 [{ x: 2 }] -``` - -`null`이나 `undefined` 배열은 빈 배열로 처리해요. - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -const array1 = [{ x: 1 }, { x: 2 }]; -const result = intersectionBy(array1, null, 'x'); -// result는 [] -``` - -부분 객체나 프로퍼티-값 쌍으로도 조건을 지정할 수 있어요. - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -const products1 = [ - { category: 'fruit', name: 'apple' }, - { category: 'vegetable', name: 'carrot' }, -]; -const products2 = [ - { category: 'fruit', name: 'banana' }, - { category: 'meat', name: 'beef' }, -]; - -// 부분 객체로 조건 지정 -const byCategory = intersectionBy(products1, products2, { category: 'fruit' }); -// 프로퍼티-값 쌍으로 조건 지정 -const byCategoryPair = intersectionBy(products1, products2, ['category', 'fruit']); -``` - -#### 파라미터 - -- `...arrays` (`Array | null | undefined>`): 교집합을 구할 배열들이에요. -- `iteratee` (`Function | PropertyKey | Array | Object`): 각 요소를 변환할 조건이에요. 함수, 프로퍼티 이름, 프로퍼티-값 쌍, 또는 부분 객체일 수 있어요. - -#### 반환 값 - -(`T[]`): 변환된 값을 기준으로 모든 배열에 공통으로 존재하는 요소들의 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/intersectionWith.md b/docs/ko/reference/compat/array/intersectionWith.md deleted file mode 100644 index 985614823..000000000 --- a/docs/ko/reference/compat/array/intersectionWith.md +++ /dev/null @@ -1,64 +0,0 @@ -# intersectionWith (Lodash 호환성) - -::: warning `es-toolkit`의 [intersectionWith](../../array/intersectionWith.md)를 사용하세요 - -이 `intersectionWith` 함수는 `null`이나 `undefined` 처리, 다양한 오버로딩 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [intersectionWith](../../array/intersectionWith.md)를 사용하세요. - -::: - -사용자 정의 비교 함수를 사용해서 모든 배열에 포함된 공통 요소들의 배열을 만들어요. - -```typescript -const result = intersectionWith(array, ...otherArrays, comparator); -``` - -## 사용법 - -### `intersectionWith(array, ...otherArrays, comparator)` - -사용자 정의 비교 함수를 사용해서 첫 번째 배열과 나머지 배열들의 교집합을 구해요. 비교 함수로 각 요소가 동일한지 판단하고, 모든 배열에 포함된 요소들만 결과로 반환해요. - -```typescript -import { intersectionWith } from 'es-toolkit/compat'; - -const objects = [ - { id: 1, name: 'john' }, - { id: 2, name: 'jane' }, -]; -const others = [ - { id: 1, name: 'john' }, - { id: 3, name: 'joe' }, -]; - -intersectionWith(objects, others, (a, b) => a.id === b.id); -// => [{ id: 1, name: 'john' }] - -// 여러 배열과 비교할 수도 있어요 -const array1 = [{ x: 1 }, { x: 2 }]; -const array2 = [{ x: 1 }, { x: 3 }]; -const array3 = [{ x: 1 }, { x: 4 }]; - -intersectionWith(array1, array2, array3, (a, b) => a.x === b.x); -// => [{ x: 1 }] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { intersectionWith } from 'es-toolkit/compat'; - -intersectionWith(null, [1, 2], (a, b) => a === b); // [] -intersectionWith([1, 2], undefined, (a, b) => a === b); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 비교할 첫 번째 배열이에요. -- `...otherArrays` (`Array | ((a: T, b: T | U) => boolean)>`): 비교할 나머지 배열들과 마지막 요소로 비교 함수예요. -- `comparator` (`(a: T, b: T | U) => boolean`): 두 요소가 같은지 판단하는 함수예요. - -#### 반환 값 - -(`T[]`): 모든 배열에서 공통으로 찾은 요소들의 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/keyBy.md b/docs/ko/reference/compat/array/keyBy.md deleted file mode 100644 index 2a23b6dc4..000000000 --- a/docs/ko/reference/compat/array/keyBy.md +++ /dev/null @@ -1,64 +0,0 @@ -# keyBy (Lodash 호환성) - -::: warning `es-toolkit`의 [keyBy](../../array/keyBy.md)를 사용하세요 - -이 `keyBy` 함수는 `null`이나 `undefined` 처리, 다양한 매개변수 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [keyBy](../../array/keyBy.md)를 사용하세요. - -::: - -컬렉션의 요소들을 지정된 키를 기준으로 객체로 구성해요. - -```typescript -const result = keyBy(collection, iteratee); -``` - -## 사용법 - -### `keyBy(collection, iteratee)` - -배열이나 객체의 각 요소를 지정된 키 생성 함수나 속성 이름을 사용해서 객체로 구성해요. 같은 키를 가진 요소가 여러 개 있으면 마지막 요소가 사용돼요. - -```typescript -import { keyBy } from 'es-toolkit/compat'; - -// 속성 이름으로 키 생성하기 -const array = [ - { dir: 'left', code: 97 }, - { dir: 'right', code: 100 }, -]; - -keyBy(array, 'dir'); -// => { left: { dir: 'left', code: 97 }, right: { dir: 'right', code: 100 } } - -// 함수로 키 생성하기 -keyBy(array, o => String.fromCharCode(o.code)); -// => { a: { dir: 'left', code: 97 }, d: { dir: 'right', code: 100 } } - -// 객체에서도 사용 가능해요 -const obj = { - a: { id: 1, name: 'john' }, - b: { id: 2, name: 'jane' }, -}; -keyBy(obj, 'name'); -// => { john: { id: 1, name: 'john' }, jane: { id: 2, name: 'jane' } } -``` - -`null`이나 `undefined`는 빈 객체로 처리해요. - -```typescript -import { keyBy } from 'es-toolkit/compat'; - -keyBy(null, 'id'); // {} -keyBy(undefined, 'id'); // {} -``` - -#### 파라미터 - -- `collection` (`ArrayLike | null | undefined`): 키로 구성할 배열이나 객체예요. -- `iteratee` (`ValueIterateeCustom`, 선택): 키를 생성할 함수나 속성 이름이에요. 생략하면 요소 자체를 키로 사용해요. - -#### 반환 값 - -(`Record`): 각 요소가 생성된 키에 매핑된 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/array/last.md b/docs/ko/reference/compat/array/last.md deleted file mode 100644 index 1e568fa27..000000000 --- a/docs/ko/reference/compat/array/last.md +++ /dev/null @@ -1,79 +0,0 @@ -# last (Lodash 호환성) - -::: warning `es-toolkit`의 [last](../../array/last.md)를 사용하세요 - -이 `last` 함수는 `null`이나 `undefined` 처리로 인해 복잡하게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [last](../../array/last.md)를 사용하세요. - -::: - -배열의 마지막 요소를 반환해요. - -```typescript -const lastElement = last(array); -``` - -## 사용법 - -### `last(array)` - -배열의 맨 뒤 요소를 가져오고 싶을 때 `last`를 사용하세요. 배열이 비어있으면 `undefined`를 반환해요. - -```typescript -import { last } from 'es-toolkit/compat'; - -// 숫자 배열의 마지막 요소 -last([1, 2, 3, 4, 5]); -// Returns: 5 - -// 문자열 배열의 마지막 요소 -last(['a', 'b', 'c']); -// Returns: 'c' - -// 객체 배열의 마지막 요소 -const users = [{ name: 'Alice' }, { name: 'Bob' }]; -last(users); -// Returns: { name: 'Bob' } -``` - -빈 배열이나 `null`, `undefined`는 `undefined`를 반환해요. - -```typescript -import { last } from 'es-toolkit/compat'; - -// 빈 배열 -last([]); -// Returns: undefined - -// null 배열 -last(null); -// Returns: undefined - -// undefined 배열 -last(undefined); -// Returns: undefined -``` - -유사 배열 객체도 지원해요. - -```typescript -import { last } from 'es-toolkit/compat'; - -// 유사 배열 객체 -const arrayLike = { 0: 'first', 1: 'second', length: 2 }; -last(arrayLike); -// Returns: 'second' - -// 문자열도 유사 배열 객체 -last('hello'); -// Returns: 'o' -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 마지막 요소를 가져올 배열이에요. - -#### 반환 값 - -(`T | undefined`): 배열의 마지막 요소를 반환하고, 배열이 비어있거나 `null`, `undefined`이면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/array/orderBy.md b/docs/ko/reference/compat/array/orderBy.md deleted file mode 100644 index a1f91bd19..000000000 --- a/docs/ko/reference/compat/array/orderBy.md +++ /dev/null @@ -1,82 +0,0 @@ -# orderBy (Lodash 호환성) - -::: warning `es-toolkit`의 [orderBy](../../array/orderBy.md)를 사용하세요 - -이 `orderBy` 함수는 `null`이나 `undefined` 처리, 복잡한 경로 탐색, 다양한 정렬 기준 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [orderBy](../../array/orderBy.md)를 사용하세요. - -::: - -여러 기준으로 컬렉션의 요소들을 정렬해요. - -```typescript -const result = orderBy(collection, criteria, orders); -``` - -## 사용법 - -### `orderBy(collection, criteria, orders)` - -배열이나 객체의 요소들을 지정된 기준과 정렬 순서에 따라 정렬해요. 여러 기준을 사용할 수 있고, 각 기준마다 오름차순(`'asc'`) 또는 내림차순(`'desc'`) 정렬을 지정할 수 있어요. - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -const users = [ - { name: 'fred', age: 48 }, - { name: 'barney', age: 34 }, - { name: 'fred', age: 40 }, - { name: 'barney', age: 36 }, -]; - -// 이름 오름차순, 나이 내림차순으로 정렬 -orderBy(users, ['name', 'age'], ['asc', 'desc']); -// => [ -// { name: 'barney', age: 36 }, -// { name: 'barney', age: 34 }, -// { name: 'fred', age: 48 }, -// { name: 'fred', age: 40 } -// ] - -// 함수로 정렬 기준 지정하기 -orderBy(users, [user => user.name, user => user.age], ['asc', 'desc']); -// => 위와 동일한 결과 - -// 단일 기준으로 정렬 -orderBy(users, 'age', 'desc'); -// => [{ name: 'fred', age: 48 }, { name: 'fred', age: 40 }, ...] -``` - -객체의 경우 값들을 정렬해요. - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -const obj = { - a: { name: 'fred', age: 48 }, - b: { name: 'barney', age: 34 }, -}; - -orderBy(obj, 'age', 'desc'); -// => [{ name: 'fred', age: 48 }, { name: 'barney', age: 34 }] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -orderBy(null, 'name'); // [] -orderBy(undefined, 'age'); // [] -``` - -#### 파라미터 - -- `collection` (`ArrayLike | object | null | undefined`): 정렬할 배열이나 객체예요. -- `criteria` (`Criterion | Array>`, 선택): 정렬 기준이에요. 속성 이름, 속성 경로, 함수 등을 사용할 수 있어요. 기본값은 `[null]`이에요. -- `orders` (`unknown | unknown[]`, 선택): 각 기준의 정렬 순서예요. `'asc'`(오름차순), `'desc'`(내림차순), `true`(오름차순), `false`(내림차순)를 사용할 수 있어요. 기본값은 `[]`이에요. - -#### 반환 값 - -(`T[]`): 정렬된 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/partition.md b/docs/ko/reference/compat/array/partition.md deleted file mode 100644 index acf08c6eb..000000000 --- a/docs/ko/reference/compat/array/partition.md +++ /dev/null @@ -1,89 +0,0 @@ -# partition (Lodash 호환성) - -::: warning `es-toolkit`의 [partition](../../array/partition.md)를 사용하세요 - -이 `partition` 함수는 `null`이나 `undefined` 처리, 다양한 조건 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [partition](../../array/partition.md)를 사용하세요. - -::: - -컬렉션의 요소들을 조건에 따라 두 그룹으로 나누어요. - -```typescript -const [truthy, falsy] = partition(collection, predicate); -``` - -## 사용법 - -### `partition(collection, predicate)` - -배열이나 객체의 요소들을 주어진 조건 함수에 따라 두 그룹으로 나누어요. 첫 번째 그룹은 조건이 참인 요소들이고, 두 번째 그룹은 조건이 거짓인 요소들이에요. - -```typescript -import { partition } from 'es-toolkit/compat'; - -// 숫자 배열을 짝수와 홀수로 나누기 -partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); -// => [[2, 4, 6], [1, 3, 5]] - -// 속성 이름으로 조건 지정하기 -const users = [ - { name: 'john', active: true }, - { name: 'jane', active: false }, - { name: 'bob', active: true }, -]; - -partition(users, 'active'); -// => [ -// [{ name: 'john', active: true }, { name: 'bob', active: true }], -// [{ name: 'jane', active: false }] -// ] - -// 객체 조건으로 필터링하기 -partition(users, { active: true }); -// => [ -// [{ name: 'john', active: true }, { name: 'bob', active: true }], -// [{ name: 'jane', active: false }] -// ] - -// 배열 조건으로 필터링하기 -partition(users, ['name', 'john']); -// => [ -// [{ name: 'john', active: true }], -// [{ name: 'jane', active: false }, { name: 'bob', active: true }] -// ] -``` - -객체의 경우 값들을 분할해요. - -```typescript -import { partition } from 'es-toolkit/compat'; - -const obj = { - a: { score: 90 }, - b: { score: 40 }, - c: { score: 80 }, -}; - -partition(obj, item => item.score >= 80); -// => [[{ score: 90 }, { score: 80 }], [{ score: 40 }]] -``` - -`null`이나 `undefined`는 빈 배열들로 처리해요. - -```typescript -import { partition } from 'es-toolkit/compat'; - -partition(null, x => x > 0); // [[], []] -partition(undefined, 'active'); // [[], []] -``` - -#### 파라미터 - -- `collection` (`ArrayLike | T | null | undefined`): 분할할 배열이나 객체예요. -- `predicate` (`((value: T) => unknown) | Partial | [PropertyKey, any] | PropertyKey`, 선택): 각 요소를 테스트할 조건이에요. 함수, 부분 객체, 속성-값 배열, 속성 이름을 사용할 수 있어요. 기본값은 `identity`예요. - -#### 반환 값 - -(`[T[], T[]]`): 조건을 만족하는 요소들의 배열과 만족하지 않는 요소들의 배열로 구성된 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/pull.md b/docs/ko/reference/compat/array/pull.md deleted file mode 100644 index 626137d29..000000000 --- a/docs/ko/reference/compat/array/pull.md +++ /dev/null @@ -1,44 +0,0 @@ -# pull (Lodash 호환성) - -::: warning `es-toolkit`의 [pull](../../array/pull.md)을 사용하세요 - -이 `pull` 함수는 Lodash의 호환성을 위한 함수로, 더 복잡한 타입 처리와 오버로딩으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [pull](../../array/pull.md)을 사용하세요. - -::: - -배열에서 지정한 값들을 모두 제거해요. - -```typescript -const result = pull(array, ...valuesToRemove); -``` - -## 사용법 - -### `pull(array, ...valuesToRemove)` - -배열에서 지정한 값들을 모두 제거하고 원본 배열을 수정해요. 배열을 복사하지 않고 원본 배열을 직접 변경하므로 메모리를 절약할 수 있어요. - -```typescript -import { pull } from 'es-toolkit/compat'; - -// 숫자 배열에서 특정 값들 제거 -const numbers = [1, 2, 3, 2, 4, 2, 5]; -pull(numbers, 2, 3); -console.log(numbers); // [1, 4, 5] - -// 문자열 배열에서 특정 값들 제거 -const fruits = ['apple', 'banana', 'apple', 'cherry']; -pull(fruits, 'apple'); -console.log(fruits); // ['banana', 'cherry'] -``` - -#### 파라미터 - -- `array` (`T[]`): 수정할 배열이에요. -- `...valuesToRemove` (`T[]`): 배열에서 제거할 값들이에요. - -#### 반환 값 - -(`T[]`): 수정된 원본 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/pullAt.md b/docs/ko/reference/compat/array/pullAt.md deleted file mode 100644 index a1fcb76e3..000000000 --- a/docs/ko/reference/compat/array/pullAt.md +++ /dev/null @@ -1,57 +0,0 @@ -# pullAt (Lodash 호환성) - -::: warning `es-toolkit`의 [pullAt](../../array/pullAt.md)을 사용하세요 - -이 `pullAt` 함수는 복잡한 타입 처리와 오버로딩으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [pullAt](../../array/pullAt.md)을 사용하세요. - -::: - -지정된 인덱스에 있는 요소들을 배열에서 제거하고 제거된 요소들을 반환해요. - -```typescript -const removed = pullAt(array, ...indexes); -``` - -## 사용법 - -### `pullAt(array, ...indexes)` - -배열에서 지정된 인덱스에 있는 요소들을 제거하고 제거된 요소들의 배열을 반환하세요. 원본 배열이 변경돼요. - -```typescript -import { pullAt } from 'es-toolkit/compat'; - -// 단일 인덱스로 제거해요 -const array = [1, 2, 3, 4, 5]; -const removed = pullAt(array, 1, 3); -console.log(array); // [1, 3, 5] -console.log(removed); // [2, 4] - -// 배열 형태의 인덱스로 제거해요 -const colors = ['red', 'green', 'blue', 'yellow']; -const removedColors = pullAt(colors, [0, 2]); -console.log(colors); // ['green', 'yellow'] -console.log(removedColors); // ['red', 'blue'] -``` - -존재하지 않는 인덱스는 `undefined`로 처리돼요. - -```typescript -import { pullAt } from 'es-toolkit/compat'; - -const numbers = [10, 20, 30]; -const removed = pullAt(numbers, 1, 5); -console.log(numbers); // [10, 30] -console.log(removed); // [20, undefined] -``` - -#### 파라미터 - -- `array` (`ArrayLike`): 변경할 배열이에요. -- `...indexes` (`Array`): 제거할 요소들의 인덱스예요. 개별 숫자나 숫자 배열로 전달할 수 있어요. - -#### 반환 값 - -(`ArrayLike`): 제거된 요소들의 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/remove.md b/docs/ko/reference/compat/array/remove.md deleted file mode 100644 index e03d7048d..000000000 --- a/docs/ko/reference/compat/array/remove.md +++ /dev/null @@ -1,70 +0,0 @@ -# remove (Lodash 호환성) - -::: warning `es-toolkit`의 `remove`를 사용하세요 - -이 `remove` 함수는 Lodash와의 호환성을 위해 여러 형태의 predicate를 지원하므로 복잡하게 구현되어 있어요. 메인 라이브러리의 `remove` 함수는 간단한 함수 predicate만 지원하므로 더 빠르게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [remove](../../array/remove.md)를 사용하세요. - -::: - -배열에서 조건에 맞는 요소들을 제거하고 제거된 요소들을 배열로 반환해요. - -```typescript -const removedElements = remove(array, predicate); -``` - -## 사용법 - -### `remove(array, predicate)` - -배열을 순회하며 주어진 조건에 맞는 요소들을 원본 배열에서 제거하고, 제거된 요소들을 새 배열로 반환해요. 원본 배열이 직접 수정되므로 주의해야 해요. - -```typescript -import { remove } from 'es-toolkit/compat'; - -// 함수를 사용한 조건으로 제거 -const numbers = [1, 2, 3, 4, 5]; -const evens = remove(numbers, n => n % 2 === 0); -console.log(numbers); // => [1, 3, 5] -console.log(evens); // => [2, 4] - -// 객체의 부분 매칭으로 제거 -const objects = [{ a: 1 }, { a: 2 }, { a: 3 }]; -const removed = remove(objects, { a: 1 }); -console.log(objects); // => [{ a: 2 }, { a: 3 }] -console.log(removed); // => [{ a: 1 }] - -// 속성-값 쌍으로 제거 -const items = [{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }]; -const cherries = remove(items, ['name', 'cherry']); -console.log(items); // => [{ name: 'apple' }, { name: 'banana' }] -console.log(cherries); // => [{ name: 'cherry' }] -``` - -이 함수는 다양한 형태의 predicate를 지원해요. - -```typescript -import { remove } from 'es-toolkit/compat'; - -// 함수를 사용한 조건 -remove(users, user => user.active === false); - -// 객체의 부분 매칭 -remove(users, { status: 'inactive' }); - -// 속성-값 배열 -remove(users, ['type', 'guest']); - -// 속성명으로 truthy 값 확인 -remove(users, 'isDeleted'); -``` - -#### 파라미터 - -- `array` (`ArrayLike`): 수정할 배열이에요. -- `predicate` (`((value: T, index: number, array: ArrayLike) => boolean) | Partial | [keyof T, unknown] | keyof T`, 선택): 각 요소에 대해 실행할 조건이에요. 기본값은 `identity`예요. - -#### 반환 값 - -(`T[]`): 조건에 맞아서 제거된 요소들로 구성된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/sample.md b/docs/ko/reference/compat/array/sample.md deleted file mode 100644 index ee2f9a940..000000000 --- a/docs/ko/reference/compat/array/sample.md +++ /dev/null @@ -1,54 +0,0 @@ -# sample (Lodash 호환성) - -::: warning `es-toolkit`의 [sample](../../array/sample.md)을 사용하세요 - -이 `sample` 함수는 `null`이나 `undefined` 처리, 객체 값 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [sample](../../array/sample.md)을 사용하세요. - -::: - -배열이나 객체에서 랜덤한 요소 하나를 가져와요. - -```typescript -const randomItem = sample(collection); -``` - -## 사용법 - -### `sample(collection)` - -배열이나 객체에서 랜덤한 요소를 하나 선택할 때 `sample`을 사용하세요. 배열에서는 랜덤한 요소를 반환하고, 객체에서는 랜덤한 값을 반환해요. - -```typescript -import { sample } from 'es-toolkit/compat'; - -// 배열에서 랜덤한 요소 가져오기 -sample([1, 2, 3, 4, 5]); -// 1부터 5까지 중 랜덤한 숫자 하나를 반환해요 - -// 객체에서 랜덤한 값 가져오기 -sample({ a: 1, b: 2, c: 3 }); -// 1, 2, 3 중 랜덤한 값 하나를 반환해요 - -// 문자열도 처리해요 -sample('hello'); -// 'h', 'e', 'l', 'l', 'o' 중 랜덤한 문자 하나를 반환해요 -``` - -`null`이나 `undefined`는 `undefined`를 반환해요. - -```typescript -import { sample } from 'es-toolkit/compat'; - -sample(null); // undefined -sample(undefined); // undefined -``` - -#### 파라미터 - -- `collection` (`ArrayLike | Record | null | undefined`): 샘플링할 배열이나 객체예요. - -#### 반환 값 - -(`T | string | undefined`): 배열이나 객체에서 랜덤하게 선택된 요소를 반환해요. 컬렉션이 비어있거나 `null`, `undefined`면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/array/sampleSize.md b/docs/ko/reference/compat/array/sampleSize.md deleted file mode 100644 index c3bdb3a34..000000000 --- a/docs/ko/reference/compat/array/sampleSize.md +++ /dev/null @@ -1,54 +0,0 @@ -# sampleSize (Lodash 호환성) - -::: warning `es-toolkit`의 [sampleSize](../../array/sampleSize.md)를 사용하세요 - -이 `sampleSize` 함수는 `null`이나 `undefined` 처리, 객체 지원, 기본값 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [sampleSize](../../array/sampleSize.md)를 사용하세요. - -::: - -배열이나 객체에서 지정된 개수만큼 무작위로 요소를 선택해요. - -```typescript -const sampled = sampleSize(collection, size); -``` - -## 사용법 - -### `sampleSize(collection, size?)` - -배열이나 객체에서 무작위로 요소를 선택할 때 `sampleSize`를 사용하세요. Floyd 알고리즘을 사용해서 중복 없이 효율적으로 샘플링해요. - -```typescript -import { sampleSize } from 'es-toolkit/compat'; - -// 배열에서 3개의 요소를 무작위로 선택해요. -sampleSize([1, 2, 3, 4, 5], 3); -// Returns: [2, 4, 5] (실제 결과는 달라질 수 있어요) - -// 객체에서 2개의 값을 무작위로 선택해요. -sampleSize({ a: 1, b: 2, c: 3, d: 4 }, 2); -// Returns: [2, 4] (실제 결과는 달라질 수 있어요) -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { sampleSize } from 'es-toolkit/compat'; - -sampleSize(null, 2); -// Returns: [] - -sampleSize(undefined, 2); -// Returns: [] -``` - -#### 파라미터 - -- `collection` (`Record | Record | T | null | undefined`): 샘플링할 배열이나 객체예요. -- `size` (`number`, 선택): 선택할 요소의 개수예요. 기본값은 `1`이에요. - -#### 반환 값 - -(`T[]`): 무작위로 선택된 요소들로 구성된 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/shuffle.md b/docs/ko/reference/compat/array/shuffle.md deleted file mode 100644 index 0ea07e5da..000000000 --- a/docs/ko/reference/compat/array/shuffle.md +++ /dev/null @@ -1,60 +0,0 @@ -# shuffle (Lodash 호환성) - -::: warning `es-toolkit`의 `shuffle`을 사용하세요 - -이 `shuffle` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [shuffle](../../array/shuffle.md)을 사용하세요. - -::: - -배열이나 객체의 요소들을 무작위로 섞어서 새로운 배열을 반환해요. - -```typescript -const result = shuffle(collection); -``` - -## 사용법 - -### `shuffle(collection)` - -Fisher-Yates 알고리즘을 사용하여 배열이나 객체의 요소들을 무작위로 섞어서 새로운 배열을 반환해요. 원본은 변경되지 않아요. - -```typescript -import { shuffle } from 'es-toolkit/compat'; - -// 숫자 배열 섞기 -const numbers = [1, 2, 3, 4, 5]; -const shuffled1 = shuffle(numbers); -// Returns: 예를 들어 [3, 1, 5, 2, 4] (매번 다른 순서) - -// 문자열 배열 섞기 -const fruits = ['apple', 'banana', 'cherry', 'date']; -const shuffled2 = shuffle(fruits); -// Returns: 예를 들어 ['cherry', 'apple', 'date', 'banana'] - -// 객체의 값들 섞기 -const obj = { a: 1, b: 2, c: 3, d: 4 }; -const shuffled3 = shuffle(obj); -// Returns: 예를 들어 [3, 1, 4, 2] (객체 값들이 무작위로 섞임) -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { shuffle } from 'es-toolkit/compat'; - -shuffle(null); -// Returns: [] - -shuffle(undefined); -// Returns: [] -``` - -#### 파라미터 - -- `collection` (`ArrayLike | T | null | undefined`): 섞을 배열이나 객체예요. - -#### 반환 값 - -(`T[]`): 요소들이 무작위로 섞인 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/tail.md b/docs/ko/reference/compat/array/tail.md deleted file mode 100644 index 543a131df..000000000 --- a/docs/ko/reference/compat/array/tail.md +++ /dev/null @@ -1,58 +0,0 @@ -# tail (Lodash 호환성) - -::: warning `es-toolkit`의 [tail](../../array/tail.md)을 사용하세요 - -이 `tail` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [tail](../../array/tail.md)을 사용하세요. - -::: - -배열의 첫 번째 요소를 제외한 나머지 요소들을 반환해요. - -```typescript -const result = tail(array); -``` - -## 사용법 - -### `tail(array)` - -배열의 첫 번째 요소를 제외한 모든 요소들을 포함하는 새로운 배열을 만들고 싶을 때 `tail`을 사용하세요. 입력 배열이 비어있거나 요소가 하나만 있다면 빈 배열을 반환해요. - -```typescript -import { tail } from 'es-toolkit/compat'; - -// 숫자 배열에서 첫 번째 요소를 제거해요. -tail([1, 2, 3]); -// Returns: [2, 3] - -// 문자열 배열에서 첫 번째 요소를 제거해요. -tail(['a', 'b', 'c']); -// Returns: ['b', 'c'] - -// 하나의 요소만 있는 배열이에요. -tail([1]); -// Returns: [] - -// 빈 배열이에요. -tail([]); -// Returns: [] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { tail } from 'es-toolkit/compat'; - -tail(null); // [] -tail(undefined); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 첫 번째 요소를 제거할 배열이에요. - -#### 반환 값 - -(`T[]`): 첫 번째 요소를 제외한 나머지 요소들을 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/take.md b/docs/ko/reference/compat/array/take.md deleted file mode 100644 index 81fc8807e..000000000 --- a/docs/ko/reference/compat/array/take.md +++ /dev/null @@ -1,56 +0,0 @@ -# take (Lodash 호환성) - -::: warning `es-toolkit`의 [take](../../array/take.md)를 사용하세요 - -이 `take` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [take](../../array/take.md)를 사용하세요. - -::: - -배열의 앞에서부터 지정된 개수만큼의 요소를 가져와서 새로운 배열을 만들어요. - -```typescript -const result = take([1, 2, 3, 4, 5], 3); -// result는 [1, 2, 3]이 돼요. -``` - -## 사용법 - -### `take(array, count)` - -배열의 앞에서부터 지정된 개수만큼의 요소를 가져와서 새로운 배열을 반환해요. `count`가 배열의 길이보다 크면 전체 배열을 반환해요. - -```typescript -import { take } from 'es-toolkit/compat'; - -// 기본 사용법 -const numbers = [1, 2, 3, 4, 5]; -const result1 = take(numbers, 3); -// Returns: [1, 2, 3] - -// 배열 길이보다 큰 개수 요청 -const result2 = take(numbers, 10); -// Returns: [1, 2, 3, 4, 5] (전체 배열) - -// 0개 요청 -const result3 = take(numbers, 0); -// Returns: [] - -// 빈 배열 처리 -const result4 = take([], 3); -// Returns: [] - -// 음수 처리 -const result5 = take(numbers, -1); -// Returns: [] -``` - -#### 파라미터 - -- `array` (`T[]`): 요소를 가져올 배열이에요. -- `count` (`number`): 가져올 요소의 개수예요. 기본값은 1이에요. - -#### 반환 값 - -(`T[]`): 앞에서부터 지정된 개수만큼의 요소를 포함하는 새로운 배열이에요. diff --git a/docs/ko/reference/compat/array/takeRight.md b/docs/ko/reference/compat/array/takeRight.md deleted file mode 100644 index 1c64f7e76..000000000 --- a/docs/ko/reference/compat/array/takeRight.md +++ /dev/null @@ -1,63 +0,0 @@ -# takeRight (Lodash 호환성) - -::: warning `es-toolkit`의 [takeRight](../../array/takeRight.md)를 사용하세요 - -이 `takeRight` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [takeRight](../../array/takeRight.md)를 사용하세요. - -::: - -배열의 뒤에서부터 지정된 개수만큼의 요소를 가져와요. - -```typescript -const result = takeRight(array, count); -``` - -## 사용법 - -### `takeRight(array, count)` - -배열의 뒤에서부터 지정된 개수만큼의 요소를 가져와서 새로운 배열을 만들고 싶을 때 `takeRight`를 사용하세요. 요청한 개수가 배열의 길이보다 크다면 전체 배열을 반환해요. - -```typescript -import { takeRight } from 'es-toolkit/compat'; - -// 숫자 배열에서 뒤의 2개 요소를 가져와요. -takeRight([1, 2, 3, 4, 5], 2); -// Returns: [4, 5] - -// 문자열 배열에서 뒤의 3개 요소를 가져와요. -takeRight(['a', 'b', 'c'], 2); -// Returns: ['b', 'c'] - -// 요청한 개수가 배열 길이보다 클 때 -takeRight([1, 2, 3], 5); -// Returns: [1, 2, 3] - -// 0개 요청 -takeRight([1, 2, 3], 0); -// Returns: [] - -// 음수 요청 -takeRight([1, 2, 3], -1); -// Returns: [] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { takeRight } from 'es-toolkit/compat'; - -takeRight(null, 2); // [] -takeRight(undefined, 2); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 요소를 가져올 배열이에요. -- `count` (`number`, 선택): 가져올 요소의 개수예요. 기본값은 `1`이에요. - -#### 반환 값 - -(`T[]`): 뒤에서부터 지정된 개수만큼의 요소를 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/takeRightWhile.md b/docs/ko/reference/compat/array/takeRightWhile.md deleted file mode 100644 index 867990e3b..000000000 --- a/docs/ko/reference/compat/array/takeRightWhile.md +++ /dev/null @@ -1,71 +0,0 @@ -# takeRightWhile (Lodash 호환성) - -::: warning `es-toolkit`의 [takeRightWhile](../../array/takeRightWhile.md)를 사용하세요 - -이 `takeRightWhile` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [takeRightWhile](../../array/takeRightWhile.md)를 사용하세요. - -::: - -조건을 만족하는 동안 배열의 뒤에서부터 요소들을 가져와요. - -```typescript -const result = takeRightWhile(array, predicate); -``` - -## 사용법 - -### `takeRightWhile(array, predicate)` - -배열의 끝에서부터 시작해서 조건을 만족하는 동안 요소들을 가져와서 새로운 배열을 만들고 싶을 때 `takeRightWhile`를 사용하세요. 조건이 거짓으로 평가되면 멈춰요. - -```typescript -import { takeRightWhile } from 'es-toolkit/compat'; - -// 함수 조건 사용 -const numbers = [1, 2, 3, 4, 5]; -takeRightWhile(numbers, x => x > 3); -// Returns: [4, 5] - -// 객체 속성 조건 사용 -const users = [ - { user: 'barney', active: true }, - { user: 'fred', active: false }, - { user: 'pebbles', active: false }, -]; - -takeRightWhile(users, o => !o.active); -// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] - -// 부분 객체로 조건 매칭 -takeRightWhile(users, { active: false }); -// Returns: [{ user: 'pebbles', active: false }] - -// 속성-값 배열로 조건 매칭 -takeRightWhile(users, ['active', false]); -// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] - -// 속성명으로 참으로 평가되는 값 확인 -const items = [{ active: false }, { active: true }, { active: true }]; -takeRightWhile(items, 'active'); -// Returns: [{ active: true }, { active: true }] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { takeRightWhile } from 'es-toolkit/compat'; - -takeRightWhile(null, x => x > 0); // [] -takeRightWhile(undefined, x => x > 0); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 처리할 배열이에요. -- `predicate` (`ListIteratee`, 선택): 각 요소에 대해 실행할 조건이에요. 함수, 부분 객체, 속성-값 배열, 속성명을 사용할 수 있어요. 기본값은 항등 함수예요. - -#### 반환 값 - -(`T[]`): 조건을 만족하는 동안 배열의 뒤에서부터 가져온 요소들의 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/takeWhile.md b/docs/ko/reference/compat/array/takeWhile.md deleted file mode 100644 index 083920534..000000000 --- a/docs/ko/reference/compat/array/takeWhile.md +++ /dev/null @@ -1,71 +0,0 @@ -# takeWhile (Lodash 호환성) - -::: warning `es-toolkit`의 [takeWhile](../../array/takeWhile.md)를 사용하세요 - -이 `takeWhile` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [takeWhile](../../array/takeWhile.md)를 사용하세요. - -::: - -조건을 만족하는 동안 배열의 앞에서부터 요소들을 가져와요. - -```typescript -const result = takeWhile(array, predicate); -``` - -## 사용법 - -### `takeWhile(array, predicate)` - -배열의 시작에서부터 조건을 만족하는 동안 요소들을 가져와서 새로운 배열을 만들고 싶을 때 `takeWhile`을 사용하세요. 조건이 거짓으로 평가되면 멈춰요. - -```typescript -import { takeWhile } from 'es-toolkit/compat'; - -// 함수 조건 사용 -const numbers = [1, 2, 3, 4, 5]; -takeWhile(numbers, x => x < 3); -// Returns: [1, 2] - -// 객체 속성 조건 사용 -const users = [ - { user: 'barney', active: false }, - { user: 'fred', active: false }, - { user: 'pebbles', active: true }, -]; - -takeWhile(users, o => !o.active); -// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] - -// 부분 객체로 조건 매칭 -takeWhile(users, { active: false }); -// Returns: [{ user: 'barney', active: false }] - -// 속성-값 배열로 조건 매칭 -takeWhile(users, ['active', false]); -// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] - -// 속성명으로 참으로 평가되는 값 확인 -const items = [{ active: true }, { active: true }, { active: false }]; -takeWhile(items, 'active'); -// Returns: [{ active: true }, { active: true }] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { takeWhile } from 'es-toolkit/compat'; - -takeWhile(null, x => x > 0); // [] -takeWhile(undefined, x => x > 0); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 처리할 배열이에요. -- `predicate` (`ListIteratee`, 선택): 각 요소에 대해 실행할 조건이에요. 함수, 부분 객체, 속성-값 배열, 속성명을 사용할 수 있어요. 기본값은 항등 함수예요. - -#### 반환 값 - -(`T[]`): 조건을 만족하는 동안 배열의 앞에서부터 가져온 요소들의 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/union.md b/docs/ko/reference/compat/array/union.md deleted file mode 100644 index 3bb366098..000000000 --- a/docs/ko/reference/compat/array/union.md +++ /dev/null @@ -1,62 +0,0 @@ -# union (Lodash 호환성) - -::: warning `es-toolkit`의 [union](../../array/union.md)을 사용하세요 - -이 `union` 함수는 복잡한 배열 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [union](../../array/union.md)을 사용하세요. - -::: - -여러 배열에서 고유한 값들만 모아서 새로운 배열을 만들어요. - -```typescript -const result = union(...arrays); -``` - -## 사용법 - -### `union(...arrays)` - -여러 배열들을 합치고 중복을 제거해서 고유한 값들만 포함하는 새로운 배열을 만들고 싶을 때 `union`을 사용하세요. 각 값이 처음 나타나는 순서를 유지해요. - -```typescript -import { union } from 'es-toolkit/compat'; - -// 숫자 배열들 합치기 -union([2], [1, 2]); -// Returns: [2, 1] - -// 여러 배열 합치기 -union([2], [1, 2], [2, 3]); -// Returns: [2, 1, 3] - -// 중첩된 배열은 평평하게 하지 않아요 -union([1, 3, 2], [1, [5]], [2, [4]]); -// Returns: [1, 3, 2, [5], [4]] - -// 배열이 아닌 값은 무시해요 -union([0], 3, { '0': 1 }, null, [2, 1]); -// Returns: [0, 2, 1] - -// 배열과 유사한 객체도 처리해요 -union([0], { 0: 'a', length: 1 }, [2, 1]); -// Returns: [0, 'a', 2, 1] -``` - -`null`이나 `undefined`는 무시해요. - -```typescript -import { union } from 'es-toolkit/compat'; - -union([1, 2], null, undefined, [3, 4]); -// Returns: [1, 2, 3, 4] -``` - -#### 파라미터 - -- `...arrays` (`Array | null | undefined>`): 합칠 배열들이에요. 배열이 아닌 값들은 무시돼요. - -#### 반환 값 - -(`T[]`): 모든 배열의 고유한 값들을 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/unionBy.md b/docs/ko/reference/compat/array/unionBy.md deleted file mode 100644 index 8f8204c7a..000000000 --- a/docs/ko/reference/compat/array/unionBy.md +++ /dev/null @@ -1,66 +0,0 @@ -# unionBy (Lodash 호환성) - -::: warning `es-toolkit`의 [unionBy](../../array/unionBy.md)를 사용하세요 - -이 `unionBy` 함수는 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [unionBy](../../array/unionBy.md)를 사용하세요. - -::: - -여러 배열을 합치고 지정한 기준으로 고유한 값들만 남겨요. - -```typescript -const result = unionBy(...arrays, iteratee); -``` - -## 사용법 - -### `unionBy(...arrays, iteratee)` - -여러 배열들을 합치고 주어진 기준 함수로 중복을 제거해서 고유한 값들만 포함하는 새로운 배열을 만들고 싶을 때 `unionBy`를 사용하세요. 각 값이 처음 나타나는 순서를 유지해요. - -```typescript -import { unionBy } from 'es-toolkit/compat'; - -// 소수점을 내림해서 비교 -unionBy([2.1], [1.2, 2.3], Math.floor); -// Returns: [2.1, 1.2] - -// 객체의 속성으로 비교 -unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); -// Returns: [{ x: 1 }, { x: 2 }] - -// 함수로 비교 -unionBy( - [{ id: 1, name: 'a' }], - [ - { id: 2, name: 'b' }, - { id: 1, name: 'c' }, - ], - item => item.id -); -// Returns: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }] - -// 부분 객체로 비교 -unionBy([{ x: 1, y: 1 }], [{ x: 1, y: 2 }], { x: 1 }); -// Returns: [{ x: 1, y: 1 }] -``` - -`null`이나 `undefined` 배열은 무시해요. - -```typescript -import { unionBy } from 'es-toolkit/compat'; - -unionBy([1, 2], null, undefined, [3, 4], x => x); -// Returns: [1, 2, 3, 4] -``` - -#### 파라미터 - -- `...arrays` (`Array | null | undefined>`): 합칠 배열들이에요. -- `iteratee` (`ValueIteratee`): 고유성을 결정할 기준이에요. 함수, 속성 이름, 부분 객체, 속성-값 배열을 사용할 수 있어요. - -#### 반환 값 - -(`T[]`): 지정한 기준으로 중복을 제거한 고유한 값들을 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/unionWith.md b/docs/ko/reference/compat/array/unionWith.md deleted file mode 100644 index 6e323d5e2..000000000 --- a/docs/ko/reference/compat/array/unionWith.md +++ /dev/null @@ -1,64 +0,0 @@ -# unionWith (Lodash 호환성) - -::: warning `es-toolkit`의 [unionWith](../../array/unionWith.md)를 사용하세요 - -이 `unionWith` 함수는 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [unionWith](../../array/unionWith.md)를 사용하세요. - -::: - -여러 배열을 합치고 비교 함수로 고유한 값들만 남겨요. - -```typescript -const result = unionWith(...arrays, comparator); -``` - -## 사용법 - -### `unionWith(...arrays, comparator)` - -여러 배열들을 합치고 커스텀 비교 함수로 중복을 제거해서 고유한 값들만 포함하는 새로운 배열을 만들고 싶을 때 `unionWith`를 사용하세요. 각 값이 처음 나타나는 순서를 유지해요. - -```typescript -import { unionWith } from 'es-toolkit/compat'; - -// 커스텀 비교 함수 사용 -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, -]; -const others = [ - { x: 1, y: 1 }, - { x: 1, y: 2 }, -]; - -unionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); -// Returns: [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 1, y: 1 }] - -// 간단한 동등성 비교 -unionWith([1, 2], [2, 3], (a, b) => a === b); -// Returns: [1, 2, 3] - -// 문자열 길이로 비교 -unionWith(['ab', 'cd'], ['ef', 'gh', 'ab'], (a, b) => a.length === b.length); -// Returns: ['ab'] -``` - -`null`이나 `undefined` 배열은 무시해요. - -```typescript -import { unionWith } from 'es-toolkit/compat'; - -unionWith([1, 2], null, undefined, [3, 4], (a, b) => a === b); -// Returns: [1, 2, 3, 4] -``` - -#### 파라미터 - -- `...arrays` (`Array | null | undefined>`): 합칠 배열들이에요. -- `comparator` (`(a: T, b: T) => boolean`): 두 값이 같은지 판단하는 비교 함수예요. - -#### 반환 값 - -(`T[]`): 비교 함수로 중복을 제거한 고유한 값들을 포함하는 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/uniq.md b/docs/ko/reference/compat/array/uniq.md deleted file mode 100644 index 5acfb5347..000000000 --- a/docs/ko/reference/compat/array/uniq.md +++ /dev/null @@ -1,51 +0,0 @@ -# uniq (Lodash 호환성) - -::: warning `es-toolkit`의 [uniq](../../array/uniq.md)를 사용하세요 - -이 `uniq` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [uniq](../../array/uniq.md)를 사용하세요. - -::: - -배열에서 중복된 요소를 제거하여 고유한 요소만 남긴 새로운 배열을 만들어요. - -```typescript -const result = uniq([1, 2, 2, 3, 3, 4]); -// result는 [1, 2, 3, 4]가 돼요. -``` - -## 사용법 - -### `uniq(array)` - -배열에서 중복된 요소를 제거하고 고유한 요소만 포함하는 새로운 배열을 반환해요. 첫 번째로 나타나는 요소만 유지되고 순서는 보존돼요. - -```typescript -import { uniq } from 'es-toolkit/compat'; - -// 숫자 배열에서 중복 제거 -const numbers = [1, 2, 2, 3, 3, 4, 1]; -const result1 = uniq(numbers); -// Returns: [1, 2, 3, 4] - -// 문자열 배열에서 중복 제거 -const strings = ['a', 'b', 'b', 'c', 'a']; -const result2 = uniq(strings); -// Returns: ['a', 'b', 'c'] - -// 객체 배열에서 중복 제거 (참조값 비교) -const obj1 = { id: 1 }; -const obj2 = { id: 2 }; -const objects = [obj1, obj2, obj1]; -const result3 = uniq(objects); -// Returns: [{ id: 1 }, { id: 2 }] -``` - -#### 파라미터 - -- `array` (`T[]`): 처리할 배열이에요. - -#### 반환 값 - -(`T[]`): 중복이 제거된 새로운 배열이에요. diff --git a/docs/ko/reference/compat/array/uniqBy.md b/docs/ko/reference/compat/array/uniqBy.md deleted file mode 100644 index 97dc26ab3..000000000 --- a/docs/ko/reference/compat/array/uniqBy.md +++ /dev/null @@ -1,55 +0,0 @@ -# uniqBy (Lodash 호환성) - -::: warning `es-toolkit`의 [uniqBy](../../array/uniqBy.md)를 사용하세요 - -이 `uniqBy` 함수는 `null`이나 `undefined` 처리, 복잡한 인자 타입 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [uniqBy](../../array/uniqBy.md)를 사용하세요. - -::: - -배열에서 변환 함수가 반환하는 값으로 중복을 제거하여 유일한 요소들로 구성된 새 배열을 만들어요. - -```typescript -const result = uniqBy(array, iteratee); -``` - -## 사용법 - -### `uniqBy(array, iteratee)` - -배열의 각 요소에 변환 함수를 적용하여, 변환 결과가 같은 요소들 중에서 첫 번째 요소만 유지해요. 객체 배열에서 특정 속성을 기준으로 중복을 제거하거나, 숫자 배열에서 특정 계산 결과를 기준으로 중복을 제거할 때 유용해요. - -```typescript -import { uniqBy } from 'es-toolkit/compat'; - -// 숫자 배열에서 Math.floor 결과로 중복 제거 -uniqBy([2.1, 1.2, 2.3], Math.floor); -// Returns: [2.1, 1.2] - -// 객체 배열에서 속성으로 중복 제거 -uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); -// Returns: [{ x: 1 }, { x: 2 }] - -// 함수로 중복 제거 -uniqBy([{ name: 'John' }, { name: 'Jane' }, { name: 'John' }], obj => obj.name); -// Returns: [{ name: 'John' }, { name: 'Jane' }] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { uniqBy } from 'es-toolkit/compat'; - -uniqBy(null, Math.floor); // [] -uniqBy(undefined, 'x'); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 중복을 제거할 배열이에요. -- `iteratee` (`ValueIteratee`): 각 요소에 적용할 변환 함수예요. 함수, 속성 이름, 부분 객체 등을 사용할 수 있어요. - -#### 반환 값 - -(`T[]`): 변환 함수 결과를 기준으로 중복이 제거된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/uniqWith.md b/docs/ko/reference/compat/array/uniqWith.md deleted file mode 100644 index 544cf3e37..000000000 --- a/docs/ko/reference/compat/array/uniqWith.md +++ /dev/null @@ -1,60 +0,0 @@ -# uniqWith (Lodash 호환성) - -::: warning `es-toolkit`의 [uniqWith](../../array/uniqWith.md)를 사용하세요 - -이 `uniqWith` 함수는 `null`이나 `undefined` 처리, 복잡한 인자 타입 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [uniqWith](../../array/uniqWith.md)를 사용하세요. - -::: - -배열에서 비교 함수를 사용하여 중복을 제거하고 유일한 요소들로 구성된 새 배열을 만들어요. - -```typescript -const result = uniqWith(array, comparator); -``` - -## 사용법 - -### `uniqWith(array, comparator)` - -배열의 각 요소를 비교 함수로 비교하여 중복을 제거해요. 비교 함수가 `true`를 반환하면 두 요소를 같다고 판단하고, 첫 번째로 나타나는 요소만 유지해요. 비교 함수를 제공하지 않으면 기본적으로 얕은 동등성 비교를 사용해요. - -```typescript -import { uniqWith } from 'es-toolkit/compat'; - -// 비교 함수 없이 사용 (얕은 동등성 비교) -uniqWith([1, 2, 2, 3]); -// Returns: [1, 2, 3] - -// 사용자 정의 비교 함수로 홀수/짝수 기준 중복 제거 -uniqWith([1, 2, 3, 4], (a, b) => a % 2 === b % 2); -// Returns: [1, 2] - -// 객체 배열에서 속성 기준 중복 제거 -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 1, y: 2 }, -]; -uniqWith(objects, (a, b) => a.x === b.x && a.y === b.y); -// Returns: [{ x: 1, y: 2 }, { x: 2, y: 1 }] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { uniqWith } from 'es-toolkit/compat'; - -uniqWith(null); // [] -uniqWith(undefined); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 중복을 제거할 배열이에요. -- `comparator` (`(a: T, b: T) => boolean`, 선택): 두 요소가 같은지 비교할 함수예요. `true`를 반환하면 같다고 판단해요. 기본값은 얕은 동등성 비교예요. - -#### 반환 값 - -(`T[]`): 비교 함수 결과를 기준으로 중복이 제거된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/unzip.md b/docs/ko/reference/compat/array/unzip.md deleted file mode 100644 index db206d43f..000000000 --- a/docs/ko/reference/compat/array/unzip.md +++ /dev/null @@ -1,68 +0,0 @@ -# unzip (Lodash 호환성) - -::: warning `es-toolkit`의 [unzip](../../array/unzip.md)를 사용하세요 - -이 `unzip` 함수는 `null`이나 `undefined` 처리, 배열이 아닌 값 필터링 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [unzip](../../array/unzip.md)를 사용하세요. - -::: - -묶여있는 배열의 같은 위치에 있는 요소들을 모아서 새 배열로 만들어요. - -```typescript -const result = unzip(array); -``` - -## 사용법 - -### `unzip(array)` - -중첩된 배열에서 같은 인덱스에 있는 요소들을 모아서 새로운 배열로 반환해요. `zip` 함수의 반대 동작을 수행해요. 행렬을 전치하거나 구조화된 데이터를 재정렬할 때 유용해요. - -```typescript -import { unzip } from 'es-toolkit/compat'; - -// 문자열과 불린, 숫자가 섞인 배열 언집 -const zipped = [ - ['a', true, 1], - ['b', false, 2], -]; -const result = unzip(zipped); -// Returns: [['a', 'b'], [true, false], [1, 2]] - -// 숫자 배열들 언집 -const numbers = [ - [1, 4], - [2, 5], - [3, 6], -]; -unzip(numbers); -// Returns: [[1, 2, 3], [4, 5, 6]] - -// 길이가 다른 배열들도 처리 -const uneven = [ - ['a', 1], - ['b', 2, true], -]; -unzip(uneven); -// Returns: [['a', 'b'], [1, 2], [undefined, true]] -``` - -`null`이나 `undefined`, 빈 배열은 빈 배열로 처리해요. - -```typescript -import { unzip } from 'es-toolkit/compat'; - -unzip(null); // [] -unzip(undefined); // [] -unzip([]); // [] -``` - -#### 파라미터 - -- `array` (`T[][] | ArrayLike> | null | undefined`): 언집할 중첩 배열이에요. 각 내부 배열의 같은 위치 요소들이 모여요. - -#### 반환 값 - -(`T[][]`): 같은 위치의 요소들이 모인 새로운 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/unzipWith.md b/docs/ko/reference/compat/array/unzipWith.md deleted file mode 100644 index d4c6e5392..000000000 --- a/docs/ko/reference/compat/array/unzipWith.md +++ /dev/null @@ -1,84 +0,0 @@ -# unzipWith (Lodash 호환성) - -::: warning `es-toolkit`의 `unzipWith`를 사용하세요 - -이 `unzipWith` 함수는 `null`이나 `undefined` 처리, `ArrayLike` 타입 처리, 다양한 조건 함수 형태 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [unzipWith](../../array/unzipWith.md)를 사용하세요. - -::: - -묶여있는 배열의 같은 위치에 있는 요소들을 모아서 변환 함수를 적용한 새 배열을 만들어요. - -```typescript -const result = unzipWith(array, iteratee); -``` - -## 사용법 - -### `unzipWith(array, iteratee)` - -중첩된 배열에서 같은 인덱스에 있는 요소들을 모아서 변환 함수를 적용해요. `unzip` 함수와 비슷하지만, 각 그룹에 변환 함수를 적용할 수 있어요. 변환 함수를 제공하지 않으면 기본 `unzip` 동작을 수행해요. - -```typescript -import { unzipWith } from 'es-toolkit/compat'; - -// 같은 위치의 요소들을 더하기 -unzipWith( - [ - [1, 10, 100], - [2, 20, 200], - ], - (a, b) => a + b -); -// Returns: [3, 30, 300] - -// 변환 함수 없이 사용 (기본 unzip 동작) -unzipWith([ - [1, 4], - [2, 5], - [3, 6], -]); -// Returns: [[1, 2, 3], [4, 5, 6]] - -// 문자열 연결 -unzipWith( - [ - ['a', 'x'], - ['b', 'y'], - ['c', 'z'], - ], - (a, b) => a + b -); -// Returns: ['abc', 'xyz'] - -// 최대값 찾기 -unzipWith( - [ - [1, 10], - [2, 20], - [3, 5], - ], - Math.max -); -// Returns: [3, 20] -``` - -`null`이나 `undefined`, 빈 배열은 빈 배열로 처리해요. - -```typescript -import { unzipWith } from 'es-toolkit/compat'; - -unzipWith(null, (a, b) => a + b); // [] -unzipWith(undefined, (a, b) => a + b); // [] -unzipWith([], (a, b) => a + b); // [] -``` - -#### 파라미터 - -- `array` (`ArrayLike> | null | undefined`): 언집할 중첩 배열이에요. -- `iteratee` (`(...values: T[]) => R`, 선택): 각 그룹의 요소들에 적용할 변환 함수예요. 제공하지 않으면 기본 `unzip` 동작을 수행해요. - -#### 반환 값 - -(`R[]` 또는 `T[][]`): 변환 함수가 있으면 변환된 결과 배열을, 없으면 언집된 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/without.md b/docs/ko/reference/compat/array/without.md deleted file mode 100644 index 29a37a9a4..000000000 --- a/docs/ko/reference/compat/array/without.md +++ /dev/null @@ -1,49 +0,0 @@ -# without (Lodash 호환성) - -::: warning `es-toolkit`의 [without](../../array/without.md)을 사용하세요 - -이 `without` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [without](../../array/without.md)을 사용하세요. - -::: - -배열에서 지정된 값들을 제외한 새로운 배열을 만들어요. - -```typescript -const result = without([1, 2, 3, 4, 5], 2, 4); -// result는 [1, 3, 5]가 돼요. -``` - -## 사용법 - -### `without(array, ...values)` - -배열에서 지정된 값들을 제거한 새로운 배열을 반환해요. 원본 배열은 변경되지 않아요. - -```typescript -import { without } from 'es-toolkit/compat'; - -// 숫자 배열에서 여러 값 제거 -const numbers = [1, 2, 3, 4, 5, 2, 4]; -const result1 = without(numbers, 2, 4); -// Returns: [1, 3, 5] - -// 문자열 배열에서 값 제거 -const fruits = ['apple', 'banana', 'cherry', 'banana']; -const result2 = without(fruits, 'banana'); -// Returns: ['apple', 'cherry'] - -// 빈 배열 처리 -const result3 = without([], 1, 2, 3); -// Returns: [] -``` - -#### 파라미터 - -- `array` (`T[]`): 처리할 원본 배열이에요. -- `...values` (`T[]`): 제거할 값들이에요. - -#### 반환 값 - -(`T[]`): 지정된 값들을 제거한 새로운 배열이에요. diff --git a/docs/ko/reference/compat/array/xor.md b/docs/ko/reference/compat/array/xor.md deleted file mode 100644 index ce89c510b..000000000 --- a/docs/ko/reference/compat/array/xor.md +++ /dev/null @@ -1,61 +0,0 @@ -# xor (Lodash 호환성) - -::: warning `es-toolkit`의 [xor](../../array/xor.md)을 사용하세요 - -이 `xor` 함수는 `null`이나 `undefined` 처리, 복잡한 중복 계산 로직 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [xor](../../array/xor.md)를 사용하세요. - -::: - -여러 배열들에서 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 만들어요. - -```typescript -const result = xor(...arrays); -``` - -## 사용법 - -### `xor(...arrays)` - -여러 배열의 대칭 차집합을 계산해요. 즉, 주어진 배열들 중 정확히 하나의 배열에만 존재하는 요소들을 반환해요. 두 개 이상의 배열을 비교할 때 겹치지 않는 고유한 요소들을 찾고 싶을 때 유용해요. - -```typescript -import { xor } from 'es-toolkit/compat'; - -// 두 배열의 대칭 차집합 -xor([1, 2, 3, 4], [3, 4, 5, 6]); -// Returns: [1, 2, 5, 6] - -// 세 배열의 대칭 차집합 -xor([1, 2], [2, 3], [4, 5]); -// Returns: [1, 3, 4, 5] - -// 문자열 배열 -xor(['a', 'b'], ['b', 'c']); -// Returns: ['a', 'c'] - -// 하나의 배열만 제공 -xor([1, 2, 3]); -// Returns: [1, 2, 3] -``` - -`null`이나 `undefined`, 빈 배열은 무시되고 유효한 배열만 처리해요. - -```typescript -import { xor } from 'es-toolkit/compat'; - -xor([1, 2], null, [2, 3]); -// Returns: [1, 3] - -xor([], [1, 2], [2, 3]); -// Returns: [1, 3] -``` - -#### 파라미터 - -- `...arrays` (`Array | null | undefined>`): 대칭 차집합을 계산할 배열들이에요. `null`이나 `undefined`는 무시돼요. - -#### 반환 값 - -(`T[]`): 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/xorBy.md b/docs/ko/reference/compat/array/xorBy.md deleted file mode 100644 index 5b5231f90..000000000 --- a/docs/ko/reference/compat/array/xorBy.md +++ /dev/null @@ -1,63 +0,0 @@ -# xorBy (Lodash 호환성) - -::: warning `es-toolkit`의 [xorBy](../../array/xorBy.md)을 사용하세요 - -이 `xorBy` 함수는 `null`이나 `undefined` 처리, 복잡한 중복 계산 로직 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [xorBy](../../array/xorBy.md)를 사용하세요. - -::: - -여러 배열들에서 변환 함수를 기준으로 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 만들어요. - -```typescript -const result = xorBy(...arrays, iteratee); -``` - -## 사용법 - -### `xorBy(...arrays, iteratee)` - -여러 배열의 대칭 차집합을 변환 함수를 기준으로 계산해요. 각 요소에 변환 함수를 적용한 결과가 정확히 하나의 배열에만 존재하는 요소들을 반환해요. 객체 배열에서 특정 속성을 기준으로 비교하거나, 숫자 배열에서 특정 계산 결과를 기준으로 비교할 때 유용해요. - -```typescript -import { xorBy } from 'es-toolkit/compat'; - -// Math.floor 결과로 대칭 차집합 계산 -xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); -// Returns: [1.2, 4.3] - -// 객체 속성으로 대칭 차집합 계산 -xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); -// Returns: [{ x: 2 }] - -// 함수로 대칭 차집합 계산 -const users1 = [{ name: 'John', age: 30 }]; -const users2 = [ - { name: 'Jane', age: 25 }, - { name: 'John', age: 30 }, -]; -xorBy(users1, users2, user => user.name); -// Returns: [{ name: 'Jane', age: 25 }] - -// 세 배열의 대칭 차집합 -xorBy([1.2, 2.3], [3.4, 4.5], [5.6, 6.7], Math.floor); -// Returns: [1.2, 2.3, 3.4, 4.5, 5.6, 6.7] -``` - -`null`이나 `undefined`는 무시돼요. - -```typescript -import { xorBy } from 'es-toolkit/compat'; - -xorBy([2.1, 1.2], null, [4.3, 2.4], Math.floor); -// Returns: [1.2, 4.3] -``` - -#### 파라미터 - -- `...arrays` (`Array | null | undefined | ValueIteratee>`): 대칭 차집합을 계산할 배열들과 마지막에 변환 함수예요. 함수, 속성 이름, 부분 객체 등을 사용할 수 있어요. - -#### 반환 값 - -(`T[]`): 변환 함수 결과를 기준으로 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/xorWith.md b/docs/ko/reference/compat/array/xorWith.md deleted file mode 100644 index a692238ce..000000000 --- a/docs/ko/reference/compat/array/xorWith.md +++ /dev/null @@ -1,66 +0,0 @@ -# xorWith (Lodash 호환성) - -::: warning `es-toolkit`의 [xorWith](../../array/xorWith.md)을 사용하세요 - -이 `xorWith` 함수는 `null`이나 `undefined` 처리, 복잡한 중복 계산 로직 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [xorWith](../../array/xorWith.md)를 사용하세요. - -::: - -여러 배열들에서 비교 함수를 사용하여 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 만들어요. - -```typescript -const result = xorWith(...arrays, comparator); -``` - -## 사용법 - -### `xorWith(...arrays, comparator)` - -여러 배열의 대칭 차집합을 비교 함수를 사용하여 계산해요. 비교 함수가 `true`를 반환하면 두 요소를 같다고 판단하고, 정확히 하나의 배열에만 존재하는 요소들을 반환해요. 복잡한 객체나 사용자 정의 비교 로직이 필요할 때 유용해요. - -```typescript -import { xorWith } from 'es-toolkit/compat'; - -// 간단한 숫자 비교 -xorWith([1, 2], [2, 3], (a, b) => a === b); -// Returns: [1, 3] - -// 객체의 속성 비교 -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, -]; -const others = [ - { x: 1, y: 1 }, - { x: 1, y: 2 }, -]; -xorWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); -// Returns: [{ x: 2, y: 1 }, { x: 1, y: 1 }] - -// 세 배열의 대칭 차집합 -xorWith([1], [2], [3], (a, b) => a === b); -// Returns: [1, 2, 3] - -// 문자열 길이로 비교 -xorWith(['hello'], ['world', 'hi'], (a, b) => a.length === b.length); -// Returns: ['hi'] -``` - -비교 함수를 제공하지 않으면 기본적으로 얕은 동등성 비교를 사용해요. - -```typescript -import { xorWith } from 'es-toolkit/compat'; - -xorWith([1, 2], [2, 3]); -// Returns: [1, 3] -``` - -#### 파라미터 - -- `...arrays` (`Array | null | undefined | ((a: T, b: T) => boolean)>`): 대칭 차집합을 계산할 배열들과 마지막에 비교 함수예요. 비교 함수는 두 요소가 같으면 `true`를 반환해야 해요. - -#### 반환 값 - -(`T[]`): 비교 함수 결과를 기준으로 정확히 하나의 배열에만 존재하는 요소들로 구성된 새 배열을 반환해요. diff --git a/docs/ko/reference/compat/array/zip.md b/docs/ko/reference/compat/array/zip.md deleted file mode 100644 index a3f6438c0..000000000 --- a/docs/ko/reference/compat/array/zip.md +++ /dev/null @@ -1,48 +0,0 @@ -# zip (Lodash 호환성) - -::: warning `es-toolkit`의 [zip](../../array/zip.md)을 사용하세요 - -이 `zip` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [zip](../../array/zip.md)을 사용하세요. - -::: - -여러 배열을 튜플의 단일 배열로 결합해요. - -```typescript -const result = zip([1, 2], ['a', 'b']); -// result는 [[1, 'a'], [2, 'b']]가 돼요. -``` - -## 사용법 - -### `zip(...arrs)` - -여러 배열을 받아서 각 인덱스의 요소들을 하나의 튜플로 묶어 새로운 배열을 만들어요. 입력 배열의 길이가 다를 경우, 결과 배열의 길이는 가장 긴 입력 배열의 길이를 가지며, 누락된 요소는 `undefined`로 채워져요. - -```typescript -import { zip } from 'es-toolkit/compat'; - -const arr1 = [1, 2, 3]; -const arr2 = ['a', 'b', 'c']; -const result = zip(arr1, arr2); -// Returns: [[1, 'a'], [2, 'b'], [3, 'c']] - -// 길이가 다른 배열들 -const arr3 = [true, false]; -const result2 = zip(arr1, arr2, arr3); -// Returns: [[1, 'a', true], [2, 'b', false], [3, 'c', undefined]] - -// 빈 배열이 포함된 경우 -zip([1, 2], [], ['a', 'b']); -// Returns: [[1, undefined, 'a'], [2, undefined, 'b']] -``` - -#### 파라미터 - -- `...arrs` (`any[][]`): 결합할 배열들이에요. - -#### 반환 값 - -(`any[][]`): 입력 배열들의 각 인덱스 요소들을 포함하는 튜플로 이루어진 새로운 배열이에요. diff --git a/docs/ko/reference/compat/array/zipObject.md b/docs/ko/reference/compat/array/zipObject.md deleted file mode 100644 index 3352b390f..000000000 --- a/docs/ko/reference/compat/array/zipObject.md +++ /dev/null @@ -1,50 +0,0 @@ -# zipObject (Lodash 호환성) - -::: warning `es-toolkit`의 [zipObject](../../array/zipObject.md)를 사용하세요 - -이 `zipObject` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [zipObject](../../array/zipObject.md)를 사용하세요. - -::: - -두 배열을 사용해서 객체를 만들어요. 첫 번째 배열은 버전망을 프로퍼티 이름으로, 두 번째 배열은 해당 값으로 사용해요. - -```typescript -const result = zipObject(keys, values); -``` - -## 사용법 - -### `zipObject(keys, values)` - -키 배열과 값 배열을 받아서 하나의 객체로 만들고 싶을 때 `zipObject`를 사용하세요. 첫 번째 배열의 요소들을 프로퍼티 이름으로, 두 번째 배열의 요소들을 해당 값으로 사용해서 객체를 만들어요. API 응답을 처리하거나 데이터를 변환할 때 특히 유용해요. - -```typescript -import { zipObject } from 'es-toolkit/compat'; - -// 기본 사용법 -const keys = ['a', 'b', 'c']; -const values = [1, 2, 3]; -const result = zipObject(keys, values); -// Returns: { a: 1, b: 2, c: 3 } - -// 길이가 다른 배열들 -const keys2 = ['x', 'y', 'z']; -const values2 = [10, 20]; -const result2 = zipObject(keys2, values2); -// Returns: { x: 10, y: 20, z: undefined } - -// 빈 배열이 전달된 경우 -const result3 = zipObject([], []); -// Returns: {} -``` - -#### 파라미터 - -- `keys` (`PropertyKey[]`): 프로퍼티 이름으로 사용할 배열이에요. -- `values` (`T[]`): 프로퍼티 값으로 사용할 배열이에요. - -#### 반환 값 - -(`Record`): 만들어진 객체예요. diff --git a/docs/ko/reference/compat/array/zipWith.md b/docs/ko/reference/compat/array/zipWith.md deleted file mode 100644 index 74492cce9..000000000 --- a/docs/ko/reference/compat/array/zipWith.md +++ /dev/null @@ -1,47 +0,0 @@ -# zipWith (Lodash 호환성) - -::: warning `es-toolkit`의 [zipWith](../../array/zipWith.md)을 사용하세요 - -이 `zipWith` 함수는 Lodash와의 호환성을 위해 추가적인 처리가 포함되어 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [zipWith](../../array/zipWith.md)을 사용하세요. - -::: - -여러 배열의 요소를 결합 함수를 사용해서 새로운 배열로 결합해요. - -```typescript -const result = zipWith([1, 2], [3, 4], (a, b) => a + b); -// result는 [4, 6]이 돼요. -``` - -## 사용법 - -### `zipWith(...arrs, iteratee)` - -여러 배열을 받아서 각 인덱스의 요소들을 제공된 함수로 결합하여 새로운 배열을 만들어요. 배열의 길이가 다를 경우, 가장 긴 배열의 길이까지 처리하며 누락된 값은 `undefined`로 전달돼요. - -```typescript -import { zipWith } from 'es-toolkit/compat'; - -// 두 배열의 요소를 더하기 -const result1 = zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b); -// Returns: [5, 7, 9] - -// 세 배열의 요소를 결합 -const result2 = zipWith([1, 2], [3, 4], [5, 6], (a, b, c) => a + b + c); -// Returns: [9, 12] - -// 길이가 다른 배열들 -const result3 = zipWith([1, 2, 3], [4, 5], (a, b) => (a || 0) + (b || 0)); -// Returns: [5, 7, 3] -``` - -#### 파라미터 - -- `...arrs` (`any[][]`): 결합할 배열들이에요. -- `iteratee` (`Function`): 각 인덱스의 요소들을 결합하는 함수예요. - -#### 반환 값 - -(`any[]`): 결합 함수를 적용한 결과로 이루어진 새로운 배열이에요. diff --git a/docs/ko/reference/compat/function/after.md b/docs/ko/reference/compat/function/after.md deleted file mode 100644 index 18373c2b8..000000000 --- a/docs/ko/reference/compat/function/after.md +++ /dev/null @@ -1,75 +0,0 @@ -# after (Lodash 호환성) - -::: warning `es-toolkit`의 [`after`](../../function/after.md)를 사용하세요 - -이 `after` 함수는 복잡한 타입 검증과 정수 변환 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [after](../../function/after.md)를 사용하세요. - -::: - -함수가 지정된 호출 횟수 이후에만 실행되도록 하는 함수를 만들어요. - -```typescript -const restrictedFunction = after(n, func); -``` - -## 사용법 - -### `after(n, func)` - -함수가 특정 횟수만큼 호출된 후에야 실행되도록 제한하고 싶을 때 `after`를 사용하세요. 여러 비동기 작업이 완료된 후 콜백을 실행하거나, 초기화 단계를 거친 후 함수를 활성화할 때 유용해요. - -```typescript -import { after } from 'es-toolkit/compat'; - -// 기본 사용법 -const logAfterThree = after(3, () => { - console.log('3번째 호출부터 실행돼요!'); -}); - -logAfterThree(); // 실행되지 않음 -logAfterThree(); // 실행되지 않음 -logAfterThree(); // "3번째 호출부터 실행돼요!" 출력 -logAfterThree(); // "3번째 호출부터 실행돼요!" 출력 (계속 실행됨) -``` - -여러 비동기 작업이 모두 완료된 후에 특정 콜백을 실행할 때도 사용할 수 있어요. - -```typescript -import { after } from 'es-toolkit/compat'; - -const tasks = ['task1', 'task2', 'task3']; -const allTasksComplete = after(tasks.length, () => { - console.log('모든 작업이 완료되었습니다!'); -}); - -// 각 작업이 완료될 때마다 호출 -tasks.forEach(task => { - performAsyncTask(task, () => { - console.log(`${task} 완료`); - allTasksComplete(); // 3번째 호출에서 "모든 작업이 완료되었습니다!" 출력 - }); -}); -``` - -0이나 음수를 전달하면 첫 번째 호출부터 바로 실행돼요. - -```typescript -import { after } from 'es-toolkit/compat'; - -const immediate = after(0, () => console.log('즉시 실행')); -immediate(); // "즉시 실행" - -const negative = after(-1, () => console.log('즉시 실행')); -negative(); // "즉시 실행" -``` - -#### 파라미터 - -- `n` (`number`): 함수가 실행되기 전에 필요한 호출 횟수예요. -- `func` (`TFunc`): 제한할 함수예요. - -#### 반환 값 - -(`TFunc`): n번째 호출부터 원본 함수를 실행하는 새로운 제한된 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/ary.md b/docs/ko/reference/compat/function/ary.md deleted file mode 100644 index 386515648..000000000 --- a/docs/ko/reference/compat/function/ary.md +++ /dev/null @@ -1,90 +0,0 @@ -# ary (Lodash 호환성) - -::: warning `es-toolkit`의 [`ary`](../../function/ary.md)를 사용하세요 - -이 `ary` 함수는 파라미터를 복잡하게 검증하고 있어서 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [ary](../../function/ary.md)를 사용하세요. - -::: - -함수가 받을 수 있는 인수의 개수를 제한하는 함수를 만들어요. - -```typescript -const cappedFunction = ary(func, n); -``` - -## 사용법 - -### `ary(func, n)` - -함수가 받는 인수의 개수를 제한하고 싶을 때 `ary`를 사용하세요. 너무 많은 인수를 받는 함수를 안전하게 사용하거나, 콜백 함수에서 불필요한 인수를 무시할 때 유용해요. - -```typescript -import { ary } from 'es-toolkit/compat'; - -// 기본 사용법 -function greet(name, age, city) { - return `안녕하세요, ${name}님! ${age}세, ${city}에서 오셨군요.`; -} - -const limitedGreet = ary(greet, 2); -console.log(limitedGreet('김철수', 30, '서울', '추가인수')); -// "안녕하세요, 김철수님! 30세, undefined에서 오셨군요." -// 3번째 인수부터는 무시됨 -``` - -배열 메서드와 함께 사용할 때 콜백 함수에 불필요한 인자가 전달되지 않도록 할 수 있어요. - -```typescript -import { ary } from 'es-toolkit/compat'; - -// parseInt는 두 번째 인수(기수)를 받지만, map의 콜백은 3개 인수를 전달함 -const numbers = ['1', '2', '3', '4', '5']; - -// 잘못된 사용 - parseInt가 인덱스를 기수로 받음 -console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] - -// ary를 사용해서 첫 번째 인수만 전달 -console.log(numbers.map(ary(parseInt, 1))); // [1, 2, 3, 4, 5] -``` - -함수가 원하는 파라미터 인자 숫자만 받도록 제한할 수 있어요. - -```typescript -import { ary } from 'es-toolkit/compat'; - -function sum(...args) { - return args.reduce((total, num) => total + num, 0); -} - -const sum0 = ary(sum, 0); -const sum1 = ary(sum, 1); -const sum2 = ary(sum, 2); -const sum3 = ary(sum, 3); - -console.log(sum0(1, 2, 3, 4, 5)); // 0 (인수 없음) -console.log(sum1(1, 2, 3, 4, 5)); // 1 (첫 번째 인수만) -console.log(sum2(1, 2, 3, 4, 5)); // 3 (첫 두 인수만) -console.log(sum3(1, 2, 3, 4, 5)); // 6 (첫 세 인수만) -``` - -음수나 `NaN`을 전달하면 0으로 처리되어 모든 인수가 무시돼요. - -```typescript -import { ary } from 'es-toolkit/compat'; - -const func = (a, b, c) => [a, b, c]; - -console.log(ary(func, -1)(1, 2, 3)); // [] (음수는 0으로 처리) -console.log(ary(func, NaN)(1, 2, 3)); // [] (NaN은 0으로 처리) -``` - -#### 파라미터 - -- `func` (`Function`): 인수 개수를 제한할 함수예요. -- `n` (`number`, 선택): 허용할 최대 인수 개수예요. 생략하면 함수의 `length` 속성을 사용해요. - -#### 반환 값 - -(`Function`): 최대 `n`개의 인수만 받는 새로운 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/attempt.md b/docs/ko/reference/compat/function/attempt.md deleted file mode 100644 index e7bfca1cc..000000000 --- a/docs/ko/reference/compat/function/attempt.md +++ /dev/null @@ -1,66 +0,0 @@ -# attempt (Lodash 호환성) - -::: warning `es-toolkit`의 [`attempt`](../../util/attempt.md) 함수나 try-catch 블록을 사용하세요 - -이 `attempt` 함수는 에러와 반환 값을 구분하지 않고 반환해서 사용할 때 혼란이 있을 수 있어요. - -대신 더 직접적이고 명확한 [`attempt`](../../util/attempt.md) 함수나 try-catch 블록을 사용하세요. - -::: - -함수를 실행하고 에러가 발생하면 에러 객체를 반환하는 함수예요. - -```typescript -const result = attempt(func, ...args); -``` - -## 사용법 - -### `attempt(func, ...args)` - -함수를 안전하게 실행하고 싶을 때 `attempt`를 사용하세요. 에러가 발생할 수 있는 함수를 실행할 때 프로그램이 중단되지 않도록 하고, 에러를 반환값으로 처리할 때 유용해요. - -```typescript -import { attempt } from 'es-toolkit/compat'; - -// 기본 사용법 - 성공하는 경우 -const result = attempt((x, y) => x + y, 2, 3); -console.log(result); // 5 - -// 에러가 발생하는 경우 -const errorResult = attempt(() => { - throw new Error('뭔가 잘못됐어요'); -}); -console.log(errorResult); // Error: 뭔가 잘못됐어요 -``` - -try-catch 블록 사용과의 차이점을 살펴보면 다음과 같아요. - -```typescript -// attempt 사용 -import { attempt } from 'es-toolkit/compat'; - -const result = attempt(riskyFunction, arg1, arg2); -if (result instanceof Error) { - console.log('에러 발생:', result.message); -} else { - console.log('결과:', result); -} - -// try-catch 사용 (더 직접적) -try { - const result = riskyFunction(arg1, arg2); - console.log('결과:', result); -} catch (error) { - console.log('에러 발생:', error.message); -} -``` - -#### 파라미터 - -- `func` (`Function`): 실행할 함수예요. -- `args` (`...any[]`): 함수에 전달할 인수들이에요. - -#### 반환 값 - -(`ReturnType | Error`): 함수가 성공하면 반환값을, 에러가 발생하면 Error 객체를 반환해요. diff --git a/docs/ko/reference/compat/function/before.md b/docs/ko/reference/compat/function/before.md deleted file mode 100644 index bace60152..000000000 --- a/docs/ko/reference/compat/function/before.md +++ /dev/null @@ -1,186 +0,0 @@ -# before (Lodash 호환성) - -::: warning `es-toolkit`의 [`before`](../../function/before.md)를 사용하세요 - -이 `before` 함수는 복잡한 타입 검증과 정수 변환 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [before](../../function/before.md)를 사용하세요. - -::: - -함수를 지정된 횟수까지만 실행하고, 그 이후엔 마지막 결과를 반환하는 함수를 만들어요. - -```typescript -const limitedFunction = before(n, func); -``` - -## 사용법 - -### `before(n, func)` - -함수가 특정 횟수까지만 실행되도록 제한하고 싶을 때 `before`를 사용하세요. 함수 호출 횟수를 제한하거나, 초기 설정 단계에서만 함수를 실행하고 싶을 때 유용해요. - -```typescript -import { before } from 'es-toolkit/compat'; - -// 기본 사용법 -let count = 0; -const beforeThree = before(3, () => ++count); - -console.log(beforeThree()); // 1 (첫 번째 호출) -console.log(beforeThree()); // 2 (두 번째 호출) -console.log(beforeThree()); // 2 (세 번째 호출부터는 마지막 결과 반환) -console.log(beforeThree()); // 2 (계속 마지막 결과만 반환) -``` - -클로저를 사용한 대안: - -```typescript -// before 사용 -const beforeThree = before(3, myFunction); - -// 클로저 사용 (더 간단하고 빠름) -function createBefore(limit, callback) { - let callCount = 0; - let lastResult; - - return function (...args) { - if (callCount < limit - 1) { - lastResult = callback.apply(this, args); - callCount++; - } - return lastResult; - }; -} - -const beforeThreeAlternative = createBefore(3, myFunction); -``` - -초기화 함수로 활용: - -```typescript -import { before } from 'es-toolkit/compat'; - -class Database { - constructor() { - this.isInitialized = false; - - // 초기화는 한 번만 실행 - this.initialize = before(2, () => { - console.log('데이터베이스 초기화 중...'); - this.setupConnection(); - this.isInitialized = true; - return '초기화 완료'; - }); - } - - setupConnection() { - // 실제 연결 설정 로직 - } - - query(sql) { - const initResult = this.initialize(); - console.log(initResult); // 첫 번째 호출: "초기화 완료", 이후: 동일 결과 - - // 쿼리 실행 로직 - return `쿼리 실행: ${sql}`; - } -} - -const db = new Database(); -db.query('SELECT * FROM users'); // 초기화 실행됨 -db.query('SELECT * FROM products'); // 초기화는 실행되지 않음 -``` - -API 호출 제한: - -```typescript -import { before } from 'es-toolkit/compat'; - -// API 호출을 최대 5번까지만 허용 -const limitedApiCall = before(6, endpoint => { - console.log(`API 호출: ${endpoint}`); - return fetch(endpoint).then(res => res.json()); -}); - -// 처음 5번은 실제 API 호출 -limitedApiCall('/api/data1'); // 실제 호출 -limitedApiCall('/api/data2'); // 실제 호출 -limitedApiCall('/api/data3'); // 실제 호출 -limitedApiCall('/api/data4'); // 실제 호출 -limitedApiCall('/api/data5'); // 실제 호출 -limitedApiCall('/api/data6'); // 마지막 결과 반환 (API 호출 안 함) -``` - -이벤트 리스너 제한: - -```typescript -import { before } from 'es-toolkit/compat'; - -// 클릭 이벤트를 3번까지만 처리 -const limitedClickHandler = before(4, event => { - console.log('클릭 처리됨:', event.target.id); - return `처리 완료: ${Date.now()}`; -}); - -document.getElementById('button').addEventListener('click', limitedClickHandler); -// 처음 3번 클릭만 처리되고, 그 이후엔 마지막 결과만 반환 -``` - -파라미터와 반환값 처리: - -```typescript -import { before } from 'es-toolkit/compat'; - -const limitedCalculator = before(3, (operation, a, b) => { - const result = operation === 'add' ? a + b : a - b; - console.log(`계산: ${a} ${operation} ${b} = ${result}`); - return result; -}); - -console.log(limitedCalculator('add', 5, 3)); // "계산: 5 add 3 = 8", 반환: 8 -console.log(limitedCalculator('subtract', 10, 4)); // "계산: 10 subtract 4 = 6", 반환: 6 -console.log(limitedCalculator('multiply', 7, 2)); // 계산 안 함, 반환: 6 (마지막 결과) -``` - -0 또는 1을 전달하면 함수가 실행되지 않아요: - -```typescript -import { before } from 'es-toolkit/compat'; - -const neverCalled = before(0, () => { - console.log('이 함수는 실행되지 않아요'); - return '결과'; -}); - -const onceOnly = before(1, () => { - console.log('이 함수도 실행되지 않아요'); - return '결과'; -}); - -console.log(neverCalled()); // undefined -console.log(onceOnly()); // undefined -``` - -리소스 정리 최적화: - -```typescript -import { before } from 'es-toolkit/compat'; - -// 함수 참조가 자동으로 정리되어 메모리 누수 방지 -const limitedProcessor = before(2, data => { - // 복잡한 데이터 처리 - return processComplexData(data); -}); - -// 2번째 호출 이후에는 원본 함수 참조가 제거됨 (가비지 컬렉션) -``` - -#### 파라미터 - -- `n` (`number`): 함수를 실행할 최대 횟수예요. n-1번째까지 실행되고, n번째부터는 마지막 결과를 반환해요. -- `func` (`Function`): 제한할 함수예요. - -#### 반환 값 - -(`Function`): 지정된 횟수까지만 원본 함수를 실행하고, 그 이후엔 마지막 결과를 반환하는 새로운 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/curry.md b/docs/ko/reference/compat/function/curry.md deleted file mode 100644 index 8a3ab4e83..000000000 --- a/docs/ko/reference/compat/function/curry.md +++ /dev/null @@ -1,224 +0,0 @@ -# curry (Lodash 호환성) - -::: warning `es-toolkit`의 `curry`나 수동 클로저를 사용하세요 - -이 `curry` 함수는 복잡한 placeholder 처리, arity 검증, 인수 합성 로직으로 인해 느리게 동작해요. - -placeholder가 필요하지 않다면 대신 더 빠른 `es-toolkit`의 [`curry`](../../function/curry.md)나 간단한 클로저를 사용하세요. - -::: - -함수를 커링해서 인수를 하나씩 받거나 여러 개씩 받을 수 있는 함수를 만들어요. - -```typescript -const curriedFunction = curry(func, arity); -``` - -## 사용법 - -### `curry(func, arity)` - -함수를 커링해서 부분 적용을 쉽게 하고 싶을 때 `curry`를 사용하세요. 인수를 단계적으로 제공하거나 placeholder를 사용해서 특정 위치의 인수를 나중에 제공할 때 유용해요. - -```typescript -import { curry } from 'es-toolkit/compat'; - -// 기본 사용법 -function add(a, b, c) { - return a + b + c; -} - -const curriedAdd = curry(add); - -// 다양한 방식으로 호출 가능 -console.log(curriedAdd(1)(2)(3)); // 6 -console.log(curriedAdd(1, 2)(3)); // 6 -console.log(curriedAdd(1)(2, 3)); // 6 -console.log(curriedAdd(1, 2, 3)); // 6 -``` - -메인 라이브러리 curry와 비교: - -```typescript -// compat 버전 (유연함, 하지만 느림) -import { curry } from 'es-toolkit/compat'; -const curriedCompat = curry(add); -curriedCompat(1, 2)(3); // 지원됨 -curriedCompat(1)(curry.placeholder, 3)(2); // placeholder 지원 - -// 메인 라이브러리 버전 (더 빠름, 하지만 한 번에 하나씩만) -import { curry } from 'es-toolkit'; -const curriedMain = curry(add); -curriedMain(1)(2)(3); // 지원됨 -curriedMain(1, 2)(3); // 지원되지 않음 -``` - -placeholder 기능 사용: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function greet(greeting, name, punctuation) { - return `${greeting}, ${name}${punctuation}`; -} - -const curriedGreet = curry(greet); - -// placeholder로 중간 인수 건너뛰기 -const greetWithExclamation = curriedGreet(curry.placeholder, curry.placeholder, '!'); -console.log(greetWithExclamation('Hello', '김철수')); // "Hello, 김철수!" - -const sayHello = curriedGreet('Hello'); -console.log(sayHello(curry.placeholder, '~')('이영희')); // "Hello, 이영희~" -``` - -함수형 프로그래밍에서 활용: - -```typescript -import { curry } from 'es-toolkit/compat'; - -// 맵핑 함수 만들기 -const map = curry((fn, array) => array.map(fn)); -const filter = curry((predicate, array) => array.filter(predicate)); - -const numbers = [1, 2, 3, 4, 5]; - -// 재사용 가능한 함수들 생성 -const double = x => x * 2; -const isEven = x => x % 2 === 0; - -const mapDouble = map(double); -const filterEven = filter(isEven); - -console.log(mapDouble(numbers)); // [2, 4, 6, 8, 10] -console.log(filterEven(numbers)); // [2, 4] - -// 함수 합성 -const processNumbers = nums => mapDouble(filterEven(nums)); -console.log(processNumbers(numbers)); // [4, 8] -``` - -API 클라이언트 구성: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function apiRequest(method, baseUrl, endpoint, options) { - return fetch(`${baseUrl}${endpoint}`, { - method, - ...options, - }); -} - -const curriedApiRequest = curry(apiRequest); - -// 기본 설정으로 특화된 함수들 생성 -const apiGet = curriedApiRequest('GET', 'https://api.example.com'); -const apiPost = curriedApiRequest('POST', 'https://api.example.com'); - -// 인증 헤더 포함 -const authenticatedPost = apiPost(curry.placeholder, { - headers: { Authorization: 'Bearer token123' }, -}); - -// 사용 -apiGet('/users'); // GET https://api.example.com/users -authenticatedPost('/users'); // POST with auth headers -``` - -수학 연산 함수: - -```typescript -import { curry } from 'es-toolkit/compat'; - -const calculate = curry((operation, a, b) => { - switch (operation) { - case '+': - return a + b; - case '-': - return a - b; - case '*': - return a * b; - case '/': - return a / b; - default: - throw new Error('지원하지 않는 연산'); - } -}); - -// 특화된 연산 함수들 -const add = calculate('+'); -const subtract = calculate('-'); -const multiply = calculate('*'); - -console.log(add(5, 3)); // 8 -console.log(subtract(10)(4)); // 6 -console.log(multiply(3, 4)); // 12 - -// placeholder로 두 번째 피연산자 고정 -const addFive = calculate('+', curry.placeholder, 5); -console.log(addFive(10)); // 15 -``` - -Arity 지정: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function variableArgsFunction(a, b, c, ...rest) { - return [a, b, c, rest]; -} - -// arity를 3으로 제한 -const curriedFixed = curry(variableArgsFunction, 3); - -console.log(curriedFixed(1)(2)(3)); // [1, 2, 3, []] -console.log(curriedFixed(1, 2)(3)); // [1, 2, 3, []] - -// arity 없이 사용 (기본값: function.length) -const curriedDefault = curry(variableArgsFunction); // arity = 3 -``` - -간단한 커링 대안: - -```typescript -// curry 사용 -const curriedAdd = curry((a, b, c) => a + b + c); - -// 수동 클로저 (더 빠름) -const manualCurry = a => b => c => a + b + c; - -// 둘 다 같은 결과 -console.log(curriedAdd(1)(2)(3)); // 6 -console.log(manualCurry(1)(2)(3)); // 6 -``` - -생성자 함수도 지원: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function Person(name, age, city) { - this.name = name; - this.age = age; - this.city = city; -} - -const CurriedPerson = curry(Person); -const SeoulPerson = CurriedPerson(curry.placeholder, curry.placeholder, '서울'); - -const person1 = new SeoulPerson('김철수', 30); -const person2 = new SeoulPerson('이영희', 25); - -console.log(person1.city); // "서울" -console.log(person2.city); // "서울" -``` - -#### 파라미터 - -- `func` (`Function`): 커링할 함수예요. -- `arity` (`number`, 선택): 함수의 arity(인수 개수)예요. 생략하면 `func.length`를 사용해요. - -#### 반환 값 - -(`Function & { placeholder: symbol }`): 커링된 함수를 반환해요. `placeholder` 속성으로 인수 위치를 제어할 수 있어요. diff --git a/docs/ko/reference/compat/function/curryRight.md b/docs/ko/reference/compat/function/curryRight.md deleted file mode 100644 index 7685f462d..000000000 --- a/docs/ko/reference/compat/function/curryRight.md +++ /dev/null @@ -1,242 +0,0 @@ -# curryRight (Lodash 호환성) - -::: warning `es-toolkit`의 [`curryRight`](../../function/curryRight.md)나 수동 클로저를 사용하세요 - -이 `curryRight` 함수는 복잡한 placeholder 처리, arity 검증, 인수 합성 로직으로 인해 느리게 동작해요. - -placeholder가 필요하지 않다면 대신 더 빠른 `es-toolkit`의 [`curryRight`](../../function/curryRight.md)나 간단한 클로저를 사용하세요. - -::: - -함수를 오른쪽부터 커링해서 마지막 인수부터 하나씩 받거나 여러 개씩 받을 수 있는 함수를 만들어요. - -```typescript -const curriedFunction = curryRight(func, arity); -``` - -## 사용법 - -### `curryRight(func, arity)` - -함수를 오른쪽부터 커링해서 마지막 인수부터 부분 적용하고 싶을 때 `curryRight`를 사용하세요. 일반적인 `curry`와 달리 마지막 인수부터 먼저 받아서 처리해요. - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 기본 사용법 -function subtract(a, b, c) { - return a - b - c; -} - -const curriedSubtract = curryRight(subtract); - -// 오른쪽부터(마지막 인수부터) 커링 -console.log(curriedSubtract(1)(2)(5)); // 5 - 2 - 1 = 2 -console.log(curriedSubtract(1, 2)(5)); // 5 - 2 - 1 = 2 -console.log(curriedSubtract(1)(2, 5)); // 2 - 5 - 1 = -4 -console.log(curriedSubtract(1, 2, 5)); // 1 - 2 - 5 = -6 -``` - -`curry`와 `curryRight` 차이점: - -```typescript -import { curry, curryRight } from 'es-toolkit/compat'; - -function divide(a, b, c) { - return a / b / c; -} - -// 일반 curry (왼쪽부터) -const leftCurried = curry(divide); -console.log(leftCurried(12)(3)(2)); // ((12 / 3) / 2) = 2 - -// curryRight (오른쪽부터) -const rightCurried = curryRight(divide); -console.log(rightCurried(2)(3)(12)); // ((12 / 3) / 2) = 2 -// 마지막에 전달한 12가 첫 번째 인수(a)가 됨 -``` - -메인 라이브러리와 비교: - -```typescript -// compat 버전 (유연함, 하지만 느림) -import { curryRight } from 'es-toolkit/compat'; -const curriedCompat = curryRight(subtract); -curriedCompat(1, 2)(3); // 지원됨 -curriedCompat(1)(curryRight.placeholder, 3)(2); // placeholder 지원 - -// 메인 라이브러리 버전 (더 빠름, 하지만 한 번에 하나씩만) -import { curryRight } from 'es-toolkit'; -const curriedMain = curryRight(subtract); -curriedMain(1)(2)(3); // 지원됨 -curriedMain(1, 2)(3); // 지원되지 않음 -``` - -placeholder 기능 사용: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function formatMessage(name, action, time) { - return `${name}님이 ${action}을 ${time}에 했습니다`; -} - -const curriedFormat = curryRight(formatMessage); - -// placeholder로 특정 위치 건너뛰기 -const todayAction = curriedFormat('오늘'); -const todayLoginAction = todayAction(curryRight.placeholder, '로그인'); - -console.log(todayLoginAction('김철수')); -// "김철수님이 로그인을 오늘에 했습니다" - -// 시간을 먼저 고정 -const morningFormat = curriedFormat('아침 9시'); -console.log(morningFormat('댓글 작성', '이영희')); -// "이영희님이 댓글 작성을 아침 9시에 했습니다" -``` - -배열 처리에서 활용: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 배열에서 특정 개수만큼 뒤에서 자르기 -function takeFromEnd(array, count, separator = ', ') { - return array.slice(-count).join(separator); -} - -const curriedTake = curryRight(takeFromEnd); - -// 쉼표로 구분하는 함수 생성 -const takeWithComma = curriedTake(', '); - -// 마지막 3개 가져오기 -const takeLast3 = takeWithComma(3); - -const fruits = ['사과', '바나나', '오렌지', '포도', '키위']; -console.log(takeLast3(fruits)); // "오렌지, 포도, 키위" - -// 다른 구분자 사용 -const takeWithDash = curriedTake(' - '); -console.log(takeWithDash(2, fruits)); // "포도 - 키위" -``` - -함수 합성에서 활용: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 로그 출력 함수 -function logWithPrefix(message, level, timestamp) { - return `[${timestamp}] ${level}: ${message}`; -} - -const curriedLog = curryRight(logWithPrefix); - -// 현재 시간으로 고정 -const currentTimeLog = curriedLog(new Date().toISOString()); - -// 레벨별 로거 생성 -const errorLog = currentTimeLog('ERROR'); -const infoLog = currentTimeLog('INFO'); -const debugLog = currentTimeLog('DEBUG'); - -// 사용 -console.log(errorLog('데이터베이스 연결 실패')); -console.log(infoLog('서버 시작됨')); -console.log(debugLog('사용자 요청 처리 중')); -``` - -함수형 프로그래밍 파이프라인: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 데이터 변환 함수들 -const mapWith = curryRight((array, fn) => array.map(fn)); -const filterWith = curryRight((array, predicate) => array.filter(predicate)); -const reduceWith = curryRight((array, reducer, initial) => array.reduce(reducer, initial)); - -const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - -// 변환 함수들 정의 -const double = x => x * 2; -const isEven = x => x % 2 === 0; -const sum = (acc, val) => acc + val; - -// 파이프라인 구성 (오른쪽 먼저) -const processNumbers = nums => { - return reduceWith(filterWith(mapWith(nums, double), isEven), sum, 0); -}; - -console.log(processNumbers(numbers)); // 모든 수를 2배 후 짝수만 필터링해서 합계 -``` - -API 요청 빌더: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function makeRequest(url, method, headers, body) { - return fetch(url, { method, headers, body }); -} - -const curriedRequest = curryRight(makeRequest); - -// body부터 설정 -const withJsonBody = curriedRequest(JSON.stringify({ data: 'test' })); - -// headers 추가 -const withHeaders = withJsonBody({ - 'Content-Type': 'application/json', - Authorization: 'Bearer token123', -}); - -// POST 메서드 설정 -const postRequest = withHeaders('POST'); - -// 최종 사용 -postRequest('/api/data') - .then(response => response.json()) - .then(data => console.log(data)); -``` - -수동 커링 대안: - -```typescript -// curryRight 사용 -const curriedSubtract = curryRight((a, b, c) => a - b - c); - -// 수동 클로저 (더 빠름, 오른쪽부터) -const manualCurryRight = c => b => a => a - b - c; - -// 둘 다 같은 결과 -console.log(curriedSubtract(1)(2)(5)); // 2 -console.log(manualCurryRight(1)(2)(5)); // 2 -``` - -Arity 지정: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function variableArgsFunction(a, b, c, ...rest) { - return { a, b, c, rest }; -} - -// arity를 3으로 제한 (뒤의 rest는 무시) -const curriedFixed = curryRight(variableArgsFunction, 3); - -// 오른쪽부터 c, b, a 순서로 받음 -console.log(curriedFixed(3)(2)(1)); // { a: 1, b: 2, c: 3, rest: [] } -``` - -#### 파라미터 - -- `func` (`Function`): 오른쪽부터 커링할 함수예요. -- `arity` (`number`, 선택): 함수의 arity(인수 개수)예요. 생략하면 `func.length`를 사용해요. - -#### 반환 값 - -(`Function & { placeholder: symbol }`): 오른쪽부터 커링된 함수를 반환해요. `placeholder` 속성으로 인수 위치를 제어할 수 있어요. diff --git a/docs/ko/reference/compat/function/debounce.md b/docs/ko/reference/compat/function/debounce.md deleted file mode 100644 index f8d691a1f..000000000 --- a/docs/ko/reference/compat/function/debounce.md +++ /dev/null @@ -1,264 +0,0 @@ -# debounce (Lodash 호환성) - -::: warning `es-toolkit`의 [`debounce`](../../function/debounce.md)를 사용하세요 - -이 `debounce` 함수는 복잡한 `maxWait` 처리와 Lodash 호환 옵션 구조로 인해 오버헤드가 있어요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [`debounce`](../../function/debounce.md)를 사용하세요. - -::: - -함수 호출을 지연시키고, 마지막 호출 후 지정된 시간이 경과한 후에만 실행되도록 하는 디바운스 함수를 만들어요. - -```typescript -const debouncedFunction = debounce(func, wait, options); -``` - -## 사용법 - -### `debounce(func, wait, options)` - -함수 호출을 지연시키고 싶을 때 `debounce`를 사용하세요. 검색 입력, 스크롤 이벤트, 버튼 클릭 등에서 과도한 호출을 방지할 때 유용해요. - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// 기본 사용법 -const searchFunction = debounce(query => { - console.log('검색:', query); -}, 300); - -// 300ms 내에 다시 호출되지 않으면 실행 -searchFunction('리액트'); // 실행 안됨 -searchFunction('뷰'); // 실행 안됨 -searchFunction('앵귤러'); // 300ms 후에 "검색: 앵귤러" 출력 -``` - -메인 라이브러리 debounce와 비교: - -```typescript -// compat 버전 (Lodash 호환, maxWait 등 추가 옵션) -import { debounce } from 'es-toolkit/compat'; -const debouncedCompat = debounce(func, 300, { - leading: true, - trailing: false, - maxWait: 1000 -}); - -// 메인 라이브러리 버전 (더 빠름, 간단함) -import { debounce } from 'es-toolkit'; -const debouncedMain = debounce(func, 300, { - edges: ['leading'] // leading/trailing 대신 edges 사용 -}); -``` - -leading과 trailing 옵션: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const func = () => console.log('실행됨'); - -// leading: true - 첫 호출 시 즉시 실행 -const leadingDebounce = debounce(func, 1000, { leading: true }); -leadingDebounce(); // 즉시 "실행됨" 출력 -leadingDebounce(); // 1초 대기 -// 1초 후 추가 실행 없음 - -// trailing: true (기본값) - 마지막 호출 후 지연 시간 뒤 실행 -const trailingDebounce = debounce(func, 1000, { trailing: true }); -trailingDebounce(); // 1초 대기 -trailingDebounce(); // 1초 대기 (이전 타이머 취소) -// 1초 후 "실행됨" 출력 - -// 둘 다 true - 시작과 끝에서 실행 -const bothDebounce = debounce(func, 1000, { - leading: true, - trailing: true, -}); -bothDebounce(); // 즉시 "실행됨" 출력 -bothDebounce(); // 1초 대기 -// 1초 후 "실행됨" 출력 (trailing) -``` - -maxWait 옵션: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// 최대 2초마다는 반드시 실행 -const debouncedWithMaxWait = debounce(() => console.log('저장됨'), 500, { maxWait: 2000 }); - -// 빠르게 연속 호출해도 최대 2초마다는 실행됨 -setInterval(() => { - debouncedWithMaxWait(); -}, 100); // 100ms마다 호출하지만 2초마다 "저장됨" 출력 -``` - -실제 검색 예제: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -class SearchComponent { - constructor() { - this.searchInput = document.getElementById('search'); - - // 사용자 입력을 300ms 디바운스 - this.debouncedSearch = debounce(this.performSearch.bind(this), 300, { - leading: false, // 입력 시작시 즉시 검색하지 않음 - trailing: true, // 입력 멈춘 후 검색 - }); - - this.searchInput.addEventListener('input', e => { - this.debouncedSearch(e.target.value); - }); - } - - performSearch(query) { - if (query.length < 2) return; - - console.log('API 호출:', query); - // fetch(`/api/search?q=${query}`)... - } -} -``` - -스크롤 이벤트 최적화: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// 스크롤 이벤트를 100ms 디바운스하되, 최대 500ms마다는 실행 -const optimizedScrollHandler = debounce( - () => { - const scrollTop = window.pageYOffset; - console.log('스크롤 위치:', scrollTop); - - // 헤더 숨김/표시 로직 - if (scrollTop > 100) { - document.header.classList.add('hidden'); - } else { - document.header.classList.remove('hidden'); - } - }, - 100, - { maxWait: 500 } -); - -window.addEventListener('scroll', optimizedScrollHandler); -``` - -API 호출 제한: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -class AutoSave { - constructor() { - // 500ms 디바운스, 최대 5초마다는 저장 - this.debouncedSave = debounce(this.saveToServer.bind(this), 500, { maxWait: 5000 }); - } - - onTextChange(content) { - this.pendingContent = content; - this.debouncedSave(); - } - - saveToServer() { - if (!this.pendingContent) return; - - console.log('서버에 저장:', this.pendingContent); - // fetch('/api/save', { ... }) - - this.pendingContent = null; - } -} -``` - -cancel과 flush 메서드: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const debouncedFunc = debounce(() => { - console.log('실행됨'); -}, 1000); - -debouncedFunc(); // 1초 대기 중 - -// 대기 중인 실행을 취소 -debouncedFunc.cancel(); - -// 또는 즉시 실행 -debouncedFunc(); // 1초 대기 시작 -debouncedFunc.flush(); // 즉시 "실행됨" 출력하고 타이머 취소 -``` - -버튼 클릭 중복 방지: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const handleSubmit = debounce( - async formData => { - console.log('폼 제출 중...'); - try { - const response = await fetch('/api/submit', { - method: 'POST', - body: formData, - }); - console.log('제출 완료'); - } catch (error) { - console.error('제출 실패:', error); - } - }, - 1000, - { leading: true, trailing: false } // 첫 클릭만 처리 -); - -document.getElementById('submit-btn').addEventListener('click', e => { - const formData = new FormData(e.target.form); - handleSubmit(formData); -}); -``` - -리사이즈 이벤트 처리: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const handleResize = debounce( - () => { - const width = window.innerWidth; - const height = window.innerHeight; - - console.log('창 크기 변경:', { width, height }); - - // 레이아웃 재계산 - recalculateLayout(); - }, - 250, - { leading: false, trailing: true } -); - -window.addEventListener('resize', handleResize); - -// 페이지 종료 시 정리 -window.addEventListener('beforeunload', () => { - handleResize.cancel(); -}); -``` - -#### 파라미터 - -- `func` (`Function`): 디바운스할 함수예요. -- `wait` (`number`, 선택): 지연할 밀리초 수예요. 기본값은 `0`이에요. -- `options` (`DebounceSettings`, 선택): 옵션 객체예요. - - `leading` (`boolean`): `true`이면 지연 시작 시점에 함수를 실행해요. 기본값은 `false`예요. - - `trailing` (`boolean`): `true`이면 지연 종료 시점에 함수를 실행해요. 기본값은 `true`예요. - - `maxWait` (`number`): 함수 실행이 지연될 수 있는 최대 시간이에요. 기본값은 `Infinity`예요. - -#### 반환 값 - -(`DebouncedFunc`): 디바운스된 함수를 반환해요. `cancel()`과 `flush()` 메서드가 포함되어 있어요. diff --git a/docs/ko/reference/compat/function/flow.md b/docs/ko/reference/compat/function/flow.md deleted file mode 100644 index 5c0b60d16..000000000 --- a/docs/ko/reference/compat/function/flow.md +++ /dev/null @@ -1,89 +0,0 @@ -# flow (Lodash 호환성) - -::: warning `es-toolkit`의 `flow`를 사용하세요 - -이 `flow` 함수는 Lodash 호환성을 위해 배열 평탄화 처리가 추가되어 복잡해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [flow](../../function/flow.md)를 사용하세요. - -::: - -주어진 함수들을 왼쪽부터 오른쪽으로 순차적으로 실행하는 새로운 함수를 만들어요. - -```typescript -const combinedFunc = flow(...functions); -``` - -## 사용법 - -### `flow(...functions)` - -여러 함수를 왼쪽부터 오른쪽으로 순차적으로 실행하는 하나의 합성 함수를 만들고 싶을 때 `flow`를 사용하세요. 데이터 변환 파이프라인을 만들 때 유용해요. - -```typescript -import { flow } from 'es-toolkit/compat'; - -// 기본 사용법 -function add(x, y) { - return x + y; -} - -function square(n) { - return n * n; -} - -function double(n) { - return n * 2; -} - -// 왼쪽부터 오른쪽으로 실행: double(square(add(x, y))) -const calculate = flow(add, square, double); -console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 - -// 배열로 함수 전달 -const calculate2 = flow([add, square], double); -console.log(calculate2(2, 3)); // 50 - -// 현대적인 대안 (권장) -const modernCalculate = (x, y) => double(square(add(x, y))); -console.log(modernCalculate(1, 2)); // 18 - -// 파이프 연산자 사용 (미래 JavaScript) -const pipeCalculate = (x, y) => add(x, y) |> square |> double; - -// 또는 체이닝 패턴 -class Calculator { - constructor(value) { - this.value = value; - } - - add(n) { - this.value += n; - return this; - } - - square() { - this.value *= this.value; - return this; - } - - double() { - this.value *= 2; - return this; - } - - valueOf() { - return this.value; - } -} - -const chainedResult = new Calculator(3).square().double().valueOf(); // 18 -``` - -#### 파라미터 - -- `...functions` (`Array`): 왼쪽부터 오른쪽으로 실행할 함수들이에요. 배열로 전달할 수도 있어요. - -#### 반환 값 - -(`Function`): 모든 함수를 왼쪽부터 오른쪽으로 순차적으로 실행하는 새로운 합성 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/flowRight.md b/docs/ko/reference/compat/function/flowRight.md deleted file mode 100644 index 852f95bcc..000000000 --- a/docs/ko/reference/compat/function/flowRight.md +++ /dev/null @@ -1,67 +0,0 @@ -# flowRight (Lodash 호환성) - -::: warning `es-toolkit`의 `flowRight`를 사용하세요 - -이 `flowRight` 함수는 Lodash 호환성을 위해 배열 평탄화 처리가 추가되어 복잡해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [flowRight](../../function/flowRight.md)를 사용하세요. - -::: - -주어진 함수들을 오른쪽부터 왼쪽으로 순차적으로 실행하는 새로운 함수를 만들어요. - -```typescript -const combinedFunc = flowRight(...functions); -``` - -## 사용법 - -### `flowRight(...functions)` - -여러 함수를 오른쪽부터 왼쪽으로 순차적으로 실행하는 하나의 합성 함수를 만들고 싶을 때 `flowRight`를 사용하세요. 데이터 변환 파이프라인을 만들 때 유용해요. - -```typescript -import { flowRight } from 'es-toolkit/compat'; - -// 기본 사용법 -function add(x, y) { - return x + y; -} - -function square(n) { - return n * n; -} - -function double(n) { - return n * 2; -} - -// 오른쪽부터 왼쪽으로 실행: double(square(add(x, y))) -const calculate = flowRight(double, square, add); -console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 - -// 배열로 함수 전달 -const calculate2 = flowRight([double, square], add); -console.log(calculate2(2, 3)); // 50 - -// 현대적인 대안 (권장) -const modernCalculate = (x, y) => double(square(add(x, y))); -console.log(modernCalculate(1, 2)); // 18 - -// 또는 함수 체이닝 사용 -const chainedCalculate = (x, y) => [x, y] - .reduce((acc, val, idx) => idx === 0 ? val : acc + val) - .valueOf() - |> (n => n * n) - |> (n => n * 2); -``` - -일반적으로 `flow`와 반대 순서로 동작해요. 합성 함수와 비슷한 방식으로 동작하여 직관적입니다. - -#### 파라미터 - -- `...functions` (`Array`): 오른쪽부터 왼쪽으로 실행할 함수들이에요. 배열로 전달할 수도 있어요. - -#### 반환 값 - -(`Function`): 모든 함수를 오른쪽부터 왼쪽으로 순차적으로 실행하는 새로운 합성 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/identity.md b/docs/ko/reference/compat/function/identity.md deleted file mode 100644 index 5227cf54b..000000000 --- a/docs/ko/reference/compat/function/identity.md +++ /dev/null @@ -1,64 +0,0 @@ -# identity (Lodash 호환성) - -::: warning `es-toolkit`의 `identity`를 사용하세요 - -이 `identity` 함수는 `es-toolkit`의 메인 라이브러리에도 동일한 기능의 함수가 있어요. 단순히 입력값을 그대로 반환하는 기능이에요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [identity](../../function/identity.md)를 사용하세요. - -::: - -입력받은 값을 그대로 반환해요. - -```typescript -const result = identity(value); -``` - -## 사용법 - -### `identity(value)` - -입력받은 값을 그대로 반환하고 싶을 때 `identity`를 사용하세요. 주로 기본값이나 플레이스홀더 함수로 사용되며, 함수형 프로그래밍에서 자주 사용돼요. - -```typescript -import { identity } from 'es-toolkit/compat'; - -// 기본 사용법 -console.log(identity(5)); // 5 -console.log(identity('hello')); // 'hello' -console.log(identity({ key: 'value' })); // { key: 'value' } - -// 배열의 map과 함께 사용 (값 복사) -const numbers = [1, 2, 3, 4, 5]; -const copied = numbers.map(identity); -console.log(copied); // [1, 2, 3, 4, 5] - -// 필터링에서 기본값으로 사용 -const values = [1, 0, '', 'hello', null, undefined, false, true]; -const filtered = values.filter(identity); // 참으로 평가되는 값들만 남김 -console.log(filtered); // [1, 'hello', true] - -// 기본 변환 함수로 사용 -function processData(data, transform = identity) { - return transform(data); -} - -console.log(processData('hello')); // 'hello' -console.log(processData('hello', x => x.toUpperCase())); // 'HELLO' -``` - -대부분의 경우 더 간단한 화살표 함수 `x => x`로 대체할 수 있어요: - -```typescript -// identity 대신 화살표 함수 사용 (권장) -const copied = numbers.map(x => x); -const filtered = values.filter(x => x); -``` - -#### 파라미터 - -- `value` (`T`): 반환할 값이에요. - -#### 반환 값 - -(`T`): 입력받은 값을 그대로 반환해요. diff --git a/docs/ko/reference/compat/function/memoize.md b/docs/ko/reference/compat/function/memoize.md deleted file mode 100644 index 287adff9f..000000000 --- a/docs/ko/reference/compat/function/memoize.md +++ /dev/null @@ -1,68 +0,0 @@ -# memoize (Lodash 호환성) - -::: warning `es-toolkit`의 `memoize`를 사용하세요 - -이 `memoize` 함수는 `resolver` 함수의 `null` 체크, `MapCache` 인터페이스의 복잡한 타입 처리, 그리고 Lodash 호환성을 위한 추가적인 오버헤드로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [memoize](../../function/memoize.md)를 사용하세요. - -::: - -함수의 결과를 캐시하여 동일한 인수로 호출할 때 성능을 향상시켜요. - -```typescript -const memoizedFunc = memoize(func, resolver); -``` - -## 사용법 - -### `memoize(func, resolver)` - -함수의 결과를 메모이제이션하여 동일한 인수로 호출할 때 이전 결과를 재사용하고 싶을 때 `memoize`를 사용하세요. 비용이 많이 드는 계산이나 API 호출에 유용해요. - -```typescript -import { memoize } from 'es-toolkit/compat'; - -// 기본 사용법 -function expensiveCalculation(n) { - console.log('계산 중...', n); - return n * n; -} - -const memoizedCalc = memoize(expensiveCalculation); - -console.log(memoizedCalc(5)); // '계산 중... 5', 25 -console.log(memoizedCalc(5)); // 25 (캐시된 결과, 계산하지 않음) -console.log(memoizedCalc(10)); // '계산 중... 10', 100 - -// 커스텀 리졸버 사용 -function fetchUserData(userId, includeProfile) { - console.log('사용자 데이터 가져오는 중...', userId, includeProfile); - return { id: userId, profile: includeProfile ? '프로필 데이터' : null }; -} - -// 모든 인수를 고려한 캐시 키 생성 -const memoizedFetch = memoize(fetchUserData, (userId, includeProfile) => { - return `${userId}_${includeProfile}`; -}); - -memoizedFetch(1, true); // '사용자 데이터 가져오는 중... 1 true' -memoizedFetch(1, true); // 캐시된 결과 사용 -memoizedFetch(1, false); // '사용자 데이터 가져오는 중... 1 false' (다른 캐시 키) - -// 캐시 접근 및 수정 -console.log(memoizedCalc.cache.get(5)); // 25 -memoizedCalc.cache.set(7, 49); // 수동으로 캐시 설정 -console.log(memoizedCalc(7)); // 49 (계산하지 않고 캐시된 값 사용) -``` - -대부분의 경우 기본 해시 맵을 사용하지만, 필요에 따라 커스텀 캐시 구현체를 사용할 수도 있어요. - -#### 파라미터 - -- `func` (`Function`): 메모이제이션할 함수예요. -- `resolver` (`Function`, 선택): 캐시 키를 결정하는 함수예요. 제공되지 않으면 첫 번째 인수를 키로 사용해요. - -#### 반환 값 - -(`Function & { cache: MapCache }`): 메모이제이션된 함수를 반환해요. 반환된 함수에는 `cache` 프로퍼티가 있어서 캐시에 직접 접근할 수 있어요. diff --git a/docs/ko/reference/compat/function/noop.md b/docs/ko/reference/compat/function/noop.md deleted file mode 100644 index b839d7759..000000000 --- a/docs/ko/reference/compat/function/noop.md +++ /dev/null @@ -1,60 +0,0 @@ -# noop (Lodash 호환성) - -::: warning `es-toolkit`의 `noop`을 사용하세요 - -`es-toolkit`에도 동일한 동작을 하는 [noop](../../function/noop.md) 함수가 있어요. - -::: - -아무것도 하지 않는 빈 함수예요. - -```typescript -noop(); -``` - -## 사용법 - -### `noop(...args)` - -아무것도 하지 않는 플레이스홀더 함수가 필요할 때 `noop`을 사용하세요. 기본값이나 콜백 함수로 자주 사용돼요. - -```typescript -import { noop } from 'es-toolkit/compat'; - -// 기본 사용법 -noop(); // 아무것도 하지 않음 -noop(1, 2, 3); // 인수를 받지만 아무것도 하지 않음 - -// 기본 콜백으로 사용 -function processData(data, callback = noop) { - // 데이터 처리 - console.log('데이터 처리 중...', data); - - // 콜백 호출 (제공되지 않았다면 noop) - callback(data); -} - -processData('테스트'); // 콜백이 제공되지 않았지만 오류 없이 동작 - -// 현대적인 대안 (권장) -function modernProcessData(data, callback = () => {}) { - console.log('데이터 처리 중...', data); - callback(data); -} - -// 또는 선택적 콜백 사용 -function processDataOptional(data, callback) { - console.log('데이터 처리 중...', data); - callback?.(data); // 콜백이 제공된 경우만 호출 -} -``` - -기본값이나 플레이스홀더가 필요한 상황에서 유용하지만, 현대 JavaScript에서는 선택적 체이닝(`?.`)이나 기본 매개변수를 사용하는 것이 더 일반적이에요. - -#### 파라미터 - -- `...args` (`any[]`): 어떤 인수들이든 받을 수 있지만 모두 무시돼요. - -#### 반환 값 - -(`void`): 아무것도 반환하지 않아요. diff --git a/docs/ko/reference/compat/function/once.md b/docs/ko/reference/compat/function/once.md deleted file mode 100644 index 51166c774..000000000 --- a/docs/ko/reference/compat/function/once.md +++ /dev/null @@ -1,56 +0,0 @@ -# once (Lodash 호환성) - -::: warning `es-toolkit`의 `once`를 사용하세요 - -이 `once` 함수는 `es-toolkit`의 메인 라이브러리 [once](../../function/once.md) 함수와 동일한 기능을 가지고 있어요. - -::: - -함수가 한 번만 호출되도록 제한해요. - -```typescript -const limitedFunc = once(func); -``` - -## 사용법 - -### `once(func)` - -함수가 한 번만 호출되도록 제한하고 싶을 때 `once`를 사용하세요. 첫 번째 호출 후에는 결과가 캐시되어 동일한 값을 반환해요. - -```typescript -import { once } from 'es-toolkit/compat'; - -// 기본 사용법 -let count = 0; -const increment = once(() => { - count++; - console.log('카운터 증가:', count); - return count; -}); - -increment(); // '카운터 증가: 1' 출력, 1 반환 -increment(); // 아무것도 출력하지 않음, 1 반환 -increment(); // 아무것도 출력하지 않음, 1 반환 - -// 실용 예시 - 초기화 함수 -const initialize = once(() => { - console.log('애플리케이션 초기화 중...'); - // 비용 많은 초기화 작업 - return '초기화 완료'; -}); - -// 여러 번 호출해도 초기화는 한 번만 실행됨 -initialize(); // '애플리케이션 초기화 중...' 출력 -initialize(); // 아무것도 출력하지 않음 -``` - -비용이 많이 드는 초기화 작업이나 설정 함수를 만들 때 유용해요. 예를 들어 데이터베이스 연결, API 토큰 초기화 등에 사용할 수 있어요. - -#### 파라미터 - -- `func` (`Function`): 한 번만 호출되도록 제한할 함수예요. - -#### 반환 값 - -(`Function`): 한 번만 호출되는 새로운 함수를 반환해요. 두 번째 호출부터는 첫 번째 호출의 결과를 반환해요. diff --git a/docs/ko/reference/compat/function/partial.md b/docs/ko/reference/compat/function/partial.md deleted file mode 100644 index 3561e0e13..000000000 --- a/docs/ko/reference/compat/function/partial.md +++ /dev/null @@ -1,59 +0,0 @@ -# partial (Lodash 호환성) - -::: warning `es-toolkit`의 `partial`을 사용하세요 - -이 `partial` 함수는 많은 오버로드와 공용체 타입 처리로 인해 비효율적이에요. 또한 대부분의 경우 더 간단한 화살표 함수로 대체할 수 있어요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [partial](../../function/partial.md)을 사용하세요. - -::: - -함수의 인수를 미리 채워서 부분 적용된 함수를 만들어요. - -```typescript -const partialFunc = partial(func, ...args); -``` - -## 사용법 - -### `partial(func, ...args)` - -함수의 인수를 미리 채워서 부분 적용된 함수를 만들고 싶을 때 `partial`을 사용하세요. 주로 인수 순서가 중요한 함수에서 첫 번째 인수들을 고정할 때 유용해요. - -```typescript -import { partial } from 'es-toolkit/compat'; - -// 기본 사용법 -function greet(greeting, name, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// 첫 번째 인수를 미리 설정 -const sayHello = partial(greet, 'Hello'); -sayHello('Alice', '!'); // 'Hello Alice!' - -// 여러 인수를 미리 설정 -const greetAlice = partial(greet, 'Hello', 'Alice'); -greetAlice('!'); // 'Hello Alice!' - -// placeholder를 사용하여 인수 순서 조절 -const greetWithExclamation = partial(greet, partial.placeholder, 'Alice', '!'); -greetWithExclamation('Hi'); // 'Hi Alice!' -``` - -대부분의 경우 화살표 함수로 대체할 수 있어요: - -```typescript -// partial 대신 화살표 함수 사용 (권장) -const sayHello = (name, punctuation) => greet('Hello', name, punctuation); -const greetAlice = punctuation => greet('Hello', 'Alice', punctuation); -``` - -#### 파라미터 - -- `func` (`Function`): 부분 적용할 함수예요. -- `...args` (`any[]`): 미리 채울 인수들이에요. `partial.placeholder`를 사용해서 인수 순서를 조절할 수 있어요. - -#### 반환 값 - -(`Function`): 인수가 미리 채워진 새로운 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/partialRight.md b/docs/ko/reference/compat/function/partialRight.md deleted file mode 100644 index f5b4284a4..000000000 --- a/docs/ko/reference/compat/function/partialRight.md +++ /dev/null @@ -1,59 +0,0 @@ -# partialRight (Lodash 호환성) - -::: warning `es-toolkit`의 `partialRight`를 사용하세요 - -이 `partialRight` 함수는 많은 오버로드와 공용체 타입 처리로 인해 비효율적이에요. 또한 대부분의 경우 더 간단한 냄자마 함수로 대체할 수 있어요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [partialRight](../../function/partialRight.md)를 사용하세요. - -::: - -함수의 오른쪽부터 인수를 미리 채워서 부분 적용된 함수를 만들어요. - -```typescript -const partialFunc = partialRight(func, ...args); -``` - -## 사용법 - -### `partialRight(func, ...args)` - -함수의 오른쪽부터 인수를 미리 채워서 부분 적용된 함수를 만들고 싶을 때 `partialRight`를 사용하세요. 주로 인수 순서가 중요한 함수에서 마지막 인수들을 고정할 때 유용해요. - -```typescript -import { partialRight } from 'es-toolkit/compat'; - -// 기본 사용법 -function greet(greeting, name, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// 마지막 인수를 미리 설정 -const greetWithExclamation = partialRight(greet, '!'); -greetWithExclamation('Hello', 'Alice'); // 'Hello Alice!' - -// 여러 인수를 미리 설정 -const sayHiToAlice = partialRight(greet, 'Alice', '!'); -sayHiToAlice('Hi'); // 'Hi Alice!' - -// placeholder를 사용하여 인수 순서 조절 -const greetAliceWithCustom = partialRight(greet, 'Alice', partialRight.placeholder); -greetAliceWithCustom('Hello', '?'); // 'Hello Alice?' -``` - -대부분의 경우 화살표 함수로 대체할 수 있어요: - -```typescript -// partialRight 대신 화살표 함수 사용 (권장) -const greetWithExclamation = (greeting, name) => greet(greeting, name, '!'); -const sayHiToAlice = greeting => greet(greeting, 'Alice', '!'); -``` - -#### 파라미터 - -- `func` (`Function`): 부분 적용할 함수예요. -- `...args` (`any[]`): 미리 채울 인수들이에요. `partialRight.placeholder`를 사용해서 인수 순서를 조절할 수 있어요. - -#### 반환 값 - -(`Function`): 오른쪽부터 인수가 미리 채워진 새로운 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/rest.md b/docs/ko/reference/compat/function/rest.md deleted file mode 100644 index 703bf22cc..000000000 --- a/docs/ko/reference/compat/function/rest.md +++ /dev/null @@ -1,54 +0,0 @@ -# rest (Lodash 호환성) - -::: warning `es-toolkit`의 `rest`를 사용하세요 - -이 `rest` 함수는 기본값 처리나 인덱스 유효성 검사 등의 추가 로직으로 인해 성능이 떨어질 수 있어요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [rest](../../function/rest.md)를 사용하세요. - -::: - -지정된 인덱스부터 나머지 인수들을 배열로 그룹화하는 함수를 만들어요. - -```typescript -const restFunc = rest(func, start); -``` - -## 사용법 - -### `rest(func, start)` - -함수의 인수들을 변환하여 지정된 인덱스부터 나머지 인수들을 배열로 그룹화하고 싶을 때 `rest`를 사용하세요. 가변 인수를 받는 함수를 만들 때 유용해요. - -```typescript -import { rest } from 'es-toolkit/compat'; - -// 기본 사용법 - 마지막 인수들을 배열로 그룹화 -function logMessage(level, message, ...details) { - console.log(`[${level}] ${message}`, details); -} - -const restLogger = rest(logMessage, 2); -restLogger('ERROR', '오류 발생', '상세정보 1', '상세정보 2'); -// 내부적으로 logMessage('ERROR', '오류 발생', [['상세정보 1', '상세정보 2']])로 호출 - -// 다른 인덱스 예시 -function process(action, target, ...args) { - return { action, target, args }; -} - -const restProcess = rest(process, 1); -restProcess('update', 'user', 'name', 'John', 'age', 25); -// { action: 'update', target: ['user', 'name', 'John', 'age', 25], args: [] } -``` - -함수의 마지막 인수들을 배열로 받고 싶을 때 사용하면 됩니다. 현대 JavaScript에서는 나머지 매개변수 문법(`...args`)을 사용하는 것이 더 일반적이에요. - -#### 파라미터 - -- `func` (`Function`): 변환할 함수예요. -- `start` (`number`, 선택): 배열로 그룹화를 시작할 인덱스예요. 기본값은 `func.length - 1`이에요. - -#### 반환 값 - -(`Function`): 지정된 인덱스부터 나머지 인수들을 배열로 그룹화하는 새로운 함수를 반환해요. diff --git a/docs/ko/reference/compat/function/throttle.md b/docs/ko/reference/compat/function/throttle.md deleted file mode 100644 index f7b87b0a1..000000000 --- a/docs/ko/reference/compat/function/throttle.md +++ /dev/null @@ -1,52 +0,0 @@ -# throttle (Lodash 호환성) - -::: warning `es-toolkit`의 `throttle`을 사용하세요 - -이 `throttle` 함수는 Lodash 호환성을 위해 debounce 함수를 내부적으로 사용해서 방식이 조금 복잡해요. 또한 기본값 처리나 옵션 처리 등이 더 복잡해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [throttle](../../function/throttle.md)을 사용하세요. - -::: - -함수 호출을 지정된 시간 간격마다 최대 한 번만 실행되도록 제한해요. - -```typescript -const throttledFunc = throttle(func, wait, options); -``` - -## 사용법 - -### `throttle(func, wait, options)` - -함수 호출을 지정된 시간 간격마다 최대 한 번만 실행되도록 제한하고 싶을 때 `throttle`을 사용하세요. 이벤트 핸들러나 API 호출 빈도를 제한할 때 유용해요. - -```typescript -import { throttle } from 'es-toolkit/compat'; - -// 기본 사용법 - 1초마다 최대 한 번 실행 -const throttledLog = throttle(() => { - console.log('이벤트 발생!'); -}, 1000); - -// 옵션을 사용한 예시 -const throttledScroll = throttle(handleScroll, 100, { - leading: true, // 처음에 바로 실행 - trailing: false, // 마지막에 실행하지 않음 -}); - -window.addEventListener('scroll', throttledScroll); -``` - -스크롤 이벤트나 리사이즈 이벤트처럼 빠르게 발생하는 이벤트를 처리할 때 성능을 위해 필수적이에요. - -#### 파라미터 - -- `func` (`Function`): 스로틀링할 함수예요. -- `wait` (`number`, 선택): 밀리세컨드 단위의 대기 시간이에요. 기본값은 `0`이에요. -- `options` (`ThrottleSettings`, 선택): 스로틀링 옵션이에요. - - `leading` (`boolean`): 첫 번째 호출에서 바로 실행할지 여부예요. 기본값은 `true`예요. - - `trailing` (`boolean`): 마지막 호출 후에 실행할지 여부예요. 기본값은 `true`예요. - -#### 반환 값 - -(`DebouncedFunc`): 스로틀링된 함수를 반환해요. `cancel()` 메소드로 대기 중인 실행을 취소할 수 있어요. diff --git a/docs/ko/reference/compat/function/unary.md b/docs/ko/reference/compat/function/unary.md deleted file mode 100644 index d67591034..000000000 --- a/docs/ko/reference/compat/function/unary.md +++ /dev/null @@ -1,47 +0,0 @@ -# unary (Lodash 호환성) - -::: warning `es-toolkit`의 `ary`를 사용하세요 - -이 `unary` 함수는 `ary` 함수의 특수한 경우로 구현되어 있어요. 더 많은 제어가 필요하다면 `es-toolkit`의 [ary](../../function/ary.md)를 직접 사용하는 것이 더 효율적이에요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [ary](../../function/ary.md)를 사용하세요. - -::: - -함수가 최대 하나의 인수만 받도록 제한해요. - -```typescript -const limitedFunc = unary(func); -``` - -## 사용법 - -### `unary(func)` - -함수가 최대 하나의 인수만 받도록 제한하고 싶을 때 `unary`를 사용하세요. 추가로 전달되는 인수들은 모두 무시돼요. - -```typescript -import { unary } from 'es-toolkit/compat'; - -function greet(name, greeting, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// 첫 번째 인수만 받는 함수로 변환 -const greetOne = unary(greet); -greetOne('Alice', 'Hello', '!'); // greet('Alice')와 동일하게 동작 - -// 배열의 map 함수와 함께 사용할 때 유용해요 -const numbers = ['1', '2', '3']; -numbers.map(parseInt); // [1, NaN, NaN] - 예상치 못한 결과 -numbers.map(unary(parseInt)); // [1, 2, 3] - 올바른 결과 -``` - -#### 파라미터 - -- `func` (`(...args: any[]) => any`): 인수를 제한할 함수예요. - -#### 반환 값 - -(`(...args: any[]) => any`): 최대 하나의 인수만 받는 새로운 함수를 반환해요. -ㅇ깆 diff --git a/docs/ko/reference/compat/math/clamp.md b/docs/ko/reference/compat/math/clamp.md deleted file mode 100644 index c647d88f1..000000000 --- a/docs/ko/reference/compat/math/clamp.md +++ /dev/null @@ -1,82 +0,0 @@ -# clamp (Lodash 호환성) - -::: warning `es-toolkit`의 [clamp](../../math/clamp.md)를 사용하세요 - -이 `clamp` 함수는 NaN 검증과 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [clamp](../../math/clamp.md)를 사용하세요. - -::: - -숫자를 지정된 범위 내로 제한해요. - -```typescript -const clamped = clamp(number, lower, upper); -``` - -## 사용법 - -### `clamp(number, lower, upper)` - -숫자를 지정된 최솟값과 최댓값 사이로 제한하고 싶을 때 `clamp`를 사용하세요. - -```typescript -import { clamp } from 'es-toolkit/compat'; - -// 기본 사용법 -clamp(3, 2, 4); -// Returns: 3 (범위 안에 있음) - -clamp(0, 5, 10); -// Returns: 5 (최솟값으로 제한) - -clamp(15, 5, 10); -// Returns: 10 (최댓값으로 제한) - -// 음수도 처리 -clamp(-5, -10, -1); -// Returns: -5 - -clamp(-15, -10, -1); -// Returns: -10 (최솟값으로 제한) -``` - -### `clamp(number, upper)` - -하나의 인수만 제공하면 그 값을 최댓값으로 사용해요. - -```typescript -import { clamp } from 'es-toolkit/compat'; - -// 최댓값만 지정 -clamp(5, 3); -// Returns: 3 (최댓값으로 제한) - -clamp(2, 3); -// Returns: 2 (범위 안에 있음) - -clamp(1, 5); -// Returns: 1 -``` - -NaN 값은 0으로 처리해요. - -```typescript -import { clamp } from 'es-toolkit/compat'; - -clamp(5, NaN, 10); -// Returns: 5 (NaN이 0으로 처리되어 범위는 0~10) - -clamp(5, 2, NaN); -// Returns: 2 (NaN이 0으로 처리되어 범위는 0~2) -``` - -#### 파라미터 - -- `number` (`number`): 제한할 숫자예요. -- `lower` (`number`): 최솟값이에요. 두 번째 파라미터만 있으면 최댓값이 돼요. -- `upper` (`number`, 선택): 최댓값이에요. - -#### 반환 값 - -(`number`): 지정된 범위 내로 제한된 숫자를 반환해요. diff --git a/docs/ko/reference/compat/math/inRange.md b/docs/ko/reference/compat/math/inRange.md deleted file mode 100644 index 3c7012d5c..000000000 --- a/docs/ko/reference/compat/math/inRange.md +++ /dev/null @@ -1,101 +0,0 @@ -# inRange (Lodash 호환성) - -::: warning `es-toolkit`의 [inRange](../../math/inRange.md)을 사용하세요 - -이 `inRange` 함수는 복잡한 타입 변환과 null/undefined 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [inRange](../../math/inRange.md)을 사용하세요. - -::: - -숫자가 지정된 범위 내에 있는지 확인해요. - -```typescript -const result = inRange(value, minimum, maximum); -``` - -## 사용법 - -### `inRange(value, minimum, maximum?)` - -숫자가 특정 범위 안에 있는지 확인하고 싶을 때 `inRange`을 사용하세요. 최솟값은 포함되고 최댓값은 포함되지 않아요. - -```typescript -import { inRange } from 'es-toolkit/compat'; - -// 기본 사용법 -inRange(3, 2, 4); -// Returns: true (2 ≤ 3 < 4) - -inRange(1, 2, 5); -// Returns: false (1 < 2) - -inRange(5, 2, 5); -// Returns: false (5는 포함되지 않음) - -// 범위 경계값 -inRange(2, 2, 4); -// Returns: true (최솟값은 포함) - -inRange(4, 2, 4); -// Returns: false (최댓값은 포함되지 않음) -``` - -### `inRange(value, maximum)` - -두 개의 인수만 제공하면 0부터 maximum까지의 범위로 처리해요. - -```typescript -import { inRange } from 'es-toolkit/compat'; - -inRange(3, 5); -// Returns: true (0 ≤ 3 < 5) - -inRange(-1, 5); -// Returns: false (-1 < 0) - -inRange(0, 5); -// Returns: true (0 ≤ 0 < 5) - -inRange(5, 5); -// Returns: false (5는 포함되지 않음) -``` - -최솟값이 최댓값보다 크면 자동으로 교체해요. - -```typescript -import { inRange } from 'es-toolkit/compat'; - -inRange(3, 5, 2); -// Returns: true (범위가 2~5로 바뀌고, 2 ≤ 3 < 5) - -inRange(1, 5, 2); -// Returns: false (1 < 2) -``` - -잘못된 값들은 적절히 변환해요. - -```typescript -import { inRange } from 'es-toolkit/compat'; - -// 문자열 숫자 변환 -inRange(3, '2', '4'); -// Returns: true - -// falsy 값은 0으로 처리 -inRange(1, null, 5); -// Returns: true (null이 0으로 처리되어 0~5 범위) - -inRange(3, false, 5); -// Returns: true (false가 0으로 처리) -``` - -#### 파라미터 - -- `value` (`number`): 범위 안에 있는지 확인할 숫자예요. -- `minimum` (`number`): 범위의 최솟값이에요 (포함). `maximum`이 없으면 이 값이 최댓값이 돼요. -- `maximum` (`number`, 선택): 범위의 최댓값이에요 (포함되지 않음). - -#### 반환 값 - -(`boolean`): 값이 지정된 범위 안에 있으면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/math/maxBy.md b/docs/ko/reference/compat/math/maxBy.md deleted file mode 100644 index 191279491..000000000 --- a/docs/ko/reference/compat/math/maxBy.md +++ /dev/null @@ -1,114 +0,0 @@ -# maxBy (Lodash 호환성) - -::: warning es-toolkit의 [maxBy](../../array/maxBy.md)를 사용하세요 - -이 `maxBy` 함수는 iteratee 함수 처리와 타입 변환으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [maxBy](../../array/maxBy.md)를 사용하세요. - -::: - -조건에 맞는 값 중에서 최댓값 요소를 찾아요. - -```typescript -const maxItem = maxBy(array, iteratee); -``` - -## 사용법 - -### `maxBy(array, iteratee)` - -배열에서 함수로 계산한 값이 가장 큰 요소를 찾아요. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -// 객체 배열에서 특정 속성이 최대인 요소 -const people = [ - { name: '홍길동', age: 25 }, - { name: '김철수', age: 30 }, - { name: '이영희', age: 35 }, -]; - -maxBy(people, person => person.age); -// Returns: { name: '이영희', age: 35 } - -// 속성명으로도 가능 -maxBy(people, 'age'); -// Returns: { name: '이영희', age: 35 } -``` - -함수로 값을 변환해서 최댓값을 찾아요. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -maxBy(items, x => x.a); -// Returns: { a: 3 } - -const numbers = [-1, -2, -3]; -maxBy(numbers, x => Math.abs(x)); -// Returns: -3 (절댓값이 가장 큰 요소) -``` - -배열 요소로 접근해요. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const arrays = [ - [1, 2], - [3, 4], - [0, 5], -]; -maxBy(arrays, 0); // 첫 번째 요소가 최대인 배열 -// Returns: [3, 4] - -maxBy(arrays, 1); // 두 번째 요소가 최대인 배열 -// Returns: [0, 5] -``` - -객체의 특정 속성과 값이 일치하는 경우를 찾아요. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const users = [ - { name: '홍길동', age: 25, active: true }, - { name: '김철수', age: 30, active: false }, - { name: '이영희', age: 35, active: true }, -]; - -// active가 true인 요소들 중에서 첫 번째 -maxBy(users, ['active', true]); -// Returns: { name: '홍길동', age: 25, active: true } - -// 객체로 조건 지정 -maxBy(users, { active: true }); -// Returns: { name: '홍길동', age: 25, active: true } -``` - -빈 배열은 undefined를 반환해요. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -maxBy([], x => x.a); -// Returns: undefined - -maxBy(null); -// Returns: undefined - -maxBy(undefined); -// Returns: undefined -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 검색할 배열이에요. -- `iteratee` (`ValueIteratee`, 선택): 각 요소에 적용할 함수, 속성명, 또는 조건이에요. - -#### 반환 값 - -(`T | undefined`): 조건에 맞는 값이 가장 큰 요소를 반환해요. 빈 배열이면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/math/mean.md b/docs/ko/reference/compat/math/mean.md deleted file mode 100644 index cceebee3a..000000000 --- a/docs/ko/reference/compat/math/mean.md +++ /dev/null @@ -1,76 +0,0 @@ -# mean (Lodash 호환성) - -::: warning es-toolkit의 [mean](../../math/mean.md)를 사용하세요 - -이 `mean` 함수는 타입 변환과 null/undefined 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [mean](../../math/mean.md)를 사용하세요. - -::: - -배열의 평균값을 구해요. - -```typescript -const average = mean(array); -``` - -## 사용법 - -### `mean(array)` - -숫자 배열의 평균값을 계산해요. - -```typescript -import { mean } from 'es-toolkit/compat'; - -// 숫자 배열 -mean([1, 2, 3, 4, 5]); -// Returns: 3 - -mean([10, 20, 30]); -// Returns: 20 - -mean([1.5, 2.5, 3.5]); -// Returns: 2.5 -``` - -빈 배열은 NaN을 반환해요. - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean([]); -// Returns: NaN - -mean(null); -// Returns: NaN - -mean(undefined); -// Returns: NaN -``` - -유효하지 않은 값은 0으로 간주되어 계산에 포함돼요. - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean([1, undefined, 2, null, 3]); -// Returns: 1.2 (1 + 2 + 3) / 5 = 1.2 -``` - -문자열 숫자도 처리돼요. - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean(['1', '2', '3']); -// Returns: 41 (123 / 3 = 41) -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 평균을 구할 숫자들이 있는 배열이에요. - -#### 반환 값 - -(`number`): 배열의 평균값을 반환해요. 빈 배열이면 `NaN`을 반환해요. diff --git a/docs/ko/reference/compat/math/meanBy.md b/docs/ko/reference/compat/math/meanBy.md deleted file mode 100644 index 54edce2e0..000000000 --- a/docs/ko/reference/compat/math/meanBy.md +++ /dev/null @@ -1,103 +0,0 @@ -# meanBy (Lodash 호환성) - -::: warning es-toolkit의 [meanBy](../../math/meanBy.md)를 사용하세요 - -이 `meanBy` 함수는 iteratee 함수 처리와 타입 변환으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [meanBy](../../math/meanBy.md)를 사용하세요. - -::: - -조건에 맞는 값들의 평균을 구해요. - -```typescript -const average = meanBy(array, iteratee); -``` - -## 사용법 - -### `meanBy(array, iteratee)` - -배열의 각 요소에 함수를 적용한 결과의 평균을 계산해요. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -// 객체 배열에서 특정 속성의 평균 -const people = [ - { name: '홍길동', age: 25 }, - { name: '김철수', age: 30 }, - { name: '이영희', age: 35 }, -]; - -meanBy(people, person => person.age); -// Returns: 30 - -// 속성명으로도 가능 -meanBy(people, 'age'); -// Returns: 30 -``` - -함수로 값을 변환해서 평균을 구해요. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const numbers = [1.5, 2.7, 3.2, 4.8]; -meanBy(numbers, x => Math.floor(x)); -// Returns: 2.5 (1 + 2 + 3 + 4) / 4 - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -meanBy(items, x => x.a); -// Returns: 2 -``` - -배열 요소로 접근해요. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const arrays = [[2], [3], [1]]; -meanBy(arrays, 0); // 첫 번째 요소들의 평균 -// Returns: 2 -``` - -객체의 특정 속성과 값이 일치하는 경우만 계산해요. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const users = [ - { name: '홍길동', age: 25, active: true }, - { name: '김철수', age: 30, active: false }, - { name: '이영희', age: 35, active: true }, -]; - -// active가 true인 사람들만 -meanBy(users, { active: true }); -// Returns: 0.6666666 (active 가 true 인 사람의 비율) -``` - -빈 배열은 NaN을 반환해요. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -meanBy([], x => x.a); -// Returns: NaN - -meanBy(null); -// Returns: NaN - -meanBy(undefined); -// Returns: NaN -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 처리할 배열이에요. -- `iteratee` (`ValueIteratee`, 선택): 각 요소에 적용할 함수, 속성명, 또는 조건이에요. - -#### 반환 값 - -(`number`): 조건에 맞는 값들의 평균을 반환해요. 빈 배열이면 `NaN`을 반환해요. diff --git a/docs/ko/reference/compat/math/minBy.md b/docs/ko/reference/compat/math/minBy.md deleted file mode 100644 index 0cc0e3807..000000000 --- a/docs/ko/reference/compat/math/minBy.md +++ /dev/null @@ -1,114 +0,0 @@ -# minBy (Lodash 호환성) - -::: warning es-toolkit의 [minBy](../../array/minBy.md)를 사용하세요 - -이 `minBy` 함수는 iteratee 함수 처리와 타입 변환으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [minBy](../../array/minBy.md)를 사용하세요. - -::: - -조건에 맞는 값 중에서 최솟값 요소를 찾아요. - -```typescript -const minItem = minBy(array, iteratee); -``` - -## 사용법 - -### `minBy(array, iteratee)` - -배열에서 함수로 계산한 값이 가장 작은 요소를 찾아요. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -// 객체 배열에서 특정 속성이 최소인 요소 -const people = [ - { name: '홍길동', age: 25 }, - { name: '김철수', age: 30 }, - { name: '이영희', age: 35 }, -]; - -minBy(people, person => person.age); -// Returns: { name: '홍길동', age: 25 } - -// 속성명으로도 가능 -minBy(people, 'age'); -// Returns: { name: '홍길동', age: 25 } -``` - -함수로 값을 변환해서 최솟값을 찾아요. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -minBy(items, x => x.a); -// Returns: { a: 1 } - -const numbers = [-1, -2, -3]; -minBy(numbers, x => Math.abs(x)); -// Returns: -1 (절댓값이 가장 작은 요소) -``` - -배열 요소로 접근해요. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const arrays = [ - [1, 2], - [3, 4], - [0, 5], -]; -minBy(arrays, 0); // 첫 번째 요소가 최소인 배열 -// Returns: [0, 5] - -minBy(arrays, 1); // 두 번째 요소가 최소인 배열 -// Returns: [1, 2] -``` - -객체의 특정 속성과 값이 일치하는 경우를 찾아요. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const users = [ - { name: '홍길동', age: 25, active: true }, - { name: '김철수', age: 30, active: false }, - { name: '이영희', age: 35, active: true }, -]; - -// active가 true인 요소들 중에서 첫 번째가 아닌 것을 찾음 -minBy(users, ['active', true]); -// Returns: { name: '김철수', age: 30, active: false } - -// 객체로 조건 지정 -minBy(users, { active: true }); -// Returns: { name: '김철수', age: 30, active: false } -``` - -빈 배열은 undefined를 반환해요. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -minBy([], x => x.a); -// Returns: undefined - -minBy(null); -// Returns: undefined - -minBy(undefined); -// Returns: undefined -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 검색할 배열이에요. -- `iteratee` (`ValueIteratee`, 선택): 각 요소에 적용할 함수, 속성명, 또는 조건이에요. - -#### 반환 값 - -(`T | undefined`): 조건에 맞는 값이 가장 작은 요소를 반환해요. 빈 배열이면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/math/range.md b/docs/ko/reference/compat/math/range.md deleted file mode 100644 index d59f7a7ab..000000000 --- a/docs/ko/reference/compat/math/range.md +++ /dev/null @@ -1,99 +0,0 @@ -# range (Lodash 호환성) - -::: warning es-toolkit의 [range](../../math/range.md)를 사용하세요 - -이 `range` 함수는 복잡한 인수 처리와 타입 변환으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [range](../../math/range.md)를 사용하세요. - -::: - -숫자 범위 배열을 만들어요. - -```typescript -const numbers = range(start, end, step); -``` - -## 사용법 - -### `range(end)` - -0부터 end까지 1씩 증가하는 배열을 만들어요. - -```typescript -import { range } from 'es-toolkit/compat'; - -range(4); -// Returns: [0, 1, 2, 3] - -range(0); -// Returns: [] - -range(-4); -// Returns: [0, -1, -2, -3] -``` - -### `range(start, end)` - -start부터 end까지 1씩 증가하는 배열을 만들어요. - -```typescript -import { range } from 'es-toolkit/compat'; - -range(1, 5); -// Returns: [1, 2, 3, 4] - -range(5, 1); -// Returns: [5, 4, 3, 2] (자동으로 -1씩 감소) - -range(-2, 3); -// Returns: [-2, -1, 0, 1, 2] -``` - -### `range(start, end, step)` - -start부터 end까지 step만큼 증가하는 배열을 만들어요. - -```typescript -import { range } from 'es-toolkit/compat'; - -range(0, 20, 5); -// Returns: [0, 5, 10, 15] - -range(0, -4, -1); -// Returns: [0, -1, -2, -3] - -range(1, 4, 0); -// Returns: [1, 1, 1] -``` - -소수 step도 가능해요. - -```typescript -import { range } from 'es-toolkit/compat'; - -range(0, 1, 0.2); -// Returns: [0, 0.2, 0.4, 0.6, 0.8] - -range(1, 0, -0.25); -// Returns: [1, 0.75, 0.5, 0.25] -``` - -iteratee로 사용할 때는 guard 객체로 처리해요. - -```typescript -import { range } from 'es-toolkit/compat'; - -[1, 2, 3].map(range); -// Returns: [[0], [0, 1], [0, 1, 2]] -``` - -#### 파라미터 - -- `start` (`number`): 범위의 시작값이에요 (포함). `end`가 없으면 이 값이 end가 돼요. -- `end` (`number`, 선택): 범위의 끝값이에요 (포함되지 않음). -- `step` (`number`, 선택): 증가폭이에요. 기본값은 1 또는 -1이에요. - -#### 반환 값 - -(`number[]`): 지정된 범위의 숫자 배열을 반환해요. diff --git a/docs/ko/reference/compat/math/rangeRight.md b/docs/ko/reference/compat/math/rangeRight.md deleted file mode 100644 index f3470d75a..000000000 --- a/docs/ko/reference/compat/math/rangeRight.md +++ /dev/null @@ -1,99 +0,0 @@ -# rangeRight (Lodash 호환성) - -::: warning es-toolkit의 [rangeRight](../../math/rangeRight.md)를 사용하세요 - -이 `rangeRight` 함수는 복잡한 인수 처리와 타입 변환으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [rangeRight](../../math/rangeRight.md)를 사용하세요. - -::: - -숫자 범위 배열을 역순으로 만들어요. - -```typescript -const numbers = rangeRight(start, end, step); -``` - -## 사용법 - -### `rangeRight(end)` - -0부터 end까지 1씩 증가한 뒤 역순으로 배열을 만들어요. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(4); -// Returns: [3, 2, 1, 0] - -rangeRight(0); -// Returns: [] - -rangeRight(-4); -// Returns: [-3, -2, -1, 0] -``` - -### `rangeRight(start, end)` - -start부터 end까지 1씩 증가한 뒤 역순으로 배열을 만들어요. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(1, 5); -// Returns: [4, 3, 2, 1] - -rangeRight(5, 1); -// Returns: [2, 3, 4, 5] (자동으로 -1씩 감소했다가 역순) - -rangeRight(-2, 3); -// Returns: [2, 1, 0, -1, -2] -``` - -### `rangeRight(start, end, step)` - -start부터 end까지 step만큼 증가한 뒤 역순으로 배열을 만들어요. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(0, 8, 2); -// Returns: [6, 4, 2, 0] - -rangeRight(0, -4, -1); -// Returns: [-3, -2, -1, 0] - -rangeRight(1, 4, 0); -// Returns: [1, 1, 1] -``` - -소수 step도 가능해요. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(0, 1, 0.2); -// Returns: [0.8, 0.6, 0.4, 0.2, 0] - -rangeRight(1, 0, -0.25); -// Returns: [0.25, 0.5, 0.75, 1] -``` - -iteratee로 사용할 때는 guard 객체로 처리해요. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -[1, 2, 3].map(rangeRight); -// Returns: [[0], [1, 0], [2, 1, 0]] -``` - -#### 파라미터 - -- `start` (`number`): 범위의 시작값이에요 (포함). `end`가 없으면 이 값이 end가 돼요. -- `end` (`number`, 선택): 범위의 끝값이에요 (포함되지 않음). -- `step` (`number`, 선택): 증가폭이에요. 기본값은 1 또는 -1이에요. - -#### 반환 값 - -(`number[]`): 지정된 범위의 숫자 배열을 역순으로 반환해요. diff --git a/docs/ko/reference/compat/math/sum.md b/docs/ko/reference/compat/math/sum.md deleted file mode 100644 index 0e0a65746..000000000 --- a/docs/ko/reference/compat/math/sum.md +++ /dev/null @@ -1,73 +0,0 @@ -# sum (Lodash 호환성) - -::: warning es-toolkit의 [sum](../../math/sum.md)를 사용하세요 - -이 `sum` 함수는 타입 변환과 null/undefined 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [sum](../../math/sum.md)를 사용하세요. - -::: - -배열의 모든 값을 더해요. - -```typescript -const total = sum(array); -``` - -## 사용법 - -### `sum(array)` - -배열 안의 모든 숫자를 더해서 총합을 구해요. - -```typescript -import { sum } from 'es-toolkit/compat'; - -// 숫자 배열 -sum([1, 2, 3]); -// Returns: 6 - -sum([1.5, 2.5, 3]); -// Returns: 7 - -// 빈 배열 -sum([]); -// Returns: 0 -``` - -BigInt와 문자열도 처리해요. - -```typescript -import { sum } from 'es-toolkit/compat'; - -// BigInt 배열 -sum([1n, 2n, 3n]); -// Returns: 6n - -// 문자열 배열 (연결됨) -sum(['1', '2']); -// Returns: '12' -``` - -잘못된 값들은 무시해요. - -```typescript -import { sum } from 'es-toolkit/compat'; - -sum([1, undefined, 2]); -// Returns: 3 (undefined 무시) - -sum(null); -// Returns: 0 - -sum(undefined); -// Returns: 0 -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 더할 값들이 있는 배열이에요. - -#### 반환 값 - -(`number`): 모든 값을 더한 총합을 반환해요. diff --git a/docs/ko/reference/compat/math/sumBy.md b/docs/ko/reference/compat/math/sumBy.md deleted file mode 100644 index d9ef4d5ba..000000000 --- a/docs/ko/reference/compat/math/sumBy.md +++ /dev/null @@ -1,103 +0,0 @@ -# sumBy (Lodash 호환성) - -::: warning es-toolkit의 [sumBy](../../math/sumBy.md)를 사용하세요 - -이 `sumBy` 함수는 iteratee 함수 처리와 타입 변환으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [sumBy](../../math/sumBy.md)를 사용하세요. - -::: - -조건에 맞는 값들을 더해요. - -```typescript -const total = sumBy(array, iteratee); -``` - -## 사용법 - -### `sumBy(array, iteratee)` - -배열의 각 요소에 함수를 적용한 결과를 더해요. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -// 숫자 배열 -sumBy([1, 2, 3], value => value); -// Returns: 6 - -sumBy([1.5, 2.5, 3.5], value => Math.floor(value)); -// Returns: 6 (1 + 2 + 3) - -// 빈 배열 -sumBy([], value => value); -// Returns: 0 -``` - -### `sumBy(array)` - -함수를 주지 않으면 배열 값을 그대로 더해요. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -sumBy([1, 2, 3]); -// Returns: 6 - -sumBy([1n, 2n, 3n]); -// Returns: 6n -``` - -객체 배열에서 특정 속성을 더해요. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -const people = [ - { name: '홍길동', age: 25 }, - { name: '김철수', age: 30 }, - { name: '이영희', age: 35 }, -]; - -sumBy(people, person => person.age); -// Returns: 90 - -// 속성명으로도 가능 -sumBy(people, 'age'); -// Returns: 90 -``` - -문자열도 연결해요. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -const items = [{ a: '1' }, { a: '2' }]; -sumBy(items, obj => obj.a); -// Returns: '12' -``` - -잘못된 값들은 무시해요. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -sumBy([1, undefined, 2], value => value); -// Returns: 3 (undefined 무시) - -sumBy(null); -// Returns: 0 - -sumBy(undefined); -// Returns: 0 -``` - -#### 파라미터 - -- `array` (`ArrayLike | null | undefined`): 처리할 배열이에요. -- `iteratee` (`((value: T) => number) | string`, 선택): 각 요소에 적용할 함수나 속성명이에요. - -#### 반환 값 - -(`number`): 조건에 맞는 값들을 더한 총합을 반환해요. diff --git a/docs/ko/reference/compat/object/clone.md b/docs/ko/reference/compat/object/clone.md deleted file mode 100644 index 77378c0e8..000000000 --- a/docs/ko/reference/compat/object/clone.md +++ /dev/null @@ -1,89 +0,0 @@ -# clone (Lodash 호환성) - -::: warning `es-toolkit`의 `clone`을 사용하세요 - -이 `clone` 함수는 특수한 객체 타입들을 처리하는 복잡한 로직으로 인해 상대적으로 느려요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [clone](../../object/clone.md)을 사용하세요. - -::: - -객체의 얕은 복사본을 만들어요. - -```typescript -const cloned = clone(value); -``` - -## 사용법 - -### `clone(value)` - -값의 얕은 복사본을 만들고 싶을 때 `clone`을 사용하세요. 다양한 타입의 객체와 원시값을 복사할 수 있어요. - -```typescript -import { clone } from 'es-toolkit/compat'; - -// 원시 값 복사 -const num = 42; -const clonedNum = clone(num); -// Returns: 42 (같은 값) - -// 배열 복사 -const arr = [1, 2, 3]; -const clonedArr = clone(arr); -// Returns: [1, 2, 3] (새로운 배열 인스턴스) - -// 객체 복사 -const obj = { a: 1, b: 'hello' }; -const clonedObj = clone(obj); -// Returns: { a: 1, b: 'hello' } (새로운 객체 인스턴스) - -// Date 객체 복사 -const date = new Date('2023-01-01'); -const clonedDate = clone(date); -// Returns: new Date('2023-01-01') (새로운 Date 인스턴스) - -// 정규 표현식 복사 -const regex = /hello/gi; -regex.lastIndex = 3; -const clonedRegex = clone(regex); -// Returns: /hello/gi with lastIndex = 3 - -// Map 복사 -const map = new Map([ - ['a', 1], - ['b', 2], -]); -const clonedMap = clone(map); -// Returns: new Map([['a', 1], ['b', 2]]) - -// Set 복사 -const set = new Set([1, 2, 3]); -const clonedSet = clone(set); -// Returns: new Set([1, 2, 3]) -``` - -중첩된 객체는 얕은 복사만 수행해요. - -```typescript -import { clone } from 'es-toolkit/compat'; - -const nested = { - a: 1, - b: { - c: 2, - }, -}; -const clonedNested = clone(nested); - -console.log(clonedNested !== nested); // true (다른 객체) -console.log(clonedNested.b === nested.b); // true (중첩 객체는 같은 참조) -``` - -#### 파라미터 - -- `value` (`T`): 복사할 값이에요. - -#### 반환 값 - -(`T`): 복사된 값을 반환해요. diff --git a/docs/ko/reference/compat/object/cloneDeep.md b/docs/ko/reference/compat/object/cloneDeep.md deleted file mode 100644 index 45c346903..000000000 --- a/docs/ko/reference/compat/object/cloneDeep.md +++ /dev/null @@ -1,88 +0,0 @@ -# cloneDeep (Lodash 호환성) - -::: warning `es-toolkit`의 `cloneDeep`을 사용하세요 - -이 `cloneDeep` 함수는 특수한 객체 타입들을 처리하는 복잡한 로직으로 인해 상대적으로 느려요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [cloneDeep](../../object/cloneDeep.md)을 사용하세요. - -::: - -객체의 깊은 복사본을 만들어요. - -```typescript -const cloned = cloneDeep(value); -``` - -## 사용법 - -### `cloneDeep(value)` - -값의 깊은 복사본을 만들고 싶을 때 `cloneDeep`을 사용하세요. 중첩된 객체와 배열까지 완전히 새로운 인스턴스로 복사해요. - -```typescript -import { cloneDeep } from 'es-toolkit/compat'; - -// 원시 값 복사 -const num = 42; -const clonedNum = cloneDeep(num); -// Returns: 42 (같은 값) - -// 배열 깊은 복사 -const arr = [1, [2, 3], { a: 4 }]; -const clonedArr = cloneDeep(arr); -clonedArr[1][0] = 99; -console.log(arr[1][0]); // 2 (원본은 변경되지 않음) -console.log(clonedArr[1][0]); // 99 - -// 객체 깊은 복사 -const obj = { - a: 1, - b: { - c: 2, - d: { - e: 3, - }, - }, -}; -const clonedObj = cloneDeep(obj); -clonedObj.b.d.e = 99; -console.log(obj.b.d.e); // 3 (원본은 변경되지 않음) -console.log(clonedObj.b.d.e); // 99 - -// Date 객체 깊은 복사 -const date = new Date('2023-01-01'); -const clonedDate = cloneDeep(date); -// Returns: new Date('2023-01-01') (새로운 Date 인스턴스) - -// 복잡한 중첩 구조 -const complex = { - arr: [1, { nested: true }], - map: new Map([['key', { value: 1 }]]), - set: new Set([{ item: 1 }]), - date: new Date(), -}; -const clonedComplex = cloneDeep(complex); -// 모든 중첩된 객체들이 완전히 새로운 인스턴스로 복사됨 -``` - -순환 참조도 올바르게 처리해요. - -```typescript -import { cloneDeep } from 'es-toolkit/compat'; - -const obj = { a: 1 }; -obj.self = obj; // 순환 참조 - -const cloned = cloneDeep(obj); -console.log(cloned !== obj); // true -console.log(cloned.self === cloned); // true (순환 참조 유지) -``` - -#### 파라미터 - -- `value` (`T`): 깊은 복사할 값이에요. - -#### 반환 값 - -(`T`): 깊은 복사된 값을 반환해요. diff --git a/docs/ko/reference/compat/object/findKey.md b/docs/ko/reference/compat/object/findKey.md deleted file mode 100644 index 96cfd53c1..000000000 --- a/docs/ko/reference/compat/object/findKey.md +++ /dev/null @@ -1,61 +0,0 @@ -# findKey (Lodash 호환성) - -::: warning `es-toolkit`의 `findKey`를 사용하세요 - -이 `findKey` 함수는 다양한 조건 타입 처리와 호환성 로직으로 인해 복잡하게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [findKey](../../object/findKey.md)를 사용하세요. - -::: - -조건에 맞는 첫 번째 요소의 키를 찾아요. - -```typescript -const key = findKey(obj, predicate); -``` - -## 사용법 - -### `findKey(obj, predicate)` - -객체에서 조건에 맞는 첫 번째 요소의 키를 찾을 때 `findKey`를 사용하세요. 함수, 객체, 배열, 문자열 등 다양한 형태의 조건을 사용할 수 있어요. - -```typescript -import { findKey } from 'es-toolkit/compat'; - -// 함수 조건으로 키 찾기 -const users = { - alice: { age: 25, active: true }, - bob: { age: 30, active: false }, - charlie: { age: 35, active: true }, -}; - -findKey(users, user => user.age > 30); -// 반환값: 'charlie' - -// 객체 조건으로 키 찾기 -findKey(users, { active: false }); -// 반환값: 'bob' - -// 속성 경로로 키 찾기 -findKey(users, 'active'); -// 반환값: 'alice' -``` - -조건에 맞는 요소가 없으면 `undefined`를 반환해요. - -```typescript -import { findKey } from 'es-toolkit/compat'; - -findKey({ a: 1, b: 2 }, value => value > 5); -// 반환값: undefined -``` - -#### 파라미터 - -- `obj` (`T | null | undefined`): 검색할 객체예요. -- `predicate` (`ObjectIteratee`, 선택): 각 요소에 적용할 조건이에요. 함수, 객체, 배열, 문자열이 될 수 있어요. - -#### 반환 값 - -(`string | undefined`): 조건에 맞는 첫 번째 요소의 키를 반환해요. 없으면 `undefined`를 반환해요. diff --git a/docs/ko/reference/compat/object/invert.md b/docs/ko/reference/compat/object/invert.md deleted file mode 100644 index a11b47841..000000000 --- a/docs/ko/reference/compat/object/invert.md +++ /dev/null @@ -1,60 +0,0 @@ -# invert (Lodash 호환성) - -::: warning `es-toolkit`의 `invert`를 사용하세요 - -이 `invert` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [invert](../../object/invert.md)를 사용하세요. - -::: - -객체의 키와 값을 뒤바꿔요. - -```typescript -const inverted = invert(object); -``` - -## 사용법 - -### `invert(object)` - -객체의 키와 값을 서로 바꾸고 싶을 때 `invert`를 사용하세요. 원래 객체의 키는 새 객체의 값이 되고, 원래 객체의 값은 새 객체의 키가 돼요. - -```typescript -import { invert } from 'es-toolkit/compat'; - -// 기본 키-값 뒤바꾸기 -const object = { a: 1, b: 2, c: 3 }; -invert(object); -// => { '1': 'a', '2': 'b', '3': 'c' } - -// 문자열 값들 뒤바꾸기 -const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' }; -invert(colors); -// => { '#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue' } - -// 혼합된 키와 값 타입 -const mixed = { a: 1, 2: 'b', c: 3, 4: 'd' }; -invert(mixed); -// => { '1': 'a', 'b': '2', '3': 'c', 'd': '4' } -``` - -중복된 값이 있을 때는 마지막 키가 사용돼요. - -```typescript -import { invert } from 'es-toolkit/compat'; - -// 중복된 값이 있는 경우 -const object = { a: 1, b: 1, c: 2 }; -invert(object); -// => { '1': 'b', '2': 'c' } -// 'a'는 덮어쓰여져서 사라져요 -``` - -#### 파라미터 - -- `object` (`object`): 뒤바꿀 객체예요. - -#### 반환 값 - -(`Record`): 키와 값이 뒤바뀐 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/mapKeys.md b/docs/ko/reference/compat/object/mapKeys.md deleted file mode 100644 index b0cad684c..000000000 --- a/docs/ko/reference/compat/object/mapKeys.md +++ /dev/null @@ -1,63 +0,0 @@ -# mapKeys (Lodash 호환성) - -::: warning `es-toolkit`의 `mapKeys`를 사용하세요 - -이 `mapKeys` 함수는 `null`이나 `undefined` 처리, `iteratee` 변환 과정 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [mapKeys](../../object/mapKeys.md)를 사용하세요. - -::: - -객체의 값은 그대로 두고 키를 변환해서 새로운 객체를 만들어요. - -```typescript -const result = mapKeys(obj, iteratee); -``` - -## 사용법 - -### `mapKeys(object, iteratee)` - -객체의 각 키를 `iteratee` 함수로 변환해서 새로운 객체를 만들어요. 값은 원래대로 유지되고 키만 변경돼요. 객체의 키를 변환하거나 정규화할 때 유용해요. - -```typescript -import { mapKeys } from 'es-toolkit/compat'; - -// 키에 접두사 추가 -const obj = { a: 1, b: 2, c: 3 }; -const result = mapKeys(obj, (value, key) => 'prefix_' + key); -// 결과: { prefix_a: 1, prefix_b: 2, prefix_c: 3 } - -// 키를 대문자로 변환 -const data = { name: 'John', age: 30 }; -const uppercased = mapKeys(data, (value, key) => key.toUpperCase()); -// 결과: { NAME: 'John', AGE: 30 } - -// 배열 인덱스를 키로 변환 -const arr = ['apple', 'banana', 'orange']; -const indexed = mapKeys(arr, (value, index) => `item_${index}`); -// 결과: { item_0: 'apple', item_1: 'banana', item_2: 'orange' } - -// 키와 값을 조합해서 새로운 키 생성 -const scores = { math: 90, science: 85, english: 92 }; -const detailed = mapKeys(scores, (value, key) => `${key}_score_${value}`); -// 결과: { math_score_90: 90, science_score_85: 85, english_score_92: 92 } -``` - -`null`이나 `undefined`는 빈 객체로 처리해요. - -```typescript -import { mapKeys } from 'es-toolkit/compat'; - -mapKeys(null, iteratee); // {} -mapKeys(undefined, iteratee); // {} -``` - -#### 파라미터 - -- `object` (`ArrayLike | T | null | undefined`): 키를 변환할 객체나 배열이에요. -- `iteratee` (`ListIteratee | ObjectIteratee`, 선택): 각 키를 변환할 함수예요. 기본값은 `identity` 함수예요. - -#### 반환 값 - -(`Record | Record`): 변환된 키를 가진 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/mapValues.md b/docs/ko/reference/compat/object/mapValues.md deleted file mode 100644 index adde2fa0c..000000000 --- a/docs/ko/reference/compat/object/mapValues.md +++ /dev/null @@ -1,71 +0,0 @@ -# mapValues (Lodash 호환성) - -::: warning `es-toolkit`의 `mapValues`를 사용하세요 - -이 `mapValues` 함수는 `null`이나 `undefined` 처리, `iteratee` 변환 과정 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [mapValues](../../object/mapValues.md)를 사용하세요. - -::: - -객체의 키는 그대로 두고 값을 변환해서 새로운 객체를 만들어요. - -```typescript -const result = mapValues(obj, iteratee); -``` - -## 사용법 - -### `mapValues(object, iteratee)` - -객체의 각 값을 `iteratee` 함수로 변환해서 새로운 객체를 만들어요. 키는 원래대로 유지되고 값만 변경돼요. 문자열, 배열, 객체 모두 처리할 수 있어요. 데이터를 변환하거나 계산할 때 유용해요. - -```typescript -import { mapValues } from 'es-toolkit/compat'; - -// 객체의 값을 변환 -const obj = { a: 1, b: 2, c: 3 }; -const doubled = mapValues(obj, value => value * 2); -// 결과: { a: 2, b: 4, c: 6 } - -// 문자열을 대문자로 변환 -const names = { first: 'john', last: 'doe' }; -const uppercased = mapValues(names, value => value.toUpperCase()); -// 결과: { first: 'JOHN', last: 'DOE' } - -// 문자열의 각 문자 변환 -const str = 'abc'; -const charMap = mapValues(str, char => char.toUpperCase()); -// 결과: { '0': 'A', '1': 'B', '2': 'C' } - -// 배열을 객체로 변환 -const arr = [10, 20, 30]; -const arrMap = mapValues(arr, (value, index) => value + index); -// 결과: { '0': 10, '1': 21, '2': 32 } - -// 속성 경로로 값 추출 -const users = { - user1: { profile: { name: 'Alice' } }, - user2: { profile: { name: 'Bob' } }, -}; -const userNames = mapValues(users, 'profile.name'); -// 결과: { user1: 'Alice', user2: 'Bob' } -``` - -`null`이나 `undefined`는 빈 객체로 처리해요. - -```typescript -import { mapValues } from 'es-toolkit/compat'; - -mapValues(null, iteratee); // {} -mapValues(undefined, iteratee); // {} -``` - -#### 파라미터 - -- `object` (`string | T[] | T | null | undefined`): 값을 변환할 객체, 배열, 또는 문자열이에요. -- `iteratee` (`ValueIteratee`, 선택): 각 값을 변환할 함수, 속성 경로, 또는 매칭 객체예요. 기본값은 `identity` 함수예요. - -#### 반환 값 - -(`Record | { [P in keyof T]: U } | Record | Record | Partial`): 변환된 값을 가진 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/merge.md b/docs/ko/reference/compat/object/merge.md deleted file mode 100644 index 6eae80618..000000000 --- a/docs/ko/reference/compat/object/merge.md +++ /dev/null @@ -1,82 +0,0 @@ -# merge (Lodash 호환성) - -::: warning `es-toolkit`의 `merge`를 사용하세요 - -이 `merge` 함수는 내부적으로 복잡한 `mergeWith` 함수를 호출하여 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [merge](../../object/merge.md)를 사용하세요. - -::: - -여러 객체를 깊게 병합해서 하나의 객체로 만들어요. - -```typescript -const result = merge(target, ...sources); -``` - -## 사용법 - -### `merge(object, ...sources)` - -대상 객체에 하나 이상의 소스 객체를 깊게 병합해요. 중첩된 객체와 배열도 재귀적으로 병합돼요. 소스 객체의 속성이 `undefined`이면 대상 객체의 기존 값을 덮어쓰지 않아요. 객체 설정 병합이나 기본값 적용에 유용해요. - -```typescript -import { merge } from 'es-toolkit/compat'; - -// 기본 객체 병합 -const target = { a: 1, b: { x: 1, y: 2 } }; -const source = { b: { y: 3, z: 4 }, c: 5 }; -const result = merge(target, source); -// 결과: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } - -// 배열 병합 -const obj1 = { arr: [1, 2] }; -const obj2 = { arr: [3, 4] }; -const merged = merge(obj1, obj2); -// 결과: { arr: [3, 4] } (배열은 교체됨) - -// 여러 객체 병합 -const base = { a: 1 }; -const ext1 = { b: 2 }; -const ext2 = { c: 3 }; -const ext3 = { d: 4 }; -const combined = merge(base, ext1, ext2, ext3); -// 결과: { a: 1, b: 2, c: 3, d: 4 } - -// 중첩된 객체 병합 -const config = { - api: { url: 'https://api.example.com', timeout: 5000 }, - features: { auth: true }, -}; -const overrides = { - api: { timeout: 10000, retries: 3 }, - features: { analytics: true }, -}; -const finalConfig = merge(config, overrides); -// 결과: { -// api: { url: 'https://api.example.com', timeout: 10000, retries: 3 }, -// features: { auth: true, analytics: true } -// } -``` - -대상 객체가 수정되므로 원본을 보존하려면 빈 객체를 사용하세요. - -```typescript -import { merge } from 'es-toolkit/compat'; - -const original = { a: 1, b: { x: 1 } }; -const source = { b: { y: 2 } }; - -// 원본 보존 -const result = merge({}, original, source); -// original은 변경되지 않음 -``` - -#### 파라미터 - -- `object` (`any`): 병합 대상이 되는 객체예요. 이 객체가 수정돼요. -- `...sources` (`any[]`): 병합할 소스 객체들이에요. - -#### 반환 값 - -(`any`): 병합된 대상 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/mergeWith.md b/docs/ko/reference/compat/object/mergeWith.md deleted file mode 100644 index c5b6356f7..000000000 --- a/docs/ko/reference/compat/object/mergeWith.md +++ /dev/null @@ -1,94 +0,0 @@ -# mergeWith (Lodash 호환성) - -::: warning `es-toolkit`의 `mergeWith`를 사용하세요 - -이 `mergeWith` 함수는 복잡한 타입 체크와 순환 참조 처리, 특수 객체 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [mergeWith](../../object/mergeWith.md)를 사용하세요. - -::: - -사용자 정의 함수로 병합 방식을 제어하면서 여러 객체를 깊게 병합해요. - -```typescript -const result = mergeWith(target, ...sources, customizer); -``` - -## 사용법 - -### `mergeWith(object, ...sources, customizer)` - -대상 객체에 하나 이상의 소스 객체를 깊게 병합하되, 커스터마이저 함수로 병합 방식을 제어해요. 커스터마이저 함수가 `undefined`를 반환하면 기본 병합 로직이 사용돼요. 배열 합치기나 특별한 병합 규칙이 필요할 때 유용해요. - -```typescript -import { mergeWith } from 'es-toolkit/compat'; - -// 숫자 더하기 -const obj1 = { a: 1, b: 2 }; -const obj2 = { b: 3, c: 4 }; -const result = mergeWith(obj1, obj2, (objValue, srcValue) => { - if (typeof objValue === 'number' && typeof srcValue === 'number') { - return objValue + srcValue; - } -}); -// 결과: { a: 1, b: 5, c: 4 } - -// 배열 합치기 -const arr1 = { items: [1, 2] }; -const arr2 = { items: [3, 4] }; -const merged = mergeWith(arr1, arr2, (objValue, srcValue) => { - if (Array.isArray(objValue)) { - return objValue.concat(srcValue); - } -}); -// 결과: { items: [1, 2, 3, 4] } - -// 문자열 연결 -const str1 = { message: 'Hello' }; -const str2 = { message: 'World' }; -const combined = mergeWith(str1, str2, (objValue, srcValue, key) => { - if (key === 'message' && typeof objValue === 'string') { - return objValue + ' ' + srcValue; - } -}); -// 결과: { message: 'Hello World' } - -// 여러 소스 객체와 커스터마이저 -const base = { scores: [80] }; -const quiz1 = { scores: [90] }; -const quiz2 = { scores: [85] }; -const final = mergeWith(base, quiz1, quiz2, (objValue, srcValue) => { - if (Array.isArray(objValue)) { - return objValue.concat(srcValue); - } -}); -// 결과: { scores: [80, 90, 85] } -``` - -커스터마이저 함수는 다양한 매개변수를 받아요. - -```typescript -import { mergeWith } from 'es-toolkit/compat'; - -const customizer = (objValue, srcValue, key, object, source, stack) => { - console.log('병합 중:', key, objValue, '->', srcValue); - - // 특정 키에 대해서만 커스터마이징 - if (key === 'specialField') { - return `${objValue}_${srcValue}`; - } - - // undefined를 반환하면 기본 병합 로직 사용 - return undefined; -}; -``` - -#### 파라미터 - -- `object` (`any`): 병합 대상이 되는 객체예요. 이 객체가 수정돼요. -- `...sources` (`any[]`): 병합할 소스 객체들이에요. -- `customizer` (`MergeWithCustomizer`): 값 할당을 커스터마이즈하는 함수예요. `(objValue, srcValue, key, object, source, stack) => any` 형태예요. - -#### 반환 값 - -(`any`): 병합된 대상 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/omit.md b/docs/ko/reference/compat/object/omit.md deleted file mode 100644 index e52b06667..000000000 --- a/docs/ko/reference/compat/object/omit.md +++ /dev/null @@ -1,82 +0,0 @@ -# omit (Lodash 호환성) - -::: warning `es-toolkit`의 `omit`를 사용하세요 - -이 `omit` 함수는 깊은 복사와 `unset` 함수 호출 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [omit](../../object/omit.md)를 사용하세요. - -::: - -객체에서 지정된 키들을 제외한 새로운 객체를 만들어요. - -```typescript -const result = omit(obj, ...keys); -``` - -## 사용법 - -### `omit(object, ...paths)` - -객체에서 지정된 키들을 제외한 새로운 객체를 생성해요. 깊은 키 경로도 지원하며, 배열로 여러 키를 한 번에 지정할 수도 있어요. 객체에서 민감한 정보를 제거하거나 필요한 속성만 선택할 때 유용해요. - -```typescript -import { omit } from 'es-toolkit/compat'; - -// 기본 키 제거 -const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }; -const publicUser = omit(user, 'password', 'email'); -// 결과: { id: 1, name: 'John' } - -// 배열로 여러 키 제거 -const data = { a: 1, b: 2, c: 3, d: 4 }; -const filtered = omit(data, ['a', 'c']); -// 결과: { b: 2, d: 4 } - -// 깊은 키 경로 제거 -const nested = { - user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, - admin: true, -}; -const result = omit(nested, 'user.profile.age', 'admin'); -// 결과: { user: { profile: { name: 'John' }, settings: { theme: 'dark' } } } - -// 중첩된 배열과 키 조합 -const complex = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; -const simplified = omit(complex, 'a', ['b', 'c'], 'd.f'); -// 결과: { d: { e: 4 } } -``` - -배열이나 문자열, 키 경로를 자유롭게 조합할 수 있어요. - -```typescript -import { omit } from 'es-toolkit/compat'; - -const config = { - api: { url: 'https://api.example.com', key: 'secret', timeout: 5000 }, - ui: { theme: 'dark', language: 'en' }, - debug: true, -}; - -// 여러 방식으로 키 지정 -const cleaned = omit(config, 'api.key', ['debug'], 'ui.language'); -// 결과: { api: { url: 'https://api.example.com', timeout: 5000 }, ui: { theme: 'dark' } } -``` - -`null`이나 `undefined`는 빈 객체로 처리해요. - -```typescript -import { omit } from 'es-toolkit/compat'; - -omit(null, 'key'); // {} -omit(undefined, 'key'); // {} -``` - -#### 파라미터 - -- `object` (`T | null | undefined`): 키를 제거할 원본 객체예요. -- `...paths` (`Array>`): 제거할 키들이에요. 단일 키, 키 배열, 또는 깊은 키 경로를 지정할 수 있어요. - -#### 반환 값 - -(`Partial`): 지정된 키들이 제거된 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/omitBy.md b/docs/ko/reference/compat/object/omitBy.md deleted file mode 100644 index 1b554710a..000000000 --- a/docs/ko/reference/compat/object/omitBy.md +++ /dev/null @@ -1,76 +0,0 @@ -# omitBy (Lodash 호환성) - -::: warning `es-toolkit`의 `omitBy`를 사용하세요 - -이 `omitBy` 함수는 배열 유사 객체 체크, `iteratee` 변환, 키 변환 과정 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [omitBy](../../object/omitBy.md)를 사용하세요. - -::: - -조건 함수가 참을 반환하는 속성들을 제외한 새로운 객체를 만들어요. - -```typescript -const result = omitBy(obj, predicate); -``` - -## 사용법 - -### `omitBy(object, predicate)` - -객체의 각 속성에 대해 조건 함수를 실행하고, 조건 함수가 참을 반환하는 속성들을 제외한 새로운 객체를 생성해요. 조건에 따라 동적으로 속성을 필터링할 때 유용해요. - -```typescript -import { omitBy } from 'es-toolkit/compat'; - -// 특정 타입의 값 제거 -const data = { a: 1, b: 'remove', c: 3, d: 'keep' }; -const numbers = omitBy(data, value => typeof value === 'string'); -// 결과: { a: 1, c: 3 } - -// 조건에 따른 속성 제거 -const user = { id: 1, name: 'John', age: 0, active: false, email: '' }; -const validData = omitBy(user, value => !value); -// 결과: { id: 1, name: 'John' } (falsy 값들 제거) - -// 키 이름으로 필터링 -const settings = { userSetting: true, adminSetting: false, debugMode: true }; -const userOnly = omitBy(settings, (value, key) => key.startsWith('admin')); -// 결과: { userSetting: true, debugMode: true } - -// 숫자 속성만 제거 -const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; -const noNumbers = omitBy(mixed, value => typeof value === 'number'); -// 결과: { str: 'hello', bool: true, obj: {} } - -// 배열에서도 사용 가능 -const arr = [1, 2, 3, 4, 5]; -const filtered = omitBy(arr, value => value % 2 === 0); -// 결과: { '0': 1, '2': 3, '4': 5 } (짝수 인덱스의 홀수 값들) - -// 객체와 키, 원본 객체 모두 활용 -const scores = { math: 90, science: 75, english: 85, art: 60 }; -const passingGrades = omitBy(scores, (value, key, obj) => { - console.log(`${key}: ${value} (평균: ${Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length})`); - return value < 80; -}); -// 결과: { math: 90, english: 85 } -``` - -`null`이나 `undefined`는 빈 객체로 처리해요. - -```typescript -import { omitBy } from 'es-toolkit/compat'; - -omitBy(null, () => true); // {} -omitBy(undefined, () => true); // {} -``` - -#### 파라미터 - -- `object` (`Record | Record | object | null | undefined`): 필터링할 원본 객체예요. -- `predicate` (`ValueKeyIteratee | ValueKeyIteratee`, 선택): 각 속성에 대해 실행할 조건 함수예요. 참을 반환하면 해당 속성이 제거돼요. 기본값은 `identity` 함수예요. - -#### 반환 값 - -(`Record | Record | Partial`): 조건에 맞지 않는 속성들로 구성된 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/pick.md b/docs/ko/reference/compat/object/pick.md deleted file mode 100644 index ababa90aa..000000000 --- a/docs/ko/reference/compat/object/pick.md +++ /dev/null @@ -1,73 +0,0 @@ -# pick (Lodash 호환성) - -::: warning `es-toolkit`의 `pick`을 사용하세요 - -이 `pick` 함수는 복잡한 경로 처리, `get`/`set` 함수 호출, `null`/`undefined` 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [pick](../../object/pick.md)을 사용하세요. - -::: - -객체에서 지정한 속성들만 선택해서 새로운 객체를 만들어요. - -```typescript -const result = pick(obj, ...keys); -``` - -## 사용법 - -### `pick(object, ...props)` - -객체에서 원하는 속성들만 골라서 새로운 객체를 만들고 싶을 때 `pick`을 사용하세요. 배열로 여러 키를 한번에 전달하거나, 개별 인수로 하나씩 전달할 수 있어요. 깊은 키 경로도 지원하므로 중첩된 속성도 선택할 수 있어요. - -```typescript -import { pick } from 'es-toolkit/compat'; - -// 기본 사용법 -const obj = { a: 1, b: 2, c: 3, d: 4 }; -const result = pick(obj, ['a', 'c']); -// 결과: { a: 1, c: 3 } - -// 개별 인수로 전달 -const result2 = pick(obj, 'a', 'c'); -// 결과: { a: 1, c: 3 } - -// 깊은 경로 선택 -const nested = { - user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, - admin: true, -}; -const userInfo = pick(nested, 'user.profile.name', 'admin'); -// 결과: { user: { profile: { name: 'John' } }, admin: true } - -// 배열과 개별 키 혼합 -const mixed = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; -const selected = pick(mixed, ['a', 'b'], 'c', 'd.e'); -// 결과: { a: 1, b: 2, c: 3, d: { e: 4 } } - -// 점 표기법 키와 실제 점이 있는 키 구분 -const ambiguous = { - 'a.b': 1, // 실제로 'a.b'라는 키 - a: { b: 2, c: 3 }, // 중첩된 객체 -}; -const dotKey = pick(ambiguous, 'a.b'); -// 결과: { 'a.b': 1 } (실제 키를 우선 선택) -``` - -`null`이나 `undefined`는 빈 객체로 처리해요. - -```typescript -import { pick } from 'es-toolkit/compat'; - -pick(null, ['a', 'b']); // {} -pick(undefined, ['a', 'b']); // {} -``` - -#### 파라미터 - -- `object` (`T | null | undefined`): 속성을 선택할 객체예요. -- `...props` (`Array>`): 선택할 속성의 키들이에요. 단일 키, 키 배열, 또는 깊은 키 경로를 지정할 수 있어요. - -#### 반환 값 - -(`Pick | Partial`): 지정한 속성들만 포함하는 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/object/pickBy.md b/docs/ko/reference/compat/object/pickBy.md deleted file mode 100644 index 9a033387e..000000000 --- a/docs/ko/reference/compat/object/pickBy.md +++ /dev/null @@ -1,86 +0,0 @@ -# pickBy (Lodash 호환성) - -::: warning `es-toolkit`의 `pickBy`를 사용하세요 - -이 `pickBy` 함수는 배열 유사 객체 체크, `iteratee` 변환, 키 변환 과정 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [pickBy](../../object/pickBy.md)를 사용하세요. - -::: - -조건 함수가 참을 반환하는 속성들만 선택해서 새로운 객체를 만들어요. - -```typescript -const result = pickBy(obj, predicate); -``` - -## 사용법 - -### `pickBy(object, predicate)` - -객체의 각 속성에 대해 조건 함수를 실행하고, 조건 함수가 참을 반환하는 속성들만 포함한 새로운 객체를 생성해요. 조건에 따라 동적으로 속성을 선택할 때 유용해요. - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -// 특정 타입의 값만 선택 -const data = { a: 1, b: 'keep', c: 3, d: 'select' }; -const strings = pickBy(data, value => typeof value === 'string'); -// 결과: { b: 'keep', d: 'select' } - -// 조건에 따른 속성 선택 -const user = { id: 1, name: 'John', age: 0, active: true, email: '' }; -const validData = pickBy(user, value => Boolean(value)); -// 결과: { id: 1, name: 'John', active: true } (참으로 평가되는 값들만) - -// 키 이름으로 필터링 -const settings = { userSetting: true, adminSetting: false, debugMode: true }; -const userOnly = pickBy(settings, (value, key) => key.startsWith('user')); -// 결과: { userSetting: true } - -// 숫자 속성만 선택 -const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; -const numbersOnly = pickBy(mixed, value => typeof value === 'number'); -// 결과: { num1: 42, num2: 0 } - -// 배열에서도 사용 가능 -const arr = [1, 2, 3, 4, 5]; -const evens = pickBy(arr, value => value % 2 === 0); -// 결과: { '1': 2, '3': 4 } (짝수 값들의 인덱스와 값) - -// 객체와 키, 원본 객체 모두 활용 -const scores = { math: 90, science: 75, english: 85, art: 60 }; -const highScores = pickBy(scores, (value, key, obj) => { - const average = Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length; - return value > average; -}); -// 결과: { math: 90, english: 85 } -``` - -조건 함수 없이 호출하면 참으로 평가되는 값들만 선택해요. - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -const data = { a: 1, b: '', c: 0, d: 'hello', e: null, f: true }; -const truthyValues = pickBy(data); -// 결과: { a: 1, d: 'hello', f: true } -``` - -`null`이나 `undefined`는 빈 객체로 처리해요. - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -pickBy(null, () => true); // {} -pickBy(undefined, () => true); // {} -``` - -#### 파라미터 - -- `object` (`Record | Record | object | null | undefined`): 필터링할 원본 객체예요. -- `predicate` (`ValueKeyIterateeTypeGuard | ValueKeyIteratee | ValueKeyIteratee`, 선택): 각 속성에 대해 실행할 조건 함수예요. 참을 반환하면 해당 속성이 선택돼요. 기본값은 `identity` 함수예요. - -#### 반환 값 - -(`Record | Record | Partial`): 조건에 맞는 속성들로 구성된 새로운 객체를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isArrayBuffer.md b/docs/ko/reference/compat/predicate/isArrayBuffer.md deleted file mode 100644 index 025f890d0..000000000 --- a/docs/ko/reference/compat/predicate/isArrayBuffer.md +++ /dev/null @@ -1,44 +0,0 @@ -# isArrayBuffer (Lodash 호환성) - -::: warning es-toolkit의 [isArrayBuffer](../../predicate/isArrayBuffer.md)를 사용하세요 -이 `isArrayBuffer` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isArrayBuffer](../../predicate/isArrayBuffer.md)를 사용하세요. -::: - -값이 ArrayBuffer인지 확인해요. - -```typescript -const result = isArrayBuffer(value); -``` - -## 사용법 - -### `isArrayBuffer(value)` - -값이 ArrayBuffer인지 타입 안전하게 확인하고 싶을 때 `isArrayBuffer`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isArrayBuffer } from 'es-toolkit/compat'; - -// ArrayBuffer 확인 -const buffer = new ArrayBuffer(16); -isArrayBuffer(buffer); // true - -// 다른 타입들은 false -isArrayBuffer(new Array()); // false -isArrayBuffer(new Map()); // false -isArrayBuffer({}); // false -isArrayBuffer('hello'); // false -isArrayBuffer(123); // false -isArrayBuffer(null); // false -isArrayBuffer(undefined); // false -``` - -#### 파라미터 - -- `value` (`unknown`): ArrayBuffer인지 확인할 값이에요. - -#### 반환 값 - -(`value is ArrayBuffer`): 값이 ArrayBuffer이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isBuffer.md b/docs/ko/reference/compat/predicate/isBuffer.md deleted file mode 100644 index db5341285..000000000 --- a/docs/ko/reference/compat/predicate/isBuffer.md +++ /dev/null @@ -1,43 +0,0 @@ -# isBuffer (Lodash 호환성) - -::: warning es-toolkit의 [isBuffer](../../predicate/isBuffer.md)를 사용하세요 -이 `isBuffer` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isBuffer](../../predicate/isBuffer.md)를 사용하세요. -::: - -값이 Buffer 인스턴스인지 확인해요. - -```typescript -const result = isBuffer(value); -``` - -## 사용법 - -### `isBuffer(value)` - -값이 Buffer 인스턴스인지 타입 안전하게 확인하고 싶을 때 `isBuffer`를 사용하세요. Node.js 환경에서 Buffer 객체를 다룰 때 유용해요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isBuffer } from 'es-toolkit/compat'; - -// Buffer 인스턴스 확인 -const buffer = Buffer.from('hello'); -isBuffer(buffer); // true - -// 다른 타입들은 false -isBuffer('hello'); // false -isBuffer([1, 2, 3]); // false -isBuffer(new Uint8Array([1, 2, 3])); // false -isBuffer({}); // false -isBuffer(null); // false -isBuffer(undefined); // false -``` - -#### 파라미터 - -- `value` (`unknown`): Buffer 인스턴스인지 확인할 값이에요. - -#### 반환 값 - -(`boolean`): 값이 Buffer 인스턴스면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isDate.md b/docs/ko/reference/compat/predicate/isDate.md deleted file mode 100644 index ba54a9029..000000000 --- a/docs/ko/reference/compat/predicate/isDate.md +++ /dev/null @@ -1,46 +0,0 @@ -# isDate (Lodash 호환성) - -::: warning es-toolkit의 [isDate](../../predicate/isDate.md)를 사용하세요 -이 `isDate` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isDate](../../predicate/isDate.md)를 사용하세요. -::: - -값이 Date 객체인지 확인해요. - -```typescript -const result = isDate(value); -``` - -## 사용법 - -### `isDate(value)` - -값이 Date 객체인지 타입 안전하게 확인하고 싶을 때 `isDate`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isDate } from 'es-toolkit/compat'; - -// Date 객체 확인 -const date = new Date(); -isDate(date); // true - -// 유효하지 않은 Date도 Date 객체로 인식해요 -const invalidDate = new Date('invalid'); -isDate(invalidDate); // true - -// 다른 타입들은 false -isDate('2024-01-01'); // false -isDate(1640995200000); // false -isDate({}); // false -isDate(null); // false -isDate(undefined); // false -``` - -#### 파라미터 - -- `value` (`unknown`): Date 객체인지 확인할 값이에요. - -#### 반환 값 - -(`value is Date`): 값이 Date 객체이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isEqual.md b/docs/ko/reference/compat/predicate/isEqual.md deleted file mode 100644 index 6db5dfcd0..000000000 --- a/docs/ko/reference/compat/predicate/isEqual.md +++ /dev/null @@ -1,82 +0,0 @@ -# isEqual (Lodash 호환성) - -::: warning `es-toolkit`의 [isEqual](../../predicate/isEqual.md)를 사용하세요 -이 `isEqual` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isEqual](../../predicate/isEqual.md)를 사용하세요. -::: - -두 값이 같은지 깊이 비교해서 확인해요. - -```typescript -const result = isEqual(value1, value2); -``` - -## 사용법 - -### `isEqual(a, b)` - -두 값이 같은지 깊이 비교해서 확인하고 싶을 때 `isEqual`를 사용하세요. Date, RegExp, 객체, 배열 등 복잡한 타입도 내용까지 비교해요. - -```typescript -import { isEqual } from 'es-toolkit/compat'; - -// 기본 타입 비교 -isEqual(1, 1); // true -isEqual('hello', 'hello'); // true -isEqual(true, true); // true - -// 객체 깊이 비교 -isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true -isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true -isEqual({ a: 1 }, { a: 1, b: undefined }); // false - -// 배열 깊이 비교 -isEqual([1, 2, 3], [1, 2, 3]); // true -isEqual([1, [2, 3]], [1, [2, 3]]); // true - -// Date 객체 비교 -isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true -isEqual(new Date('2020-01-01'), new Date('2020-01-02')); // false - -// RegExp 객체 비교 -isEqual(/abc/g, /abc/g); // true -isEqual(/abc/g, /abc/i); // false -``` - -중첩된 객체나 배열도 재귀적으로 비교해요. - -```typescript -import { isEqual } from 'es-toolkit/compat'; - -const obj1 = { - user: { - name: 'John', - details: { - age: 30, - hobbies: ['reading', 'gaming'], - }, - }, -}; - -const obj2 = { - user: { - name: 'John', - details: { - age: 30, - hobbies: ['reading', 'gaming'], - }, - }, -}; - -isEqual(obj1, obj2); // true -``` - -#### 파라미터 - -- `a` (`unknown`): 비교할 첫 번째 값이에요. -- `b` (`unknown`): 비교할 두 번째 값이에요. - -#### 반환 값 - -(`boolean`): 두 값이 같으면 `true`, 다르면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isEqualWith.md b/docs/ko/reference/compat/predicate/isEqualWith.md deleted file mode 100644 index 4fb18c28a..000000000 --- a/docs/ko/reference/compat/predicate/isEqualWith.md +++ /dev/null @@ -1,92 +0,0 @@ -# isEqualWith (Lodash 호환성) - -::: warning es-toolkit의 [isEqualWith](../../predicate/isEqualWith.md)를 사용하세요 -이 `isEqualWith` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isEqualWith](../../predicate/isEqualWith.md)를 사용하세요. -::: - -사용자 정의 비교 함수를 사용해서 두 값이 같은지 확인해요. - -```typescript -const result = isEqualWith(a, b, customizer); -``` - -## 사용법 - -### `isEqualWith(a, b, areValuesEqual?)` - -사용자 정의 비교 함수를 사용해서 두 값을 깊게 비교해요. 사용자 정의 함수가 불린 값을 반환하면 그 결과를 사용하고, `undefined`를 반환하면 기본 동등성 비교를 사용해요. - -사용자 정의 비교 함수는 객체, 배열, Map, Set 등의 복잡한 구조 내부의 값들을 비교할 때도 사용되어서 깊은 비교를 보장해요. - -```typescript -import { isEqualWith } from 'es-toolkit/compat'; - -// 대소문자 무시하는 문자열 비교 -const customizer = (a: any, b: any) => { - if (typeof a === 'string' && typeof b === 'string') { - return a.toLowerCase() === b.toLowerCase(); - } -}; - -isEqualWith('Hello', 'hello', customizer); // true -isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true - -// 숫자의 절댓값으로 비교 -const absCustomizer = (a: any, b: any) => { - if (typeof a === 'number' && typeof b === 'number') { - return Math.abs(a) === Math.abs(b); - } -}; - -isEqualWith([-1, 2], [1, -2], absCustomizer); // true - -// 복잡한 객체 비교 -const obj1 = { - name: 'JOHN', - details: { age: 30, city: 'NYC' }, -}; -const obj2 = { - name: 'john', - details: { age: 30, city: 'nyc' }, -}; - -isEqualWith(obj1, obj2, customizer); // true -``` - -Map과 Set에 대해서는 특별한 처리를 해요. - -```typescript -import { isEqualWith } from 'es-toolkit/compat'; - -const customizer = (a: any, b: any) => { - if (typeof a === 'string' && typeof b === 'string') { - return a.toLowerCase() === b.toLowerCase(); - } -}; - -const map1 = new Map([['KEY', 'value']]); -const map2 = new Map([['key', 'value']]); -isEqualWith(map1, map2, customizer); // true - -const set1 = new Set(['HELLO']); -const set2 = new Set(['hello']); -isEqualWith(set1, set2, customizer); // true -``` - -#### 파라미터 - -- `a` (`any`): 비교할 첫 번째 값이에요. -- `b` (`any`): 비교할 두 번째 값이에요. -- `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): 사용자 정의 비교 함수예요. - - `x`: 첫 번째 객체 `a`에서 온 값 - - `y`: 두 번째 객체 `b`에서 온 값 - - `property`: `x`와 `y`를 가져올 때 사용한 속성 키 - - `xParent`: 첫 번째 값 `x`의 부모 객체 - - `yParent`: 두 번째 값 `y`의 부모 객체 - - `stack`: 순환 참조를 처리하는 내부 스택 (Map) - -#### 반환 값 - -(`boolean`): 사용자 정의 함수에 따라 두 값이 같으면 `true`, 다르면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isError.md b/docs/ko/reference/compat/predicate/isError.md deleted file mode 100644 index a09d02aa3..000000000 --- a/docs/ko/reference/compat/predicate/isError.md +++ /dev/null @@ -1,47 +0,0 @@ -# isError (Lodash 호환성) - -::: warning es-toolkit의 [isError](../../predicate/isError.md)를 사용하세요 -이 `isError` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isError](../../predicate/isError.md)를 사용하세요. -::: - -값이 Error 객체인지 확인해요. - -```typescript -const result = isError(value); -``` - -## 사용법 - -### `isError(value)` - -값이 Error 객체인지 타입 안전하게 확인하고 싶을 때 `isError`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isError } from 'es-toolkit/compat'; - -// Error 객체 확인 -isError(new Error()); // true -isError(new TypeError('Type error')); // true -isError(new ReferenceError('Reference error')); // true - -// Error를 상속한 사용자 정의 에러 -class CustomError extends Error {} -isError(new CustomError()); // true - -// 다른 타입들은 false -isError('Error'); // false -isError({ name: 'Error', message: 'Something went wrong' }); // false -isError({}); // false -isError(null); // false -isError(undefined); // false -``` - -#### 파라미터 - -- `value` (`unknown`): Error 객체인지 확인할 값이에요. - -#### 반환 값 - -(`value is Error`): 값이 Error 객체이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isFunction.md b/docs/ko/reference/compat/predicate/isFunction.md deleted file mode 100644 index b1b721ad8..000000000 --- a/docs/ko/reference/compat/predicate/isFunction.md +++ /dev/null @@ -1,52 +0,0 @@ -# isFunction (Lodash 호환성) - -::: warning es-toolkit의 [isFunction](../../predicate/isFunction.md)를 사용하세요 -이 `isFunction` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isFunction](../../predicate/isFunction.md)를 사용하세요. -::: - -값이 함수인지 확인해요. - -```typescript -const result = isFunction(value); -``` - -## 사용법 - -### `isFunction(value)` - -값이 함수인지 타입 안전하게 확인하고 싶을 때 `isFunction`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isFunction } from 'es-toolkit/compat'; - -// 일반 함수 -isFunction(function () {}); // true -isFunction(() => {}); // true - -// 내장 함수와 생성자 -isFunction(Array.prototype.slice); // true -isFunction(Proxy); // true -isFunction(Int8Array); // true - -// 비동기 함수와 제너레이터 함수 -isFunction(async function () {}); // true -isFunction(function* () {}); // true - -// 다른 타입들은 false -isFunction('function'); // false -isFunction({}); // false -isFunction([]); // false -isFunction(null); // false -isFunction(undefined); // false -isFunction(123); // false -``` - -#### 파라미터 - -- `value` (`unknown`): 함수인지 확인할 값이에요. - -#### 반환 값 - -(`value is (...args: any[]) => any`): 값이 함수이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isLength.md b/docs/ko/reference/compat/predicate/isLength.md deleted file mode 100644 index 5bf3a2fc1..000000000 --- a/docs/ko/reference/compat/predicate/isLength.md +++ /dev/null @@ -1,63 +0,0 @@ -# isLength (Lodash 호환성) - -::: warning es-toolkit의 [isLength](../../predicate/isLength.md)를 사용하세요 -이 `isLength` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isLength](../../predicate/isLength.md)를 사용하세요. -::: - -값이 유효한 길이인지 확인해요. - -```typescript -const result = isLength(value); -``` - -## 사용법 - -### `isLength(value)` - -값이 유효한 길이인지 확인하고 싶을 때 `isLength`를 사용하세요. 유효한 길이는 숫자 타입이고, 음이 아닌 정수이며, JavaScript의 최대 안전 정수(`Number.MAX_SAFE_INTEGER`) 이하여야 해요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isLength } from 'es-toolkit/compat'; - -// 유효한 길이들 -isLength(0); // true -isLength(42); // true -isLength(100); // true -isLength(Number.MAX_SAFE_INTEGER); // true - -// 유효하지 않은 길이들 -isLength(-1); // false (음수) -isLength(1.5); // false (정수가 아님) -isLength(Number.MAX_SAFE_INTEGER + 1); // false (안전 범위 초과) -isLength('3'); // false (문자열) -isLength(null); // false -isLength(undefined); // false -isLength({}); // false -isLength([]); // false -``` - -배열이나 문자열의 length 속성이 유효한지 확인할 때 유용해요. - -```typescript -import { isLength } from 'es-toolkit/compat'; - -function validateArrayLength(arr: any[]) { - if (isLength(arr.length)) { - console.log(`배열의 길이 ${arr.length}는 유효해요`); - return true; - } - return false; -} - -validateArrayLength([1, 2, 3]); // "배열의 길이 3는 유효해요" -``` - -#### 파라미터 - -- `value` (`any`): 유효한 길이인지 확인할 값이에요. - -#### 반환 값 - -(`boolean`): 값이 유효한 길이이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isMap.md b/docs/ko/reference/compat/predicate/isMap.md deleted file mode 100644 index 17b041722..000000000 --- a/docs/ko/reference/compat/predicate/isMap.md +++ /dev/null @@ -1,63 +0,0 @@ -# isMap (Lodash 호환성) - -::: warning es-toolkit의 [isMap](../../predicate/isMap.md)를 사용하세요 - -이 `isMap` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isMap](../../predicate/isMap.md)를 사용하세요. - -::: - -값이 Map인지 확인해요. - -```typescript -const result = isMap(value); -``` - -## 사용법 - -### `isMap(value)` - -값이 Map인지 타입 안전하게 확인하고 싶을 때 `isMap`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isMap } from 'es-toolkit/compat'; - -// Map 확인 -const map = new Map(); -isMap(map); // true - -// 다른 타입들은 false -isMap(new Set()); // false -isMap(new WeakMap()); // false -isMap({}); // false -isMap([]); // false -isMap('map'); // false -isMap(123); // false -isMap(null); // false -isMap(undefined); // false -``` - -Map과 비슷한 다른 컬렉션들과도 구분해요. - -```typescript -import { isMap } from 'es-toolkit/compat'; - -// Map vs Set vs WeakMap -isMap(new Map([['key', 'value']])); // true -isMap(new Set(['value'])); // false -isMap(new WeakMap()); // false - -// Map vs 일반 객체 -isMap({}); // false -isMap({ key: 'value' }); // false -isMap(Object.create(null)); // false -``` - -#### 파라미터 - -- `value` (`unknown`): Map인지 확인할 값이에요. - -#### 반환 값 - -(`value is Map`): 값이 Map이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isNil.md b/docs/ko/reference/compat/predicate/isNil.md deleted file mode 100644 index fcc0dbf32..000000000 --- a/docs/ko/reference/compat/predicate/isNil.md +++ /dev/null @@ -1,62 +0,0 @@ -# isNil (Lodash 호환성) - -::: warning es-toolkit의 [isNil](../../predicate/isNil.md)를 사용하세요 - -이 `isNil` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isNil](../../predicate/isNil.md)를 사용하세요. - -::: - -값이 `null` 또는 `undefined`인지 확인해요. - -```typescript -const result = isNil(value); -``` - -## 사용법 - -### `isNil(x)` - -값이 `null` 또는 `undefined`인지 타입 안전하게 확인하고 싶을 때 `isNil`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isNil } from 'es-toolkit/compat'; - -// null과 undefined는 true -isNil(null); // true -isNil(undefined); // true - -// 다른 모든 값들은 false -isNil(0); // false -isNil(''); // false -isNil(false); // false -isNil([]); // false -isNil({}); // false -isNil('hello'); // false -isNil(42); // false -``` - -참으로 평가되지만 `null`이나 `undefined`가 아닌 값들과 구분해요. - -```typescript -import { isNil } from 'es-toolkit/compat'; - -// 거짓으로 평가되지만 null/undefined가 아닌 값들 -isNil(0); // false -isNil(''); // false -isNil(false); // false -isNil(NaN); // false - -// null과 undefined만 true -isNil(null); // true -isNil(undefined); // true -``` - -#### 파라미터 - -- `x` (`any`): `null` 또는 `undefined`인지 확인할 값이에요. - -#### 반환 값 - -(`x is null | undefined`): 값이 `null` 또는 `undefined`이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isNull.md b/docs/ko/reference/compat/predicate/isNull.md deleted file mode 100644 index 8efb1cf38..000000000 --- a/docs/ko/reference/compat/predicate/isNull.md +++ /dev/null @@ -1,68 +0,0 @@ -# isNull (Lodash 호환성) - -::: warning es-toolkit의 [isNull](../../predicate/isNull.md)를 사용하세요 - -이 `isNull` 함수는 Lodash 호환성을 위한 함수이지만, 메인 라이브러리와 같은 구현이에요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isNull](../../predicate/isNull.md)를 사용하세요. - -::: - -값이 `null`인지 확인해요. - -```typescript -const result = isNull(value); -``` - -## 사용법 - -### `isNull(value)` - -값이 정확히 `null`인지 타입 안전하게 확인하고 싶을 때 `isNull`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isNull } from 'es-toolkit/compat'; - -// null만 true -isNull(null); // true - -// undefined도 false -isNull(undefined); // false - -// 다른 모든 값들도 false -isNull(0); // false -isNull(''); // false -isNull(false); // false -isNull([]); // false -isNull({}); // false -isNull('null'); // false -isNull(NaN); // false -``` - -`null`과 `undefined`를 구분해서 확인할 수 있어요. - -```typescript -import { isNull } from 'es-toolkit/compat'; - -function handleValue(value: string | null | undefined) { - if (isNull(value)) { - console.log('값이 명시적으로 null이에요'); - } else if (value === undefined) { - console.log('값이 undefined에요'); - } else { - console.log(`값이 있어요: ${value}`); - } -} - -handleValue(null); // "값이 명시적으로 null이에요" -handleValue(undefined); // "값이 undefined에요" -handleValue('hello'); // "값이 있어요: hello" -``` - -#### 파라미터 - -- `value` (`any`): `null`인지 확인할 값이에요. - -#### 반환 값 - -(`value is null`): 값이 `null`이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isPlainObject.md b/docs/ko/reference/compat/predicate/isPlainObject.md deleted file mode 100644 index 6776f9530..000000000 --- a/docs/ko/reference/compat/predicate/isPlainObject.md +++ /dev/null @@ -1,85 +0,0 @@ -# isPlainObject (Lodash 호환성) - -::: warning es-toolkit의 [isPlainObject](../../predicate/isPlainObject.md)를 사용하세요 - -이 `isPlainObject` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isPlainObject](../../predicate/isPlainObject.md)를 사용하세요. - -::: - -값이 순수 객체인지 확인해요. - -```typescript -const result = isPlainObject(object); -``` - -## 사용법 - -### `isPlainObject(object)` - -값이 순수 객체인지 확인하고 싶을 때 `isPlainObject`를 사용하세요. 순수 객체는 `{}` 리터럴, `new Object()`, 또는 `Object.create(null)`로 생성된 객체예요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -// 순수 객체들 -isPlainObject({}); // true -isPlainObject(new Object()); // true -isPlainObject(Object.create(null)); // true -isPlainObject({ name: 'John', age: 30 }); // true - -// 순수 객체가 아닌 값들 -isPlainObject([]); // false (배열) -isPlainObject(new Date()); // false (Date 인스턴스) -isPlainObject(new Map()); // false (Map 인스턴스) -isPlainObject(new Set()); // false (Set 인스턴스) -isPlainObject(/regex/); // false (정규식) -isPlainObject(function () {}); // false (함수) -isPlainObject(null); // false -isPlainObject(undefined); // false -isPlainObject('object'); // false (문자열) -isPlainObject(42); // false (숫자) -``` - -클래스 인스턴스와 순수 객체를 구분해요. - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -class Person { - name: string; - constructor(name: string) { - this.name = name; - } -} - -const person = new Person('John'); -const plainObj = { name: 'John' }; - -isPlainObject(person); // false (클래스 인스턴스) -isPlainObject(plainObj); // true (순수 객체) -``` - -커스텀 `Symbol.toStringTag` 속성도 올바르게 처리해요. - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -// 쓰기 가능한 Symbol.toStringTag -const obj1 = {}; -obj1[Symbol.toStringTag] = 'CustomObject'; -isPlainObject(obj1); // true - -// 읽기 전용 Symbol.toStringTag (내장 객체들) -const date = new Date(); -isPlainObject(date); // false -``` - -#### 파라미터 - -- `object` (`any`): 순수 객체인지 확인할 값이에요. - -#### 반환 값 - -(`boolean`): 값이 순수 객체이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isRegExp.md b/docs/ko/reference/compat/predicate/isRegExp.md deleted file mode 100644 index 72a43ffaf..000000000 --- a/docs/ko/reference/compat/predicate/isRegExp.md +++ /dev/null @@ -1,82 +0,0 @@ -# isRegExp (Lodash 호환성) - -::: warning es-toolkit의 [isRegExp](../../predicate/isRegExp.md)를 사용하세요 - -이 `isRegExp` 함수는 Lodash 호환성을 위한 함수이지만, 단순한 타입 확인이에요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isRegExp](../../predicate/isRegExp.md)를 사용하세요. - -::: - -값이 정규식인지 확인해요. - -```typescript -const result = isRegExp(value); -``` - -## 사용법 - -### `isRegExp(value)` - -값이 정규식인지 타입 안전하게 확인하고 싶을 때 `isRegExp`을 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// 정규식들 -isRegExp(/abc/); // true -isRegExp(new RegExp('abc')); // true -isRegExp(/[a-z]+/g); // true -isRegExp(/pattern/gi); // true - -// 다른 타입들은 false -isRegExp('/abc/'); // false (문자열) -isRegExp('pattern'); // false (문자열) -isRegExp({}); // false (객체) -isRegExp([]); // false (배열) -isRegExp(null); // false -isRegExp(undefined); // false -isRegExp(123); // false (숫자) -``` - -정규식 문자열과 실제 정규식 객체를 구분해요. - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// 정규식 vs 정규식 문자열 -isRegExp(/test/); // true -isRegExp('/test/'); // false -isRegExp('\\d+'); // false -isRegExp('/\\d+/g'); // false - -// 다양한 정규식 플래그들 -isRegExp(/test/i); // true (대소문자 무시) -isRegExp(/test/g); // true (전역 검색) -isRegExp(/test/m); // true (다중행) -isRegExp(/test/gim); // true (모든 플래그 조합) -``` - -동적으로 생성된 정규식도 인식해요. - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// RegExp 생성자로 만든 정규식 -const dynamicRegex = new RegExp('\\d{3}-\\d{4}', 'g'); -isRegExp(dynamicRegex); // true - -// 문자열을 통해 생성한 정규식 -const pattern = 'hello'; -const flags = 'gi'; -const regex = new RegExp(pattern, flags); -isRegExp(regex); // true -``` - -#### 파라미터 - -- `value` (`any`): 정규식인지 확인할 값이에요. - -#### 반환 값 - -(`value is RegExp`): 값이 정규식이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isSet.md b/docs/ko/reference/compat/predicate/isSet.md deleted file mode 100644 index 3c93df79b..000000000 --- a/docs/ko/reference/compat/predicate/isSet.md +++ /dev/null @@ -1,67 +0,0 @@ -# isSet (Lodash 호환성) - -::: warning `es-toolkit`의 [isSet](../../predicate/isSet.md)를 사용하세요 - -이 `isSet` 함수는 Lodash 호환성을 위한 함수이지만, 메인 라이브러리와 같은 구현이에요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isSet](../../predicate/isSet.md)를 사용하세요. - -::: - -값이 Set인지 확인해요. - -```typescript -const result = isSet(value); -``` - -## 사용법 - -### `isSet(value)` - -값이 Set인지 타입 안전하게 확인하고 싶을 때 `isSet`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isSet } from 'es-toolkit/compat'; - -// Set 확인 -const set = new Set(); -isSet(set); // true - -// 다른 타입들은 false -isSet(new Map()); // false -isSet(new WeakSet()); // false -isSet([]); // false -isSet({}); // false -isSet('set'); // false -isSet(123); // false -isSet(null); // false -isSet(undefined); // false -``` - -Set과 비슷한 다른 컬렉션들과도 구분해요. - -```typescript -import { isSet } from 'es-toolkit/compat'; - -// Set vs Map vs WeakSet -isSet(new Set([1, 2, 3])); // true -isSet(new Map([['key', 'value']])); // false -isSet(new WeakSet()); // false - -// Set vs 배열 -isSet(new Set([1, 2, 3])); // true -isSet([1, 2, 3]); // false - -// Set vs 일반 객체 -isSet(new Set()); // true -isSet({}); // false -isSet(Object.create(null)); // false -``` - -#### 파라미터 - -- `value` (`unknown`): Set인지 확인할 값이에요. - -#### 반환 값 - -(`value is Set`): 값이 Set이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/predicate/isUndefined.md b/docs/ko/reference/compat/predicate/isUndefined.md deleted file mode 100644 index 0356847bc..000000000 --- a/docs/ko/reference/compat/predicate/isUndefined.md +++ /dev/null @@ -1,92 +0,0 @@ -# isUndefined (Lodash 호환성) - -::: warning es-toolkit의 [ isUndefined](../../predicate/isUndefined.md)를 사용하세요 - -이 `isUndefined` 함수는 Lodash 호환성을 위한 복잡한 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [isUndefined](../../predicate/isUndefined.md)를 사용하세요. - -::: - -값이 `undefined`인지 확인해요. - -```typescript -const result = isUndefined(value); -``` - -## 사용법 - -### `isUndefined(x)` - -값이 정확히 `undefined`인지 타입 안전하게 확인하고 싶을 때 `isUndefined`를 사용하세요. TypeScript에서 타입 가드로도 동작해요. - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -// undefined만 true -isUndefined(undefined); // true - -// null도 false -isUndefined(null); // false - -// 다른 모든 값들도 false -isUndefined(0); // false -isUndefined(''); // false -isUndefined(false); // false -isUndefined([]); // false -isUndefined({}); // false -isUndefined('undefined'); // false -isUndefined(NaN); // false -``` - -`undefined`와 `null`을 구분해서 확인할 수 있어요. - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -function handleValue(value: string | null | undefined) { - if (isUndefined(value)) { - console.log('값이 undefined에요'); - } else if (value === null) { - console.log('값이 명시적으로 null이에요'); - } else { - console.log(`값이 있어요: ${value}`); - } -} - -handleValue(undefined); // "값이 undefined에요" -handleValue(null); // "값이 명시적으로 null이에요" -handleValue('hello'); // "값이 있어요: hello" -``` - -선언되지 않은 변수나 초기화되지 않은 속성을 확인할 때 유용해요. - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -const obj: { name?: string; age?: number } = { name: 'John' }; - -if (isUndefined(obj.age)) { - console.log('나이가 설정되지 않았어요'); - obj.age = 25; // 기본값 설정 -} - -// 함수 매개변수의 기본값 처리 -function greet(name: string, title?: string) { - if (isUndefined(title)) { - title = '님'; - } - console.log(`안녕하세요, ${name}${title}!`); -} - -greet('김철수'); // "안녕하세요, 김철수님!" -greet('김철수', '선생'); // "안녕하세요, 김철수선생!" -``` - -#### 파라미터 - -- `x` (`any`): `undefined`인지 확인할 값이에요. - -#### 반환 값 - -(`x is undefined`): 값이 `undefined`이면 `true`, 아니면 `false`를 반환해요. diff --git a/docs/ko/reference/compat/string/camelCase.md b/docs/ko/reference/compat/string/camelCase.md deleted file mode 100644 index e0538feaa..000000000 --- a/docs/ko/reference/compat/string/camelCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# camelCase (Lodash 호환성) - -::: warning `es-toolkit`의 `camelCase`를 사용하세요 - -이 `camelCase` 함수는 문자열이 아닌 입력값 처리와 축약 아포스트로피 제거 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [camelCase](../../string/camelCase.md)를 사용하세요. - -::: - -문자열을 카멜 케이스로 변환해요. - -```typescript -const result = camelCase(str); -``` - -## 사용법 - -### `camelCase(str)` - -문자열을 카멜 케이스로 변환해요. 카멜 케이스는 첫 번째 단어는 소문자로 시작하고, 이후 단어들의 첫 글자는 대문자로 하여 공백 없이 연결하는 명명 규칙이에요. - -```typescript -import { camelCase } from 'es-toolkit/compat'; - -camelCase('camelCase'); // 'camelCase' -camelCase('some whitespace'); // 'someWhitespace' -camelCase('hyphen-text'); // 'hyphenText' -camelCase('HTTPRequest'); // 'httpRequest' -``` - -문자열이 아닌 값도 문자열로 변환해서 처리해요. - -```typescript -import { camelCase } from 'es-toolkit/compat'; - -camelCase(123); // '123' -camelCase(null); // '' -camelCase(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string | object`, 선택): 카멜 케이스로 변환할 값이에요. - -#### 반환 값 - -(`string`): 카멜 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/capitalize.md b/docs/ko/reference/compat/string/capitalize.md deleted file mode 100644 index eeb4ae8df..000000000 --- a/docs/ko/reference/compat/string/capitalize.md +++ /dev/null @@ -1,48 +0,0 @@ -# capitalize (Lodash 호환성) - -::: warning `es-toolkit`의 `capitalize`를 사용하세요 - -이 `capitalize` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [capitalize](../../string/capitalize.md)를 사용하세요. - -::: - -문자열의 첫 글자를 대문자로, 나머지 글자는 소문자로 변환해요. - -```typescript -const result = capitalize(str); -``` - -## 사용법 - -### `capitalize(str)` - -문자열의 첫 글자를 대문자로, 나머지 글자는 소문자로 변환해요. 단어의 첫 인상을 좋게 하거나 제목 형태로 만들 때 유용해요. - -```typescript -import { capitalize } from 'es-toolkit/compat'; - -capitalize('fred'); // 'Fred' -capitalize('FRED'); // 'Fred' -capitalize('fRED'); // 'Fred' -``` - -빈 문자열이나 문자열이 아닌 값도 처리할 수 있어요. - -```typescript -import { capitalize } from 'es-toolkit/compat'; - -capitalize(''); // '' -capitalize(123); // '123' -capitalize(null); // '' -capitalize(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 첫 글자를 대문자로 변환할 문자열이에요. - -#### 반환 값 - -(`string`): 첫 글자가 대문자이고 나머지가 소문자인 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/deburr.md b/docs/ko/reference/compat/string/deburr.md deleted file mode 100644 index 0c28444aa..000000000 --- a/docs/ko/reference/compat/string/deburr.md +++ /dev/null @@ -1,47 +0,0 @@ -# deburr (Lodash 호환성) - -::: warning `es-toolkit`의 `deburr`를 사용하세요 - -이 `deburr` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [deburr](../../string/deburr.md)를 사용하세요. - -::: - -문자열에서 특수 문자와 발음 구별 기호를 ASCII 문자로 변환해요. - -```typescript -const result = deburr(str); -``` - -## 사용법 - -### `deburr(str)` - -문자열에서 특수 문자와 발음 구별 기호를 ASCII 문자로 변환해요. 다국어 텍스트를 검색이나 정렬에 사용하기 쉽게 만들 때 유용해요. - -```typescript -import { deburr } from 'es-toolkit/compat'; - -deburr('Æthelred'); // 'Aethelred' -deburr('München'); // 'Munchen' -deburr('Crème brûlée'); // 'Creme brulee' -``` - -문자열이 아닌 값도 문자열로 변환해서 처리해요. - -```typescript -import { deburr } from 'es-toolkit/compat'; - -deburr(123); // '123' -deburr(null); // '' -deburr(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 특수 문자를 제거할 문자열이에요. - -#### 반환 값 - -(`string`): 특수 문자와 발음 구별 기호가 ASCII 문자로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/escape.md b/docs/ko/reference/compat/string/escape.md deleted file mode 100644 index 821d3169d..000000000 --- a/docs/ko/reference/compat/string/escape.md +++ /dev/null @@ -1,48 +0,0 @@ -# escape (Lodash 호환성) - -::: warning `es-toolkit`의 `escape`를 사용하세요 - -이 `escape` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [escape](../../string/escape.md)를 사용하세요. - -::: - -문자열에서 HTML 특수 문자를 HTML 엔티티로 변환해요. - -```typescript -const result = escape(str); -``` - -## 사용법 - -### `escape(str)` - -문자열에서 `&`, `<`, `>`, `"`, `'` 문자를 해당하는 HTML 엔티티로 변환해요. HTML 문서에 텍스트를 안전하게 삽입할 때 XSS 공격을 방지하는 데 유용해요. - -```typescript -import { escape } from 'es-toolkit/compat'; - -escape('This is a
element.'); // 'This is a <div> element.' -escape('This is a "quote"'); // 'This is a "quote"' -escape("This is a 'quote'"); // 'This is a 'quote'' -escape('This is a & symbol'); // 'This is a & symbol' -``` - -문자열이 아닌 값도 문자열로 변환해서 처리해요. - -```typescript -import { escape } from 'es-toolkit/compat'; - -escape(123); // '123' -escape(null); // '' -escape(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): HTML 특수 문자를 이스케이프할 문자열이에요. - -#### 반환 값 - -(`string`): HTML 특수 문자가 엔티티로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/escapeRegExp.md b/docs/ko/reference/compat/string/escapeRegExp.md deleted file mode 100644 index 0f4fd9788..000000000 --- a/docs/ko/reference/compat/string/escapeRegExp.md +++ /dev/null @@ -1,49 +0,0 @@ -# escapeRegExp (Lodash 호환성) - -::: warning `es-toolkit`의 `escapeRegExp`를 사용하세요 - -이 `escapeRegExp` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [escapeRegExp](../../string/escapeRegExp.md)를 사용하세요. - -::: - -문자열에서 정규 표현식 특수 문자를 이스케이프해요. - -```typescript -const result = escapeRegExp(str); -``` - -## 사용법 - -### `escapeRegExp(str)` - -문자열에서 정규 표현식 특수 문자 `^`, `$`, `\`, `.`, `*`, `+`, `?`, `(`, `)`, `[`, `]`, `{`, `}`, `|`를 이스케이프해요. 동적으로 정규 표현식을 생성할 때 문자열을 문자 그대로 처리하고 싶을 때 유용해요. - -```typescript -import { escapeRegExp } from 'es-toolkit/compat'; - -escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); -// '\\[es-toolkit\\]\\(https://es-toolkit\\.dev/\\)' - -escapeRegExp('$^{}.+*?()[]|\\'); -// '\\$\\^\\{\\}\\.\\+\\*\\?\\(\\)\\[\\]\\|\\\\' -``` - -문자열이 아닌 값도 문자열로 변환해서 처리해요. - -```typescript -import { escapeRegExp } from 'es-toolkit/compat'; - -escapeRegExp(123); // '123' -escapeRegExp(null); // '' -escapeRegExp(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 정규 표현식 특수 문자를 이스케이프할 문자열이에요. - -#### 반환 값 - -(`string`): 정규 표현식 특수 문자가 이스케이프된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/kebabCase.md b/docs/ko/reference/compat/string/kebabCase.md deleted file mode 100644 index 2fc2ea507..000000000 --- a/docs/ko/reference/compat/string/kebabCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# kebabCase (Lodash 호환성) - -::: warning `es-toolkit`의 `kebabCase`를 사용하세요 - -이 `kebabCase` 함수는 문자열이 아닌 입력값 처리와 축약 아포스트로피 제거 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [kebabCase](../../string/kebabCase.md)를 사용하세요. - -::: - -문자열을 케밥 케이스로 변환해요. - -```typescript -const result = kebabCase(str); -``` - -## 사용법 - -### `kebabCase(str)` - -문자열을 케밥 케이스로 변환해요. 케밥 케이스는 각 단어를 소문자로 쓰고 대시(-) 문자로 연결하는 명명 규칙이에요. URL이나 CSS 클래스 이름에서 주로 사용돼요. - -```typescript -import { kebabCase } from 'es-toolkit/compat'; - -kebabCase('camelCase'); // 'camel-case' -kebabCase('some whitespace'); // 'some-whitespace' -kebabCase('hyphen-text'); // 'hyphen-text' -kebabCase('HTTPRequest'); // 'http-request' -``` - -문자열이 아닌 값도 문자열로 변환해서 처리해요. - -```typescript -import { kebabCase } from 'es-toolkit/compat'; - -kebabCase(123); // '123' -kebabCase(null); // '' -kebabCase(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string | object`, 선택): 케밥 케이스로 변환할 값이에요. - -#### 반환 값 - -(`string`): 케밥 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/lowerCase.md b/docs/ko/reference/compat/string/lowerCase.md deleted file mode 100644 index 3bcb0bb41..000000000 --- a/docs/ko/reference/compat/string/lowerCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# lowerCase (Lodash 호환성) - -::: warning `es-toolkit`의 `lowerCase`를 사용하세요 - -이 `lowerCase` 함수는 문자열이 아닌 입력값 처리와 축약 아포스트로피 제거 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [lowerCase](../../string/lowerCase.md)를 사용하세요. - -::: - -문자열을 소문자로 된 단어들을 공백으로 분리한 형태로 변환해요. - -```typescript -const result = lowerCase(str); -``` - -## 사용법 - -### `lowerCase(str)` - -문자열을 소문자로 된 단어들을 공백으로 분리한 형태로 변환해요. 각 단어는 소문자로 변환되고 공백 문자로 연결돼요. 사람이 읽기 쉬운 텍스트 형태로 만들 때 유용해요. - -```typescript -import { lowerCase } from 'es-toolkit/compat'; - -lowerCase('camelCase'); // 'camel case' -lowerCase('some whitespace'); // 'some whitespace' -lowerCase('hyphen-text'); // 'hyphen text' -lowerCase('HTTPRequest'); // 'http request' -``` - -문자열이 아닌 값도 문자열로 변환해서 처리해요. - -```typescript -import { lowerCase } from 'es-toolkit/compat'; - -lowerCase(123); // '123' -lowerCase(null); // '' -lowerCase(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string | object`, 선택): 소문자 형태로 변환할 값이에요. - -#### 반환 값 - -(`string`): 소문자로 된 단어들이 공백으로 분리된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/lowerFirst.md b/docs/ko/reference/compat/string/lowerFirst.md deleted file mode 100644 index bb843350f..000000000 --- a/docs/ko/reference/compat/string/lowerFirst.md +++ /dev/null @@ -1,48 +0,0 @@ -# lowerFirst (Lodash 호환성) - -::: warning `es-toolkit`의 `lowerFirst`를 사용하세요 - -이 `lowerFirst` 함수는 문자열이 아닌 입력값 처리로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [lowerFirst](../../string/lowerFirst.md)를 사용하세요. - -::: - -문자열의 첫 글자를 소문자로 변환해요. - -```typescript -const result = lowerFirst(str); -``` - -## 사용법 - -### `lowerFirst(str)` - -문자열의 첫 글자를 소문자로 변환해요. 나머지 글자들은 그대로 유지돼요. 변수명을 camelCase로 만들거나 첫 글자만 소문자로 바꾸고 싶을 때 유용해요. - -```typescript -import { lowerFirst } from 'es-toolkit/compat'; - -lowerFirst('fred'); // 'fred' -lowerFirst('Fred'); // 'fred' -lowerFirst('FRED'); // 'fRED' -lowerFirst(''); // '' -``` - -문자열이 아닌 값도 문자열로 변환해서 처리해요. - -```typescript -import { lowerFirst } from 'es-toolkit/compat'; - -lowerFirst(123); // '123' -lowerFirst(null); // '' -lowerFirst(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 첫 글자를 소문자로 변환할 문자열이에요. - -#### 반환 값 - -(`string`): 첫 글자가 소문자로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/pad.md b/docs/ko/reference/compat/string/pad.md deleted file mode 100644 index 292e18ff7..000000000 --- a/docs/ko/reference/compat/string/pad.md +++ /dev/null @@ -1,60 +0,0 @@ -# pad (Lodash 호환성) - -::: warning `es-toolkit`의 `pad`를 사용하세요 - -이 `pad` 함수는 `null`이나 `undefined` 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [pad](../../string/pad.md)를 사용하세요. - -::: - -문자열의 앞뒤로 패딩 문자를 추가해서 지정된 길이만큼 맞춰요. - -```typescript -const padded = pad(str, length, chars); -``` - -## 사용법 - -### `pad(str, length, chars)` - -문자열이 원하는 길이보다 짧을 때 앞뒤로 패딩 문자를 추가해서 길이를 맞추고 싶을 때 `pad`를 사용하세요. 패딩 문자가 균등하게 나누어 떨어지지 않으면, 추가 문자는 오른쪽에 배치돼요. - -```typescript -import { pad } from 'es-toolkit/compat'; - -// 기본 공백으로 패딩 -pad('abc', 8); -// Returns: ' abc ' - -// 지정된 문자로 패딩 -pad('abc', 8, '_-'); -// Returns: '_-abc_-_' - -// 이미 충분한 길이이면 그대로 반환 -pad('abc', 3); -// Returns: 'abc' - -// 길이가 더 짧으면 그대로 반환 -pad('abc', 2); -// Returns: 'abc' -``` - -`null`이나 `undefined`는 빈 문자열로 처리해요. - -```typescript -import { pad } from 'es-toolkit/compat'; - -pad(null, 5); // ' ' -pad(undefined, 3, '*'); // '***' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 패딩할 문자열이에요. -- `length` (`number`, 선택): 목표 길이예요. 기본값은 `0`이에요. -- `chars` (`string`, 선택): 패딩에 사용할 문자들이에요. 기본값은 공백 `' '`이에요. - -#### 반환 값 - -(`string`): 지정된 길이만큼 패딩된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/snakeCase.md b/docs/ko/reference/compat/string/snakeCase.md deleted file mode 100644 index 616c2ebf3..000000000 --- a/docs/ko/reference/compat/string/snakeCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# snakeCase (Lodash 호환성) - -::: warning `es-toolkit`의 `snakeCase`를 사용하세요 - -이 `snakeCase` 함수는 `null`이나 `undefined` 처리를 위한 정규화 로직으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [snakeCase](../../string/snakeCase.md)를 사용하세요. - -::: - -문자열을 스네이크 케이스로 변환해요. - -```typescript -const snakeCased = snakeCase(str); -``` - -## 사용법 - -### `snakeCase(str)` - -문자열을 스네이크 케이스(snake*case)로 변환하고 싶을 때 `snakeCase`를 사용하세요. 스네이크 케이스는 각 단어를 소문자로 쓰고 밑줄(*)로 연결하는 명명 규칙이에요. - -```typescript -import { snakeCase } from 'es-toolkit/compat'; - -// 카멜 케이스 변환 -snakeCase('camelCase'); -// Returns: 'camel_case' - -// 공백으로 구분된 문자열 변환 -snakeCase('some whitespace'); -// Returns: 'some_whitespace' - -// 하이픈으로 구분된 문자열 변환 -snakeCase('hyphen-text'); -// Returns: 'hyphen_text' - -// 대문자가 연속으로 나타나는 경우 -snakeCase('HTTPRequest'); -// Returns: 'http_request' -``` - -`null`이나 `undefined`는 빈 문자열로 처리해요. - -```typescript -import { snakeCase } from 'es-toolkit/compat'; - -snakeCase(null); // '' -snakeCase(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 스네이크 케이스로 변환할 문자열이에요. - -#### 반환 값 - -(`string`): 스네이크 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/startCase.md b/docs/ko/reference/compat/string/startCase.md deleted file mode 100644 index 72d6e67a0..000000000 --- a/docs/ko/reference/compat/string/startCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# startCase (Lodash 호환성) - -::: warning `es-toolkit`의 `startCase`를 사용하세요 - -이 `startCase` 함수는 `null`이나 `undefined` 처리를 위한 정규화 로직으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [startCase](../../string/startCase.md)를 사용하세요. - -::: - -문자열을 스타트 케이스로 변환해요. - -```typescript -const startCased = startCase(str); -``` - -## 사용법 - -### `startCase(str)` - -문자열을 스타트 케이스(Start Case)로 변환하고 싶을 때 `startCase`를 사용하세요. 스타트 케이스는 각 단어의 첫 글자를 대문자로 쓰고 공백으로 구분하는 명명 규칙이에요. - -```typescript -import { startCase } from 'es-toolkit/compat'; - -// 일반 문자열 변환 -startCase('hello world'); -// Returns: 'Hello World' - -// 이미 대문자인 단어는 그대로 유지 -startCase('HELLO WORLD'); -// Returns: 'HELLO WORLD' - -// 하이픈으로 구분된 문자열 변환 -startCase('hello-world'); -// Returns: 'Hello World' - -// 밑줄로 구분된 문자열 변환 -startCase('hello_world'); -// Returns: 'Hello World' -``` - -`null`이나 `undefined`는 빈 문자열로 처리해요. - -```typescript -import { startCase } from 'es-toolkit/compat'; - -startCase(null); // '' -startCase(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 스타트 케이스로 변환할 문자열이에요. - -#### 반환 값 - -(`string`): 스타트 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/trim.md b/docs/ko/reference/compat/string/trim.md deleted file mode 100644 index e17f52758..000000000 --- a/docs/ko/reference/compat/string/trim.md +++ /dev/null @@ -1,55 +0,0 @@ -# trim (Lodash 호환성) - -::: warning `es-toolkit`의 `trim`을 사용하세요 - -이 `trim` 함수는 `null`이나 `undefined` 처리, 배열 형태의 `chars` 처리 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [trim](../../string/trim.md)을 사용하세요. - -::: - -문자열의 앞뒤 공백이나 지정된 문자들을 제거해요. - -```typescript -const trimmed = trim(str, chars); -``` - -## 사용법 - -### `trim(str, chars)` - -문자열의 앞뒤에서 공백이나 특정 문자들을 제거하고 싶을 때 `trim`을 사용하세요. `chars`를 지정하지 않으면 앞뒤 공백만 제거해요. - -```typescript -import { trim } from 'es-toolkit/compat'; - -// 앞뒤 공백 제거 -trim(' hello '); -// Returns: 'hello' - -// 지정된 문자 제거 -trim('--hello--', '-'); -// Returns: 'hello' - -// 배열로 여러 문자 제거 -trim('##hello##', ['#', 'o']); -// Returns: 'hell' -``` - -`null`이나 `undefined`는 빈 문자열로 처리해요. - -```typescript -import { trim } from 'es-toolkit/compat'; - -trim(null); // '' -trim(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 정리할 문자열이에요. -- `chars` (`string`, 선택): 제거할 문자들이에요. 지정하지 않으면 공백을 제거해요. - -#### 반환 값 - -(`string`): 앞뒤의 지정된 문자들이 제거된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/trimEnd.md b/docs/ko/reference/compat/string/trimEnd.md deleted file mode 100644 index 4cbe6270d..000000000 --- a/docs/ko/reference/compat/string/trimEnd.md +++ /dev/null @@ -1,55 +0,0 @@ -# trimEnd (Lodash 호환성) - -::: warning `es-toolkit`의 `trimEnd`를 사용하세요 - -이 `trimEnd` 함수는 `null`이나 `undefined` 처리, 파라미터 순서 변경 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [trimEnd](../../string/trimEnd.md)를 사용하세요. - -::: - -문자열의 뒤쪽 공백이나 지정된 문자들을 제거해요. - -```typescript -const trimmed = trimEnd(str, chars); -``` - -## 사용법 - -### `trimEnd(str, chars)` - -문자열의 뒤쪽에서 공백이나 특정 문자들을 제거하고 싶을 때 `trimEnd`를 사용하세요. `chars`를 지정하지 않으면 뒤쪽 공백만 제거해요. - -```typescript -import { trimEnd } from 'es-toolkit/compat'; - -// 뒤쪽 공백 제거 -trimEnd(' abc '); -// Returns: ' abc' - -// 지정된 문자 제거 -trimEnd('-_-abc-_-', '_-'); -// Returns: '-_-abc' - -// 문자열의 뒤쪽에만 적용 -trimEnd('abc', 'a'); -// Returns: 'abc' -``` - -`null`이나 `undefined`는 빈 문자열로 처리해요. - -```typescript -import { trimEnd } from 'es-toolkit/compat'; - -trimEnd(null); // '' -trimEnd(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 뒤쪽을 정리할 문자열이에요. -- `chars` (`string`, 선택): 제거할 문자들이에요. 지정하지 않으면 공백을 제거해요. - -#### 반환 값 - -(`string`): 뒤쪽의 지정된 문자들이 제거된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/trimStart.md b/docs/ko/reference/compat/string/trimStart.md deleted file mode 100644 index 391ccdd5e..000000000 --- a/docs/ko/reference/compat/string/trimStart.md +++ /dev/null @@ -1,55 +0,0 @@ -# trimStart (Lodash 호환성) - -::: warning `es-toolkit`의 `trimStart`를 사용하세요 - -이 `trimStart` 함수는 `null`이나 `undefined` 처리, 파라미터 순서 변경 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [trimStart](../../string/trimStart.md)를 사용하세요. - -::: - -문자열의 앞쪽 공백이나 지정된 문자들을 제거해요. - -```typescript -const trimmed = trimStart(str, chars); -``` - -## 사용법 - -### `trimStart(str, chars)` - -문자열의 앞쪽에서 공백이나 특정 문자들을 제거하고 싶을 때 `trimStart`를 사용하세요. `chars`를 지정하지 않으면 앞쪽 공백만 제거해요. - -```typescript -import { trimStart } from 'es-toolkit/compat'; - -// 앞쪽 공백 제거 -trimStart(' abc '); -// Returns: 'abc ' - -// 지정된 문자 제거 -trimStart('-_-abc-_-', '_-'); -// Returns: 'abc-_-' - -// 문자열의 앞쪽에만 적용 -trimStart('abc', 'c'); -// Returns: 'abc' -``` - -`null`이나 `undefined`는 빈 문자열로 처리해요. - -```typescript -import { trimStart } from 'es-toolkit/compat'; - -trimStart(null); // '' -trimStart(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 앞쪽을 정리할 문자열이에요. -- `chars` (`string`, 선택): 제거할 문자들이에요. 지정하지 않으면 공백을 제거해요. - -#### 반환 값 - -(`string`): 앞쪽의 지정된 문자들이 제거된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/unescape.md b/docs/ko/reference/compat/string/unescape.md deleted file mode 100644 index b87af1c01..000000000 --- a/docs/ko/reference/compat/string/unescape.md +++ /dev/null @@ -1,58 +0,0 @@ -# unescape (Lodash 호환성) - -::: warning `es-toolkit`의 `unescape`를 사용하세요 - -이 `unescape` 함수는 `null`이나 `undefined` 처리를 위한 변환 로직으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [unescape](../../string/unescape.md)를 사용하세요. - -::: - -HTML 엔터티를 원래 문자로 변환해요. - -```typescript -const unescaped = unescape(str); -``` - -## 사용법 - -### `unescape(str)` - -HTML 엔터티 `&`, `<`, `>`, `"`, `'`를 원래 문자로 되돌리고 싶을 때 `unescape`를 사용하세요. 이는 `escape` 함수의 반대 동작을 해요. - -```typescript -import { unescape } from 'es-toolkit/compat'; - -// HTML 태그 언이스케이프 -unescape('This is a <div> element.'); -// Returns: 'This is a
element.' - -// 따옴표 언이스케이프 -unescape('This is a "quote"'); -// Returns: 'This is a "quote"' - -// 작은따옴표 언이스케이프 -unescape('This is a 'quote''); -// Returns: 'This is a 'quote'' - -// 앰퍼샌드 언이스케이프 -unescape('This is a & symbol'); -// Returns: 'This is a & symbol' -``` - -`null`이나 `undefined`는 빈 문자열로 처리해요. - -```typescript -import { unescape } from 'es-toolkit/compat'; - -unescape(null); // '' -unescape(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 언이스케이프할 문자열이에요. - -#### 반환 값 - -(`string`): HTML 엔터티가 원래 문자로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/upperCase.md b/docs/ko/reference/compat/string/upperCase.md deleted file mode 100644 index a6bf0e2c0..000000000 --- a/docs/ko/reference/compat/string/upperCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# upperCase (Lodash 호환성) - -::: warning `es-toolkit`의 `upperCase`를 사용하세요 - -이 `upperCase` 함수는 `null`이나 `undefined` 처리를 위한 정규화 로직으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [upperCase](../../string/upperCase.md)를 사용하세요. - -::: - -문자열을 대문자 케이스로 변환해요. - -```typescript -const upperCased = upperCase(str); -``` - -## 사용법 - -### `upperCase(str)` - -문자열을 대문자 케이스(UPPER CASE)로 변환하고 싶을 때 `upperCase`를 사용하세요. 대문자 케이스는 각 단어를 대문자로 쓰고 공백으로 연결하는 명명 규칙이에요. - -```typescript -import { upperCase } from 'es-toolkit/compat'; - -// 카멜 케이스 변환 -upperCase('camelCase'); -// Returns: 'CAMEL CASE' - -// 공백으로 구분된 문자열 변환 -upperCase('some whitespace'); -// Returns: 'SOME WHITESPACE' - -// 하이픈으로 구분된 문자열 변환 -upperCase('hyphen-text'); -// Returns: 'HYPHEN TEXT' - -// 대문자가 연속으로 나타나는 경우 -upperCase('HTTPRequest'); -// Returns: 'HTTP REQUEST' -``` - -`null`이나 `undefined`는 빈 문자열로 처리해요. - -```typescript -import { upperCase } from 'es-toolkit/compat'; - -upperCase(null); // '' -upperCase(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 대문자 케이스로 변환할 문자열이에요. - -#### 반환 값 - -(`string`): 대문자 케이스로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/upperFirst.md b/docs/ko/reference/compat/string/upperFirst.md deleted file mode 100644 index 960b0e146..000000000 --- a/docs/ko/reference/compat/string/upperFirst.md +++ /dev/null @@ -1,54 +0,0 @@ -# upperFirst (Lodash 호환성) - -::: warning `es-toolkit`의 `upperFirst`를 사용하세요 - -이 `upperFirst` 함수는 `null`이나 `undefined` 처리를 위한 변환 로직으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [upperFirst](../../string/upperFirst.md)를 사용하세요. - -::: - -문자열의 첫 번째 문자를 대문자로 변환해요. - -```typescript -const upperCased = upperFirst(str); -``` - -## 사용법 - -### `upperFirst(str)` - -문자열의 첫 번째 문자만 대문자로 만들고 싶을 때 `upperFirst`를 사용하세요. 나머지 문자들은 그대로 유지돼요. - -```typescript -import { upperFirst } from 'es-toolkit/compat'; - -// 소문자로 시작하는 문자열 -upperFirst('fred'); -// Returns: 'Fred' - -// 이미 대문자로 시작하는 문자열 -upperFirst('Fred'); -// Returns: 'Fred' - -// 모두 대문자인 문자열 -upperFirst('FRED'); -// Returns: 'FRED' -``` - -`null`이나 `undefined`는 빈 문자열로 처리해요. - -```typescript -import { upperFirst } from 'es-toolkit/compat'; - -upperFirst(null); // '' -upperFirst(undefined); // '' -``` - -#### 파라미터 - -- `str` (`string`, 선택): 첫 문자를 대문자로 변환할 문자열이에요. - -#### 반환 값 - -(`string`): 첫 문자가 대문자로 변환된 문자열을 반환해요. diff --git a/docs/ko/reference/compat/string/words.md b/docs/ko/reference/compat/string/words.md deleted file mode 100644 index 48aafe3bf..000000000 --- a/docs/ko/reference/compat/string/words.md +++ /dev/null @@ -1,69 +0,0 @@ -# words (Lodash 호환성) - -::: warning `es-toolkit`의 `words`를 사용하세요 - -이 `words` 함수는 `null`이나 `undefined` 처리, 복잡한 유니코드 지원 등으로 인해 느리게 동작해요. - -대신 더 빠르고 현대적인 `es-toolkit`의 [words](../../string/words.md)를 사용하세요. - -::: - -문자열을 단어들로 나누어요. - -```typescript -const wordArray = words(str, pattern); -``` - -## 사용법 - -### `words(str, pattern)` - -문자열을 단어 단위로 나누고 싶을 때 `words`를 사용하세요. 기본적으로 영문자, 숫자, 이모지 등을 인식하여 단어를 추출해요. - -```typescript -import { words } from 'es-toolkit/compat'; - -// 기본 단어 추출 -words('fred, barney, & pebbles'); -// Returns: ['fred', 'barney', 'pebbles'] - -// 카멜 케이스에서 단어 추출 -words('camelCaseWord'); -// Returns: ['camel', 'Case', 'Word'] - -// 숫자가 포함된 문자열 -words('hello123world'); -// Returns: ['hello', '123', 'world'] -``` - -사용자 정의 패턴을 사용하여 단어를 추출할 수도 있어요. - -```typescript -import { words } from 'es-toolkit/compat'; - -// 정규식을 사용한 단어 추출 -words('hello world', /\w+/g); -// Returns: ['hello', 'world'] - -// 문자열 패턴 사용 -words('one-two-three', '-'); -// Returns: ['-'] -``` - -`null`이나 `undefined`는 빈 배열로 처리해요. - -```typescript -import { words } from 'es-toolkit/compat'; - -words(null); // [] -words(undefined); // [] -``` - -#### 파라미터 - -- `str` (`string`, 선택): 단어로 나눌 문자열이에요. -- `pattern` (`RegExp | string`, 선택): 단어를 매치할 패턴이에요. 기본값은 내장 유니코드 단어 패턴이에요. - -#### 반환 값 - -(`string[]`): 추출된 단어들의 배열을 반환해요. diff --git a/docs/reference/compat/array/chunk.md b/docs/reference/compat/array/chunk.md deleted file mode 100644 index c044ce033..000000000 --- a/docs/reference/compat/array/chunk.md +++ /dev/null @@ -1,70 +0,0 @@ -# chunk (Lodash Compatibility) - -::: warning Use [`chunk`](../../array/chunk.md) from `es-toolkit` - -This `chunk` function operates slower due to handling of `null`, `undefined`, and default `size` values. - -For better performance and a more modern implementation, use [chunk](../../array/chunk.md) from `es-toolkit` instead. - -::: - -Divides an array into smaller arrays of a specified size. - -```typescript -const chunked = chunk(arr, size); -``` - -## Usage - -### `chunk(arr, size?)` - -Use `chunk` when you want to split a long array into multiple smaller arrays of the same size. If the array cannot be divided evenly, the last array will contain the remaining elements. - -```typescript -import { chunk } from 'es-toolkit/compat'; - -// Divide an array of numbers into chunks of size 2. -chunk([1, 2, 3, 4], 2); -// Returns: [[1, 2], [3, 4]] - -// Divide an array of strings into chunks of size 3. -chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); -// Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] - -// When not evenly divisible -chunk([1, 2, 3, 4, 5], 2); -// Returns: [[1, 2], [3, 4], [5]] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { chunk } from 'es-toolkit/compat'; - -chunk(null, 2); -// Returns: [] - -chunk(undefined, 2); -// Returns: [] -``` - -If size is 0 or negative, returns an empty array. - -```typescript -import { chunk } from 'es-toolkit/compat'; - -chunk([1, 2, 3], 0); -// Returns: [] - -chunk([1, 2, 3], -1); -// Returns: [] -``` - -#### Parameters - -- `arr` (`ArrayLike | null | undefined`): The array to divide. -- `size` (`number`, optional): The size of each smaller array. Default is `1`. - -#### Returns - -(`T[][]`): Returns a two-dimensional array divided by size `size`. diff --git a/docs/reference/compat/array/compact.md b/docs/reference/compat/array/compact.md deleted file mode 100644 index 685cf1047..000000000 --- a/docs/reference/compat/array/compact.md +++ /dev/null @@ -1,77 +0,0 @@ -# compact (Lodash compatible) - -::: warning Use [`compact`](../../array/compact.md) from `es-toolkit` instead - -This `compact` function operates slowly due to handling `null` or `undefined`, `size` default value processing, and more. - -Use the faster and more modern [compact](../../array/compact.md) from `es-toolkit` instead. - -::: - -Removes falsy values from an array. - -```typescript -const compacted = compact(arr); -``` - -## Usage - -### `compact(arr)` - -Use `compact` when you want to remove falsy values like `false`, `null`, `0`, `""`, `undefined`, `NaN` from an array. - -```typescript -import { compact } from 'es-toolkit/compat'; - -// Remove falsy values -compact([0, 1, false, 2, '', 3]); -// Returns: [1, 2, 3] - -compact(['a', null, 'b', undefined, 'c', NaN]); -// Returns: ['a', 'b', 'c'] - -// BigInt 0 is also removed -compact([0n, 1n, false, 2n]); -// Returns: [1n, 2n] - -// Works with empty arrays -compact([]); -// Returns: [] - -// When all values are falsy -compact([false, null, 0, '', undefined, NaN]); -// Returns: [] -``` - -Truthy values are preserved. - -```typescript -import { compact } from 'es-toolkit/compat'; - -compact([1, 'hello', true, {}, []]); -// Returns: [1, 'hello', true, {}, []] - -// Non-zero numbers -compact([0, -1, 2, -3]); -// Returns: [-1, 2, -3] -``` - -`null` or `undefined` arrays are treated as empty arrays. - -```typescript -import { compact } from 'es-toolkit/compat'; - -compact(null); -// Returns: [] - -compact(undefined); -// Returns: [] -``` - -#### Parameters - -- `arr` (`ArrayLike | null | undefined`): The array to compact. - -#### Returns - -(`T[]`): Returns a new array with falsy values removed. diff --git a/docs/reference/compat/array/countBy.md b/docs/reference/compat/array/countBy.md deleted file mode 100644 index f65adbb81..000000000 --- a/docs/reference/compat/array/countBy.md +++ /dev/null @@ -1,88 +0,0 @@ -# countBy (Lodash compatible) - -::: warning Use `countBy` from `es-toolkit` instead - -This `countBy` function operates slowly due to complex transformation function processing and type conversion. - -Use the faster and more modern [countBy](../../array/countBy.md) from `es-toolkit` instead. - -::: - -Counts the occurrences of elements in an array or object, grouped by a criterion. - -```typescript -const counts = countBy(collection, iteratee); -``` - -## Usage - -### `countBy(collection, iteratee?)` - -Use `countBy` when you want to group elements of an array or object by some criterion and count how many elements are in each group. The value returned by the iteratee function becomes the key, and the count of elements with that key becomes the value. - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// Group numbers by floor value -countBy([6.1, 4.2, 6.3], Math.floor); -// Returns: { '4': 1, '6': 2 } - -// Group strings by length -countBy(['one', 'two', 'three'], 'length'); -// Returns: { '3': 2, '5': 1 } - -// Group users by age range -const users = [ - { name: 'Alice', age: 25 }, - { name: 'Bob', age: 35 }, - { name: 'Charlie', age: 25 }, -]; -countBy(users, user => Math.floor(user.age / 10) * 10); -// Returns: { '20': 2, '30': 1 } -``` - -Works with objects too. - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// Classify object values by type -const obj = { a: 1, b: 'string', c: 2, d: 'text' }; -countBy(obj, value => typeof value); -// Returns: { 'number': 2, 'string': 2 } -``` - -When used without an iteratee function, groups by the value itself. - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// Group by value itself -countBy([1, 2, 1, 3, 2, 1]); -// Returns: { '1': 3, '2': 2, '3': 1 } - -// Group boolean values -countBy([true, false, true, true]); -// Returns: { 'true': 3, 'false': 1 } -``` - -`null` or `undefined` collections return an empty object. - -```typescript -import { countBy } from 'es-toolkit/compat'; - -countBy(null); -// Returns: {} - -countBy(undefined); -// Returns: {} -``` - -#### Parameters - -- `collection` (`ArrayLike | object | null | undefined`): The array or object to process. -- `iteratee` (`ValueIteratee`, optional): The function that defines the grouping criterion for each element. Can be a function, property name, or partial object. - -#### Returns - -(`Record`): Returns an object with keys for each group and values representing the count of elements in that group. diff --git a/docs/reference/compat/array/difference.md b/docs/reference/compat/array/difference.md deleted file mode 100644 index 18ba96daf..000000000 --- a/docs/reference/compat/array/difference.md +++ /dev/null @@ -1,94 +0,0 @@ -# difference (Lodash compatible) - -::: warning Use `difference` from `es-toolkit` instead - -This `difference` function operates in a complex manner due to handling `null` or `undefined` and processing multiple array arguments. - -Use the faster and more modern [difference](../../array/difference.md) from `es-toolkit` instead. - -::: - -Computes the difference between the first array and the other arrays, excluding values from the first array that are present in the other arrays. - -```typescript -const result = difference(arr, ...values); -``` - -## Usage - -### `difference(arr, ...values)` - -Use `difference` when you want to remove all values from the first array that are present in the other arrays. The order is preserved from the first array. - -```typescript -import { difference } from 'es-toolkit/compat'; - -// Basic usage -const array1 = [1, 2, 3, 4, 5]; -const array2 = [2, 4]; -const array3 = [5, 6]; -difference(array1, array2, array3); -// Returns: [1, 3] - -// String arrays -difference(['a', 'b', 'c'], ['b'], ['c', 'd']); -// Returns: ['a'] - -// Handling duplicates -difference([1, 2, 2, 3], [2]); -// Returns: [1, 3] -``` - -Handles empty arrays or empty differences. - -```typescript -import { difference } from 'es-toolkit/compat'; - -// Difference with empty array -difference([1, 2, 3], []); -// Returns: [1, 2, 3] - -// When all values are excluded -difference([1, 2, 3], [1, 2, 3]); -// Returns: [] - -// When there are no overlapping values -difference([1, 2], [3, 4]); -// Returns: [1, 2] -``` - -`null` or `undefined` arrays are treated as empty arrays. - -```typescript -import { difference } from 'es-toolkit/compat'; - -difference(null, [1, 2]); -// Returns: [] - -difference(undefined, [1, 2]); -// Returns: [] - -difference([1, 2, 3], null, undefined); -// Returns: [1, 2, 3] (null and undefined are ignored) -``` - -Supports array-like objects. - -```typescript -import { difference } from 'es-toolkit/compat'; - -// Array-like objects -const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; -const arrayLike2 = { 0: 2, 1: 4, length: 2 }; -difference(arrayLike1, arrayLike2); -// Returns: [1, 3] -``` - -#### Parameters - -- `arr` (`ArrayLike | null | undefined`): The base array to compute the difference from. -- `values` (`...ArrayLike[]`): Arrays containing values to exclude. - -#### Returns - -(`T[]`): Returns a new array with values from the first array excluding values present in the other arrays. diff --git a/docs/reference/compat/array/differenceBy.md b/docs/reference/compat/array/differenceBy.md deleted file mode 100644 index d6c92b44a..000000000 --- a/docs/reference/compat/array/differenceBy.md +++ /dev/null @@ -1,88 +0,0 @@ -# differenceBy (Lodash compatible) - -::: warning Use `differenceBy` from `es-toolkit` instead - -This `differenceBy` function operates slowly due to complex argument processing and iteratee transformation. - -Use the faster and more modern [differenceBy](../../array/differenceBy.md) from `es-toolkit` instead. - -::: - -Computes the difference between the first array and other arrays after applying an iteratee function to transform the values for comparison. - -```typescript -const result = differenceBy(array, ...values, iteratee); -``` - -## Usage - -### `differenceBy(array, ...values, iteratee)` - -Use `differenceBy` when you want to remove elements from the first array that have equivalent transformed values in the other arrays. This is useful for comparing arrays of objects by a specific property or transformed value. - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// Compare using Math.floor -differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); -// Returns: [1.2] (2.1 is excluded because Math.floor(2.1) === Math.floor(2.3)) - -// Compare by string length -differenceBy(['one', 'two', 'three'], ['four', 'eight'], 'length'); -// Returns: ['one', 'two'] (three is excluded because it has the same length as eight) - -// Compare objects by property -const users1 = [ - { id: 1, name: 'Alice' }, - { id: 2, name: 'Bob' }, -]; -const users2 = [{ id: 1, name: 'Different Alice' }]; -differenceBy(users1, users2, 'id'); -// Returns: [{ id: 2, name: 'Bob' }] (excludes object with id 1) -``` - -Can exclude from multiple arrays at once. - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// Exclude from multiple arrays -differenceBy([2.1, 1.2, 3.5], [2.3], [1.4], [3.2], Math.floor); -// Returns: [] (all elements are excluded) - -// Compare strings by length from multiple arrays -differenceBy(['a', 'bb', 'ccc'], ['x'], ['yy'], ['zzz'], 'length'); -// Returns: [] (lengths 1, 2, 3 are all excluded) -``` - -Without an iteratee function, it behaves like regular `difference`. - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// Without iteratee function -differenceBy([1, 2, 3], [2, 4]); -// Returns: [1, 3] -``` - -`null` or `undefined` arrays are treated as empty arrays. - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -differenceBy(null, [1, 2], Math.floor); -// Returns: [] - -differenceBy(undefined, [1, 2], x => x); -// Returns: [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The base array to compute the difference from. -- `values` (`...ArrayLike[]`): Arrays containing values to exclude. -- `iteratee` (`ValueIteratee`): The function that transforms each element for comparison. Can be a function, property name, or partial object. - -#### Returns - -(`T[]`): Returns a new array with elements excluded based on the transformed values. diff --git a/docs/reference/compat/array/differenceWith.md b/docs/reference/compat/array/differenceWith.md deleted file mode 100644 index ae682c6d8..000000000 --- a/docs/reference/compat/array/differenceWith.md +++ /dev/null @@ -1,79 +0,0 @@ -# differenceWith (Lodash compatible) - -::: warning Use `differenceWith` from `es-toolkit` instead - -This `differenceWith` function operates slowly due to handling `null` or `undefined`, processing multiple arrays, and `ArrayLike` type processing. - -Use the faster and more modern [differenceWith](../../array/differenceWith.md) from `es-toolkit` instead. - -::: - -Removes elements from the first array that are present in the other arrays using a comparator function. - -```typescript -const result = differenceWith(array, ...values, comparator); -``` - -## Usage - -### `differenceWith(array, ...values, comparator)` - -Use `differenceWith` when you want to compute the difference using a comparator function to compare elements. The last argument becomes the comparator function. - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -// Compare objects by id -const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; -const others = [{ id: 2 }]; -const comparator = (a, b) => a.id === b.id; - -differenceWith(objects, others, comparator); -// Returns: [{ id: 1 }, { id: 3 }] - -// Exclude from multiple arrays at once -const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]; -const values1 = [{ id: 2 }]; -const values2 = [{ id: 3 }]; - -differenceWith(array, values1, values2, comparator); -// Returns: [{ id: 1 }, { id: 4 }] -``` - -Without a comparator function, it behaves like regular `difference`. - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -// Without comparator, uses regular comparison -differenceWith([1, 2, 3], [2], [3]); -// Returns: [1] -``` - -Can use complex comparison logic. - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -const users = [ - { name: 'alice', age: 25 }, - { name: 'bob', age: 30 }, - { name: 'charlie', age: 35 }, -]; -const excludeUsers = [{ name: 'bob', age: 25 }]; // Different age - -// Compare only by name -const compareByName = (a, b) => a.name === b.name; -differenceWith(users, excludeUsers, compareByName); -// Returns: [{ name: 'alice', age: 25 }, { name: 'charlie', age: 35 }] -// bob is excluded (even though age is different, name matches) -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The base array to compute the difference from. -- `...values` (`Array>` + `(a: T, b: T) => boolean`): Arrays containing elements to exclude, with the last argument being the comparator function. - -#### Returns - -(`T[]`): Returns a new array with elements from the first array excluding those found in the other arrays using the comparator function. diff --git a/docs/reference/compat/array/drop.md b/docs/reference/compat/array/drop.md deleted file mode 100644 index 7224607f5..000000000 --- a/docs/reference/compat/array/drop.md +++ /dev/null @@ -1,97 +0,0 @@ -# drop (Lodash Compatibility) - -::: warning Use `drop` from `es-toolkit` - -This `drop` function operates in a complex manner due to handling of `null` or `undefined`, `toInteger` conversion, etc. - -Instead, use the faster and more modern [`drop`](../../array/drop.md) from `es-toolkit`. - -::: - -Removes a specified number of elements from the beginning of an array. - -```typescript -const result = drop(array, n); -``` - -## Usage - -### `drop(array, n?)` - -Use `drop` when you want to remove several elements from the beginning of an array and get the rest. By default, it removes the first element. - -```typescript -import { drop } from 'es-toolkit/compat'; - -// Basic usage (removes first element) -drop([1, 2, 3, 4, 5]); -// Returns: [2, 3, 4, 5] - -// Remove first 2 elements -drop([1, 2, 3, 4, 5], 2); -// Returns: [3, 4, 5] - -// Remove first 3 elements -drop(['a', 'b', 'c', 'd'], 3); -// Returns: ['d'] -``` - -When specifying 0 or a negative number, it returns the original array as is. - -```typescript -import { drop } from 'es-toolkit/compat'; - -// Remove 0 elements -drop([1, 2, 3], 0); -// Returns: [1, 2, 3] - -// Specify negative number -drop([1, 2, 3], -1); -// Returns: [1, 2, 3] -``` - -When specifying a number larger than the array, it returns an empty array. - -```typescript -import { drop } from 'es-toolkit/compat'; - -// Specify number larger than array size -drop([1, 2, 3], 5); -// Returns: [] - -// Remove from empty array -drop([], 1); -// Returns: [] -``` - -`null` or `undefined` arrays are treated as empty arrays. - -```typescript -import { drop } from 'es-toolkit/compat'; - -drop(null, 1); -// Returns: [] - -drop(undefined, 2); -// Returns: [] -``` - -Array-like objects are also supported. - -```typescript -import { drop } from 'es-toolkit/compat'; - -// Array-like object -const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; -drop(arrayLike, 1); -// Returns: ['b', 'c'] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array from which elements will be removed. -- `n` (`number`, optional): The number of elements to remove. Default is `1`. - -#### Returns - -(`T[]`): Returns a new array with the specified number of elements removed from the beginning. diff --git a/docs/reference/compat/array/dropRight.md b/docs/reference/compat/array/dropRight.md deleted file mode 100644 index 2fd9b92f7..000000000 --- a/docs/reference/compat/array/dropRight.md +++ /dev/null @@ -1,55 +0,0 @@ -# dropRight (Lodash Compatibility) - -::: warning Use `dropRight` from `es-toolkit` - -This `dropRight` function operates slowly due to handling `null` or `undefined`, `guard` parameter processing, `toInteger` conversion, etc. - -Instead, use the faster and more modern [`dropRight`](../../array/dropRight.md) from `es-toolkit`. - -::: - -Returns a new array with a specified number of elements removed from the end. - -```typescript -const result = dropRight(array, itemsCount); -``` - -## Usage - -### `dropRight(array, itemsCount)` - -Use `dropRight` when you want to remove a certain number of elements from the end of an array and create a new array with the remaining elements. - -```typescript -import { dropRight } from 'es-toolkit/compat'; - -// Remove the last 2 elements from a number array. -dropRight([1, 2, 3, 4, 5], 2); -// Returns: [1, 2, 3] - -// Remove the last 1 element from a string array. -dropRight(['a', 'b', 'c'], 1); -// Returns: ['a', 'b'] - -// If the number to remove is not specified, the default value 1 is used. -dropRight([1, 2, 3]); -// Returns: [1, 2] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { dropRight } from 'es-toolkit/compat'; - -dropRight(null, 2); // [] -dropRight(undefined, 2); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to remove elements from. -- `itemsCount` (`number`, optional): The number of elements to remove from the end of the array. Default is `1`. - -#### Returns - -(`T[]`): Returns a new array with `itemsCount` elements removed from the end. diff --git a/docs/reference/compat/array/dropRightWhile.md b/docs/reference/compat/array/dropRightWhile.md deleted file mode 100644 index b3e60e079..000000000 --- a/docs/reference/compat/array/dropRightWhile.md +++ /dev/null @@ -1,65 +0,0 @@ -# dropRightWhile (Lodash Compatibility) - -::: warning Use `dropRightWhile` from `es-toolkit` - -This `dropRightWhile` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. - -Instead, use the faster and more modern [`dropRightWhile`](../../array/dropRightWhile.md) from `es-toolkit`. - -::: - -Removes elements from the end of an array based on a predicate function. - -```typescript -const result = dropRightWhile(array, predicate); -``` - -## Usage - -### `dropRightWhile(array, predicate)` - -Use `dropRightWhile` when you want to consecutively remove elements from the end of an array that satisfy a specific condition. Removal stops when the predicate function returns `false`. - -```typescript -import { dropRightWhile } from 'es-toolkit/compat'; - -// Using a function as a predicate. -const users = [ - { user: 'barney', active: true }, - { user: 'fred', active: false }, - { user: 'pebbles', active: false }, -]; - -dropRightWhile(users, user => !user.active); -// Returns: [{ user: 'barney', active: true }] - -// Matching with an object pattern. -dropRightWhile(users, { user: 'pebbles', active: false }); -// Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }] - -// Specifying property and value in array format. -dropRightWhile(users, ['active', false]); -// Returns: [{ user: 'barney', active: true }] - -// Checking condition by property name. -dropRightWhile(users, 'active'); -// Returns: [{ user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { dropRightWhile } from 'es-toolkit/compat'; - -dropRightWhile(null, x => x > 0); // [] -dropRightWhile(undefined, x => x > 0); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to remove elements from. -- `predicate` (`ListIteratee`, optional): The predicate function to apply to each element. Can accept a function, object pattern, array pattern, or property name. - -#### Returns - -(`T[]`): Returns a new array starting from the first element that does not satisfy the condition. diff --git a/docs/reference/compat/array/dropWhile.md b/docs/reference/compat/array/dropWhile.md deleted file mode 100644 index dd827d8e6..000000000 --- a/docs/reference/compat/array/dropWhile.md +++ /dev/null @@ -1,67 +0,0 @@ -# dropWhile (Lodash Compatibility) - -::: warning Use `dropWhile` from `es-toolkit` - -This `dropWhile` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. - -Instead, use the faster and more modern [`dropWhile`](../../array/dropWhile.md) from `es-toolkit`. - -::: - -Removes elements from the beginning of an array based on a predicate function. - -```typescript -const result = dropWhile(array, predicate); -``` - -## Usage - -### `dropWhile(array, predicate)` - -Use `dropWhile` when you want to consecutively remove elements from the beginning of an array that satisfy a specific condition. Removal stops when the predicate function returns `false`. - -```typescript -import { dropWhile } from 'es-toolkit/compat'; - -// Using a function as a predicate. -dropWhile([1, 2, 3, 4, 5], n => n < 3); -// Returns: [3, 4, 5] - -// Matching with an object pattern. -const users = [ - { name: 'alice', active: false }, - { name: 'bob', active: false }, - { name: 'charlie', active: true }, -]; - -dropWhile(users, { active: false }); -// Returns: [{ name: 'charlie', active: true }] - -// Specifying property and value in array format. -dropWhile(users, ['active', false]); -// Returns: [{ name: 'charlie', active: true }] - -// Checking condition by property name. -const items = [{ visible: false }, { visible: false }, { visible: true }]; - -dropWhile(items, 'visible'); -// Returns: [{ visible: false }, { visible: false }, { visible: true }] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { dropWhile } from 'es-toolkit/compat'; - -dropWhile(null, x => x > 0); // [] -dropWhile(undefined, x => x > 0); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to remove elements from. -- `predicate` (`ListIteratee`, optional): The predicate function to apply to each element. Can accept a function, object pattern, array pattern, or property name. Default is `identity`. - -#### Returns - -(`T[]`): Returns a new array starting from the first element that does not satisfy the condition. diff --git a/docs/reference/compat/array/eachRight.md b/docs/reference/compat/array/eachRight.md deleted file mode 100644 index 4a20f523a..000000000 --- a/docs/reference/compat/array/eachRight.md +++ /dev/null @@ -1,58 +0,0 @@ -# eachRight (Lodash Compatibility) - -::: warning Use `forEachRight` from `es-toolkit` - -This `eachRight` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. - -Instead, use the faster and more modern [`forEachRight`](../../array/forEachRight.md) from `es-toolkit`. - -::: - -Performs an iteration operation from right to left on each element of an array or object. - -```typescript -const result = eachRight(collection, iteratee); -``` - -## Usage - -### `eachRight(collection, iteratee)` - -Iterates through each element of an array, object, or string from right to left and executes the given function. For arrays, it iterates in reverse order from the last index; for objects, it iterates through enumerable properties in reverse order. - -```typescript -import { eachRight } from 'es-toolkit/compat'; - -// Iterate array in reverse order -eachRight([1, 2, 3], (value, index) => console.log(value, index)); -// Logs: 3 2, 2 1, 1 0 - -// Iterate object in reverse order -eachRight({ a: 1, b: 2 }, (value, key) => console.log(key, value)); -// Logs: 'b' 2, 'a' 1 - -// Iterate string in reverse order -eachRight('hello', (char, index) => console.log(char, index)); -// Logs: 'o' 4, 'l' 3, 'l' 2, 'e' 1, 'h' 0 -``` - -If the function returns `false`, iteration stops. - -```typescript -import { eachRight } from 'es-toolkit/compat'; - -eachRight([1, 2, 3, 4], value => { - console.log(value); - return value !== 2; // Stop at 2 -}); -// Logs: 4, 3, 2 -``` - -#### Parameters - -- `collection` (`ArrayLike | Record | string | null | undefined`): The collection to iterate over. -- `iteratee` (`(item: any, index: any, collection: any) => unknown`, optional): The function to execute for each element. Default is the `identity` function. - -#### Returns - -(`ArrayLike | Record | string | null | undefined`): Returns the original collection. diff --git a/docs/reference/compat/array/fill.md b/docs/reference/compat/array/fill.md deleted file mode 100644 index 6a190678b..000000000 --- a/docs/reference/compat/array/fill.md +++ /dev/null @@ -1,82 +0,0 @@ -# fill (Lodash Compatibility) - -::: warning Use `fill` from `es-toolkit` - -This `fill` function operates with complex behavior due to handling `null` or `undefined`, support for array-like objects, etc. - -Instead, use the faster and more modern [`fill`](../../array/fill.md) from `es-toolkit`. - -::: - -Fills the elements of an array with a specified value. - -```typescript -const result = fill(array, value, start, end); -``` - -## Usage - -### `fill(array, value, start?, end?)` - -Use `fill` when you want to fill a specific range or the entire array with the same value. It modifies the original array directly. - -```typescript -import { fill } from 'es-toolkit/compat'; - -// Fill entire array -const arr1 = [1, 2, 3]; -fill(arr1, 'a'); -// Returns: ['a', 'a', 'a'] - -// Fill specific range -const arr2 = [1, 2, 3, 4, 5]; -fill(arr2, '*', 1, 4); -// Returns: [1, '*', '*', '*', 5] - -// Use negative indices -const arr3 = [1, 2, 3, 4, 5]; -fill(arr3, 'x', -3, -1); -// Returns: [1, 2, 'x', 'x', 5] -``` - -Array-like objects are also supported. - -```typescript -import { fill } from 'es-toolkit/compat'; - -const arrayLike = { 0: 1, 1: 2, 2: 3, length: 3 }; -fill(arrayLike, 'a', 1, 2); -// Returns: { 0: 1, 1: 'a', 2: 3, length: 3 } -``` - -`null` or `undefined` arrays are treated as empty arrays. - -```typescript -import { fill } from 'es-toolkit/compat'; - -fill(null, 'a'); -// Returns: [] - -fill(undefined, 'a'); -// Returns: [] -``` - -Strings are read-only, so they are returned as is. - -```typescript -import { fill } from 'es-toolkit/compat'; - -fill('abc', 'x'); -// Returns: 'abc' (not modified) -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to fill. -- `value` (`U`): The value to fill the array with. -- `start` (`number`, optional): The start position. Defaults to `0`. -- `end` (`number`, optional): The end position (not included). Defaults to `array.length`. - -#### Returns - -(`ArrayLike`): Returns the array filled with the value. diff --git a/docs/reference/compat/array/first.md b/docs/reference/compat/array/first.md deleted file mode 100644 index 7495c51cc..000000000 --- a/docs/reference/compat/array/first.md +++ /dev/null @@ -1,78 +0,0 @@ -# first (Lodash Compatibility) - -::: warning Use `head` from `es-toolkit` - -This `first` function operates slowly due to handling `null` or `undefined` and array-like object conversion. The `head` function from `es-toolkit` operates faster and simpler without this additional processing. - -Use the faster and more modern [head](../../array/head.md) from `es-toolkit` instead. - -::: - -Returns the first element of an array. - -```typescript -const firstElement = first(array); -``` - -## Usage - -### `first(array)` - -Use `first` when you want to get the first element of an array. Returns `undefined` if the array is empty or is `null` or `undefined`. - -```typescript -import { first } from 'es-toolkit/compat'; - -// Get the first element from a regular array -first([1, 2, 3]); -// Returns: 1 - -// Get the first element from a string array -first(['a', 'b', 'c']); -// Returns: 'a' - -// Empty array -first([]); -// Returns: undefined -``` - -`null` or `undefined` returns `undefined`. - -```typescript -import { first } from 'es-toolkit/compat'; - -first(null); // undefined -first(undefined); // undefined -``` - -Can be used with array-like objects. - -```typescript -import { first } from 'es-toolkit/compat'; - -const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; -first(arrayLike); -// Returns: 'a' - -// Strings are also treated like arrays -first('hello'); -// Returns: 'h' -``` - -For type-guaranteed tuples, returns the exact type. - -```typescript -import { first } from 'es-toolkit/compat'; - -const tuple = [1, 'two', true] as const; -first(tuple); -// Returns: 1 (type is inferred as 1) -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to get the first element from. - -#### Returns - -(`T | undefined`): Returns the first element of the array. Returns `undefined` if the array is empty or invalid. diff --git a/docs/reference/compat/array/flatMap.md b/docs/reference/compat/array/flatMap.md deleted file mode 100644 index d8462ffc1..000000000 --- a/docs/reference/compat/array/flatMap.md +++ /dev/null @@ -1,77 +0,0 @@ -# flatMap (Lodash Compatibility) - -::: warning Use `flatMap` from `es-toolkit` - -This `flatMap` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, and supporting various condition function formats. - -Use the faster and more modern [flatMap](../../array/flatMap.md) from `es-toolkit` instead. - -::: - -Applies a function to each element and flattens the result. - -```typescript -const result = flatMap(collection, iteratee); -``` - -## Usage - -### `flatMap(collection, iteratee)` - -Applies an iteratee function to each element of a collection and returns an array flattened by one level. Supports arrays, objects, and strings, and can use various forms of iteratees. - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -// Apply a function to an array -function duplicate(n) { - return [n, n]; -} -flatMap([1, 2], duplicate); -// Result: [1, 1, 2, 2] - -// Apply a function to an object -const obj = { a: 1, b: 2 }; -flatMap(obj, (value, key) => [key, value]); -// Result: ['a', 1, 'b', 2] - -// Map with a string property -const users = [ - { user: 'barney', hobbies: ['hiking', 'coding'] }, - { user: 'fred', hobbies: ['reading'] }, -]; -flatMap(users, 'hobbies'); -// Result: ['hiking', 'coding', 'reading'] -``` - -Using without an iteratee flattens the values by one level. - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -const obj = { a: [1, 2], b: [3, 4] }; -flatMap(obj); -// Result: [1, 2, 3, 4] -``` - -Conditional mapping with a partial object is also possible. - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -const users = [ - { user: 'barney', age: 36, active: true }, - { user: 'fred', age: 40, active: false }, -]; -flatMap(users, { active: false }); -// Result: [false, true] (matching result of elements where active is false) -``` - -#### Parameters - -- `collection` (`object | null | undefined`): The collection to iterate over. Can be an array, object, or string. -- `iteratee` (`ListIterator | ObjectIterator | string | object`, optional): The iteratee to apply to each element. Can be a function, property name, or partial object. - -#### Returns - -(`any[]`): Returns a new array flattened by one level after mapping. diff --git a/docs/reference/compat/array/flatMapDeep.md b/docs/reference/compat/array/flatMapDeep.md deleted file mode 100644 index a88ccfb54..000000000 --- a/docs/reference/compat/array/flatMapDeep.md +++ /dev/null @@ -1,77 +0,0 @@ -# flatMapDeep (Lodash Compatibility) - -::: warning Use [`flatMapDeep`](../../array/flatMapDeep.md) from `es-toolkit` - -This `flatMapDeep` function operates slowly due to complex collection type handling and deep flattening logic. - -Use the faster and more modern [flatMapDeep](../../array/flatMapDeep.md) from `es-toolkit` instead. - -::: - -Applies a function to each element and recursively flattens the result. - -```typescript -const result = flatMapDeep(collection, iteratee); -``` - -## Usage - -### `flatMapDeep(collection, iteratee)` - -Applies an iteratee function to each element of a collection and returns an array flattened to infinite depth. All nested array structures are flattened into a one-dimensional array. - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -// Apply a function to an array and deeply flatten -function duplicate(n) { - return [[[n, n]]]; -} -flatMapDeep([1, 2], duplicate); -// Result: [1, 1, 2, 2] - -// Apply a function to an object and deeply flatten -const obj = { a: 1, b: 2 }; -flatMapDeep(obj, (value, key) => [[[key, value]]]); -// Result: ['a', 1, 'b', 2] - -// Map with a string property and deeply flatten -const users = [ - { user: 'barney', hobbies: [['hiking', 'coding']] }, - { user: 'fred', hobbies: [['reading']] }, -]; -flatMapDeep(users, 'hobbies'); -// Result: ['hiking', 'coding', 'reading'] -``` - -Using without an iteratee recursively flattens the values. - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -const obj = { a: [[1, 2]], b: [[[3]]] }; -flatMapDeep(obj); -// Result: [1, 2, 3] -``` - -Conditional mapping with a partial object is also possible. - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -const users = [ - { user: 'barney', active: [true, false] }, - { user: 'fred', active: [false] }, -]; -flatMapDeep(users, { active: [false] }); -// Result: [true, true] (matching result of elements with active array containing [false]) -``` - -#### Parameters - -- `collection` (`object | null | undefined`): The collection to iterate over. Can be an array, object, or string. -- `iteratee` (`ListIterator | ObjectIterator | string | object`, optional): The iteratee to apply to each element. Can be a function, property name, or partial object. - -#### Returns - -(`any[]`): Returns a new array recursively flattened after mapping. diff --git a/docs/reference/compat/array/flatMapDepth.md b/docs/reference/compat/array/flatMapDepth.md deleted file mode 100644 index 7a7ff6353..000000000 --- a/docs/reference/compat/array/flatMapDepth.md +++ /dev/null @@ -1,79 +0,0 @@ -# flatMapDepth (Lodash Compatibility) - -::: warning Use [flatMap](../../array/flatMap.md) from `es-toolkit` - -This `flatMapDepth` function is implemented in a complex way to support various forms of iteratees and handle `null` or `undefined` for Lodash compatibility. The `flatMap` function in the main library only supports simple function iteratees, so it operates faster. - -Use the faster and more modern [flatMap](../../array/flatMap.md) from `es-toolkit` instead. - -::: - -Transforms each element of an array with an iteratee function and flattens to the specified depth. - -```typescript -const result = flatMapDepth(collection, iteratee, depth); -``` - -## Usage - -### `flatMapDepth(collection, iteratee, depth)` - -Transforms each element of an array or object with the given function, then flattens the result to the specified depth and returns a new array. Useful when you want to flatten nested array structures only to a desired depth. - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -// Transform an array and flatten to depth 2 -flatMapDepth([1, 2], n => [[n, n]], 2); -// => [1, 1, 2, 2] - -// When limited to depth 1, it's not fully flattened -flatMapDepth([1, 2], n => [[n, n]], 1); -// => [[1, 1], [2, 2]] - -// Extract values from an object and flatten -const users = [ - { user: 'barney', hobbies: [['hiking'], ['coding']] }, - { user: 'fred', hobbies: [['reading']] }, -]; -flatMapDepth(users, 'hobbies', 2); -// => ['hiking', 'coding', 'reading'] -``` - -This function supports various forms of iteratees. - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -// Transform with a function -flatMapDepth([1, 2, 3], n => [[n, n]], 2); - -// Extract values by property name -const objects = [{ items: [['a'], ['b']] }, { items: [['c']] }]; -flatMapDepth(objects, 'items', 2); -// => ['a', 'b', 'c'] - -// Partial matching with an object -const users = [{ active: [[true], [false]] }, { active: [[false]] }]; -flatMapDepth(users, { active: [[false]] }, 2); -// => [true, true] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -flatMapDepth(null, n => [n], 1); // => [] -flatMapDepth(undefined, n => [n], 1); // => [] -``` - -#### Parameters - -- `collection` (`ArrayLike | Record | Record | object | null | undefined`): The array or object to iterate over. -- `iteratee` (`((value: T, index: number, collection: any) => any) | string | object`, optional): The transformation function or property name to execute for each element. Default is `identity`. -- `depth` (`number`, optional): The maximum depth to flatten. Default is `1`. - -#### Returns - -(`T[]`): Returns a new array flattened to the specified depth after transformation with the iteratee. diff --git a/docs/reference/compat/array/flatten.md b/docs/reference/compat/array/flatten.md deleted file mode 100644 index 70a772e7a..000000000 --- a/docs/reference/compat/array/flatten.md +++ /dev/null @@ -1,69 +0,0 @@ -# flatten (Lodash Compatibility) - -::: warning Use `flatten` from `es-toolkit` - -This `flatten` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, and supporting various condition function formats. - -Use the faster and more modern [flatten](../../array/flatten.md) from `es-toolkit` instead. - -::: - -Flattens an array by one level. - -```typescript -const result = flatten(array, depth); -``` - -## Usage - -### `flatten(value, depth)` - -Flattens a nested array by the specified depth. By default, it flattens only one level, and also supports Arguments objects and objects with Symbol.isConcatSpreadable. - -```typescript -import { flatten } from 'es-toolkit/compat'; - -// Basic flattening (one level) -flatten([1, [2, [3, [4]], 5]]); -// Result: [1, 2, [3, [4]], 5] - -// Specify depth -flatten([1, [2, [3, [4]], 5]], 2); -// Result: [1, 2, 3, [4], 5] - -// Support for Arguments objects -function example() { - return flatten(arguments); -} -example(1, [2, 3], [[4]]); -// Result: [1, 2, 3, [4]] -``` - -Empty arrays, null, or undefined return empty arrays. - -```typescript -import { flatten } from 'es-toolkit/compat'; - -flatten(null); // [] -flatten(undefined); // [] -flatten([]); // [] -``` - -Objects with Symbol.isConcatSpreadable are also flattened like arrays. - -```typescript -import { flatten } from 'es-toolkit/compat'; - -const spreadable = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true }; -flatten([1, spreadable, 3]); -// Result: [1, 'a', 'b', 3] -``` - -#### Parameters - -- `value` (`ArrayLike | null | undefined`): The array to flatten. -- `depth` (`number`, optional): The maximum depth to flatten. Default is `1`. - -#### Returns - -(`T[]`): Returns a new flattened array. diff --git a/docs/reference/compat/array/flattenDeep.md b/docs/reference/compat/array/flattenDeep.md deleted file mode 100644 index f60cd7266..000000000 --- a/docs/reference/compat/array/flattenDeep.md +++ /dev/null @@ -1,64 +0,0 @@ -# flattenDeep (Lodash Compatibility) - -::: warning Use `flattenDeep` from `es-toolkit` - -This `flattenDeep` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, and supporting various condition function formats. - -Use the faster and more modern [flattenDeep](../../array/flattenDeep.md) from `es-toolkit` instead. - -::: - -Completely flattens an array. - -```typescript -const result = flattenDeep(array); -``` - -## Usage - -### `flattenDeep(value)` - -Recursively flattens a nested array at all depths. All nesting levels are removed, returning a completely flattened one-dimensional array. - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -// Completely flatten a deeply nested array -flattenDeep([1, [2, [3, [4]], 5]]); -// Result: [1, 2, 3, 4, 5] - -// Completely flatten a complex nested structure -flattenDeep([1, [2, [3, [[[[4]]]]], 5]]); -// Result: [1, 2, 3, 4, 5] - -// Support for mixed types -flattenDeep(['a', ['b', ['c', [['d']]]]]); -// Result: ['a', 'b', 'c', 'd'] -``` - -Empty arrays, null, or undefined return empty arrays. - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -flattenDeep(null); // [] -flattenDeep(undefined); // [] -flattenDeep([]); // [] -``` - -Already flattened arrays are copied as-is. - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -flattenDeep([1, 2, 3, 4, 5]); -// Result: [1, 2, 3, 4, 5] -``` - -#### Parameters - -- `value` (`ListOfRecursiveArraysOrValues | null | undefined`): The array to completely flatten. - -#### Returns - -(`Array`): Returns a new completely flattened array with all nesting removed. diff --git a/docs/reference/compat/array/flattenDepth.md b/docs/reference/compat/array/flattenDepth.md deleted file mode 100644 index 44cfab380..000000000 --- a/docs/reference/compat/array/flattenDepth.md +++ /dev/null @@ -1,55 +0,0 @@ -# flattenDepth (Lodash Compatibility) - -::: warning Use `flatten` from `es-toolkit` - -This `flattenDepth` function operates slowly due to handling `null` or `undefined`. The `flatten` function from `es-toolkit` operates faster and simpler without this additional processing. - -Use the faster and more modern [flatten](../../array/flatten.md) from `es-toolkit` instead. - -::: - -Flattens an array to the specified depth. - -```typescript -const flattened = flattenDepth(array, depth); -``` - -## Usage - -### `flattenDepth(array, depth)` - -Use `flattenDepth` when you want to flatten a nested array to a desired depth. When you specify a depth, it flattens the nested array only to that depth. - -```typescript -import { flattenDepth } from 'es-toolkit/compat'; - -// Flatten to depth 1 -flattenDepth([1, [2, [3, [4]], 5]], 1); -// Returns: [1, 2, [3, [4]], 5] - -// Flatten to depth 2 -flattenDepth([1, [2, [3, [4]], 5]], 2); -// Returns: [1, 2, 3, [4], 5] - -// If no depth is specified, it defaults to 1 -flattenDepth([1, [2, [3, [4]], 5]]); -// Returns: [1, 2, [3, [4]], 5] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { flattenDepth } from 'es-toolkit/compat'; - -flattenDepth(null, 2); // [] -flattenDepth(undefined, 2); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to flatten. -- `depth` (`number`, optional): The maximum depth to flatten. Default is `1`. - -#### Returns - -(`T[]`): Returns a new array flattened to the specified depth. diff --git a/docs/reference/compat/array/forEachRight.md b/docs/reference/compat/array/forEachRight.md deleted file mode 100644 index 154a01ac7..000000000 --- a/docs/reference/compat/array/forEachRight.md +++ /dev/null @@ -1,75 +0,0 @@ -# forEachRight (Lodash Compatibility) - -::: warning Use `forEachRight` from `es-toolkit` - -This `forEachRight` function operates slowly due to handling `null` or `undefined`, `ArrayLike` type processing, support for various predicate function formats, etc. - -Instead, use the faster and more modern [`forEachRight`](../../array/forEachRight.md) from `es-toolkit`. - -::: - -Iterates over elements of an array or object from right to left and executes a function for each element. - -```typescript -forEachRight(collection, callback); -``` - -## Usage - -### `forEachRight(collection, callback)` - -Iterates through each element of an array, object, or string from right to left and executes the given callback function. The iteration stops if the callback returns `false`. - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -// Iterate array in reverse order -forEachRight([1, 2, 3], (value, index) => { - console.log(value, index); -}); -// Output: 3 2, 2 1, 1 0 - -// Iterate string in reverse order -forEachRight('abc', (char, index) => { - console.log(char, index); -}); -// Output: 'c' 2, 'b' 1, 'a' 0 - -// Iterate object in reverse order -forEachRight({ a: 1, b: 2, c: 3 }, (value, key) => { - console.log(value, key); -}); -// Output: 3 'c', 2 'b', 1 'a' -``` - -`null` or `undefined` are returned as is. - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -forEachRight(null, value => console.log(value)); // null -forEachRight(undefined, value => console.log(value)); // undefined -``` - -The iteration stops if the callback returns `false`. - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -forEachRight([1, 2, 3, 4], value => { - console.log(value); - if (value === 2) { - return false; // Stop iteration - } -}); -// Output: 4, 3, 2 -``` - -#### Parameters - -- `collection` (`ArrayLike | Record | string | null | undefined`): The collection to iterate over. Can be an array, object, string, or null/undefined. -- `callback` (`(item: any, index: any, arr: any) => unknown`, optional): The function to execute for each element. Returns `false` to stop iteration. Default is the `identity` function. - -#### Returns - -(`ArrayLike | Record | string | null | undefined`): Returns the original collection as is. diff --git a/docs/reference/compat/array/groupBy.md b/docs/reference/compat/array/groupBy.md deleted file mode 100644 index 580d7654f..000000000 --- a/docs/reference/compat/array/groupBy.md +++ /dev/null @@ -1,79 +0,0 @@ -# groupBy (Lodash Compatibility) - -::: warning Use [`groupBy`](../../array/groupBy.md) from `es-toolkit` - -This `groupBy` function operates slowly due to handling `null` or `undefined`, object support, complex type processing, etc. - -Instead, use the faster and more modern [`groupBy`](../../array/groupBy.md) from `es-toolkit`. - -::: - -Groups elements of an array or object based on a given condition. - -```typescript -const grouped = groupBy(collection, iteratee); -``` - -## Usage - -### `groupBy(collection, iteratee)` - -Groups each element of an array or object based on a given condition function and returns an object with groups. The condition can be provided in various forms such as a function, property name, partial object, etc. - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -// Group by function -const array = [6.1, 4.2, 6.3]; -const result = groupBy(array, Math.floor); -// result is { '4': [4.2], '6': [6.1, 6.3] } - -// Group by property name -const users = [ - { name: 'john', age: 30 }, - { name: 'jane', age: 25 }, - { name: 'bob', age: 30 }, -]; -const byAge = groupBy(users, 'age'); -// byAge is { '25': [{ name: 'jane', age: 25 }], '30': [{ name: 'john', age: 30 }, { name: 'bob', age: 30 }] } - -// Group from object -const obj = { a: 6.1, b: 4.2, c: 6.3 }; -const groupedObj = groupBy(obj, Math.floor); -// groupedObj is { '4': [4.2], '6': [6.1, 6.3] } -``` - -`null` or `undefined` are treated as empty objects. - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -groupBy(null, x => x); // {} -groupBy(undefined, x => x); // {} -``` - -You can also group by partial object or property-value pair. - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -const products = [ - { category: 'fruit', name: 'apple' }, - { category: 'fruit', name: 'banana' }, - { category: 'vegetable', name: 'carrot' }, -]; - -// Group by partial object -const byCategory = groupBy(products, { category: 'fruit' }); -// Group by property-value pair -const byName = groupBy(products, ['name', 'apple']); -``` - -#### Parameters - -- `collection` (`ArrayLike | Record | null | undefined`): The array or object to group. -- `iteratee` (`Function | PropertyKey | Array | Object`, optional): The condition to group by. Can be a function, property name, property-value pair, or partial object. Default is the `identity` function. - -#### Returns - -(`Record`): Returns an object where each key is the condition value and the value is an array of elements belonging to that group. diff --git a/docs/reference/compat/array/head.md b/docs/reference/compat/array/head.md deleted file mode 100644 index 56a786abe..000000000 --- a/docs/reference/compat/array/head.md +++ /dev/null @@ -1,61 +0,0 @@ -# head (Lodash Compatibility) - -::: warning Use [`head`](../../array/head.md) from `es-toolkit` - -This `head` function operates slowly due to `ArrayLike` object processing and array conversion process. - -Instead, use the faster and more modern [`head`](../../array/head.md) from `es-toolkit`. - -::: - -Returns the first element of an array. - -```typescript -const firstElement = head(array); -``` - -## Usage - -### `head(array)` - -Returns the first element of an array or array-like object. Returns `undefined` if the array is empty or invalid. - -```typescript -import { head } from 'es-toolkit/compat'; - -// First element of number array -const numbers = [1, 2, 3, 4]; -const first = head(numbers); -// first is 1 - -// First element of string array -const strings = ['a', 'b', 'c']; -const firstChar = head(strings); -// firstChar is 'a' - -// Array-like object -const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; -const firstItem = head(arrayLike); -// firstItem is 'x' -``` - -Empty arrays or invalid inputs return `undefined`. - -```typescript -import { head } from 'es-toolkit/compat'; - -const emptyArray: number[] = []; -const noElement = head(emptyArray); -// noElement is undefined - -head(null); // undefined -head(undefined); // undefined -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array or array-like object to get the first element from. - -#### Returns - -(`T | undefined`): Returns the first element of the array, or `undefined` if the array is empty or invalid. diff --git a/docs/reference/compat/array/initial.md b/docs/reference/compat/array/initial.md deleted file mode 100644 index 072050964..000000000 --- a/docs/reference/compat/array/initial.md +++ /dev/null @@ -1,65 +0,0 @@ -# initial (Lodash Compatibility) - -::: warning Use [`initial`](../../array/initial.md) from `es-toolkit` - -This `initial` function operates slowly due to `ArrayLike` object processing and array conversion process. - -Instead, use the faster and more modern [`initial`](../../array/initial.md) from `es-toolkit`. - -::: - -Returns a new array with all elements except the last one from an array. - -```typescript -const result = initial(array); -``` - -## Usage - -### `initial(array)` - -Returns a new array containing all elements except the last one from an array or array-like object. Returns an empty array if the array is empty or has only one element. - -```typescript -import { initial } from 'es-toolkit/compat'; - -// Exclude last element from number array -const numbers = [1, 2, 3, 4]; -const result = initial(numbers); -// result is [1, 2, 3] - -// Exclude last element from string array -const strings = ['a', 'b', 'c', 'd']; -const withoutLast = initial(strings); -// withoutLast is ['a', 'b', 'c'] - -// Array-like object -const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; -const items = initial(arrayLike); -// items is ['x', 'y'] -``` - -Empty arrays or invalid inputs return an empty array. - -```typescript -import { initial } from 'es-toolkit/compat'; - -const emptyArray: number[] = []; -const result = initial(emptyArray); -// result is [] - -const singleItem = [42]; -const onlyOne = initial(singleItem); -// onlyOne is [] - -initial(null); // [] -initial(undefined); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array or array-like object to exclude the last element from. - -#### Returns - -(`T[]`): Returns a new array with the last element excluded. diff --git a/docs/reference/compat/array/intersection.md b/docs/reference/compat/array/intersection.md deleted file mode 100644 index 9c640e63a..000000000 --- a/docs/reference/compat/array/intersection.md +++ /dev/null @@ -1,80 +0,0 @@ -# intersection (Lodash Compatibility) - -::: warning Use [`intersection`](../../array/intersection.md) from `es-toolkit` - -This `intersection` function operates slowly due to handling `null` or `undefined`, multiple array support, and duplicate removal process. - -Instead, use the faster and more modern [`intersection`](../../array/intersection.md) from `es-toolkit`. - -::: - -Finds the intersection of multiple arrays. - -```typescript -const result = intersection(...arrays); -``` - -## Usage - -### `intersection(...arrays)` - -Finds elements that exist in all arrays and returns them as a new array. The result is deduplicated and maintains the order of the first array. - -```typescript -import { intersection } from 'es-toolkit/compat'; - -// Intersection of two arrays -const array1 = [1, 2, 3, 4]; -const array2 = [2, 3, 5, 6]; -const result = intersection(array1, array2); -// result is [2, 3] - -// Intersection of three arrays -const array3 = [3, 4, 7, 8]; -const multiResult = intersection(array1, array2, array3); -// multiResult is [3] - -// String arrays -const strings1 = ['a', 'b', 'c']; -const strings2 = ['b', 'c', 'd']; -const stringResult = intersection(strings1, strings2); -// stringResult is ['b', 'c'] - -// Array-like objects -const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; -const arrayLike2 = { 0: 2, 1: 3, 2: 4, length: 3 }; -const likeResult = intersection(arrayLike1, arrayLike2); -// likeResult is [2, 3] -``` - -`null` or `undefined` arrays are treated as empty arrays. - -```typescript -import { intersection } from 'es-toolkit/compat'; - -const array1 = [1, 2, 3]; -const result1 = intersection(array1, null); -// result1 is [] - -const result2 = intersection(null, undefined); -// result2 is [] -``` - -Duplicate elements are removed from the result. - -```typescript -import { intersection } from 'es-toolkit/compat'; - -const array1 = [1, 1, 2, 3]; -const array2 = [1, 2, 2, 4]; -const result = intersection(array1, array2); -// result is [1, 2] (duplicates removed) -``` - -#### Parameters - -- `...arrays` (`Array | null | undefined>`): The arrays to find the intersection of. Array-like objects, null, or undefined are also allowed. - -#### Returns - -(`T[]`): Returns a new array of elements that exist in all arrays. Duplicates are removed and the order follows the first array. diff --git a/docs/reference/compat/array/intersectionBy.md b/docs/reference/compat/array/intersectionBy.md deleted file mode 100644 index ded55d8f7..000000000 --- a/docs/reference/compat/array/intersectionBy.md +++ /dev/null @@ -1,93 +0,0 @@ -# intersectionBy (Lodash Compatibility) - -::: warning Use [`intersectionBy`](../../array/intersectionBy.md) from `es-toolkit` - -This `intersectionBy` function operates slowly due to complex condition processing, multiple array support, property path parsing, etc. - -Instead, use the faster and more modern [`intersectionBy`](../../array/intersectionBy.md) from `es-toolkit`. - -::: - -Finds the intersection of multiple arrays using a given condition function. - -```typescript -const result = intersectionBy(...arrays, iteratee); -``` - -## Usage - -### `intersectionBy(...arrays, iteratee)` - -Finds the intersection of multiple arrays based on values transformed by a given condition function. The condition can be provided in various forms such as a function, property name, partial object, etc. - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -// Intersection by function -const array1 = [2.1, 1.2]; -const array2 = [2.3, 3.4]; -const result = intersectionBy(array1, array2, Math.floor); -// result is [2.1] (2 is common based on Math.floor) - -// Intersection by property -const users1 = [ - { id: 1, name: 'john' }, - { id: 2, name: 'jane' }, -]; -const users2 = [ - { id: 2, name: 'jane' }, - { id: 3, name: 'bob' }, -]; -const byId = intersectionBy(users1, users2, 'id'); -// byId is [{ id: 2, name: 'jane' }] - -// Intersection of three arrays -const array3 = [2.5, 4.1]; -const multiResult = intersectionBy(array1, array2, array3, Math.floor); -// multiResult is [2.1] - -// Array-like objects -const arrayLike1 = { 0: { x: 1 }, 1: { x: 2 }, length: 2 }; -const arrayLike2 = { 0: { x: 2 }, 1: { x: 3 }, length: 2 }; -const byProperty = intersectionBy(arrayLike1, arrayLike2, 'x'); -// byProperty is [{ x: 2 }] -``` - -`null` or `undefined` arrays are treated as empty arrays. - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -const array1 = [{ x: 1 }, { x: 2 }]; -const result = intersectionBy(array1, null, 'x'); -// result is [] -``` - -You can also specify conditions with partial objects or property-value pairs. - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -const products1 = [ - { category: 'fruit', name: 'apple' }, - { category: 'vegetable', name: 'carrot' }, -]; -const products2 = [ - { category: 'fruit', name: 'banana' }, - { category: 'meat', name: 'beef' }, -]; - -// Specify condition with partial object -const byCategory = intersectionBy(products1, products2, { category: 'fruit' }); -// Specify condition with property-value pair -const byCategoryPair = intersectionBy(products1, products2, ['category', 'fruit']); -``` - -#### Parameters - -- `...arrays` (`Array | null | undefined>`): The arrays to find the intersection of. -- `iteratee` (`Function | PropertyKey | Array | Object`): The condition to transform each element. Can be a function, property name, property-value pair, or partial object. - -#### Returns - -(`T[]`): Returns a new array of elements that exist in all arrays based on the transformed values. diff --git a/docs/reference/compat/array/intersectionWith.md b/docs/reference/compat/array/intersectionWith.md deleted file mode 100644 index 5cce73a33..000000000 --- a/docs/reference/compat/array/intersectionWith.md +++ /dev/null @@ -1,64 +0,0 @@ -# intersectionWith (Lodash Compatibility) - -::: warning Use [`intersectionWith`](../../array/intersectionWith.md) from `es-toolkit` - -This `intersectionWith` function operates slowly due to handling `null` or `undefined`, support for various overloads, etc. - -Instead, use the faster and more modern [`intersectionWith`](../../array/intersectionWith.md) from `es-toolkit`. - -::: - -Creates an array of common elements found in all arrays using a custom comparison function. - -```typescript -const result = intersectionWith(array, ...otherArrays, comparator); -``` - -## Usage - -### `intersectionWith(array, ...otherArrays, comparator)` - -Finds the intersection of the first array with the rest using a custom comparison function. The comparison function determines if elements are equal, and only elements found in all arrays are returned. - -```typescript -import { intersectionWith } from 'es-toolkit/compat'; - -const objects = [ - { id: 1, name: 'john' }, - { id: 2, name: 'jane' }, -]; -const others = [ - { id: 1, name: 'john' }, - { id: 3, name: 'joe' }, -]; - -intersectionWith(objects, others, (a, b) => a.id === b.id); -// => [{ id: 1, name: 'john' }] - -// You can compare with multiple arrays -const array1 = [{ x: 1 }, { x: 2 }]; -const array2 = [{ x: 1 }, { x: 3 }]; -const array3 = [{ x: 1 }, { x: 4 }]; - -intersectionWith(array1, array2, array3, (a, b) => a.x === b.x); -// => [{ x: 1 }] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { intersectionWith } from 'es-toolkit/compat'; - -intersectionWith(null, [1, 2], (a, b) => a === b); // [] -intersectionWith([1, 2], undefined, (a, b) => a === b); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The first array to compare. -- `...otherArrays` (`Array | ((a: T, b: T | U) => boolean)>`): The other arrays to compare and the comparison function as the last element. -- `comparator` (`(a: T, b: T | U) => boolean`): The function to determine if two elements are equal. - -#### Returns - -(`T[]`): Returns a new array of elements commonly found in all arrays. diff --git a/docs/reference/compat/array/keyBy.md b/docs/reference/compat/array/keyBy.md deleted file mode 100644 index 3cdd5e50f..000000000 --- a/docs/reference/compat/array/keyBy.md +++ /dev/null @@ -1,64 +0,0 @@ -# keyBy (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [keyBy](../../array/keyBy.md) - -This `keyBy` function is slow due to handling `null` or `undefined`, various parameter types, etc. - -Use the faster and more modern `es-toolkit`'s [keyBy](../../array/keyBy.md) instead. - -::: - -Organizes collection elements into an object based on the specified key. - -```typescript -const result = keyBy(collection, iteratee); -``` - -## Usage - -### `keyBy(collection, iteratee)` - -Organizes each element in an array or object into an object using the specified key generation function or property name. If multiple elements have the same key, the last element is used. - -```typescript -import { keyBy } from 'es-toolkit/compat'; - -// Generate keys by property name -const array = [ - { dir: 'left', code: 97 }, - { dir: 'right', code: 100 }, -]; - -keyBy(array, 'dir'); -// => { left: { dir: 'left', code: 97 }, right: { dir: 'right', code: 100 } } - -// Generate keys using a function -keyBy(array, o => String.fromCharCode(o.code)); -// => { a: { dir: 'left', code: 97 }, d: { dir: 'right', code: 100 } } - -// Can also be used with objects -const obj = { - a: { id: 1, name: 'john' }, - b: { id: 2, name: 'jane' }, -}; -keyBy(obj, 'name'); -// => { john: { id: 1, name: 'john' }, jane: { id: 2, name: 'jane' } } -``` - -`null` or `undefined` are treated as empty objects. - -```typescript -import { keyBy } from 'es-toolkit/compat'; - -keyBy(null, 'id'); // {} -keyBy(undefined, 'id'); // {} -``` - -#### Parameters - -- `collection` (`ArrayLike | null | undefined`): The array or object to organize by key. -- `iteratee` (`ValueIterateeCustom`, optional): The function or property name to generate keys. If omitted, the element itself is used as the key. - -#### Returns - -(`Record`): Returns a new object where each element is mapped to the generated key. diff --git a/docs/reference/compat/array/last.md b/docs/reference/compat/array/last.md deleted file mode 100644 index 813764156..000000000 --- a/docs/reference/compat/array/last.md +++ /dev/null @@ -1,79 +0,0 @@ -# last (Lodash compatibility) - -::: warning Use `es-toolkit`'s [last](../../array/last.md) - -This `last` function behaves complexly due to handling `null` or `undefined`. - -Instead, use the faster and more modern `es-toolkit`'s [last](../../array/last.md). - -::: - -Returns the last element of an array. - -```typescript -const lastElement = last(array); -``` - -## Usage - -### `last(array)` - -Use `last` when you want to get the last element of an array. Returns `undefined` if the array is empty. - -```typescript -import { last } from 'es-toolkit/compat'; - -// Last element of a number array -last([1, 2, 3, 4, 5]); -// Returns: 5 - -// Last element of a string array -last(['a', 'b', 'c']); -// Returns: 'c' - -// Last element of an object array -const users = [{ name: 'Alice' }, { name: 'Bob' }]; -last(users); -// Returns: { name: 'Bob' } -``` - -Empty arrays or `null`, `undefined` return `undefined`. - -```typescript -import { last } from 'es-toolkit/compat'; - -// Empty array -last([]); -// Returns: undefined - -// null array -last(null); -// Returns: undefined - -// undefined array -last(undefined); -// Returns: undefined -``` - -Array-like objects are also supported. - -```typescript -import { last } from 'es-toolkit/compat'; - -// Array-like object -const arrayLike = { 0: 'first', 1: 'second', length: 2 }; -last(arrayLike); -// Returns: 'second' - -// Strings are also array-like objects -last('hello'); -// Returns: 'o' -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to get the last element from. - -#### Returns - -(`T | undefined`): Returns the last element of the array, or `undefined` if the array is empty, `null`, or `undefined`. diff --git a/docs/reference/compat/array/orderBy.md b/docs/reference/compat/array/orderBy.md deleted file mode 100644 index bdfe9d8e0..000000000 --- a/docs/reference/compat/array/orderBy.md +++ /dev/null @@ -1,82 +0,0 @@ -# orderBy (Lodash Compatibility) - -::: warning Use [orderBy](../../array/orderBy.md) from `es-toolkit` instead - -This `orderBy` function operates slowly due to handling `null` or `undefined`, complex path navigation, and various sorting criteria. - -Use the faster and more modern [orderBy](../../array/orderBy.md) from `es-toolkit` instead. - -::: - -Sorts the elements of a collection by multiple criteria. - -```typescript -const result = orderBy(collection, criteria, orders); -``` - -## Usage - -### `orderBy(collection, criteria, orders)` - -Sorts the elements of an array or object according to specified criteria and sort orders. You can use multiple criteria, and specify ascending (`'asc'`) or descending (`'desc'`) order for each criterion. - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -const users = [ - { name: 'fred', age: 48 }, - { name: 'barney', age: 34 }, - { name: 'fred', age: 40 }, - { name: 'barney', age: 36 }, -]; - -// Sort by name ascending, age descending -orderBy(users, ['name', 'age'], ['asc', 'desc']); -// => [ -// { name: 'barney', age: 36 }, -// { name: 'barney', age: 34 }, -// { name: 'fred', age: 48 }, -// { name: 'fred', age: 40 } -// ] - -// Specify sort criteria with functions -orderBy(users, [user => user.name, user => user.age], ['asc', 'desc']); -// => Same result as above - -// Sort by single criterion -orderBy(users, 'age', 'desc'); -// => [{ name: 'fred', age: 48 }, { name: 'fred', age: 40 }, ...] -``` - -For objects, sorts the values. - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -const obj = { - a: { name: 'fred', age: 48 }, - b: { name: 'barney', age: 34 }, -}; - -orderBy(obj, 'age', 'desc'); -// => [{ name: 'fred', age: 48 }, { name: 'barney', age: 34 }] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -orderBy(null, 'name'); // [] -orderBy(undefined, 'age'); // [] -``` - -#### Parameters - -- `collection` (`ArrayLike | object | null | undefined`): The array or object to sort. -- `criteria` (`Criterion | Array>`, optional): The sort criteria. Can use property names, property paths, functions, etc. Defaults to `[null]`. -- `orders` (`unknown | unknown[]`, optional): The sort order for each criterion. Can use `'asc'` (ascending), `'desc'` (descending), `true` (ascending), `false` (descending). Defaults to `[]`. - -#### Returns - -(`T[]`): Returns a new sorted array. diff --git a/docs/reference/compat/array/partition.md b/docs/reference/compat/array/partition.md deleted file mode 100644 index d42ba6a10..000000000 --- a/docs/reference/compat/array/partition.md +++ /dev/null @@ -1,89 +0,0 @@ -# partition (Lodash Compatibility) - -::: warning Use [partition](../../array/partition.md) from `es-toolkit` instead - -This `partition` function operates slowly due to handling `null` or `undefined` and various predicate types. - -Use the faster and more modern [partition](../../array/partition.md) from `es-toolkit` instead. - -::: - -Splits the elements of a collection into two groups based on a condition. - -```typescript -const [truthy, falsy] = partition(collection, predicate); -``` - -## Usage - -### `partition(collection, predicate)` - -Splits the elements of an array or object into two groups based on a given predicate function. The first group contains elements where the predicate is true, and the second group contains elements where the predicate is false. - -```typescript -import { partition } from 'es-toolkit/compat'; - -// Split number array into even and odd -partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); -// => [[2, 4, 6], [1, 3, 5]] - -// Specify condition with property name -const users = [ - { name: 'john', active: true }, - { name: 'jane', active: false }, - { name: 'bob', active: true }, -]; - -partition(users, 'active'); -// => [ -// [{ name: 'john', active: true }, { name: 'bob', active: true }], -// [{ name: 'jane', active: false }] -// ] - -// Filter with object condition -partition(users, { active: true }); -// => [ -// [{ name: 'john', active: true }, { name: 'bob', active: true }], -// [{ name: 'jane', active: false }] -// ] - -// Filter with array condition -partition(users, ['name', 'john']); -// => [ -// [{ name: 'john', active: true }], -// [{ name: 'jane', active: false }, { name: 'bob', active: true }] -// ] -``` - -For objects, partitions the values. - -```typescript -import { partition } from 'es-toolkit/compat'; - -const obj = { - a: { score: 90 }, - b: { score: 40 }, - c: { score: 80 }, -}; - -partition(obj, item => item.score >= 80); -// => [[{ score: 90 }, { score: 80 }], [{ score: 40 }]] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { partition } from 'es-toolkit/compat'; - -partition(null, x => x > 0); // [[], []] -partition(undefined, 'active'); // [[], []] -``` - -#### Parameters - -- `collection` (`ArrayLike | T | null | undefined`): The array or object to partition. -- `predicate` (`((value: T) => unknown) | Partial | [PropertyKey, any] | PropertyKey`, optional): The condition to test each element. Can be a function, partial object, property-value array, or property name. Defaults to `identity`. - -#### Returns - -(`[T[], T[]]`): Returns an array containing an array of elements that satisfy the condition and an array of elements that don't. diff --git a/docs/reference/compat/array/pull.md b/docs/reference/compat/array/pull.md deleted file mode 100644 index aa25784cb..000000000 --- a/docs/reference/compat/array/pull.md +++ /dev/null @@ -1,44 +0,0 @@ -# pull (Lodash compatibility) - -::: warning Use [pull](../../array/pull.md) from `es-toolkit` - -This `pull` function is for Lodash compatibility and operates slower due to more complex type handling and overloading. - -Instead, use the faster and more modern [pull](../../array/pull.md) from `es-toolkit`. - -::: - -Removes all specified values from the array. - -```typescript -const result = pull(array, ...valuesToRemove); -``` - -## Usage - -### `pull(array, ...valuesToRemove)` - -Removes all specified values from the array and modifies the original array. It directly modifies the original array without copying, which can save memory. - -```typescript -import { pull } from 'es-toolkit/compat'; - -// Remove specific values from number array -const numbers = [1, 2, 3, 2, 4, 2, 5]; -pull(numbers, 2, 3); -console.log(numbers); // [1, 4, 5] - -// Remove specific values from string array -const fruits = ['apple', 'banana', 'apple', 'cherry']; -pull(fruits, 'apple'); -console.log(fruits); // ['banana', 'cherry'] -``` - -#### Parameters - -- `array` (`T[]`): The array to modify. -- `...valuesToRemove` (`T[]`): The values to remove from the array. - -#### Returns - -(`T[]`): Returns the modified original array. diff --git a/docs/reference/compat/array/pullAt.md b/docs/reference/compat/array/pullAt.md deleted file mode 100644 index cb623e8e3..000000000 --- a/docs/reference/compat/array/pullAt.md +++ /dev/null @@ -1,57 +0,0 @@ -# pullAt (Lodash Compatibility) - -::: warning Use [pullAt](../../array/pullAt.md) from `es-toolkit` instead - -This `pullAt` function operates slowly due to complex type handling and overloading. - -Use the faster and more modern [pullAt](../../array/pullAt.md) from `es-toolkit` instead. - -::: - -Removes elements at specified indexes from an array and returns the removed elements. - -```typescript -const removed = pullAt(array, ...indexes); -``` - -## Usage - -### `pullAt(array, ...indexes)` - -Removes elements at specified indexes from an array and returns an array of the removed elements. The original array is modified. - -```typescript -import { pullAt } from 'es-toolkit/compat'; - -// Remove by individual indexes -const array = [1, 2, 3, 4, 5]; -const removed = pullAt(array, 1, 3); -console.log(array); // [1, 3, 5] -console.log(removed); // [2, 4] - -// Remove by array of indexes -const colors = ['red', 'green', 'blue', 'yellow']; -const removedColors = pullAt(colors, [0, 2]); -console.log(colors); // ['green', 'yellow'] -console.log(removedColors); // ['red', 'blue'] -``` - -Non-existent indexes are treated as `undefined`. - -```typescript -import { pullAt } from 'es-toolkit/compat'; - -const numbers = [10, 20, 30]; -const removed = pullAt(numbers, 1, 5); -console.log(numbers); // [10, 30] -console.log(removed); // [20, undefined] -``` - -#### Parameters - -- `array` (`ArrayLike`): The array to modify. -- `...indexes` (`Array`): The indexes of elements to remove. Can pass individual numbers or arrays of numbers. - -#### Returns - -(`ArrayLike`): Returns an array of removed elements. diff --git a/docs/reference/compat/array/remove.md b/docs/reference/compat/array/remove.md deleted file mode 100644 index ae80182e0..000000000 --- a/docs/reference/compat/array/remove.md +++ /dev/null @@ -1,70 +0,0 @@ -# remove (Lodash Compatibility) - -::: warning Use `remove` from `es-toolkit` - -This `remove` function is implemented in a complex way to support various forms of predicates for Lodash compatibility. The `remove` function in the main library only supports simple function predicates, so it operates faster. - -Instead, use the faster and more modern [remove](../../array/remove.md) from `es-toolkit`. - -::: - -Removes elements that match a condition from an array and returns the removed elements. - -```typescript -const removedElements = remove(array, predicate); -``` - -## Usage - -### `remove(array, predicate)` - -Iterates through the array and removes elements that match the given condition from the original array, returning the removed elements as a new array. Note that the original array is directly modified. - -```typescript -import { remove } from 'es-toolkit/compat'; - -// Remove with function condition -const numbers = [1, 2, 3, 4, 5]; -const evens = remove(numbers, n => n % 2 === 0); -console.log(numbers); // => [1, 3, 5] -console.log(evens); // => [2, 4] - -// Remove with partial object matching -const objects = [{ a: 1 }, { a: 2 }, { a: 3 }]; -const removed = remove(objects, { a: 1 }); -console.log(objects); // => [{ a: 2 }, { a: 3 }] -console.log(removed); // => [{ a: 1 }] - -// Remove with property-value pair -const items = [{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }]; -const cherries = remove(items, ['name', 'cherry']); -console.log(items); // => [{ name: 'apple' }, { name: 'banana' }] -console.log(cherries); // => [{ name: 'cherry' }] -``` - -This function supports various forms of predicates. - -```typescript -import { remove } from 'es-toolkit/compat'; - -// Function condition -remove(users, user => user.active === false); - -// Partial object matching -remove(users, { status: 'inactive' }); - -// Property-value array -remove(users, ['type', 'guest']); - -// Check truthy value by property name -remove(users, 'isDeleted'); -``` - -#### Parameters - -- `array` (`ArrayLike`): The array to modify. -- `predicate` (`((value: T, index: number, array: ArrayLike) => boolean) | Partial | [keyof T, unknown] | keyof T`, optional): The condition to execute for each element. Default is `identity`. - -#### Returns - -(`T[]`): Returns a new array consisting of elements that were removed because they matched the condition. diff --git a/docs/reference/compat/array/sample.md b/docs/reference/compat/array/sample.md deleted file mode 100644 index 2f37f12cb..000000000 --- a/docs/reference/compat/array/sample.md +++ /dev/null @@ -1,54 +0,0 @@ -# sample (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [sample](../../array/sample.md) - -This `sample` function operates slowly due to `null` or `undefined` handling, object value processing, etc. - -Instead, use the faster and more modern `es-toolkit`'s [sample](../../array/sample.md). - -::: - -Gets a random element from an array or object. - -```typescript -const randomItem = sample(collection); -``` - -## Usage - -### `sample(collection)` - -Use `sample` to select a random element from an array or object. For arrays, it returns a random element, and for objects, it returns a random value. - -```typescript -import { sample } from 'es-toolkit/compat'; - -// Get a random element from an array -sample([1, 2, 3, 4, 5]); -// Returns a random number between 1 and 5 - -// Get a random value from an object -sample({ a: 1, b: 2, c: 3 }); -// Returns a random value among 1, 2, 3 - -// Handles strings as well -sample('hello'); -// Returns a random character among 'h', 'e', 'l', 'l', 'o' -``` - -`null` or `undefined` returns `undefined`. - -```typescript -import { sample } from 'es-toolkit/compat'; - -sample(null); // undefined -sample(undefined); // undefined -``` - -#### Parameters - -- `collection` (`ArrayLike | Record | null | undefined`): The array or object to sample from. - -#### Returns - -(`T | string | undefined`): Returns a randomly selected element from the array or object. Returns `undefined` if the collection is empty or `null`, `undefined`. diff --git a/docs/reference/compat/array/sampleSize.md b/docs/reference/compat/array/sampleSize.md deleted file mode 100644 index 303fc09c8..000000000 --- a/docs/reference/compat/array/sampleSize.md +++ /dev/null @@ -1,54 +0,0 @@ -# sampleSize (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [sampleSize](../../array/sampleSize.md) - -This `sampleSize` function operates slowly due to `null` or `undefined` handling, object support, default value processing, etc. - -Instead, use the faster and more modern `es-toolkit`'s [sampleSize](../../array/sampleSize.md). - -::: - -Randomly selects a specified number of elements from an array or object. - -```typescript -const sampled = sampleSize(collection, size); -``` - -## Usage - -### `sampleSize(collection, size?)` - -Use `sampleSize` to randomly select elements from an array or object. It uses Floyd's algorithm to sample efficiently without duplicates. - -```typescript -import { sampleSize } from 'es-toolkit/compat'; - -// Randomly select 3 elements from an array. -sampleSize([1, 2, 3, 4, 5], 3); -// Returns: [2, 4, 5] (actual results may vary) - -// Randomly select 2 values from an object. -sampleSize({ a: 1, b: 2, c: 3, d: 4 }, 2); -// Returns: [2, 4] (actual results may vary) -``` - -`null` or `undefined` is handled as an empty array. - -```typescript -import { sampleSize } from 'es-toolkit/compat'; - -sampleSize(null, 2); -// Returns: [] - -sampleSize(undefined, 2); -// Returns: [] -``` - -#### Parameters - -- `collection` (`Record | Record | T | null | undefined`): The array or object to sample from. -- `size` (`number`, optional): The number of elements to select. The default is `1`. - -#### Returns - -(`T[]`): Returns a new array composed of randomly selected elements. diff --git a/docs/reference/compat/array/shuffle.md b/docs/reference/compat/array/shuffle.md deleted file mode 100644 index 73b711f59..000000000 --- a/docs/reference/compat/array/shuffle.md +++ /dev/null @@ -1,60 +0,0 @@ -# shuffle (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `shuffle` - -This `shuffle` function includes additional processing for Lodash compatibility and operates slowly. - -Instead, use the faster and more modern `es-toolkit`'s [shuffle](../../array/shuffle.md). - -::: - -Shuffles the elements of an array or object randomly and returns a new array. - -```typescript -const result = shuffle(collection); -``` - -## Usage - -### `shuffle(collection)` - -Uses the Fisher-Yates algorithm to randomly shuffle the elements of an array or object and returns a new array. The original is not modified. - -```typescript -import { shuffle } from 'es-toolkit/compat'; - -// Shuffle a number array -const numbers = [1, 2, 3, 4, 5]; -const shuffled1 = shuffle(numbers); -// Returns: for example [3, 1, 5, 2, 4] (different order each time) - -// Shuffle a string array -const fruits = ['apple', 'banana', 'cherry', 'date']; -const shuffled2 = shuffle(fruits); -// Returns: for example ['cherry', 'apple', 'date', 'banana'] - -// Shuffle object values -const obj = { a: 1, b: 2, c: 3, d: 4 }; -const shuffled3 = shuffle(obj); -// Returns: for example [3, 1, 4, 2] (object values are randomly shuffled) -``` - -`null` or `undefined` is handled as an empty array. - -```typescript -import { shuffle } from 'es-toolkit/compat'; - -shuffle(null); -// Returns: [] - -shuffle(undefined); -// Returns: [] -``` - -#### Parameters - -- `collection` (`ArrayLike | T | null | undefined`): The array or object to shuffle. - -#### Returns - -(`T[]`): Returns a new array with elements randomly shuffled. diff --git a/docs/reference/compat/array/tail.md b/docs/reference/compat/array/tail.md deleted file mode 100644 index 4c26c14fa..000000000 --- a/docs/reference/compat/array/tail.md +++ /dev/null @@ -1,58 +0,0 @@ -# tail (Lodash compatibility) - -::: warning Please use [tail](../../array/tail.md) from `es-toolkit` - -This `tail` function operates slowly due to handling `null` or `undefined`. - -Please use the faster and modern [tail](../../array/tail.md) from `es-toolkit` instead. - -::: - -Returns all elements of an array except the first one. - -```typescript -const result = tail(array); -``` - -## Usage - -### `tail(array)` - -Use `tail` when you want to create a new array containing all elements except the first one from the input array. If the input array is empty or has only one element, it returns an empty array. - -```typescript -import { tail } from 'es-toolkit/compat'; - -// Remove the first element from a number array. -tail([1, 2, 3]); -// Returns: [2, 3] - -// Remove the first element from a string array. -tail(['a', 'b', 'c']); -// Returns: ['b', 'c'] - -// Array with only one element. -tail([1]); -// Returns: [] - -// Empty array. -tail([]); -// Returns: [] -``` - -`null` or `undefined` is treated as an empty array. - -```typescript -import { tail } from 'es-toolkit/compat'; - -tail(null); // [] -tail(undefined); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to remove the first element from. - -#### Returns - -(`T[]`): Returns a new array containing all elements except the first one. diff --git a/docs/reference/compat/array/take.md b/docs/reference/compat/array/take.md deleted file mode 100644 index 01ceec64a..000000000 --- a/docs/reference/compat/array/take.md +++ /dev/null @@ -1,56 +0,0 @@ -# take (Lodash compatibility) - -::: warning Please use [take](../../array/take.md) from `es-toolkit` - -This `take` function operates slowly due to additional processing for compatibility with Lodash. - -Please use the faster and modern [take](../../array/take.md) from `es-toolkit` instead. - -::: - -Takes a specified number of elements from the beginning of an array and creates a new array. - -```typescript -const result = take([1, 2, 3, 4, 5], 3); -// result becomes [1, 2, 3]. -``` - -## Usage - -### `take(array, count)` - -Takes a specified number of elements from the beginning of an array and returns a new array. If `count` is greater than the array length, returns the entire array. - -```typescript -import { take } from 'es-toolkit/compat'; - -// Basic usage -const numbers = [1, 2, 3, 4, 5]; -const result1 = take(numbers, 3); -// Returns: [1, 2, 3] - -// Request count greater than array length -const result2 = take(numbers, 10); -// Returns: [1, 2, 3, 4, 5] (entire array) - -// Request 0 elements -const result3 = take(numbers, 0); -// Returns: [] - -// Handle empty array -const result4 = take([], 3); -// Returns: [] - -// Handle negative number -const result5 = take(numbers, -1); -// Returns: [] -``` - -#### Parameters - -- `array` (`T[]`): The array to take elements from. -- `count` (`number`): The number of elements to take. Default is 1. - -#### Returns - -(`T[]`): A new array containing the specified number of elements from the beginning. diff --git a/docs/reference/compat/array/takeRight.md b/docs/reference/compat/array/takeRight.md deleted file mode 100644 index 7a8fed75f..000000000 --- a/docs/reference/compat/array/takeRight.md +++ /dev/null @@ -1,63 +0,0 @@ -# takeRight (Lodash compatibility) - -::: warning Please use [takeRight](../../array/takeRight.md) from `es-toolkit` - -This `takeRight` function operates slowly due to handling `null` or `undefined`. - -Please use the faster and modern [takeRight](../../array/takeRight.md) from `es-toolkit` instead. - -::: - -Takes a specified number of elements from the end of an array. - -```typescript -const result = takeRight(array, count); -``` - -## Usage - -### `takeRight(array, count)` - -Use `takeRight` when you want to create a new array by taking a specified number of elements from the end of an array. If the requested count is greater than the array length, returns the entire array. - -```typescript -import { takeRight } from 'es-toolkit/compat'; - -// Take the last 2 elements from a number array. -takeRight([1, 2, 3, 4, 5], 2); -// Returns: [4, 5] - -// Take the last 3 elements from a string array. -takeRight(['a', 'b', 'c'], 2); -// Returns: ['b', 'c'] - -// When requested count is greater than array length -takeRight([1, 2, 3], 5); -// Returns: [1, 2, 3] - -// Request 0 elements -takeRight([1, 2, 3], 0); -// Returns: [] - -// Request negative number -takeRight([1, 2, 3], -1); -// Returns: [] -``` - -`null` or `undefined` is treated as an empty array. - -```typescript -import { takeRight } from 'es-toolkit/compat'; - -takeRight(null, 2); // [] -takeRight(undefined, 2); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to take elements from. -- `count` (`number`, optional): The number of elements to take. Default is `1`. - -#### Returns - -(`T[]`): Returns a new array containing the specified number of elements from the end. diff --git a/docs/reference/compat/array/takeRightWhile.md b/docs/reference/compat/array/takeRightWhile.md deleted file mode 100644 index 91980390f..000000000 --- a/docs/reference/compat/array/takeRightWhile.md +++ /dev/null @@ -1,71 +0,0 @@ -# takeRightWhile (Lodash compatibility) - -::: warning Please use [takeRightWhile](../../array/takeRightWhile.md) from `es-toolkit` - -This `takeRightWhile` function operates slowly due to handling `null` or `undefined`. - -Please use the faster and modern [takeRightWhile](../../array/takeRightWhile.md) from `es-toolkit` instead. - -::: - -Takes elements from the end of an array while the condition is satisfied. - -```typescript -const result = takeRightWhile(array, predicate); -``` - -## Usage - -### `takeRightWhile(array, predicate)` - -Use `takeRightWhile` when you want to create a new array by taking elements from the end of an array while the condition is satisfied. It stops when the condition evaluates to false. - -```typescript -import { takeRightWhile } from 'es-toolkit/compat'; - -// Using function condition -const numbers = [1, 2, 3, 4, 5]; -takeRightWhile(numbers, x => x > 3); -// Returns: [4, 5] - -// Using object property condition -const users = [ - { user: 'barney', active: true }, - { user: 'fred', active: false }, - { user: 'pebbles', active: false }, -]; - -takeRightWhile(users, o => !o.active); -// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] - -// Matching with partial object -takeRightWhile(users, { active: false }); -// Returns: [{ user: 'pebbles', active: false }] - -// Matching with property-value array -takeRightWhile(users, ['active', false]); -// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] - -// Checking for truthy value by property name -const items = [{ active: false }, { active: true }, { active: true }]; -takeRightWhile(items, 'active'); -// Returns: [{ active: true }, { active: true }] -``` - -`null` or `undefined` is treated as an empty array. - -```typescript -import { takeRightWhile } from 'es-toolkit/compat'; - -takeRightWhile(null, x => x > 0); // [] -takeRightWhile(undefined, x => x > 0); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to process. -- `predicate` (`ListIteratee`, optional): The condition to run for each element. Can be a function, partial object, property-value array, or property name. Default is the identity function. - -#### Returns - -(`T[]`): Returns a new array of elements taken from the end while the condition is satisfied. diff --git a/docs/reference/compat/array/takeWhile.md b/docs/reference/compat/array/takeWhile.md deleted file mode 100644 index bd28eb57c..000000000 --- a/docs/reference/compat/array/takeWhile.md +++ /dev/null @@ -1,71 +0,0 @@ -# takeWhile (Lodash compatibility) - -::: warning Please use [takeWhile](../../array/takeWhile.md) from `es-toolkit` - -This `takeWhile` function operates slowly due to handling `null` or `undefined`. - -Please use the faster and modern [takeWhile](../../array/takeWhile.md) from `es-toolkit` instead. - -::: - -Takes elements from the beginning of an array while the condition is satisfied. - -```typescript -const result = takeWhile(array, predicate); -``` - -## Usage - -### `takeWhile(array, predicate)` - -Use `takeWhile` when you want to create a new array by taking elements from the beginning of an array while the condition is satisfied. It stops when the condition evaluates to false. - -```typescript -import { takeWhile } from 'es-toolkit/compat'; - -// Using function condition -const numbers = [1, 2, 3, 4, 5]; -takeWhile(numbers, x => x < 3); -// Returns: [1, 2] - -// Using object property condition -const users = [ - { user: 'barney', active: false }, - { user: 'fred', active: false }, - { user: 'pebbles', active: true }, -]; - -takeWhile(users, o => !o.active); -// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] - -// Matching with partial object -takeWhile(users, { active: false }); -// Returns: [{ user: 'barney', active: false }] - -// Matching with property-value array -takeWhile(users, ['active', false]); -// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] - -// Checking for truthy value by property name -const items = [{ active: true }, { active: true }, { active: false }]; -takeWhile(items, 'active'); -// Returns: [{ active: true }, { active: true }] -``` - -`null` or `undefined` is treated as an empty array. - -```typescript -import { takeWhile } from 'es-toolkit/compat'; - -takeWhile(null, x => x > 0); // [] -takeWhile(undefined, x => x > 0); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to process. -- `predicate` (`ListIteratee`, optional): The condition to run for each element. Can be a function, partial object, property-value array, or property name. Default is the identity function. - -#### Returns - -(`T[]`): Returns a new array of elements taken from the beginning while the condition is satisfied. diff --git a/docs/reference/compat/array/union.md b/docs/reference/compat/array/union.md deleted file mode 100644 index 504b4cedb..000000000 --- a/docs/reference/compat/array/union.md +++ /dev/null @@ -1,62 +0,0 @@ -# union (Lodash Compatibility) - -::: warning Use [union](../../array/union.md) from `es-toolkit` - -This `union` function operates slowly due to complex array processing. - -Instead, use the faster and more modern [union](../../array/union.md) from `es-toolkit`. - -::: - -Creates a new array containing only unique values from multiple arrays. - -```typescript -const result = union(...arrays); -``` - -## Usage - -### `union(...arrays)` - -Use `union` when you want to merge multiple arrays and remove duplicates to create a new array containing only unique values. The order of first appearance of each value is preserved. - -```typescript -import { union } from 'es-toolkit/compat'; - -// Merging number arrays -union([2], [1, 2]); -// Returns: [2, 1] - -// Merging multiple arrays -union([2], [1, 2], [2, 3]); -// Returns: [2, 1, 3] - -// Nested arrays are not flattened -union([1, 3, 2], [1, [5]], [2, [4]]); -// Returns: [1, 3, 2, [5], [4]] - -// Non-array values are ignored -union([0], 3, { '0': 1 }, null, [2, 1]); -// Returns: [0, 2, 1] - -// Array-like objects are also processed -union([0], { 0: 'a', length: 1 }, [2, 1]); -// Returns: [0, 'a', 2, 1] -``` - -`null` or `undefined` are ignored. - -```typescript -import { union } from 'es-toolkit/compat'; - -union([1, 2], null, undefined, [3, 4]); -// Returns: [1, 2, 3, 4] -``` - -#### Parameters - -- `...arrays` (`Array | null | undefined>`): The arrays to merge. Non-array values are ignored. - -#### Returns - -(`T[]`): Returns a new array containing unique values from all arrays. diff --git a/docs/reference/compat/array/unionBy.md b/docs/reference/compat/array/unionBy.md deleted file mode 100644 index 5de436624..000000000 --- a/docs/reference/compat/array/unionBy.md +++ /dev/null @@ -1,66 +0,0 @@ -# unionBy (Lodash Compatibility) - -::: warning Use [unionBy](../../array/unionBy.md) from `es-toolkit` - -This `unionBy` function operates slowly due to complex processing. - -Instead, use the faster and more modern [unionBy](../../array/unionBy.md) from `es-toolkit`. - -::: - -Merges multiple arrays and keeps only unique values based on a specified criterion. - -```typescript -const result = unionBy(...arrays, iteratee); -``` - -## Usage - -### `unionBy(...arrays, iteratee)` - -Use `unionBy` when you want to merge multiple arrays and remove duplicates based on a given criterion function to create a new array containing only unique values. The order of first appearance of each value is preserved. - -```typescript -import { unionBy } from 'es-toolkit/compat'; - -// Compare by flooring decimal numbers -unionBy([2.1], [1.2, 2.3], Math.floor); -// Returns: [2.1, 1.2] - -// Compare by object property -unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); -// Returns: [{ x: 1 }, { x: 2 }] - -// Compare with function -unionBy( - [{ id: 1, name: 'a' }], - [ - { id: 2, name: 'b' }, - { id: 1, name: 'c' }, - ], - item => item.id -); -// Returns: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }] - -// Compare with partial object -unionBy([{ x: 1, y: 1 }], [{ x: 1, y: 2 }], { x: 1 }); -// Returns: [{ x: 1, y: 1 }] -``` - -`null` or `undefined` arrays are ignored. - -```typescript -import { unionBy } from 'es-toolkit/compat'; - -unionBy([1, 2], null, undefined, [3, 4], x => x); -// Returns: [1, 2, 3, 4] -``` - -#### Parameters - -- `...arrays` (`Array | null | undefined>`): The arrays to merge. -- `iteratee` (`ValueIteratee`): The criterion to determine uniqueness. Can be a function, property name, partial object, or property-value array. - -#### Returns - -(`T[]`): Returns a new array containing unique values with duplicates removed based on the specified criterion. diff --git a/docs/reference/compat/array/unionWith.md b/docs/reference/compat/array/unionWith.md deleted file mode 100644 index afa081d8c..000000000 --- a/docs/reference/compat/array/unionWith.md +++ /dev/null @@ -1,64 +0,0 @@ -# unionWith (Lodash Compatibility) - -::: warning Use [unionWith](../../array/unionWith.md) from `es-toolkit` - -This `unionWith` function operates slowly due to complex processing. - -Instead, use the faster and more modern [unionWith](../../array/unionWith.md) from `es-toolkit`. - -::: - -Merges multiple arrays and keeps only unique values using a comparison function. - -```typescript -const result = unionWith(...arrays, comparator); -``` - -## Usage - -### `unionWith(...arrays, comparator)` - -Use `unionWith` when you want to merge multiple arrays and remove duplicates using a custom comparison function to create a new array containing only unique values. The order of first appearance of each value is preserved. - -```typescript -import { unionWith } from 'es-toolkit/compat'; - -// Using a custom comparison function -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, -]; -const others = [ - { x: 1, y: 1 }, - { x: 1, y: 2 }, -]; - -unionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); -// Returns: [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 1, y: 1 }] - -// Simple equality comparison -unionWith([1, 2], [2, 3], (a, b) => a === b); -// Returns: [1, 2, 3] - -// Compare by string length -unionWith(['ab', 'cd'], ['ef', 'gh', 'ab'], (a, b) => a.length === b.length); -// Returns: ['ab'] -``` - -`null` or `undefined` arrays are ignored. - -```typescript -import { unionWith } from 'es-toolkit/compat'; - -unionWith([1, 2], null, undefined, [3, 4], (a, b) => a === b); -// Returns: [1, 2, 3, 4] -``` - -#### Parameters - -- `...arrays` (`Array | null | undefined>`): The arrays to merge. -- `comparator` (`(a: T, b: T) => boolean`): The comparison function that determines if two values are equal. - -#### Returns - -(`T[]`): Returns a new array containing unique values with duplicates removed using the comparison function. diff --git a/docs/reference/compat/array/uniq.md b/docs/reference/compat/array/uniq.md deleted file mode 100644 index 8c391faf5..000000000 --- a/docs/reference/compat/array/uniq.md +++ /dev/null @@ -1,51 +0,0 @@ -# uniq (Lodash Compatibility) - -::: warning Use [uniq](../../array/uniq.md) from `es-toolkit` - -This `uniq` function operates slowly due to additional processing for Lodash compatibility. - -Instead, use the faster and more modern [uniq](../../array/uniq.md) from `es-toolkit`. - -::: - -Creates a new array with only unique elements by removing duplicates from an array. - -```typescript -const result = uniq([1, 2, 2, 3, 3, 4]); -// result is [1, 2, 3, 4]. -``` - -## Usage - -### `uniq(array)` - -Returns a new array containing only unique elements by removing duplicates from the array. Only the first occurrence of each element is kept and the order is preserved. - -```typescript -import { uniq } from 'es-toolkit/compat'; - -// Remove duplicates from number array -const numbers = [1, 2, 2, 3, 3, 4, 1]; -const result1 = uniq(numbers); -// Returns: [1, 2, 3, 4] - -// Remove duplicates from string array -const strings = ['a', 'b', 'b', 'c', 'a']; -const result2 = uniq(strings); -// Returns: ['a', 'b', 'c'] - -// Remove duplicates from object array (reference value comparison) -const obj1 = { id: 1 }; -const obj2 = { id: 2 }; -const objects = [obj1, obj2, obj1]; -const result3 = uniq(objects); -// Returns: [{ id: 1 }, { id: 2 }] -``` - -#### Parameters - -- `array` (`T[]`): The array to process. - -#### Returns - -(`T[]`): A new array with duplicates removed. diff --git a/docs/reference/compat/array/uniqBy.md b/docs/reference/compat/array/uniqBy.md deleted file mode 100644 index fdf2de27f..000000000 --- a/docs/reference/compat/array/uniqBy.md +++ /dev/null @@ -1,55 +0,0 @@ -# uniqBy (Lodash Compatibility) - -::: warning Use [uniqBy](../../array/uniqBy.md) from `es-toolkit` - -This `uniqBy` function operates slowly due to handling of `null` or `undefined`, complex argument type processing, etc. - -Instead, use the faster and more modern [uniqBy](../../array/uniqBy.md) from `es-toolkit`. - -::: - -Creates a new array of unique elements by removing duplicates based on the values returned by a transformation function. - -```typescript -const result = uniqBy(array, iteratee); -``` - -## Usage - -### `uniqBy(array, iteratee)` - -Applies a transformation function to each element of the array and keeps only the first element among those with the same transformation result. This is useful when removing duplicates based on a specific property in an object array or based on a specific calculation result in a number array. - -```typescript -import { uniqBy } from 'es-toolkit/compat'; - -// Remove duplicates by Math.floor result in number array -uniqBy([2.1, 1.2, 2.3], Math.floor); -// Returns: [2.1, 1.2] - -// Remove duplicates by property in object array -uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); -// Returns: [{ x: 1 }, { x: 2 }] - -// Remove duplicates with function -uniqBy([{ name: 'John' }, { name: 'Jane' }, { name: 'John' }], obj => obj.name); -// Returns: [{ name: 'John' }, { name: 'Jane' }] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { uniqBy } from 'es-toolkit/compat'; - -uniqBy(null, Math.floor); // [] -uniqBy(undefined, 'x'); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to remove duplicates from. -- `iteratee` (`ValueIteratee`): The transformation function to apply to each element. Can be a function, property name, partial object, etc. - -#### Returns - -(`T[]`): Returns a new array with duplicates removed based on the transformation function result. diff --git a/docs/reference/compat/array/uniqWith.md b/docs/reference/compat/array/uniqWith.md deleted file mode 100644 index c48e78747..000000000 --- a/docs/reference/compat/array/uniqWith.md +++ /dev/null @@ -1,60 +0,0 @@ -# uniqWith (Lodash Compatibility) - -::: warning Use [uniqWith](../../array/uniqWith.md) from `es-toolkit` - -This `uniqWith` function operates slowly due to handling of `null` or `undefined`, complex argument type processing, etc. - -Instead, use the faster and more modern [uniqWith](../../array/uniqWith.md) from `es-toolkit`. - -::: - -Creates a new array of unique elements by removing duplicates using a comparison function. - -```typescript -const result = uniqWith(array, comparator); -``` - -## Usage - -### `uniqWith(array, comparator)` - -Removes duplicates by comparing each element of the array with a comparison function. When the comparison function returns `true`, the two elements are considered equal, and only the first occurring element is kept. If no comparison function is provided, it uses shallow equality comparison by default. - -```typescript -import { uniqWith } from 'es-toolkit/compat'; - -// Use without comparison function (shallow equality comparison) -uniqWith([1, 2, 2, 3]); -// Returns: [1, 2, 3] - -// Remove duplicates based on odd/even criterion with custom comparison function -uniqWith([1, 2, 3, 4], (a, b) => a % 2 === b % 2); -// Returns: [1, 2] - -// Remove duplicates based on property in object array -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 1, y: 2 }, -]; -uniqWith(objects, (a, b) => a.x === b.x && a.y === b.y); -// Returns: [{ x: 1, y: 2 }, { x: 2, y: 1 }] -``` - -`null` or `undefined` are treated as empty arrays. - -```typescript -import { uniqWith } from 'es-toolkit/compat'; - -uniqWith(null); // [] -uniqWith(undefined); // [] -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to remove duplicates from. -- `comparator` (`(a: T, b: T) => boolean`, optional): The function to compare if two elements are equal. Returns `true` if they are considered equal. Default is shallow equality comparison. - -#### Returns - -(`T[]`): Returns a new array with duplicates removed based on the comparison function result. diff --git a/docs/reference/compat/array/unzip.md b/docs/reference/compat/array/unzip.md deleted file mode 100644 index a5b19a78a..000000000 --- a/docs/reference/compat/array/unzip.md +++ /dev/null @@ -1,68 +0,0 @@ -# unzip (Lodash Compatibility) - -::: warning Use [unzip](../../array/unzip.md) from `es-toolkit` - -This `unzip` function operates slowly due to handling of `null` or `undefined`, filtering of non-array values, etc. - -Instead, use the faster and more modern [unzip](../../array/unzip.md) from `es-toolkit`. - -::: - -Collects elements at the same positions in grouped arrays into new arrays. - -```typescript -const result = unzip(array); -``` - -## Usage - -### `unzip(array)` - -Collects elements at the same index in nested arrays and returns them as a new array. Performs the opposite operation of the `zip` function. This is useful when transposing matrices or reorganizing structured data. - -```typescript -import { unzip } from 'es-toolkit/compat'; - -// Unzip arrays with mixed strings, booleans, and numbers -const zipped = [ - ['a', true, 1], - ['b', false, 2], -]; -const result = unzip(zipped); -// Returns: [['a', 'b'], [true, false], [1, 2]] - -// Unzip number arrays -const numbers = [ - [1, 4], - [2, 5], - [3, 6], -]; -unzip(numbers); -// Returns: [[1, 2, 3], [4, 5, 6]] - -// Handle arrays with different lengths -const uneven = [ - ['a', 1], - ['b', 2, true], -]; -unzip(uneven); -// Returns: [['a', 'b'], [1, 2], [undefined, true]] -``` - -`null`, `undefined`, or empty arrays are treated as empty arrays. - -```typescript -import { unzip } from 'es-toolkit/compat'; - -unzip(null); // [] -unzip(undefined); // [] -unzip([]); // [] -``` - -#### Parameters - -- `array` (`T[][] | ArrayLike> | null | undefined`): The nested array to unzip. Elements at the same position in each inner array are collected together. - -#### Returns - -(`T[][]`): Returns a new array with elements at the same positions collected together. diff --git a/docs/reference/compat/array/unzipWith.md b/docs/reference/compat/array/unzipWith.md deleted file mode 100644 index 9b763878c..000000000 --- a/docs/reference/compat/array/unzipWith.md +++ /dev/null @@ -1,84 +0,0 @@ -# unzipWith (Lodash Compatibility) - -::: warning Use `unzipWith` from `es-toolkit` - -This `unzipWith` function operates slowly due to handling of `null` or `undefined`, `ArrayLike` type processing, support for various condition function forms, etc. - -Instead, use the faster and more modern [unzipWith](../../array/unzipWith.md) from `es-toolkit`. - -::: - -Collects elements at the same positions in grouped arrays and applies a transformation function to create a new array. - -```typescript -const result = unzipWith(array, iteratee); -``` - -## Usage - -### `unzipWith(array, iteratee)` - -Collects elements at the same index in nested arrays and applies a transformation function. Similar to the `unzip` function, but can apply a transformation function to each group. If no transformation function is provided, it performs the default `unzip` operation. - -```typescript -import { unzipWith } from 'es-toolkit/compat'; - -// Add elements at the same positions -unzipWith( - [ - [1, 10, 100], - [2, 20, 200], - ], - (a, b) => a + b -); -// Returns: [3, 30, 300] - -// Use without transformation function (default unzip operation) -unzipWith([ - [1, 4], - [2, 5], - [3, 6], -]); -// Returns: [[1, 2, 3], [4, 5, 6]] - -// String concatenation -unzipWith( - [ - ['a', 'x'], - ['b', 'y'], - ['c', 'z'], - ], - (a, b) => a + b -); -// Returns: ['abc', 'xyz'] - -// Find maximum values -unzipWith( - [ - [1, 10], - [2, 20], - [3, 5], - ], - Math.max -); -// Returns: [3, 20] -``` - -`null`, `undefined`, or empty arrays are treated as empty arrays. - -```typescript -import { unzipWith } from 'es-toolkit/compat'; - -unzipWith(null, (a, b) => a + b); // [] -unzipWith(undefined, (a, b) => a + b); // [] -unzipWith([], (a, b) => a + b); // [] -``` - -#### Parameters - -- `array` (`ArrayLike> | null | undefined`): The nested array to unzip. -- `iteratee` (`(...values: T[]) => R`, optional): The transformation function to apply to each group of elements. If not provided, performs the default `unzip` operation. - -#### Returns - -(`R[]` or `T[][]`): Returns an array of transformed results if a transformation function is provided, or an unzipped array if not. diff --git a/docs/reference/compat/array/without.md b/docs/reference/compat/array/without.md deleted file mode 100644 index 92585841b..000000000 --- a/docs/reference/compat/array/without.md +++ /dev/null @@ -1,49 +0,0 @@ -# without (Lodash Compatibility) - -::: warning Use [without](../../array/without.md) from `es-toolkit` - -This `without` function operates slowly due to additional processing for Lodash compatibility. - -Instead, use the faster and more modern [without](../../array/without.md) from `es-toolkit`. - -::: - -Creates a new array excluding specified values from an array. - -```typescript -const result = without([1, 2, 3, 4, 5], 2, 4); -// result is [1, 3, 5]. -``` - -## Usage - -### `without(array, ...values)` - -Returns a new array with the specified values removed from the array. The original array is not modified. - -```typescript -import { without } from 'es-toolkit/compat'; - -// Remove multiple values from number array -const numbers = [1, 2, 3, 4, 5, 2, 4]; -const result1 = without(numbers, 2, 4); -// Returns: [1, 3, 5] - -// Remove values from string array -const fruits = ['apple', 'banana', 'cherry', 'banana']; -const result2 = without(fruits, 'banana'); -// Returns: ['apple', 'cherry'] - -// Handle empty array -const result3 = without([], 1, 2, 3); -// Returns: [] -``` - -#### Parameters - -- `array` (`T[]`): The original array to process. -- `...values` (`T[]`): The values to remove. - -#### Returns - -(`T[]`): A new array with the specified values removed. diff --git a/docs/reference/compat/array/xor.md b/docs/reference/compat/array/xor.md deleted file mode 100644 index 45bf618ac..000000000 --- a/docs/reference/compat/array/xor.md +++ /dev/null @@ -1,61 +0,0 @@ -# xor (Lodash Compatibility) - -::: warning Use [xor](../../array/xor.md) from `es-toolkit` - -This `xor` function operates slowly due to handling of `null` or `undefined`, complex duplicate calculation logic, etc. - -Instead, use the faster and more modern [xor](../../array/xor.md) from `es-toolkit`. - -::: - -Creates a new array of elements that exist in exactly one of the multiple arrays. - -```typescript -const result = xor(...arrays); -``` - -## Usage - -### `xor(...arrays)` - -Computes the symmetric difference of multiple arrays. In other words, returns elements that exist in exactly one of the given arrays. This is useful when you want to find non-overlapping unique elements when comparing two or more arrays. - -```typescript -import { xor } from 'es-toolkit/compat'; - -// Symmetric difference of two arrays -xor([1, 2, 3, 4], [3, 4, 5, 6]); -// Returns: [1, 2, 5, 6] - -// Symmetric difference of three arrays -xor([1, 2], [2, 3], [4, 5]); -// Returns: [1, 3, 4, 5] - -// String arrays -xor(['a', 'b'], ['b', 'c']); -// Returns: ['a', 'c'] - -// Providing only one array -xor([1, 2, 3]); -// Returns: [1, 2, 3] -``` - -`null`, `undefined`, or empty arrays are ignored and only valid arrays are processed. - -```typescript -import { xor } from 'es-toolkit/compat'; - -xor([1, 2], null, [2, 3]); -// Returns: [1, 3] - -xor([], [1, 2], [2, 3]); -// Returns: [1, 3] -``` - -#### Parameters - -- `...arrays` (`Array | null | undefined>`): The arrays to compute the symmetric difference from. `null` or `undefined` are ignored. - -#### Returns - -(`T[]`): Returns a new array of elements that exist in exactly one of the arrays. diff --git a/docs/reference/compat/array/xorBy.md b/docs/reference/compat/array/xorBy.md deleted file mode 100644 index f0dfedc96..000000000 --- a/docs/reference/compat/array/xorBy.md +++ /dev/null @@ -1,63 +0,0 @@ -# xorBy (Lodash Compatibility) - -::: warning Use [xorBy](../../array/xorBy.md) from `es-toolkit` - -This `xorBy` function operates slowly due to handling of `null` or `undefined`, complex duplicate calculation logic, etc. - -Instead, use the faster and more modern [xorBy](../../array/xorBy.md) from `es-toolkit`. - -::: - -Creates a new array of elements that exist in exactly one of the multiple arrays based on a transformation function. - -```typescript -const result = xorBy(...arrays, iteratee); -``` - -## Usage - -### `xorBy(...arrays, iteratee)` - -Computes the symmetric difference of multiple arrays based on a transformation function. Returns elements whose transformation result exists in exactly one of the arrays. This is useful when comparing based on a specific property in object arrays or based on a specific calculation result in number arrays. - -```typescript -import { xorBy } from 'es-toolkit/compat'; - -// Compute symmetric difference by Math.floor result -xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); -// Returns: [1.2, 4.3] - -// Compute symmetric difference by object property -xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); -// Returns: [{ x: 2 }] - -// Compute symmetric difference with function -const users1 = [{ name: 'John', age: 30 }]; -const users2 = [ - { name: 'Jane', age: 25 }, - { name: 'John', age: 30 }, -]; -xorBy(users1, users2, user => user.name); -// Returns: [{ name: 'Jane', age: 25 }] - -// Symmetric difference of three arrays -xorBy([1.2, 2.3], [3.4, 4.5], [5.6, 6.7], Math.floor); -// Returns: [1.2, 2.3, 3.4, 4.5, 5.6, 6.7] -``` - -`null` or `undefined` are ignored. - -```typescript -import { xorBy } from 'es-toolkit/compat'; - -xorBy([2.1, 1.2], null, [4.3, 2.4], Math.floor); -// Returns: [1.2, 4.3] -``` - -#### Parameters - -- `...arrays` (`Array | null | undefined | ValueIteratee>`): The arrays to compute the symmetric difference from and the transformation function at the end. Can be a function, property name, partial object, etc. - -#### Returns - -(`T[]`): Returns a new array of elements that exist in exactly one of the arrays based on the transformation function result. diff --git a/docs/reference/compat/array/xorWith.md b/docs/reference/compat/array/xorWith.md deleted file mode 100644 index d2470d9ea..000000000 --- a/docs/reference/compat/array/xorWith.md +++ /dev/null @@ -1,66 +0,0 @@ -# xorWith (Lodash Compatibility) - -::: warning Use [xorWith](../../array/xorWith.md) from `es-toolkit` - -This `xorWith` function operates slowly due to handling of `null` or `undefined`, complex duplicate calculation logic, etc. - -Instead, use the faster and more modern [xorWith](../../array/xorWith.md) from `es-toolkit`. - -::: - -Creates a new array of elements that exist in exactly one of the multiple arrays using a comparison function. - -```typescript -const result = xorWith(...arrays, comparator); -``` - -## Usage - -### `xorWith(...arrays, comparator)` - -Computes the symmetric difference of multiple arrays using a comparison function. When the comparison function returns `true`, the two elements are considered equal, and returns elements that exist in exactly one of the arrays. This is useful when dealing with complex objects or when custom comparison logic is needed. - -```typescript -import { xorWith } from 'es-toolkit/compat'; - -// Simple number comparison -xorWith([1, 2], [2, 3], (a, b) => a === b); -// Returns: [1, 3] - -// Compare object properties -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, -]; -const others = [ - { x: 1, y: 1 }, - { x: 1, y: 2 }, -]; -xorWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); -// Returns: [{ x: 2, y: 1 }, { x: 1, y: 1 }] - -// Symmetric difference of three arrays -xorWith([1], [2], [3], (a, b) => a === b); -// Returns: [1, 2, 3] - -// Compare by string length -xorWith(['hello'], ['world', 'hi'], (a, b) => a.length === b.length); -// Returns: ['hi'] -``` - -If no comparison function is provided, it uses shallow equality comparison by default. - -```typescript -import { xorWith } from 'es-toolkit/compat'; - -xorWith([1, 2], [2, 3]); -// Returns: [1, 3] -``` - -#### Parameters - -- `...arrays` (`Array | null | undefined | ((a: T, b: T) => boolean)>`): The arrays to compute the symmetric difference from and the comparison function at the end. The comparison function should return `true` if two elements are equal. - -#### Returns - -(`T[]`): Returns a new array of elements that exist in exactly one of the arrays based on the comparison function result. diff --git a/docs/reference/compat/array/zip.md b/docs/reference/compat/array/zip.md deleted file mode 100644 index 8f101e000..000000000 --- a/docs/reference/compat/array/zip.md +++ /dev/null @@ -1,48 +0,0 @@ -# zip (Lodash Compatibility) - -::: warning Use [zip](../../array/zip.md) from `es-toolkit` - -This `zip` function operates slowly due to additional processing for Lodash compatibility. - -Instead, use the faster and more modern [zip](../../array/zip.md) from `es-toolkit`. - -::: - -Combines multiple arrays into a single array of tuples. - -```typescript -const result = zip([1, 2], ['a', 'b']); -// result is [[1, 'a'], [2, 'b']]. -``` - -## Usage - -### `zip(...arrs)` - -Takes multiple arrays and groups the elements at each index into a single tuple to create a new array. If the input arrays have different lengths, the result array will have the length of the longest input array, with missing elements filled with `undefined`. - -```typescript -import { zip } from 'es-toolkit/compat'; - -const arr1 = [1, 2, 3]; -const arr2 = ['a', 'b', 'c']; -const result = zip(arr1, arr2); -// Returns: [[1, 'a'], [2, 'b'], [3, 'c']] - -// Arrays with different lengths -const arr3 = [true, false]; -const result2 = zip(arr1, arr2, arr3); -// Returns: [[1, 'a', true], [2, 'b', false], [3, 'c', undefined]] - -// Including empty array -zip([1, 2], [], ['a', 'b']); -// Returns: [[1, undefined, 'a'], [2, undefined, 'b']] -``` - -#### Parameters - -- `...arrs` (`any[][]`): The arrays to combine. - -#### Returns - -(`any[][]`): A new array of tuples containing elements from each index of the input arrays. diff --git a/docs/reference/compat/array/zipObject.md b/docs/reference/compat/array/zipObject.md deleted file mode 100644 index 481f81a6c..000000000 --- a/docs/reference/compat/array/zipObject.md +++ /dev/null @@ -1,50 +0,0 @@ -# zipObject (Lodash Compatibility) - -::: warning Use [zipObject](../../array/zipObject.md) from `es-toolkit` - -This `zipObject` function operates slowly due to additional processing for Lodash compatibility. - -Instead, use the faster and more modern [zipObject](../../array/zipObject.md) from `es-toolkit`. - -::: - -Creates an object using two arrays. The first array is used as property names, and the second array is used as the corresponding values. - -```typescript -const result = zipObject(keys, values); -``` - -## Usage - -### `zipObject(keys, values)` - -Use `zipObject` when you want to create a single object from a key array and a value array. It uses elements from the first array as property names and elements from the second array as their corresponding values. This is especially useful when processing API responses or transforming data. - -```typescript -import { zipObject } from 'es-toolkit/compat'; - -// Basic usage -const keys = ['a', 'b', 'c']; -const values = [1, 2, 3]; -const result = zipObject(keys, values); -// Returns: { a: 1, b: 2, c: 3 } - -// Arrays with different lengths -const keys2 = ['x', 'y', 'z']; -const values2 = [10, 20]; -const result2 = zipObject(keys2, values2); -// Returns: { x: 10, y: 20, z: undefined } - -// Empty arrays provided -const result3 = zipObject([], []); -// Returns: {} -``` - -#### Parameters - -- `keys` (`PropertyKey[]`): The array to use as property names. -- `values` (`T[]`): The array to use as property values. - -#### Returns - -(`Record`): The created object. diff --git a/docs/reference/compat/array/zipWith.md b/docs/reference/compat/array/zipWith.md deleted file mode 100644 index fc7d6453d..000000000 --- a/docs/reference/compat/array/zipWith.md +++ /dev/null @@ -1,47 +0,0 @@ -# zipWith (Lodash Compatibility) - -::: warning Use [zipWith](../../array/zipWith.md) from `es-toolkit` - -This `zipWith` function operates slowly due to additional processing for Lodash compatibility. - -Instead, use the faster and more modern [zipWith](../../array/zipWith.md) from `es-toolkit`. - -::: - -Combines elements from multiple arrays using a combining function into a new array. - -```typescript -const result = zipWith([1, 2], [3, 4], (a, b) => a + b); -// result is [4, 6]. -``` - -## Usage - -### `zipWith(...arrs, iteratee)` - -Takes multiple arrays and combines elements at each index using a provided function to create a new array. If arrays have different lengths, it processes up to the length of the longest array, passing `undefined` for missing values. - -```typescript -import { zipWith } from 'es-toolkit/compat'; - -// Add elements from two arrays -const result1 = zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b); -// Returns: [5, 7, 9] - -// Combine elements from three arrays -const result2 = zipWith([1, 2], [3, 4], [5, 6], (a, b, c) => a + b + c); -// Returns: [9, 12] - -// Arrays with different lengths -const result3 = zipWith([1, 2, 3], [4, 5], (a, b) => (a || 0) + (b || 0)); -// Returns: [5, 7, 3] -``` - -#### Parameters - -- `...arrs` (`any[][]`): The arrays to combine. -- `iteratee` (`Function`): The function to combine elements at each index. - -#### Returns - -(`any[]`): A new array of results from applying the combining function. diff --git a/docs/reference/compat/function/after.md b/docs/reference/compat/function/after.md deleted file mode 100644 index 7963b36b5..000000000 --- a/docs/reference/compat/function/after.md +++ /dev/null @@ -1,75 +0,0 @@ -# after (Lodash Compatibility) - -::: warning Use [`after`](../../function/after.md) from `es-toolkit` - -This `after` function operates slowly due to complex type validation and integer conversion handling. - -Instead, use the faster and more modern [after](../../function/after.md) from `es-toolkit`. - -::: - -Creates a function that only executes after being called a specified number of times. - -```typescript -const restrictedFunction = after(n, func); -``` - -## Usage - -### `after(n, func)` - -Use `after` when you want to restrict a function to execute only after it has been called a certain number of times. It's useful for executing callbacks after multiple asynchronous operations are complete or activating a function after an initialization phase. - -```typescript -import { after } from 'es-toolkit/compat'; - -// Basic usage -const logAfterThree = after(3, () => { - console.log('Executed from the 3rd call!'); -}); - -logAfterThree(); // Not executed -logAfterThree(); // Not executed -logAfterThree(); // Logs "Executed from the 3rd call!" -logAfterThree(); // Logs "Executed from the 3rd call!" (continues to execute) -``` - -You can also use it to execute a specific callback after all asynchronous operations are complete. - -```typescript -import { after } from 'es-toolkit/compat'; - -const tasks = ['task1', 'task2', 'task3']; -const allTasksComplete = after(tasks.length, () => { - console.log('All tasks completed!'); -}); - -// Called when each task completes -tasks.forEach(task => { - performAsyncTask(task, () => { - console.log(`${task} complete`); - allTasksComplete(); // Logs "All tasks completed!" on the 3rd call - }); -}); -``` - -When you pass 0 or a negative number, it executes immediately from the first call. - -```typescript -import { after } from 'es-toolkit/compat'; - -const immediate = after(0, () => console.log('Executed immediately')); -immediate(); // "Executed immediately" - -const negative = after(-1, () => console.log('Executed immediately')); -negative(); // "Executed immediately" -``` - -#### Parameters - -- `n` (`number`): The number of calls required before the function executes. -- `func` (`TFunc`): The function to restrict. - -#### Returns - -(`TFunc`): Returns a new restricted function that executes the original function from the nth call onwards. diff --git a/docs/reference/compat/function/ary.md b/docs/reference/compat/function/ary.md deleted file mode 100644 index 6b4c91a8c..000000000 --- a/docs/reference/compat/function/ary.md +++ /dev/null @@ -1,90 +0,0 @@ -# ary (Lodash Compatibility) - -::: warning Use [`ary`](../../function/ary.md) from `es-toolkit` - -This `ary` function operates slowly due to complex parameter validation. - -Instead, use the faster and more modern [ary](../../function/ary.md) from `es-toolkit`. - -::: - -Creates a function that limits the number of arguments it can receive. - -```typescript -const cappedFunction = ary(func, n); -``` - -## Usage - -### `ary(func, n)` - -Use `ary` when you want to limit the number of arguments a function receives. It's useful for safely using functions that receive too many arguments or ignoring unnecessary arguments in callback functions. - -```typescript -import { ary } from 'es-toolkit/compat'; - -// Basic usage -function greet(name, age, city) { - return `Hello, ${name}! ${age} years old, from ${city}.`; -} - -const limitedGreet = ary(greet, 2); -console.log(limitedGreet('John', 30, 'Seoul', 'extraArg')); -// "Hello, John! 30 years old, from undefined." -// Arguments from the 3rd onwards are ignored -``` - -You can prevent unnecessary arguments from being passed to callback functions when using them with array methods. - -```typescript -import { ary } from 'es-toolkit/compat'; - -// parseInt accepts a second argument (radix), but map's callback passes 3 arguments -const numbers = ['1', '2', '3', '4', '5']; - -// Incorrect usage - parseInt receives the index as radix -console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] - -// Use ary to pass only the first argument -console.log(numbers.map(ary(parseInt, 1))); // [1, 2, 3, 4, 5] -``` - -You can limit functions to receive only the desired number of parameter arguments. - -```typescript -import { ary } from 'es-toolkit/compat'; - -function sum(...args) { - return args.reduce((total, num) => total + num, 0); -} - -const sum0 = ary(sum, 0); -const sum1 = ary(sum, 1); -const sum2 = ary(sum, 2); -const sum3 = ary(sum, 3); - -console.log(sum0(1, 2, 3, 4, 5)); // 0 (no arguments) -console.log(sum1(1, 2, 3, 4, 5)); // 1 (first argument only) -console.log(sum2(1, 2, 3, 4, 5)); // 3 (first two arguments only) -console.log(sum3(1, 2, 3, 4, 5)); // 6 (first three arguments only) -``` - -When passing a negative number or `NaN`, it's treated as 0 and all arguments are ignored. - -```typescript -import { ary } from 'es-toolkit/compat'; - -const func = (a, b, c) => [a, b, c]; - -console.log(ary(func, -1)(1, 2, 3)); // [] (negative treated as 0) -console.log(ary(func, NaN)(1, 2, 3)); // [] (NaN treated as 0) -``` - -#### Parameters - -- `func` (`Function`): The function to cap arguments for. -- `n` (`number`, optional): The maximum number of arguments to allow. If omitted, uses the function's `length` property. - -#### Returns - -(`Function`): Returns a new function that accepts at most `n` arguments. diff --git a/docs/reference/compat/function/attempt.md b/docs/reference/compat/function/attempt.md deleted file mode 100644 index cf1a53e7f..000000000 --- a/docs/reference/compat/function/attempt.md +++ /dev/null @@ -1,66 +0,0 @@ -# attempt (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [`attempt`](../../util/attempt.md) function or try-catch blocks instead - -This `attempt` function can be confusing because it returns both errors and return values without distinction. - -Instead, use the more direct and clear [`attempt`](../../util/attempt.md) function or try-catch blocks. - -::: - -A function that executes a function and returns an error object if an error occurs. - -```typescript -const result = attempt(func, ...args); -``` - -## Usage - -### `attempt(func, ...args)` - -Use `attempt` when you want to safely execute a function. It's useful when executing a function that may throw errors, preventing the program from crashing and handling errors as return values. - -```typescript -import { attempt } from 'es-toolkit/compat'; - -// Basic usage - successful case -const result = attempt((x, y) => x + y, 2, 3); -console.log(result); // 5 - -// Error case -const errorResult = attempt(() => { - throw new Error('Something went wrong'); -}); -console.log(errorResult); // Error: Something went wrong -``` - -Here's the difference compared to using try-catch blocks. - -```typescript -// Using attempt -import { attempt } from 'es-toolkit/compat'; - -const result = attempt(riskyFunction, arg1, arg2); -if (result instanceof Error) { - console.log('Error occurred:', result.message); -} else { - console.log('Result:', result); -} - -// Using try-catch (more direct) -try { - const result = riskyFunction(arg1, arg2); - console.log('Result:', result); -} catch (error) { - console.log('Error occurred:', error.message); -} -``` - -#### Parameters - -- `func` (`Function`): The function to execute. -- `args` (`...any[]`): The arguments to pass to the function. - -#### Returns - -(`ReturnType | Error`): Returns the return value if the function succeeds, or an Error object if an error occurs. diff --git a/docs/reference/compat/function/before.md b/docs/reference/compat/function/before.md deleted file mode 100644 index de33d02d7..000000000 --- a/docs/reference/compat/function/before.md +++ /dev/null @@ -1,186 +0,0 @@ -# before (Lodash Compatibility) - -::: warning Use [`before`](../../function/before.md) from `es-toolkit` - -This `before` function operates slower due to complex type validation and integer conversion handling. - -Instead, use the faster and more modern [before](../../function/before.md) from `es-toolkit`. - -::: - -Creates a function that executes the original function up to a specified number of times, then returns the last result for subsequent calls. - -```typescript -const limitedFunction = before(n, func); -``` - -## Usage - -### `before(n, func)` - -Use `before` when you want to restrict a function to execute only up to a certain number of times. This is useful for limiting function call counts or when you want to execute a function only during the initial setup phase. - -```typescript -import { before } from 'es-toolkit/compat'; - -// Basic usage -let count = 0; -const beforeThree = before(3, () => ++count); - -console.log(beforeThree()); // 1 (first call) -console.log(beforeThree()); // 2 (second call) -console.log(beforeThree()); // 2 (from third call onwards, returns last result) -console.log(beforeThree()); // 2 (continues to return last result) -``` - -Alternative using closures: - -```typescript -// Using before -const beforeThree = before(3, myFunction); - -// Using closures (simpler and faster) -function createBefore(limit, callback) { - let callCount = 0; - let lastResult; - - return function (...args) { - if (callCount < limit - 1) { - lastResult = callback.apply(this, args); - callCount++; - } - return lastResult; - }; -} - -const beforeThreeAlternative = createBefore(3, myFunction); -``` - -Using as an initialization function: - -```typescript -import { before } from 'es-toolkit/compat'; - -class Database { - constructor() { - this.isInitialized = false; - - // Initialization executes only once - this.initialize = before(2, () => { - console.log('Initializing database...'); - this.setupConnection(); - this.isInitialized = true; - return 'Initialization complete'; - }); - } - - setupConnection() { - // Actual connection setup logic - } - - query(sql) { - const initResult = this.initialize(); - console.log(initResult); // First call: "Initialization complete", subsequent: same result - - // Query execution logic - return `Query executed: ${sql}`; - } -} - -const db = new Database(); -db.query('SELECT * FROM users'); // Initialization executed -db.query('SELECT * FROM products'); // Initialization not executed -``` - -Limiting API calls: - -```typescript -import { before } from 'es-toolkit/compat'; - -// Allow API calls up to 5 times maximum -const limitedApiCall = before(6, endpoint => { - console.log(`API call: ${endpoint}`); - return fetch(endpoint).then(res => res.json()); -}); - -// First 5 calls execute actual API calls -limitedApiCall('/api/data1'); // Actual call -limitedApiCall('/api/data2'); // Actual call -limitedApiCall('/api/data3'); // Actual call -limitedApiCall('/api/data4'); // Actual call -limitedApiCall('/api/data5'); // Actual call -limitedApiCall('/api/data6'); // Returns last result (no API call) -``` - -Limiting event listeners: - -```typescript -import { before } from 'es-toolkit/compat'; - -// Process click events up to 3 times -const limitedClickHandler = before(4, event => { - console.log('Click processed:', event.target.id); - return `Processed: ${Date.now()}`; -}); - -document.getElementById('button').addEventListener('click', limitedClickHandler); -// Only the first 3 clicks are processed, subsequent calls return the last result -``` - -Handling parameters and return values: - -```typescript -import { before } from 'es-toolkit/compat'; - -const limitedCalculator = before(3, (operation, a, b) => { - const result = operation === 'add' ? a + b : a - b; - console.log(`Calculation: ${a} ${operation} ${b} = ${result}`); - return result; -}); - -console.log(limitedCalculator('add', 5, 3)); // "Calculation: 5 add 3 = 8", returns: 8 -console.log(limitedCalculator('subtract', 10, 4)); // "Calculation: 10 subtract 4 = 6", returns: 6 -console.log(limitedCalculator('multiply', 7, 2)); // No calculation, returns: 6 (last result) -``` - -Passing 0 or 1 prevents the function from executing: - -```typescript -import { before } from 'es-toolkit/compat'; - -const neverCalled = before(0, () => { - console.log('This function will not execute'); - return 'result'; -}); - -const onceOnly = before(1, () => { - console.log('This function will also not execute'); - return 'result'; -}); - -console.log(neverCalled()); // undefined -console.log(onceOnly()); // undefined -``` - -Resource cleanup optimization: - -```typescript -import { before } from 'es-toolkit/compat'; - -// Function references are automatically cleaned up to prevent memory leaks -const limitedProcessor = before(2, data => { - // Complex data processing - return processComplexData(data); -}); - -// After the 2nd call, the original function reference is removed (garbage collection) -``` - -#### Parameters - -- `n` (`number`): The maximum number of times to execute the function. It executes up to n-1 times, and from the nth call onwards, returns the last result. -- `func` (`Function`): The function to restrict. - -#### Returns - -(`Function`): Returns a new function that executes the original function up to the specified number of times, and thereafter returns the last result. diff --git a/docs/reference/compat/function/curry.md b/docs/reference/compat/function/curry.md deleted file mode 100644 index 02cb11d95..000000000 --- a/docs/reference/compat/function/curry.md +++ /dev/null @@ -1,222 +0,0 @@ -# curry (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `curry` or manual closures -This `curry` function performs slowly due to complex placeholder handling, arity validation, and argument composition logic. - -If you don't need placeholders, use the faster `es-toolkit`'s [`curry`](../../function/curry.md) or simple closures instead. -::: - -Curries a function so it can accept arguments one at a time or multiple at once. - -```typescript -const curriedFunction = curry(func, arity); -``` - -## Usage - -### `curry(func, arity)` - -Use `curry` when you want to curry a function to make partial application easier. It's useful for providing arguments step by step or using placeholders to provide arguments at specific positions later. - -```typescript -import { curry } from 'es-toolkit/compat'; - -// Basic usage -function add(a, b, c) { - return a + b + c; -} - -const curriedAdd = curry(add); - -// Can be called in various ways -console.log(curriedAdd(1)(2)(3)); // 6 -console.log(curriedAdd(1, 2)(3)); // 6 -console.log(curriedAdd(1)(2, 3)); // 6 -console.log(curriedAdd(1, 2, 3)); // 6 -``` - -Comparison with main library curry: - -```typescript -// compat version (flexible, but slower) -import { curry } from 'es-toolkit/compat'; -const curriedCompat = curry(add); -curriedCompat(1, 2)(3); // supported -curriedCompat(1)(curry.placeholder, 3)(2); // placeholder support - -// main library version (faster, but one at a time only) -import { curry } from 'es-toolkit'; -const curriedMain = curry(add); -curriedMain(1)(2)(3); // supported -curriedMain(1, 2)(3); // not supported -``` - -Using placeholder feature: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function greet(greeting, name, punctuation) { - return `${greeting}, ${name}${punctuation}`; -} - -const curriedGreet = curry(greet); - -// Skip middle arguments with placeholder -const greetWithExclamation = curriedGreet(curry.placeholder, curry.placeholder, '!'); -console.log(greetWithExclamation('Hello', 'John')); // "Hello, John!" - -const sayHello = curriedGreet('Hello'); -console.log(sayHello(curry.placeholder, '~')('Jane')); // "Hello, Jane~" -``` - -Using in functional programming: - -```typescript -import { curry } from 'es-toolkit/compat'; - -// Create mapping functions -const map = curry((fn, array) => array.map(fn)); -const filter = curry((predicate, array) => array.filter(predicate)); - -const numbers = [1, 2, 3, 4, 5]; - -// Create reusable functions -const double = x => x * 2; -const isEven = x => x % 2 === 0; - -const mapDouble = map(double); -const filterEven = filter(isEven); - -console.log(mapDouble(numbers)); // [2, 4, 6, 8, 10] -console.log(filterEven(numbers)); // [2, 4] - -// Function composition -const processNumbers = nums => mapDouble(filterEven(nums)); -console.log(processNumbers(numbers)); // [4, 8] -``` - -Configuring API client: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function apiRequest(method, baseUrl, endpoint, options) { - return fetch(`${baseUrl}${endpoint}`, { - method, - ...options, - }); -} - -const curriedApiRequest = curry(apiRequest); - -// Create specialized functions with default settings -const apiGet = curriedApiRequest('GET', 'https://api.example.com'); -const apiPost = curriedApiRequest('POST', 'https://api.example.com'); - -// Include authentication headers -const authenticatedPost = apiPost(curry.placeholder, { - headers: { Authorization: 'Bearer token123' }, -}); - -// Usage -apiGet('/users'); // GET https://api.example.com/users -authenticatedPost('/users'); // POST with auth headers -``` - -Mathematical operation functions: - -```typescript -import { curry } from 'es-toolkit/compat'; - -const calculate = curry((operation, a, b) => { - switch (operation) { - case '+': - return a + b; - case '-': - return a - b; - case '*': - return a * b; - case '/': - return a / b; - default: - throw new Error('Unsupported operation'); - } -}); - -// Specialized operation functions -const add = calculate('+'); -const subtract = calculate('-'); -const multiply = calculate('*'); - -console.log(add(5, 3)); // 8 -console.log(subtract(10)(4)); // 6 -console.log(multiply(3, 4)); // 12 - -// Fix second operand with placeholder -const addFive = calculate('+', curry.placeholder, 5); -console.log(addFive(10)); // 15 -``` - -Specifying arity: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function variableArgsFunction(a, b, c, ...rest) { - return [a, b, c, rest]; -} - -// Limit arity to 3 -const curriedFixed = curry(variableArgsFunction, 3); - -console.log(curriedFixed(1)(2)(3)); // [1, 2, 3, []] -console.log(curriedFixed(1, 2)(3)); // [1, 2, 3, []] - -// Use without arity (default: function.length) -const curriedDefault = curry(variableArgsFunction); // arity = 3 -``` - -Simple currying alternative: - -```typescript -// Using curry -const curriedAdd = curry((a, b, c) => a + b + c); - -// Manual closure (faster) -const manualCurry = a => b => c => a + b + c; - -// Both produce the same result -console.log(curriedAdd(1)(2)(3)); // 6 -console.log(manualCurry(1)(2)(3)); // 6 -``` - -Constructor functions are also supported: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function Person(name, age, city) { - this.name = name; - this.age = age; - this.city = city; -} - -const CurriedPerson = curry(Person); -const SeoulPerson = CurriedPerson(curry.placeholder, curry.placeholder, 'Seoul'); - -const person1 = new SeoulPerson('John', 30); -const person2 = new SeoulPerson('Jane', 25); - -console.log(person1.city); // "Seoul" -console.log(person2.city); // "Seoul" -``` - -#### Parameters - -- `func` (`Function`): The function to curry. -- `arity` (`number`, optional): The arity (number of arguments) of the function. If omitted, `func.length` is used. - -#### Returns - -(`Function & { placeholder: symbol }`): Returns the curried function. The `placeholder` property allows you to control argument positions. diff --git a/docs/reference/compat/function/curryRight.md b/docs/reference/compat/function/curryRight.md deleted file mode 100644 index b9a6d2382..000000000 --- a/docs/reference/compat/function/curryRight.md +++ /dev/null @@ -1,242 +0,0 @@ -# curryRight (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [`curryRight`](../../function/curryRight.md) or manual closures instead - -This `curryRight` function operates slowly due to complex placeholder handling, arity validation, and argument composition logic. - -If you don't need placeholders, use the faster `es-toolkit`'s [`curryRight`](../../function/curryRight.md) or simple closures instead. - -::: - -Curries a function from right to left, creating a function that accepts arguments one at a time or several at a time, starting from the last argument. - -```typescript -const curriedFunction = curryRight(func, arity); -``` - -## Usage - -### `curryRight(func, arity)` - -Use `curryRight` when you want to curry a function from right to left and partially apply arguments starting from the last one. Unlike regular `curry`, it processes arguments starting from the last one first. - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// Basic usage -function subtract(a, b, c) { - return a - b - c; -} - -const curriedSubtract = curryRight(subtract); - -// Currying from right (starting from last argument) -console.log(curriedSubtract(1)(2)(5)); // 5 - 2 - 1 = 2 -console.log(curriedSubtract(1, 2)(5)); // 5 - 2 - 1 = 2 -console.log(curriedSubtract(1)(2, 5)); // 2 - 5 - 1 = -4 -console.log(curriedSubtract(1, 2, 5)); // 1 - 2 - 5 = -6 -``` - -Difference between `curry` and `curryRight`: - -```typescript -import { curry, curryRight } from 'es-toolkit/compat'; - -function divide(a, b, c) { - return a / b / c; -} - -// Regular curry (from left) -const leftCurried = curry(divide); -console.log(leftCurried(12)(3)(2)); // ((12 / 3) / 2) = 2 - -// curryRight (from right) -const rightCurried = curryRight(divide); -console.log(rightCurried(2)(3)(12)); // ((12 / 3) / 2) = 2 -// The last provided 12 becomes the first argument (a) -``` - -Comparison with main library: - -```typescript -// compat version (flexible, but slower) -import { curryRight } from 'es-toolkit/compat'; -const curriedCompat = curryRight(subtract); -curriedCompat(1, 2)(3); // supported -curriedCompat(1)(curryRight.placeholder, 3)(2); // placeholder supported - -// main library version (faster, but one at a time only) -import { curryRight } from 'es-toolkit'; -const curriedMain = curryRight(subtract); -curriedMain(1)(2)(3); // supported -curriedMain(1, 2)(3); // not supported -``` - -Using placeholder feature: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function formatMessage(name, action, time) { - return `${name} did ${action} at ${time}`; -} - -const curriedFormat = curryRight(formatMessage); - -// Skip specific positions with placeholder -const todayAction = curriedFormat('today'); -const todayLoginAction = todayAction(curryRight.placeholder, 'login'); - -console.log(todayLoginAction('John')); -// "John did login at today" - -// Fix time first -const morningFormat = curriedFormat('9 AM'); -console.log(morningFormat('comment', 'Jane')); -// "Jane did comment at 9 AM" -``` - -Using in array processing: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// Take a specific number of items from the end of an array -function takeFromEnd(array, count, separator = ', ') { - return array.slice(-count).join(separator); -} - -const curriedTake = curryRight(takeFromEnd); - -// Create function that separates with comma -const takeWithComma = curriedTake(', '); - -// Get last 3 items -const takeLast3 = takeWithComma(3); - -const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']; -console.log(takeLast3(fruits)); // "orange, grape, kiwi" - -// Use different separator -const takeWithDash = curriedTake(' - '); -console.log(takeWithDash(2, fruits)); // "grape - kiwi" -``` - -Using in function composition: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// Log output function -function logWithPrefix(message, level, timestamp) { - return `[${timestamp}] ${level}: ${message}`; -} - -const curriedLog = curryRight(logWithPrefix); - -// Fix with current time -const currentTimeLog = curriedLog(new Date().toISOString()); - -// Create loggers by level -const errorLog = currentTimeLog('ERROR'); -const infoLog = currentTimeLog('INFO'); -const debugLog = currentTimeLog('DEBUG'); - -// Usage -console.log(errorLog('Database connection failed')); -console.log(infoLog('Server started')); -console.log(debugLog('Processing user request')); -``` - -Functional programming pipeline: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// Data transformation functions -const mapWith = curryRight((array, fn) => array.map(fn)); -const filterWith = curryRight((array, predicate) => array.filter(predicate)); -const reduceWith = curryRight((array, reducer, initial) => array.reduce(reducer, initial)); - -const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - -// Define transformation functions -const double = x => x * 2; -const isEven = x => x % 2 === 0; -const sum = (acc, val) => acc + val; - -// Compose pipeline (right first) -const processNumbers = nums => { - return reduceWith(filterWith(mapWith(nums, double), isEven), sum, 0); -}; - -console.log(processNumbers(numbers)); // Double all numbers, filter even ones, then sum -``` - -API request builder: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function makeRequest(url, method, headers, body) { - return fetch(url, { method, headers, body }); -} - -const curriedRequest = curryRight(makeRequest); - -// Set body first -const withJsonBody = curriedRequest(JSON.stringify({ data: 'test' })); - -// Add headers -const withHeaders = withJsonBody({ - 'Content-Type': 'application/json', - Authorization: 'Bearer token123', -}); - -// Set POST method -const postRequest = withHeaders('POST'); - -// Final usage -postRequest('/api/data') - .then(response => response.json()) - .then(data => console.log(data)); -``` - -Manual currying alternative: - -```typescript -// Using curryRight -const curriedSubtract = curryRight((a, b, c) => a - b - c); - -// Manual closure (faster, from right) -const manualCurryRight = c => b => a => a - b - c; - -// Both give same result -console.log(curriedSubtract(1)(2)(5)); // 2 -console.log(manualCurryRight(1)(2)(5)); // 2 -``` - -Specifying arity: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function variableArgsFunction(a, b, c, ...rest) { - return { a, b, c, rest }; -} - -// Limit arity to 3 (ignore rest) -const curriedFixed = curryRight(variableArgsFunction, 3); - -// Receive in order c, b, a from right -console.log(curriedFixed(3)(2)(1)); // { a: 1, b: 2, c: 3, rest: [] } -``` - -#### Parameters - -- `func` (`Function`): The function to curry from right to left. -- `arity` (`number`, optional): The arity (number of arguments) of the function. If omitted, `func.length` is used. - -#### Returns - -(`Function & { placeholder: symbol }`): Returns a function curried from right to left. The `placeholder` property can be used to control argument positions. diff --git a/docs/reference/compat/function/debounce.md b/docs/reference/compat/function/debounce.md deleted file mode 100644 index ca8e90f5e..000000000 --- a/docs/reference/compat/function/debounce.md +++ /dev/null @@ -1,264 +0,0 @@ -# debounce (Lodash compatibility) - -::: warning Use [`debounce`](../../function/debounce.md) from `es-toolkit` - -This `debounce` function has overhead due to complex `maxWait` handling and Lodash-compatible option structure. - -Instead, use the faster and more modern [`debounce`](../../function/debounce.md) from `es-toolkit`. - -::: - -Creates a debounced function that delays invoking the provided function until after `wait` milliseconds have elapsed since the last time it was invoked. - -```typescript -const debouncedFunction = debounce(func, wait, options); -``` - -## Usage - -### `debounce(func, wait, options)` - -Use `debounce` when you want to delay function invocation. It's useful for preventing excessive calls in search inputs, scroll events, button clicks, etc. - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// Basic usage -const searchFunction = debounce(query => { - console.log('Searching:', query); -}, 300); - -// Only executes if not called again within 300ms -searchFunction('React'); // Not executed -searchFunction('Vue'); // Not executed -searchFunction('Angular'); // Logs "Searching: Angular" after 300ms -``` - -Comparison with main library debounce: - -```typescript -// compat version (Lodash compatible, additional options like maxWait) -import { debounce } from 'es-toolkit/compat'; -const debouncedCompat = debounce(func, 300, { - leading: true, - trailing: false, - maxWait: 1000 -}); - -// Main library version (faster, simpler) -import { debounce } from 'es-toolkit'; -const debouncedMain = debounce(func, 300, { - edges: ['leading'] // Uses edges instead of leading/trailing -}); -``` - -Leading and trailing options: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const func = () => console.log('Executed'); - -// leading: true - Execute immediately on first call -const leadingDebounce = debounce(func, 1000, { leading: true }); -leadingDebounce(); // Immediately logs "Executed" -leadingDebounce(); // Wait 1 second -// No additional execution after 1 second - -// trailing: true (default) - Execute after delay following last call -const trailingDebounce = debounce(func, 1000, { trailing: true }); -trailingDebounce(); // Wait 1 second -trailingDebounce(); // Wait 1 second (cancels previous timer) -// Logs "Executed" after 1 second - -// Both true - Execute at start and end -const bothDebounce = debounce(func, 1000, { - leading: true, - trailing: true, -}); -bothDebounce(); // Immediately logs "Executed" -bothDebounce(); // Wait 1 second -// Logs "Executed" after 1 second (trailing) -``` - -maxWait option: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// Guarantees execution at least every 2 seconds -const debouncedWithMaxWait = debounce(() => console.log('Saved'), 500, { maxWait: 2000 }); - -// Even with rapid consecutive calls, executes every 2 seconds -setInterval(() => { - debouncedWithMaxWait(); -}, 100); // Calls every 100ms but logs "Saved" every 2 seconds -``` - -Real-world search example: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -class SearchComponent { - constructor() { - this.searchInput = document.getElementById('search'); - - // Debounce user input by 300ms - this.debouncedSearch = debounce(this.performSearch.bind(this), 300, { - leading: false, // Don't search immediately on input start - trailing: true, // Search after input stops - }); - - this.searchInput.addEventListener('input', e => { - this.debouncedSearch(e.target.value); - }); - } - - performSearch(query) { - if (query.length < 2) return; - - console.log('API call:', query); - // fetch(`/api/search?q=${query}`)... - } -} -``` - -Scroll event optimization: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// Debounce scroll events by 100ms, but execute at least every 500ms -const optimizedScrollHandler = debounce( - () => { - const scrollTop = window.pageYOffset; - console.log('Scroll position:', scrollTop); - - // Header hide/show logic - if (scrollTop > 100) { - document.header.classList.add('hidden'); - } else { - document.header.classList.remove('hidden'); - } - }, - 100, - { maxWait: 500 } -); - -window.addEventListener('scroll', optimizedScrollHandler); -``` - -API call throttling: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -class AutoSave { - constructor() { - // Debounce by 500ms, save at least every 5 seconds - this.debouncedSave = debounce(this.saveToServer.bind(this), 500, { maxWait: 5000 }); - } - - onTextChange(content) { - this.pendingContent = content; - this.debouncedSave(); - } - - saveToServer() { - if (!this.pendingContent) return; - - console.log('Saving to server:', this.pendingContent); - // fetch('/api/save', { ... }) - - this.pendingContent = null; - } -} -``` - -cancel and flush methods: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const debouncedFunc = debounce(() => { - console.log('Executed'); -}, 1000); - -debouncedFunc(); // Waiting 1 second - -// Cancel pending execution -debouncedFunc.cancel(); - -// Or execute immediately -debouncedFunc(); // Start waiting 1 second -debouncedFunc.flush(); // Immediately logs "Executed" and cancels timer -``` - -Preventing duplicate button clicks: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const handleSubmit = debounce( - async formData => { - console.log('Submitting form...'); - try { - const response = await fetch('/api/submit', { - method: 'POST', - body: formData, - }); - console.log('Submission complete'); - } catch (error) { - console.error('Submission failed:', error); - } - }, - 1000, - { leading: true, trailing: false } // Only handle first click -); - -document.getElementById('submit-btn').addEventListener('click', e => { - const formData = new FormData(e.target.form); - handleSubmit(formData); -}); -``` - -Resize event handling: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const handleResize = debounce( - () => { - const width = window.innerWidth; - const height = window.innerHeight; - - console.log('Window resized:', { width, height }); - - // Recalculate layout - recalculateLayout(); - }, - 250, - { leading: false, trailing: true } -); - -window.addEventListener('resize', handleResize); - -// Cleanup on page unload -window.addEventListener('beforeunload', () => { - handleResize.cancel(); -}); -``` - -#### Parameters - -- `func` (`Function`): The function to debounce. -- `wait` (`number`, optional): The number of milliseconds to delay. Defaults to `0`. -- `options` (`DebounceSettings`, optional): An options object. - - `leading` (`boolean`): If `true`, executes the function at the start of the delay. Defaults to `false`. - - `trailing` (`boolean`): If `true`, executes the function at the end of the delay. Defaults to `true`. - - `maxWait` (`number`): The maximum time the function execution can be delayed. Defaults to `Infinity`. - -#### Returns - -(`DebouncedFunc`): Returns the debounced function. It includes `cancel()` and `flush()` methods. diff --git a/docs/reference/compat/function/flow.md b/docs/reference/compat/function/flow.md deleted file mode 100644 index 5d723d767..000000000 --- a/docs/reference/compat/function/flow.md +++ /dev/null @@ -1,87 +0,0 @@ -# flow (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `flow` -This `flow` function has become complex with added array flattening for Lodash compatibility. - -Instead, use the faster and more modern `es-toolkit`'s [flow](../../function/flow.md). -::: - -Creates a new function that executes the given functions from left to right sequentially. - -```typescript -const combinedFunc = flow(...functions); -``` - -## Usage - -### `flow(...functions)` - -Use `flow` when you want to create a single composed function that executes multiple functions from left to right sequentially. It's useful for creating data transformation pipelines. - -```typescript -import { flow } from 'es-toolkit/compat'; - -// Basic usage -function add(x, y) { - return x + y; -} - -function square(n) { - return n * n; -} - -function double(n) { - return n * 2; -} - -// Executes from left to right: double(square(add(x, y))) -const calculate = flow(add, square, double); -console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 - -// Passing functions as an array -const calculate2 = flow([add, square], double); -console.log(calculate2(2, 3)); // 50 - -// Modern alternative (recommended) -const modernCalculate = (x, y) => double(square(add(x, y))); -console.log(modernCalculate(1, 2)); // 18 - -// Using pipe operator (future JavaScript) -const pipeCalculate = (x, y) => add(x, y) |> square |> double; - -// Or chaining pattern -class Calculator { - constructor(value) { - this.value = value; - } - - add(n) { - this.value += n; - return this; - } - - square() { - this.value *= this.value; - return this; - } - - double() { - this.value *= 2; - return this; - } - - valueOf() { - return this.value; - } -} - -const chainedResult = new Calculator(3).square().double().valueOf(); // 18 -``` - -#### Parameters - -- `...functions` (`Array`): Functions to execute from left to right. Can be passed as arrays. - -#### Returns - -(`Function`): Returns a new composed function that executes all functions from left to right sequentially. diff --git a/docs/reference/compat/function/flowRight.md b/docs/reference/compat/function/flowRight.md deleted file mode 100644 index b7ce0d3f5..000000000 --- a/docs/reference/compat/function/flowRight.md +++ /dev/null @@ -1,65 +0,0 @@ -# flowRight (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `flowRight` -This `flowRight` function has become complex with added array flattening for Lodash compatibility. - -Instead, use the faster and more modern `es-toolkit`'s [flowRight](../../function/flowRight.md). -::: - -Creates a new function that executes the given functions from right to left sequentially. - -```typescript -const combinedFunc = flowRight(...functions); -``` - -## Usage - -### `flowRight(...functions)` - -Use `flowRight` when you want to create a single composed function that executes multiple functions from right to left sequentially. It's useful for creating data transformation pipelines. - -```typescript -import { flowRight } from 'es-toolkit/compat'; - -// Basic usage -function add(x, y) { - return x + y; -} - -function square(n) { - return n * n; -} - -function double(n) { - return n * 2; -} - -// Executes from right to left: double(square(add(x, y))) -const calculate = flowRight(double, square, add); -console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 - -// Passing functions as an array -const calculate2 = flowRight([double, square], add); -console.log(calculate2(2, 3)); // 50 - -// Modern alternative (recommended) -const modernCalculate = (x, y) => double(square(add(x, y))); -console.log(modernCalculate(1, 2)); // 18 - -// Or using function chaining -const chainedCalculate = (x, y) => [x, y] - .reduce((acc, val, idx) => idx === 0 ? val : acc + val) - .valueOf() - |> (n => n * n) - |> (n => n * 2); -``` - -Generally works in the opposite order of `flow`. It works similarly to function composition, making it intuitive. - -#### Parameters - -- `...functions` (`Array`): Functions to execute from right to left. Can be passed as arrays. - -#### Returns - -(`Function`): Returns a new composed function that executes all functions from right to left sequentially. diff --git a/docs/reference/compat/function/identity.md b/docs/reference/compat/function/identity.md deleted file mode 100644 index d65a81319..000000000 --- a/docs/reference/compat/function/identity.md +++ /dev/null @@ -1,62 +0,0 @@ -# identity (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `identity` -This `identity` function has the same functionality in the main `es-toolkit` library. It simply returns the input value as is. - -Instead, use the faster and more modern `es-toolkit`'s [identity](../../function/identity.md). -::: - -Returns the received value as is. - -```typescript -const result = identity(value); -``` - -## Usage - -### `identity(value)` - -Use `identity` when you want to return the received value as is. It's mainly used as a default value or placeholder function, and is frequently used in functional programming. - -```typescript -import { identity } from 'es-toolkit/compat'; - -// Basic usage -console.log(identity(5)); // 5 -console.log(identity('hello')); // 'hello' -console.log(identity({ key: 'value' })); // { key: 'value' } - -// Use with array's map (value copy) -const numbers = [1, 2, 3, 4, 5]; -const copied = numbers.map(identity); -console.log(copied); // [1, 2, 3, 4, 5] - -// Use as default value in filtering -const values = [1, 0, '', 'hello', null, undefined, false, true]; -const filtered = values.filter(identity); // Keep only truthy values -console.log(filtered); // [1, 'hello', true] - -// Use as default transformation function -function processData(data, transform = identity) { - return transform(data); -} - -console.log(processData('hello')); // 'hello' -console.log(processData('hello', x => x.toUpperCase())); // 'HELLO' -``` - -In most cases, it can be replaced with a simpler arrow function `x => x`: - -```typescript -// Using arrow function instead of identity (recommended) -const copied = numbers.map(x => x); -const filtered = values.filter(x => x); -``` - -#### Parameters - -- `value` (`T`): The value to return. - -#### Returns - -(`T`): Returns the received value as is. diff --git a/docs/reference/compat/function/memoize.md b/docs/reference/compat/function/memoize.md deleted file mode 100644 index 65b0399cc..000000000 --- a/docs/reference/compat/function/memoize.md +++ /dev/null @@ -1,66 +0,0 @@ -# memoize (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `memoize` -This `memoize` function operates slowly due to `null` checks in the `resolver` function, complex type handling for the `MapCache` interface, and additional overhead for Lodash compatibility. - -Instead, use the faster and more modern `es-toolkit`'s [memoize](../../function/memoize.md). -::: - -Caches function results to improve performance when called with the same arguments. - -```typescript -const memoizedFunc = memoize(func, resolver); -``` - -## Usage - -### `memoize(func, resolver)` - -Use `memoize` when you want to memoize function results to reuse previous results when called with the same arguments. It's useful for expensive calculations or API calls. - -```typescript -import { memoize } from 'es-toolkit/compat'; - -// Basic usage -function expensiveCalculation(n) { - console.log('Calculating...', n); - return n * n; -} - -const memoizedCalc = memoize(expensiveCalculation); - -console.log(memoizedCalc(5)); // 'Calculating... 5', 25 -console.log(memoizedCalc(5)); // 25 (cached result, no calculation) -console.log(memoizedCalc(10)); // 'Calculating... 10', 100 - -// Using custom resolver -function fetchUserData(userId, includeProfile) { - console.log('Fetching user data...', userId, includeProfile); - return { id: userId, profile: includeProfile ? 'Profile data' : null }; -} - -// Generate cache key considering all arguments -const memoizedFetch = memoize(fetchUserData, (userId, includeProfile) => { - return `${userId}_${includeProfile}`; -}); - -memoizedFetch(1, true); // 'Fetching user data... 1 true' -memoizedFetch(1, true); // Uses cached result -memoizedFetch(1, false); // 'Fetching user data... 1 false' (different cache key) - -// Accessing and modifying cache -console.log(memoizedCalc.cache.get(5)); // 25 -memoizedCalc.cache.set(7, 49); // Manually set cache -console.log(memoizedCalc(7)); // 49 (uses cached value without calculation) -``` - -In most cases, it uses a basic hash map, but you can also use custom cache implementations as needed. - -#### Parameters - -- `func` (`Function`): The function to memoize. -- `resolver` (`Function`, optional): The function to determine the cache key. If not provided, uses the first argument as the key. - -#### Returns - -(`Function & { cache: MapCache }`): Returns the memoized function. The returned function has a `cache` property for direct cache access. diff --git a/docs/reference/compat/function/noop.md b/docs/reference/compat/function/noop.md deleted file mode 100644 index 244e0ab1d..000000000 --- a/docs/reference/compat/function/noop.md +++ /dev/null @@ -1,60 +0,0 @@ -# noop (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `noop` - -`es-toolkit` also has a [noop](../../function/noop.md) function that behaves the same. - -::: - -An empty function that does nothing. - -```typescript -noop(); -``` - -## Usage - -### `noop(...args)` - -Use `noop` when you need a placeholder function that does nothing. It's often used as a default value or callback function. - -```typescript -import { noop } from 'es-toolkit/compat'; - -// Basic usage -noop(); // Does nothing -noop(1, 2, 3); // Accepts arguments but does nothing - -// Use as default callback -function processData(data, callback = noop) { - // Process data - console.log('Processing data...', data); - - // Call callback (noop if not provided) - callback(data); -} - -processData('test'); // Works without errors even if callback not provided - -// Modern alternative (recommended) -function modernProcessData(data, callback = () => {}) { - console.log('Processing data...', data); - callback(data); -} - -// Or use optional callback -function processDataOptional(data, callback) { - console.log('Processing data...', data); - callback?.(data); // Only call if callback is provided -} -``` - -Useful in situations where a default value or placeholder is needed, but in modern JavaScript, it's more common to use optional chaining (`?.`) or default parameters. - -#### Parameters - -- `...args` (`any[]`): Can accept any arguments, but all are ignored. - -#### Returns - -(`void`): Returns nothing. diff --git a/docs/reference/compat/function/once.md b/docs/reference/compat/function/once.md deleted file mode 100644 index 4ac0b2acb..000000000 --- a/docs/reference/compat/function/once.md +++ /dev/null @@ -1,56 +0,0 @@ -# once (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `once` - -This `once` function has the same functionality as the main library [once](../../function/once.md) function in `es-toolkit`. - -::: - -Restricts a function to be called only once. - -```typescript -const limitedFunc = once(func); -``` - -## Usage - -### `once(func)` - -Use `once` when you want to restrict a function to be called only once. After the first call, the result is cached and the same value is returned. - -```typescript -import { once } from 'es-toolkit/compat'; - -// Basic usage -let count = 0; -const increment = once(() => { - count++; - console.log('Counter incremented:', count); - return count; -}); - -increment(); // Outputs 'Counter incremented: 1', returns 1 -increment(); // Outputs nothing, returns 1 -increment(); // Outputs nothing, returns 1 - -// Practical example - initialization function -const initialize = once(() => { - console.log('Initializing application...'); - // Expensive initialization operations - return 'Initialization complete'; -}); - -// Even if called multiple times, initialization runs only once -initialize(); // Outputs 'Initializing application...' -initialize(); // Outputs nothing -``` - -It's useful when creating expensive initialization operations or setup functions. For example, it can be used for database connections, API token initialization, etc. - -#### Parameters - -- `func` (`Function`): The function to restrict to only one call. - -#### Returns - -(`Function`): Returns a new function that is called only once. From the second call onwards, it returns the result of the first call. diff --git a/docs/reference/compat/function/partial.md b/docs/reference/compat/function/partial.md deleted file mode 100644 index 3cdd8bf75..000000000 --- a/docs/reference/compat/function/partial.md +++ /dev/null @@ -1,59 +0,0 @@ -# partial (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `partial` - -This `partial` function is inefficient due to many overloads and union type handling. In most cases, it can be replaced with a simpler arrow function. - -Instead, use the faster and more modern [`partial`](../../function/partial.md) from `es-toolkit`. - -::: - -Creates a partially applied function by pre-filling some arguments. - -```typescript -const partialFunc = partial(func, ...args); -``` - -## Usage - -### `partial(func, ...args)` - -Use `partial` when you want to create a partially applied function by pre-filling some arguments. It's mainly useful for fixing the first arguments when argument order matters. - -```typescript -import { partial } from 'es-toolkit/compat'; - -// Basic usage -function greet(greeting, name, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// Pre-set the first argument -const sayHello = partial(greet, 'Hello'); -sayHello('Alice', '!'); // 'Hello Alice!' - -// Pre-set multiple arguments -const greetAlice = partial(greet, 'Hello', 'Alice'); -greetAlice('!'); // 'Hello Alice!' - -// Use placeholder to control argument order -const greetWithExclamation = partial(greet, partial.placeholder, 'Alice', '!'); -greetWithExclamation('Hi'); // 'Hi Alice!' -``` - -In most cases, it can be replaced with arrow functions: - -```typescript -// Use arrow functions instead of partial (recommended) -const sayHello = (name, punctuation) => greet('Hello', name, punctuation); -const greetAlice = punctuation => greet('Hello', 'Alice', punctuation); -``` - -#### Parameters - -- `func` (`Function`): The function to partially apply. -- `...args` (`any[]`): The arguments to pre-fill. Use `partial.placeholder` to control argument order. - -#### Returns - -(`Function`): Returns a new function with pre-filled arguments. diff --git a/docs/reference/compat/function/partialRight.md b/docs/reference/compat/function/partialRight.md deleted file mode 100644 index f1c2f5441..000000000 --- a/docs/reference/compat/function/partialRight.md +++ /dev/null @@ -1,59 +0,0 @@ -# partialRight (Lodash Compatibility) - -::: warning Use `es-toolkit`'s `partialRight` - -This `partialRight` function is inefficient due to many overloads and union type handling. In most cases, it can be replaced with a simpler arrow function. - -Instead, use the faster and more modern [`partialRight`](../../function/partialRight.md) from `es-toolkit`. - -::: - -Creates a partially applied function by pre-filling arguments from the right. - -```typescript -const partialFunc = partialRight(func, ...args); -``` - -## Usage - -### `partialRight(func, ...args)` - -Use `partialRight` when you want to create a partially applied function by pre-filling arguments from the right. It's mainly useful for fixing the last arguments when argument order matters. - -```typescript -import { partialRight } from 'es-toolkit/compat'; - -// Basic usage -function greet(greeting, name, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// Pre-set the last argument -const greetWithExclamation = partialRight(greet, '!'); -greetWithExclamation('Hello', 'Alice'); // 'Hello Alice!' - -// Pre-set multiple arguments -const sayHiToAlice = partialRight(greet, 'Alice', '!'); -sayHiToAlice('Hi'); // 'Hi Alice!' - -// Use placeholder to control argument order -const greetAliceWithCustom = partialRight(greet, 'Alice', partialRight.placeholder); -greetAliceWithCustom('Hello', '?'); // 'Hello Alice?' -``` - -In most cases, it can be replaced with arrow functions: - -```typescript -// Use arrow functions instead of partialRight (recommended) -const greetWithExclamation = (greeting, name) => greet(greeting, name, '!'); -const sayHiToAlice = greeting => greet(greeting, 'Alice', '!'); -``` - -#### Parameters - -- `func` (`Function`): The function to partially apply. -- `...args` (`any[]`): The arguments to pre-fill. Use `partialRight.placeholder` to control argument order. - -#### Returns - -(`Function`): Returns a new function with arguments pre-filled from the right. diff --git a/docs/reference/compat/function/rest.md b/docs/reference/compat/function/rest.md deleted file mode 100644 index cbaf16353..000000000 --- a/docs/reference/compat/function/rest.md +++ /dev/null @@ -1,54 +0,0 @@ -# rest (Lodash Compatibility) - -::: warning Use `rest` from `es-toolkit` instead - -This `rest` function may have reduced performance due to additional logic such as default value handling and index validation. - -Use faster, more modern [rest](../../function/rest.md) from `es-toolkit` instead. - -::: - -Creates a function that groups the remaining arguments from a specified index into an array. - -```typescript -const restFunc = rest(func, start); -``` - -## Usage - -### `rest(func, start)` - -Use `rest` when you want to transform function arguments by grouping the remaining arguments from a specified index into an array. It's useful for creating variadic functions. - -```typescript -import { rest } from 'es-toolkit/compat'; - -// Basic usage - group the last arguments into an array -function logMessage(level, message, ...details) { - console.log(`[${level}] ${message}`, details); -} - -const restLogger = rest(logMessage, 2); -restLogger('ERROR', 'Error occurred', 'Detail 1', 'Detail 2'); -// Internally calls logMessage('ERROR', 'Error occurred', [['Detail 1', 'Detail 2']]) - -// Different index example -function process(action, target, ...args) { - return { action, target, args }; -} - -const restProcess = rest(process, 1); -restProcess('update', 'user', 'name', 'John', 'age', 25); -// { action: 'update', target: ['user', 'name', 'John', 'age', 25], args: [] } -``` - -Use this when you want the last arguments of a function to be received as an array. In modern JavaScript, it's more common to use rest parameter syntax (`...args`). - -#### Parameters - -- `func` (`Function`): The function to transform. -- `start` (`number`, optional): The index from which to start grouping arguments into an array. Default is `func.length - 1`. - -#### Returns - -(`Function`): Returns a new function that groups the remaining arguments from the specified index into an array. diff --git a/docs/reference/compat/function/throttle.md b/docs/reference/compat/function/throttle.md deleted file mode 100644 index 7e8245679..000000000 --- a/docs/reference/compat/function/throttle.md +++ /dev/null @@ -1,52 +0,0 @@ -# throttle (Lodash Compatibility) - -::: warning Use `throttle` from `es-toolkit` instead - -This `throttle` function uses the debounce function internally for Lodash compatibility, making it somewhat complex. It also has more complex default and option handling. - -Use faster, more modern [throttle](../../function/throttle.md) from `es-toolkit` instead. - -::: - -Limits function calls to execute at most once per specified time interval. - -```typescript -const throttledFunc = throttle(func, wait, options); -``` - -## Usage - -### `throttle(func, wait, options)` - -Use `throttle` when you want to limit function calls to execute at most once per specified time interval. It's useful for limiting the frequency of event handlers or API calls. - -```typescript -import { throttle } from 'es-toolkit/compat'; - -// Basic usage - execute at most once per second -const throttledLog = throttle(() => { - console.log('Event occurred!'); -}, 1000); - -// Example with options -const throttledScroll = throttle(handleScroll, 100, { - leading: true, // Execute immediately on first call - trailing: false, // Don't execute on last call -}); - -window.addEventListener('scroll', throttledScroll); -``` - -It's essential for performance when handling rapidly occurring events like scroll or resize events. - -#### Parameters - -- `func` (`Function`): The function to throttle. -- `wait` (`number`, optional): The wait time in milliseconds. Default is `0`. -- `options` (`ThrottleSettings`, optional): Throttling options. - - `leading` (`boolean`): Whether to execute on the first call. Default is `true`. - - `trailing` (`boolean`): Whether to execute after the last call. Default is `true`. - -#### Returns - -(`DebouncedFunc`): Returns the throttled function. You can cancel pending executions with the `cancel()` method. diff --git a/docs/reference/compat/function/unary.md b/docs/reference/compat/function/unary.md deleted file mode 100644 index 2f38bcb4b..000000000 --- a/docs/reference/compat/function/unary.md +++ /dev/null @@ -1,46 +0,0 @@ -# unary (Lodash Compatibility) - -::: warning Use `ary` from `es-toolkit` instead - -This `unary` function is implemented as a special case of the `ary` function. If you need more control, it's more efficient to use [ary](../../function/ary.md) from `es-toolkit` directly. - -Use faster, more modern [ary](../../function/ary.md) from `es-toolkit` instead. - -::: - -Limits a function to accept at most one argument. - -```typescript -const limitedFunc = unary(func); -``` - -## Usage - -### `unary(func)` - -Use `unary` when you want to limit a function to accept at most one argument. Any additional arguments passed will be ignored. - -```typescript -import { unary } from 'es-toolkit/compat'; - -function greet(name, greeting, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// Convert to a function that accepts only the first argument -const greetOne = unary(greet); -greetOne('Alice', 'Hello', '!'); // Works the same as greet('Alice') - -// Useful when used with array's map function -const numbers = ['1', '2', '3']; -numbers.map(parseInt); // [1, NaN, NaN] - unexpected result -numbers.map(unary(parseInt)); // [1, 2, 3] - correct result -``` - -#### Parameters - -- `func` (`(...args: any[]) => any`): The function to limit arguments for. - -#### Returns - -(`(...args: any[]) => any`): Returns a new function that accepts at most one argument. diff --git a/docs/reference/compat/math/clamp.md b/docs/reference/compat/math/clamp.md deleted file mode 100644 index 8da805e7f..000000000 --- a/docs/reference/compat/math/clamp.md +++ /dev/null @@ -1,82 +0,0 @@ -# clamp (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [clamp](../../math/clamp.md) - -This `clamp` function operates slowly due to NaN validation and handling. - -Use the faster and more modern `es-toolkit`'s [clamp](../../math/clamp.md) instead. - -::: - -Clamps a number within the specified range. - -```typescript -const clamped = clamp(number, lower, upper); -``` - -## Usage - -### `clamp(number, lower, upper)` - -Use `clamp` when you want to restrict a number between a specified minimum and maximum value. - -```typescript -import { clamp } from 'es-toolkit/compat'; - -// Basic usage -clamp(3, 2, 4); -// Returns: 3 (within range) - -clamp(0, 5, 10); -// Returns: 5 (clamped to minimum) - -clamp(15, 5, 10); -// Returns: 10 (clamped to maximum) - -// Handles negative numbers -clamp(-5, -10, -1); -// Returns: -5 - -clamp(-15, -10, -1); -// Returns: -10 (clamped to minimum) -``` - -### `clamp(number, upper)` - -When only one argument is provided, it's used as the maximum value. - -```typescript -import { clamp } from 'es-toolkit/compat'; - -// Specifying only maximum -clamp(5, 3); -// Returns: 3 (clamped to maximum) - -clamp(2, 3); -// Returns: 2 (within range) - -clamp(1, 5); -// Returns: 1 -``` - -NaN values are treated as 0. - -```typescript -import { clamp } from 'es-toolkit/compat'; - -clamp(5, NaN, 10); -// Returns: 5 (NaN is treated as 0, so range is 0-10) - -clamp(5, 2, NaN); -// Returns: 2 (NaN is treated as 0, so range is 0-2) -``` - -#### Parameters - -- `number` (`number`): The number to clamp. -- `lower` (`number`): The minimum value. If only the second parameter is provided, it becomes the maximum value. -- `upper` (`number`, optional): The maximum value. - -#### Returns - -(`number`): Returns the number clamped within the specified range. diff --git a/docs/reference/compat/math/inRange.md b/docs/reference/compat/math/inRange.md deleted file mode 100644 index a78d6a14b..000000000 --- a/docs/reference/compat/math/inRange.md +++ /dev/null @@ -1,101 +0,0 @@ -# inRange (Lodash Compatibility) - -::: warning Use [inRange](../../math/inRange.md) from `es-toolkit` - -This `inRange` function works slowly due to complex type conversion and null/undefined handling. - -Use the faster and more modern [inRange](../../math/inRange.md) from `es-toolkit` instead. - -::: - -Checks if a number is within a specified range. - -```typescript -const result = inRange(value, minimum, maximum); -``` - -## Usage - -### `inRange(value, minimum, maximum?)` - -Use `inRange` when you want to check if a number is within a specific range. The minimum value is inclusive and the maximum value is exclusive. - -```typescript -import { inRange } from 'es-toolkit/compat'; - -// Basic usage -inRange(3, 2, 4); -// Returns: true (2 ≤ 3 < 4) - -inRange(1, 2, 5); -// Returns: false (1 < 2) - -inRange(5, 2, 5); -// Returns: false (5 is not included) - -// Range boundary values -inRange(2, 2, 4); -// Returns: true (minimum value is included) - -inRange(4, 2, 4); -// Returns: false (maximum value is not included) -``` - -### `inRange(value, maximum)` - -When only two arguments are provided, it treats the range as from 0 to maximum. - -```typescript -import { inRange } from 'es-toolkit/compat'; - -inRange(3, 5); -// Returns: true (0 ≤ 3 < 5) - -inRange(-1, 5); -// Returns: false (-1 < 0) - -inRange(0, 5); -// Returns: true (0 ≤ 0 < 5) - -inRange(5, 5); -// Returns: false (5 is not included) -``` - -If the minimum value is greater than the maximum value, they are automatically swapped. - -```typescript -import { inRange } from 'es-toolkit/compat'; - -inRange(3, 5, 2); -// Returns: true (range becomes 2~5, and 2 ≤ 3 < 5) - -inRange(1, 5, 2); -// Returns: false (1 < 2) -``` - -Invalid values are appropriately converted. - -```typescript -import { inRange } from 'es-toolkit/compat'; - -// String number conversion -inRange(3, '2', '4'); -// Returns: true - -// Falsy values are treated as 0 -inRange(1, null, 5); -// Returns: true (null is treated as 0, so range is 0~5) - -inRange(3, false, 5); -// Returns: true (false is treated as 0) -``` - -#### Parameters - -- `value` (`number`): The number to check if it's within the range. -- `minimum` (`number`): The minimum value of the range (inclusive). If `maximum` is not provided, this value becomes the maximum. -- `maximum` (`number`, optional): The maximum value of the range (exclusive). - -#### Returns - -(`boolean`): Returns `true` if the value is within the specified range, otherwise `false`. diff --git a/docs/reference/compat/math/maxBy.md b/docs/reference/compat/math/maxBy.md deleted file mode 100644 index b40cfee5b..000000000 --- a/docs/reference/compat/math/maxBy.md +++ /dev/null @@ -1,114 +0,0 @@ -# maxBy (Lodash Compatibility) - -::: warning Use [maxBy](../../array/maxBy.md) from es-toolkit - -This `maxBy` function works slowly due to iteratee function processing and type conversion. - -Use the faster and more modern [maxBy](../../array/maxBy.md) from `es-toolkit` instead. - -::: - -Finds the element with the maximum value based on a condition. - -```typescript -const maxItem = maxBy(array, iteratee); -``` - -## Usage - -### `maxBy(array, iteratee)` - -Finds the element in an array that has the largest value when computed by a function. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -// Find element with maximum property in object array -const people = [ - { name: 'John', age: 25 }, - { name: 'Jane', age: 30 }, - { name: 'Bob', age: 35 }, -]; - -maxBy(people, person => person.age); -// Returns: { name: 'Bob', age: 35 } - -// Can also use property name -maxBy(people, 'age'); -// Returns: { name: 'Bob', age: 35 } -``` - -Transform values with a function to find the maximum. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -maxBy(items, x => x.a); -// Returns: { a: 3 } - -const numbers = [-1, -2, -3]; -maxBy(numbers, x => Math.abs(x)); -// Returns: -3 (element with largest absolute value) -``` - -Access array elements by index. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const arrays = [ - [1, 2], - [3, 4], - [0, 5], -]; -maxBy(arrays, 0); // Array with maximum first element -// Returns: [3, 4] - -maxBy(arrays, 1); // Array with maximum second element -// Returns: [0, 5] -``` - -Find elements matching specific property values. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const users = [ - { name: 'John', age: 25, active: true }, - { name: 'Jane', age: 30, active: false }, - { name: 'Bob', age: 35, active: true }, -]; - -// First element among those with active: true -maxBy(users, ['active', true]); -// Returns: { name: 'John', age: 25, active: true } - -// Specify condition as object -maxBy(users, { active: true }); -// Returns: { name: 'John', age: 25, active: true } -``` - -Empty arrays return undefined. - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -maxBy([], x => x.a); -// Returns: undefined - -maxBy(null); -// Returns: undefined - -maxBy(undefined); -// Returns: undefined -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to search. -- `iteratee` (`ValueIteratee`, optional): The function, property name, or condition to apply to each element. - -#### Returns - -(`T | undefined`): Returns the element with the largest value based on the condition. Returns `undefined` if the array is empty. diff --git a/docs/reference/compat/math/mean.md b/docs/reference/compat/math/mean.md deleted file mode 100644 index 4184a055e..000000000 --- a/docs/reference/compat/math/mean.md +++ /dev/null @@ -1,76 +0,0 @@ -# mean (Lodash Compatibility) - -::: warning Use [mean](../../math/mean.md) from es-toolkit - -This `mean` function works slowly due to type conversion and null/undefined handling. - -Use the faster and more modern [mean](../../math/mean.md) from `es-toolkit` instead. - -::: - -Calculates the average value of an array. - -```typescript -const average = mean(array); -``` - -## Usage - -### `mean(array)` - -Calculates the average value of a number array. - -```typescript -import { mean } from 'es-toolkit/compat'; - -// Number array -mean([1, 2, 3, 4, 5]); -// Returns: 3 - -mean([10, 20, 30]); -// Returns: 20 - -mean([1.5, 2.5, 3.5]); -// Returns: 2.5 -``` - -Empty arrays return NaN. - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean([]); -// Returns: NaN - -mean(null); -// Returns: NaN - -mean(undefined); -// Returns: NaN -``` - -Invalid values are treated as 0 and included in the calculation. - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean([1, undefined, 2, null, 3]); -// Returns: 1.2 (1 + 2 + 3) / 5 = 1.2 -``` - -Strings will be concatenated. - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean(['1', '2', '3']); -// Returns: 41 (123 / 3 = 41) -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array containing numbers to calculate the average from. - -#### Returns - -(`number`): Returns the average value of the array. Returns `NaN` if the array is empty. diff --git a/docs/reference/compat/math/meanBy.md b/docs/reference/compat/math/meanBy.md deleted file mode 100644 index 4f9a71b7d..000000000 --- a/docs/reference/compat/math/meanBy.md +++ /dev/null @@ -1,103 +0,0 @@ -# meanBy (Lodash Compatibility) - -::: warning Use [meanBy](../../math/meanBy.md) from es-toolkit - -This `meanBy` function works slowly due to iteratee function processing and type conversion. - -Use the faster and more modern [meanBy](../../math/meanBy.md) from `es-toolkit` instead. - -::: - -Calculates the average of values that meet a condition. - -```typescript -const average = meanBy(array, iteratee); -``` - -## Usage - -### `meanBy(array, iteratee)` - -Calculates the average of the results of applying a function to each element in an array. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -// Average of specific property in object array -const people = [ - { name: 'John', age: 25 }, - { name: 'Jane', age: 30 }, - { name: 'Bob', age: 35 }, -]; - -meanBy(people, person => person.age); -// Returns: 30 - -// Can also use property name -meanBy(people, 'age'); -// Returns: 30 -``` - -Transform values with a function to calculate the average. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const numbers = [1.5, 2.7, 3.2, 4.8]; -meanBy(numbers, x => Math.floor(x)); -// Returns: 2.5 (1 + 2 + 3 + 4) / 4 - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -meanBy(items, x => x.a); -// Returns: 2 -``` - -Access array elements by index. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const arrays = [[2], [3], [1]]; -meanBy(arrays, 0); // Average of first elements -// Returns: 2 -``` - -Calculate only for elements matching specific property values. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const users = [ - { name: 'John', age: 25, active: true }, - { name: 'Jane', age: 30, active: false }, - { name: 'Bob', age: 35, active: true }, -]; - -// Only active users -meanBy(users, { active: true }); -// Returns: 0.6666666 (2 out of 3 users are active) -``` - -Empty arrays return NaN. - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -meanBy([], x => x.a); -// Returns: NaN - -meanBy(null); -// Returns: NaN - -meanBy(undefined); -// Returns: NaN -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to process. -- `iteratee` (`ValueIteratee`, optional): The function, property name, or condition to apply to each element. - -#### Returns - -(`number`): Returns the average of values that meet the condition. Returns `NaN` if the array is empty. diff --git a/docs/reference/compat/math/minBy.md b/docs/reference/compat/math/minBy.md deleted file mode 100644 index 22f573fe7..000000000 --- a/docs/reference/compat/math/minBy.md +++ /dev/null @@ -1,114 +0,0 @@ -# minBy (Lodash Compatibility) - -::: warning Use [minBy](../../array/minBy.md) from es-toolkit - -This `minBy` function works slowly due to iteratee function processing and type conversion. - -Use the faster and more modern [minBy](../../array/minBy.md) from `es-toolkit` instead. - -::: - -Finds the element with the minimum value based on a condition. - -```typescript -const minItem = minBy(array, iteratee); -``` - -## Usage - -### `minBy(array, iteratee)` - -Finds the element in an array that has the smallest value when computed by a function. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -// Find element with minimum property in object array -const people = [ - { name: 'John', age: 25 }, - { name: 'Jane', age: 30 }, - { name: 'Bob', age: 35 }, -]; - -minBy(people, person => person.age); -// Returns: { name: 'John', age: 25 } - -// Can also use property name -minBy(people, 'age'); -// Returns: { name: 'John', age: 25 } -``` - -Transform values with a function to find the minimum. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -minBy(items, x => x.a); -// Returns: { a: 1 } - -const numbers = [-1, -2, -3]; -minBy(numbers, x => Math.abs(x)); -// Returns: -1 (element with smallest absolute value) -``` - -Access array elements by index. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const arrays = [ - [1, 2], - [3, 4], - [0, 5], -]; -minBy(arrays, 0); // Array with minimum first element -// Returns: [0, 5] - -minBy(arrays, 1); // Array with minimum second element -// Returns: [1, 2] -``` - -Find elements matching specific property values. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const users = [ - { name: 'John', age: 25, active: true }, - { name: 'Jane', age: 30, active: false }, - { name: 'Bob', age: 35, active: true }, -]; - -// First element among those with active: true -minBy(users, ['active', true]); -// Returns: { name: 'Jane', age: 30, active: false } - -// Specify condition as object -minBy(users, { active: true }); -// Returns: { name: 'Jane', age: 30, active: false } -``` - -Empty arrays return undefined. - -```typescript -import { minBy } from 'es-toolkit/compat'; - -minBy([], x => x.a); -// Returns: undefined - -minBy(null); -// Returns: undefined - -minBy(undefined); -// Returns: undefined -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to search. -- `iteratee` (`ValueIteratee`, optional): The function, property name, or condition to apply to each element. - -#### Returns - -(`T | undefined`): Returns the element with the smallest value based on the condition. Returns `undefined` if the array is empty. diff --git a/docs/reference/compat/math/range.md b/docs/reference/compat/math/range.md deleted file mode 100644 index 278d4bbf7..000000000 --- a/docs/reference/compat/math/range.md +++ /dev/null @@ -1,99 +0,0 @@ -# range (Lodash Compatibility) - -::: warning Use [range](../../math/range.md) from es-toolkit - -This `range` function works slowly due to complex argument processing and type conversion. - -Use the faster and more modern [range](../../math/range.md) from `es-toolkit` instead. - -::: - -Creates an array of numbers in a range. - -```typescript -const numbers = range(start, end, step); -``` - -## Usage - -### `range(end)` - -Creates an array of numbers from 0 to end, incrementing by 1. - -```typescript -import { range } from 'es-toolkit/compat'; - -range(4); -// Returns: [0, 1, 2, 3] - -range(0); -// Returns: [] - -range(-4); -// Returns: [0, -1, -2, -3] -``` - -### `range(start, end)` - -Creates an array of numbers from start to end, incrementing by 1. - -```typescript -import { range } from 'es-toolkit/compat'; - -range(1, 5); -// Returns: [1, 2, 3, 4] - -range(5, 1); -// Returns: [5, 4, 3, 2] (automatically decrements by -1) - -range(-2, 3); -// Returns: [-2, -1, 0, 1, 2] -``` - -### `range(start, end, step)` - -Creates an array of numbers from start to end, incrementing by step. - -```typescript -import { range } from 'es-toolkit/compat'; - -range(0, 20, 5); -// Returns: [0, 5, 10, 15] - -range(0, -4, -1); -// Returns: [0, -1, -2, -3] - -range(1, 4, 0); -// Returns: [1, 1, 1] -``` - -Decimal steps are also possible. - -```typescript -import { range } from 'es-toolkit/compat'; - -range(0, 1, 0.2); -// Returns: [0, 0.2, 0.4, 0.6, 0.8] - -range(1, 0, -0.25); -// Returns: [1, 0.75, 0.5, 0.25] -``` - -When used as an iteratee, it's handled with a guard object. - -```typescript -import { range } from 'es-toolkit/compat'; - -[1, 2, 3].map(range); -// Returns: [[0], [0, 1], [0, 1, 2]] -``` - -#### Parameters - -- `start` (`number`): The start value of the range (inclusive). If `end` is not provided, this becomes the end value. -- `end` (`number`, optional): The end value of the range (exclusive). -- `step` (`number`, optional): The increment step. Default is 1 or -1. - -#### Returns - -(`number[]`): Returns an array of numbers in the specified range. diff --git a/docs/reference/compat/math/rangeRight.md b/docs/reference/compat/math/rangeRight.md deleted file mode 100644 index 954315a5f..000000000 --- a/docs/reference/compat/math/rangeRight.md +++ /dev/null @@ -1,99 +0,0 @@ -# rangeRight (Lodash Compatibility) - -::: warning Use [rangeRight](../../math/rangeRight.md) from es-toolkit - -This `rangeRight` function works slowly due to complex argument processing and type conversion. - -Use the faster and more modern [rangeRight](../../math/rangeRight.md) from `es-toolkit` instead. - -::: - -Creates an array of numbers in a range in reverse order. - -```typescript -const numbers = rangeRight(start, end, step); -``` - -## Usage - -### `rangeRight(end)` - -Creates an array of numbers from 0 to end, incrementing by 1, then reverses the order. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(4); -// Returns: [3, 2, 1, 0] - -rangeRight(0); -// Returns: [] - -rangeRight(-4); -// Returns: [-3, -2, -1, 0] -``` - -### `rangeRight(start, end)` - -Creates an array of numbers from start to end, incrementing by 1, then reverses the order. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(1, 5); -// Returns: [4, 3, 2, 1] - -rangeRight(5, 1); -// Returns: [2, 3, 4, 5] (automatically decrements by -1, then reverses) - -rangeRight(-2, 3); -// Returns: [2, 1, 0, -1, -2] -``` - -### `rangeRight(start, end, step)` - -Creates an array of numbers from start to end, incrementing by step, then reverses the order. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(0, 8, 2); -// Returns: [6, 4, 2, 0] - -rangeRight(0, -4, -1); -// Returns: [-3, -2, -1, 0] - -rangeRight(1, 4, 0); -// Returns: [1, 1, 1] -``` - -Decimal steps are also possible. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(0, 1, 0.2); -// Returns: [0.8, 0.6, 0.4, 0.2, 0] - -rangeRight(1, 0, -0.25); -// Returns: [0.25, 0.5, 0.75, 1] -``` - -When used as an iteratee, it's handled with a guard object. - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -[1, 2, 3].map(rangeRight); -// Returns: [[0], [1, 0], [2, 1, 0]] -``` - -#### Parameters - -- `start` (`number`): The start value of the range (inclusive). If `end` is not provided, this becomes the end value. -- `end` (`number`, optional): The end value of the range (exclusive). -- `step` (`number`, optional): The increment step. Default is 1 or -1. - -#### Returns - -(`number[]`): Returns an array of numbers in the specified range in reverse order. diff --git a/docs/reference/compat/math/sum.md b/docs/reference/compat/math/sum.md deleted file mode 100644 index 1b7234ef9..000000000 --- a/docs/reference/compat/math/sum.md +++ /dev/null @@ -1,73 +0,0 @@ -# sum (Lodash Compatibility) - -::: warning Use [sum](../../math/sum.md) from es-toolkit - -This `sum` function works slowly due to type conversion and null/undefined handling. - -Use the faster and more modern [sum](../../math/sum.md) from `es-toolkit` instead. - -::: - -Adds all values in an array. - -```typescript -const total = sum(array); -``` - -## Usage - -### `sum(array)` - -Adds all numbers in an array to get the total sum. - -```typescript -import { sum } from 'es-toolkit/compat'; - -// Number array -sum([1, 2, 3]); -// Returns: 6 - -sum([1.5, 2.5, 3]); -// Returns: 7 - -// Empty array -sum([]); -// Returns: 0 -``` - -Handles BigInt and strings as well. - -```typescript -import { sum } from 'es-toolkit/compat'; - -// BigInt array -sum([1n, 2n, 3n]); -// Returns: 6n - -// String array (concatenated) -sum(['1', '2']); -// Returns: '12' -``` - -Invalid values are ignored. - -```typescript -import { sum } from 'es-toolkit/compat'; - -sum([1, undefined, 2]); -// Returns: 3 (undefined ignored) - -sum(null); -// Returns: 0 - -sum(undefined); -// Returns: 0 -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array containing values to add. - -#### Returns - -(`number`): Returns the total sum of all values. diff --git a/docs/reference/compat/math/sumBy.md b/docs/reference/compat/math/sumBy.md deleted file mode 100644 index c1ce46800..000000000 --- a/docs/reference/compat/math/sumBy.md +++ /dev/null @@ -1,103 +0,0 @@ -# sumBy (Lodash Compatibility) - -::: warning Use [sumBy](../../math/sumBy.md) from es-toolkit - -This `sumBy` function works slowly due to iteratee function processing and type conversion. - -Use the faster and more modern [sumBy](../../math/sumBy.md) from `es-toolkit` instead. - -::: - -Adds values that meet a condition. - -```typescript -const total = sumBy(array, iteratee); -``` - -## Usage - -### `sumBy(array, iteratee)` - -Adds the results of applying a function to each element in an array. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -// Number array -sumBy([1, 2, 3], value => value); -// Returns: 6 - -sumBy([1.5, 2.5, 3.5], value => Math.floor(value)); -// Returns: 6 (1 + 2 + 3) - -// Empty array -sumBy([], value => value); -// Returns: 0 -``` - -### `sumBy(array)` - -If no function is provided, it adds the array values directly. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -sumBy([1, 2, 3]); -// Returns: 6 - -sumBy([1n, 2n, 3n]); -// Returns: 6n -``` - -Add specific properties from object arrays. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -const people = [ - { name: 'John', age: 25 }, - { name: 'Jane', age: 30 }, - { name: 'Bob', age: 35 }, -]; - -sumBy(people, person => person.age); -// Returns: 90 - -// Can also use property name -sumBy(people, 'age'); -// Returns: 90 -``` - -Concatenates strings as well. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -const items = [{ a: '1' }, { a: '2' }]; -sumBy(items, obj => obj.a); -// Returns: '12' -``` - -Invalid values are ignored. - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -sumBy([1, undefined, 2], value => value); -// Returns: 3 (undefined ignored) - -sumBy(null); -// Returns: 0 - -sumBy(undefined); -// Returns: 0 -``` - -#### Parameters - -- `array` (`ArrayLike | null | undefined`): The array to process. -- `iteratee` (`((value: T) => number) | string`, optional): The function or property name to apply to each element. - -#### Returns - -(`number`): Returns the total sum of values that meet the condition. diff --git a/docs/reference/compat/object/clone.md b/docs/reference/compat/object/clone.md deleted file mode 100644 index cafd62ab1..000000000 --- a/docs/reference/compat/object/clone.md +++ /dev/null @@ -1,89 +0,0 @@ -# clone (Lodash compatibility) - -::: warning Use `clone` from `es-toolkit` instead - -This `clone` function is relatively slow due to complex logic that handles special object types. - -Use the faster and more modern [clone](../../object/clone.md) from `es-toolkit` instead. - -::: - -Creates a shallow copy of an object. - -```typescript -const cloned = clone(value); -``` - -## Usage - -### `clone(value)` - -Use `clone` when you want to create a shallow copy of a value. It can copy various types of objects and primitive values. - -```typescript -import { clone } from 'es-toolkit/compat'; - -// Copying primitive values -const num = 42; -const clonedNum = clone(num); -// Returns: 42 (same value) - -// Copying arrays -const arr = [1, 2, 3]; -const clonedArr = clone(arr); -// Returns: [1, 2, 3] (new array instance) - -// Copying objects -const obj = { a: 1, b: 'hello' }; -const clonedObj = clone(obj); -// Returns: { a: 1, b: 'hello' } (new object instance) - -// Copying Date objects -const date = new Date('2023-01-01'); -const clonedDate = clone(date); -// Returns: new Date('2023-01-01') (new Date instance) - -// Copying regular expressions -const regex = /hello/gi; -regex.lastIndex = 3; -const clonedRegex = clone(regex); -// Returns: /hello/gi with lastIndex = 3 - -// Copying Map -const map = new Map([ - ['a', 1], - ['b', 2], -]); -const clonedMap = clone(map); -// Returns: new Map([['a', 1], ['b', 2]]) - -// Copying Set -const set = new Set([1, 2, 3]); -const clonedSet = clone(set); -// Returns: new Set([1, 2, 3]) -``` - -Nested objects are only shallowly copied. - -```typescript -import { clone } from 'es-toolkit/compat'; - -const nested = { - a: 1, - b: { - c: 2, - }, -}; -const clonedNested = clone(nested); - -console.log(clonedNested !== nested); // true (different objects) -console.log(clonedNested.b === nested.b); // true (nested objects have same reference) -``` - -#### Parameters - -- `value` (`T`): The value to clone. - -#### Returns - -(`T`): Returns the cloned value. diff --git a/docs/reference/compat/object/cloneDeep.md b/docs/reference/compat/object/cloneDeep.md deleted file mode 100644 index f4b1e9a73..000000000 --- a/docs/reference/compat/object/cloneDeep.md +++ /dev/null @@ -1,88 +0,0 @@ -# cloneDeep (Lodash compatibility) - -::: warning Use `cloneDeep` from `es-toolkit` instead - -This `cloneDeep` function is relatively slow due to complex logic that handles special object types. - -Use the faster and more modern [cloneDeep](../../object/cloneDeep.md) from `es-toolkit` instead. - -::: - -Creates a deep copy of an object. - -```typescript -const cloned = cloneDeep(value); -``` - -## Usage - -### `cloneDeep(value)` - -Use `cloneDeep` when you want to create a deep copy of a value. It copies nested objects and arrays completely as new instances. - -```typescript -import { cloneDeep } from 'es-toolkit/compat'; - -// Copying primitive values -const num = 42; -const clonedNum = cloneDeep(num); -// Returns: 42 (same value) - -// Deep copying arrays -const arr = [1, [2, 3], { a: 4 }]; -const clonedArr = cloneDeep(arr); -clonedArr[1][0] = 99; -console.log(arr[1][0]); // 2 (original is not changed) -console.log(clonedArr[1][0]); // 99 - -// Deep copying objects -const obj = { - a: 1, - b: { - c: 2, - d: { - e: 3, - }, - }, -}; -const clonedObj = cloneDeep(obj); -clonedObj.b.d.e = 99; -console.log(obj.b.d.e); // 3 (original is not changed) -console.log(clonedObj.b.d.e); // 99 - -// Deep copying Date objects -const date = new Date('2023-01-01'); -const clonedDate = cloneDeep(date); -// Returns: new Date('2023-01-01') (new Date instance) - -// Complex nested structures -const complex = { - arr: [1, { nested: true }], - map: new Map([['key', { value: 1 }]]), - set: new Set([{ item: 1 }]), - date: new Date(), -}; -const clonedComplex = cloneDeep(complex); -// All nested objects are copied as completely new instances -``` - -Circular references are also handled correctly. - -```typescript -import { cloneDeep } from 'es-toolkit/compat'; - -const obj = { a: 1 }; -obj.self = obj; // circular reference - -const cloned = cloneDeep(obj); -console.log(cloned !== obj); // true -console.log(cloned.self === cloned); // true (circular reference preserved) -``` - -#### Parameters - -- `value` (`T`): The value to deep clone. - -#### Returns - -(`T`): Returns the deeply cloned value. diff --git a/docs/reference/compat/object/findKey.md b/docs/reference/compat/object/findKey.md deleted file mode 100644 index 0c2cda08c..000000000 --- a/docs/reference/compat/object/findKey.md +++ /dev/null @@ -1,61 +0,0 @@ -# findKey (Lodash compatibility) - -::: warning Use `es-toolkit`'s `findKey` - -This `findKey` function operates in a complex manner due to various condition type handling and compatibility logic. - -Instead, use the faster and more modern [findKey](../../object/findKey.md) from `es-toolkit`. - -::: - -Finds the key of the first element that matches the predicate. - -```typescript -const key = findKey(obj, predicate); -``` - -## Usage - -### `findKey(obj, predicate)` - -Use `findKey` to find the key of the first element in an object that matches the predicate. You can use various types of predicates such as functions, objects, arrays, and strings. - -```typescript -import { findKey } from 'es-toolkit/compat'; - -// Find key with a function predicate -const users = { - alice: { age: 25, active: true }, - bob: { age: 30, active: false }, - charlie: { age: 35, active: true }, -}; - -findKey(users, user => user.age > 30); -// Returns: 'charlie' - -// Find key with an object predicate -findKey(users, { active: false }); -// Returns: 'bob' - -// Find key with a property path -findKey(users, 'active'); -// Returns: 'alice' -``` - -If no element matches the predicate, it returns `undefined`. - -```typescript -import { findKey } from 'es-toolkit/compat'; - -findKey({ a: 1, b: 2 }, value => value > 5); -// Returns: undefined -``` - -#### Parameters - -- `obj` (`T | null | undefined`): The object to search. -- `predicate` (`ObjectIteratee`, optional): The predicate to apply to each element. Can be a function, object, array, or string. - -#### Returns - -(`string | undefined`): Returns the key of the first element that matches the predicate. Returns `undefined` if no match is found. diff --git a/docs/reference/compat/object/invert.md b/docs/reference/compat/object/invert.md deleted file mode 100644 index e499b4652..000000000 --- a/docs/reference/compat/object/invert.md +++ /dev/null @@ -1,60 +0,0 @@ -# invert (Lodash compatibility) - -::: warning Use `invert` from `es-toolkit` - -This `invert` function operates slower due to the complex processing required for Lodash compatibility. - -Instead, use the faster and more modern [`invert`](../../object/invert.md) from `es-toolkit`. - -::: - -Inverts the keys and values of an object. - -```typescript -const inverted = invert(object); -``` - -## Usage - -### `invert(object)` - -Use `invert` when you want to swap the keys and values of an object. The original object's keys become the values in the new object, and the original object's values become the keys in the new object. - -```typescript -import { invert } from 'es-toolkit/compat'; - -// Basic key-value inversion -const object = { a: 1, b: 2, c: 3 }; -invert(object); -// => { '1': 'a', '2': 'b', '3': 'c' } - -// Inverting string values -const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' }; -invert(colors); -// => { '#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue' } - -// Mixed key and value types -const mixed = { a: 1, 2: 'b', c: 3, 4: 'd' }; -invert(mixed); -// => { '1': 'a', 'b': '2', '3': 'c', 'd': '4' } -``` - -When there are duplicate values, the last key is used. - -```typescript -import { invert } from 'es-toolkit/compat'; - -// Case with duplicate values -const object = { a: 1, b: 1, c: 2 }; -invert(object); -// => { '1': 'b', '2': 'c' } -// 'a' is overwritten and lost -``` - -#### Parameters - -- `object` (`object`): The object to invert. - -#### Returns - -(`Record`): Returns a new object with keys and values inverted. diff --git a/docs/reference/compat/object/mapKeys.md b/docs/reference/compat/object/mapKeys.md deleted file mode 100644 index 87c89bdcd..000000000 --- a/docs/reference/compat/object/mapKeys.md +++ /dev/null @@ -1,63 +0,0 @@ -# mapKeys (Lodash compatibility) - -::: warning Use `mapKeys` from `es-toolkit` - -This `mapKeys` function is relatively slow due to handling `null` or `undefined` and the `iteratee` conversion process. - -Use the faster and more modern [`mapKeys`](../../object/mapKeys.md) from `es-toolkit` instead. - -::: - -Creates a new object by transforming keys while keeping values the same. - -```typescript -const result = mapKeys(obj, iteratee); -``` - -## Usage - -### `mapKeys(object, iteratee)` - -Transforms each key in an object using the `iteratee` function to create a new object. Values remain unchanged while only keys are modified. Useful for transforming or normalizing object keys. - -```typescript -import { mapKeys } from 'es-toolkit/compat'; - -// Add prefix to keys -const obj = { a: 1, b: 2, c: 3 }; -const result = mapKeys(obj, (value, key) => 'prefix_' + key); -// Result: { prefix_a: 1, prefix_b: 2, prefix_c: 3 } - -// Convert keys to uppercase -const data = { name: 'John', age: 30 }; -const uppercased = mapKeys(data, (value, key) => key.toUpperCase()); -// Result: { NAME: 'John', AGE: 30 } - -// Convert array indices to keys -const arr = ['apple', 'banana', 'orange']; -const indexed = mapKeys(arr, (value, index) => `item_${index}`); -// Result: { item_0: 'apple', item_1: 'banana', item_2: 'orange' } - -// Create new keys by combining key and value -const scores = { math: 90, science: 85, english: 92 }; -const detailed = mapKeys(scores, (value, key) => `${key}_score_${value}`); -// Result: { math_score_90: 90, science_score_85: 85, english_score_92: 92 } -``` - -`null` or `undefined` are treated as empty objects. - -```typescript -import { mapKeys } from 'es-toolkit/compat'; - -mapKeys(null, iteratee); // {} -mapKeys(undefined, iteratee); // {} -``` - -#### Parameters - -- `object` (`ArrayLike | T | null | undefined`): The object or array to transform keys from. -- `iteratee` (`ListIteratee | ObjectIteratee`, optional): The function to transform each key. Defaults to the `identity` function. - -#### Returns - -(`Record | Record`): Returns a new object with transformed keys. diff --git a/docs/reference/compat/object/mapValues.md b/docs/reference/compat/object/mapValues.md deleted file mode 100644 index 04dc0a287..000000000 --- a/docs/reference/compat/object/mapValues.md +++ /dev/null @@ -1,71 +0,0 @@ -# mapValues (Lodash compatibility) - -::: warning Use `mapValues` from `es-toolkit` - -This `mapValues` function is relatively slow due to handling `null` or `undefined` and the `iteratee` conversion process. - -Use the faster and more modern [`mapValues`](../../object/mapValues.md) from `es-toolkit` instead. - -::: - -Creates a new object by transforming values while keeping keys the same. - -```typescript -const result = mapValues(obj, iteratee); -``` - -## Usage - -### `mapValues(object, iteratee)` - -Transforms each value in an object using the `iteratee` function to create a new object. Keys remain unchanged while only values are modified. Can handle strings, arrays, and objects. Useful for transforming or calculating data. - -```typescript -import { mapValues } from 'es-toolkit/compat'; - -// Transform object values -const obj = { a: 1, b: 2, c: 3 }; -const doubled = mapValues(obj, value => value * 2); -// Result: { a: 2, b: 4, c: 6 } - -// Convert strings to uppercase -const names = { first: 'john', last: 'doe' }; -const uppercased = mapValues(names, value => value.toUpperCase()); -// Result: { first: 'JOHN', last: 'DOE' } - -// Transform each character in a string -const str = 'abc'; -const charMap = mapValues(str, char => char.toUpperCase()); -// Result: { '0': 'A', '1': 'B', '2': 'C' } - -// Convert array to object -const arr = [10, 20, 30]; -const arrMap = mapValues(arr, (value, index) => value + index); -// Result: { '0': 10, '1': 21, '2': 32 } - -// Extract values using property path -const users = { - user1: { profile: { name: 'Alice' } }, - user2: { profile: { name: 'Bob' } }, -}; -const userNames = mapValues(users, 'profile.name'); -// Result: { user1: 'Alice', user2: 'Bob' } -``` - -`null` or `undefined` are treated as empty objects. - -```typescript -import { mapValues } from 'es-toolkit/compat'; - -mapValues(null, iteratee); // {} -mapValues(undefined, iteratee); // {} -``` - -#### Parameters - -- `object` (`string | T[] | T | null | undefined`): The object, array, or string to transform values from. -- `iteratee` (`ValueIteratee`, optional): The function, property path, or matching object to transform each value. Defaults to the `identity` function. - -#### Returns - -(`Record | { [P in keyof T]: U } | Record | Record | Partial`): Returns a new object with transformed values. diff --git a/docs/reference/compat/object/merge.md b/docs/reference/compat/object/merge.md deleted file mode 100644 index 3eec38aad..000000000 --- a/docs/reference/compat/object/merge.md +++ /dev/null @@ -1,82 +0,0 @@ -# merge (Lodash compatibility) - -::: warning Use `merge` from `es-toolkit` - -This `merge` function is relatively slow as it internally calls the complex `mergeWith` function. - -Use the faster and more modern [`merge`](../../object/merge.md) from `es-toolkit` instead. - -::: - -Deeply merges multiple objects into a single object. - -```typescript -const result = merge(target, ...sources); -``` - -## Usage - -### `merge(object, ...sources)` - -Deeply merges one or more source objects into the target object. Nested objects and arrays are recursively merged. If a source object property is `undefined`, it won't overwrite the existing value in the target object. Useful for merging object configurations or applying defaults. - -```typescript -import { merge } from 'es-toolkit/compat'; - -// Basic object merge -const target = { a: 1, b: { x: 1, y: 2 } }; -const source = { b: { y: 3, z: 4 }, c: 5 }; -const result = merge(target, source); -// Result: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } - -// Array merge -const obj1 = { arr: [1, 2] }; -const obj2 = { arr: [3, 4] }; -const merged = merge(obj1, obj2); -// Result: { arr: [3, 4] } (arrays are replaced) - -// Multiple object merge -const base = { a: 1 }; -const ext1 = { b: 2 }; -const ext2 = { c: 3 }; -const ext3 = { d: 4 }; -const combined = merge(base, ext1, ext2, ext3); -// Result: { a: 1, b: 2, c: 3, d: 4 } - -// Nested object merge -const config = { - api: { url: 'https://api.example.com', timeout: 5000 }, - features: { auth: true }, -}; -const overrides = { - api: { timeout: 10000, retries: 3 }, - features: { analytics: true }, -}; -const finalConfig = merge(config, overrides); -// Result: { -// api: { url: 'https://api.example.com', timeout: 10000, retries: 3 }, -// features: { auth: true, analytics: true } -// } -``` - -The target object is modified, so use an empty object to preserve the original. - -```typescript -import { merge } from 'es-toolkit/compat'; - -const original = { a: 1, b: { x: 1 } }; -const source = { b: { y: 2 } }; - -// Preserve original -const result = merge({}, original, source); -// original is not modified -``` - -#### Parameters - -- `object` (`any`): The target object to merge into. This object is modified. -- `...sources` (`any[]`): The source objects to merge from. - -#### Returns - -(`any`): Returns the merged target object. diff --git a/docs/reference/compat/object/mergeWith.md b/docs/reference/compat/object/mergeWith.md deleted file mode 100644 index 99979f02e..000000000 --- a/docs/reference/compat/object/mergeWith.md +++ /dev/null @@ -1,94 +0,0 @@ -# mergeWith (Lodash compatibility) - -::: warning Use `mergeWith` from `es-toolkit` - -This `mergeWith` function is relatively slow due to complex type checking, circular reference handling, and special object processing. - -Use the faster and more modern [`mergeWith`](../../object/mergeWith.md) from `es-toolkit` instead. - -::: - -Deeply merges multiple objects while controlling the merge behavior with a custom function. - -```typescript -const result = mergeWith(target, ...sources, customizer); -``` - -## Usage - -### `mergeWith(object, ...sources, customizer)` - -Deeply merges one or more source objects into the target object, controlling the merge behavior with a customizer function. If the customizer function returns `undefined`, the default merge logic is used. Useful for concatenating arrays or applying special merge rules. - -```typescript -import { mergeWith } from 'es-toolkit/compat'; - -// Add numbers -const obj1 = { a: 1, b: 2 }; -const obj2 = { b: 3, c: 4 }; -const result = mergeWith(obj1, obj2, (objValue, srcValue) => { - if (typeof objValue === 'number' && typeof srcValue === 'number') { - return objValue + srcValue; - } -}); -// Result: { a: 1, b: 5, c: 4 } - -// Concatenate arrays -const arr1 = { items: [1, 2] }; -const arr2 = { items: [3, 4] }; -const merged = mergeWith(arr1, arr2, (objValue, srcValue) => { - if (Array.isArray(objValue)) { - return objValue.concat(srcValue); - } -}); -// Result: { items: [1, 2, 3, 4] } - -// Concatenate strings -const str1 = { message: 'Hello' }; -const str2 = { message: 'World' }; -const combined = mergeWith(str1, str2, (objValue, srcValue, key) => { - if (key === 'message' && typeof objValue === 'string') { - return objValue + ' ' + srcValue; - } -}); -// Result: { message: 'Hello World' } - -// Multiple source objects with customizer -const base = { scores: [80] }; -const quiz1 = { scores: [90] }; -const quiz2 = { scores: [85] }; -const final = mergeWith(base, quiz1, quiz2, (objValue, srcValue) => { - if (Array.isArray(objValue)) { - return objValue.concat(srcValue); - } -}); -// Result: { scores: [80, 90, 85] } -``` - -The customizer function receives various parameters. - -```typescript -import { mergeWith } from 'es-toolkit/compat'; - -const customizer = (objValue, srcValue, key, object, source, stack) => { - console.log('Merging:', key, objValue, '->', srcValue); - - // Customize only for specific keys - if (key === 'specialField') { - return `${objValue}_${srcValue}`; - } - - // Return undefined to use default merge logic - return undefined; -}; -``` - -#### Parameters - -- `object` (`any`): The target object to merge into. This object is modified. -- `...sources` (`any[]`): The source objects to merge from. -- `customizer` (`MergeWithCustomizer`): The function to customize value assignment. Format: `(objValue, srcValue, key, object, source, stack) => any`. - -#### Returns - -(`any`): Returns the merged target object. diff --git a/docs/reference/compat/object/omit.md b/docs/reference/compat/object/omit.md deleted file mode 100644 index 77e1c5780..000000000 --- a/docs/reference/compat/object/omit.md +++ /dev/null @@ -1,82 +0,0 @@ -# omit (Lodash compatibility) - -::: warning Use `omit` from `es-toolkit` - -This `omit` function is relatively slow due to deep copying and calling the `unset` function. - -Use the faster and more modern [`omit`](../../object/omit.md) from `es-toolkit` instead. - -::: - -Creates a new object excluding specified keys from an object. - -```typescript -const result = omit(obj, ...keys); -``` - -## Usage - -### `omit(object, ...paths)` - -Creates a new object excluding specified keys from an object. Supports deep key paths and can specify multiple keys at once using arrays. Useful for removing sensitive information from objects or selecting only needed properties. - -```typescript -import { omit } from 'es-toolkit/compat'; - -// Remove basic keys -const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }; -const publicUser = omit(user, 'password', 'email'); -// Result: { id: 1, name: 'John' } - -// Remove multiple keys with array -const data = { a: 1, b: 2, c: 3, d: 4 }; -const filtered = omit(data, ['a', 'c']); -// Result: { b: 2, d: 4 } - -// Remove deep key paths -const nested = { - user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, - admin: true, -}; -const result = omit(nested, 'user.profile.age', 'admin'); -// Result: { user: { profile: { name: 'John' }, settings: { theme: 'dark' } } } - -// Combine nested arrays and keys -const complex = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; -const simplified = omit(complex, 'a', ['b', 'c'], 'd.f'); -// Result: { d: { e: 4 } } -``` - -You can freely combine arrays, strings, and key paths. - -```typescript -import { omit } from 'es-toolkit/compat'; - -const config = { - api: { url: 'https://api.example.com', key: 'secret', timeout: 5000 }, - ui: { theme: 'dark', language: 'en' }, - debug: true, -}; - -// Specify keys in multiple ways -const cleaned = omit(config, 'api.key', ['debug'], 'ui.language'); -// Result: { api: { url: 'https://api.example.com', timeout: 5000 }, ui: { theme: 'dark' } } -``` - -`null` or `undefined` are treated as empty objects. - -```typescript -import { omit } from 'es-toolkit/compat'; - -omit(null, 'key'); // {} -omit(undefined, 'key'); // {} -``` - -#### Parameters - -- `object` (`T | null | undefined`): The source object to remove keys from. -- `...paths` (`Array>`): The keys to remove. Can specify single keys, arrays of keys, or deep key paths. - -#### Returns - -(`Partial`): Returns a new object with specified keys removed. diff --git a/docs/reference/compat/object/omitBy.md b/docs/reference/compat/object/omitBy.md deleted file mode 100644 index 4a4b59135..000000000 --- a/docs/reference/compat/object/omitBy.md +++ /dev/null @@ -1,76 +0,0 @@ -# omitBy (Lodash compatibility) - -::: warning Use `omitBy` from `es-toolkit` - -This `omitBy` function is relatively slow due to array-like object checking, `iteratee` conversion, and key transformation processes. - -Use the faster and more modern [`omitBy`](../../object/omitBy.md) from `es-toolkit` instead. - -::: - -Creates a new object excluding properties for which the predicate function returns true. - -```typescript -const result = omitBy(obj, predicate); -``` - -## Usage - -### `omitBy(object, predicate)` - -Executes a predicate function for each property of the object and creates a new object excluding properties for which the predicate returns true. Useful for dynamically filtering properties based on conditions. - -```typescript -import { omitBy } from 'es-toolkit/compat'; - -// Remove values of specific type -const data = { a: 1, b: 'remove', c: 3, d: 'keep' }; -const numbers = omitBy(data, value => typeof value === 'string'); -// Result: { a: 1, c: 3 } - -// Remove properties based on condition -const user = { id: 1, name: 'John', age: 0, active: false, email: '' }; -const validData = omitBy(user, value => !value); -// Result: { id: 1, name: 'John' } (removes falsy values) - -// Filter by key name -const settings = { userSetting: true, adminSetting: false, debugMode: true }; -const userOnly = omitBy(settings, (value, key) => key.startsWith('admin')); -// Result: { userSetting: true, debugMode: true } - -// Remove only number properties -const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; -const noNumbers = omitBy(mixed, value => typeof value === 'number'); -// Result: { str: 'hello', bool: true, obj: {} } - -// Can also be used with arrays -const arr = [1, 2, 3, 4, 5]; -const filtered = omitBy(arr, value => value % 2 === 0); -// Result: { '0': 1, '2': 3, '4': 5 } (odd values at even indices) - -// Utilize value, key, and original object -const scores = { math: 90, science: 75, english: 85, art: 60 }; -const passingGrades = omitBy(scores, (value, key, obj) => { - console.log(`${key}: ${value} (average: ${Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length})`); - return value < 80; -}); -// Result: { math: 90, english: 85 } -``` - -`null` or `undefined` are treated as empty objects. - -```typescript -import { omitBy } from 'es-toolkit/compat'; - -omitBy(null, () => true); // {} -omitBy(undefined, () => true); // {} -``` - -#### Parameters - -- `object` (`Record | Record | object | null | undefined`): The source object to filter. -- `predicate` (`ValueKeyIteratee | ValueKeyIteratee`, optional): The predicate function to execute for each property. Properties for which this returns true are removed. Defaults to the `identity` function. - -#### Returns - -(`Record | Record | Partial`): Returns a new object consisting of properties that don't match the condition. diff --git a/docs/reference/compat/object/pick.md b/docs/reference/compat/object/pick.md deleted file mode 100644 index d2ab473f6..000000000 --- a/docs/reference/compat/object/pick.md +++ /dev/null @@ -1,73 +0,0 @@ -# pick (Lodash compatibility) - -::: warning Use `pick` from `es-toolkit` - -This `pick` function is relatively slow due to complex path processing, calling `get`/`set` functions, and handling `null`/`undefined`. - -Use the faster and more modern [`pick`](../../object/pick.md) from `es-toolkit` instead. - -::: - -Creates a new object by selecting only specified properties from an object. - -```typescript -const result = pick(obj, ...keys); -``` - -## Usage - -### `pick(object, ...props)` - -Use `pick` when you want to create a new object containing only the desired properties from an object. You can pass multiple keys at once using an array, or pass them one by one as individual arguments. Supports deep key paths so you can also select nested properties. - -```typescript -import { pick } from 'es-toolkit/compat'; - -// Basic usage -const obj = { a: 1, b: 2, c: 3, d: 4 }; -const result = pick(obj, ['a', 'c']); -// Result: { a: 1, c: 3 } - -// Pass as individual arguments -const result2 = pick(obj, 'a', 'c'); -// Result: { a: 1, c: 3 } - -// Select deep paths -const nested = { - user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, - admin: true, -}; -const userInfo = pick(nested, 'user.profile.name', 'admin'); -// Result: { user: { profile: { name: 'John' } }, admin: true } - -// Mix arrays and individual keys -const mixed = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; -const selected = pick(mixed, ['a', 'b'], 'c', 'd.e'); -// Result: { a: 1, b: 2, c: 3, d: { e: 4 } } - -// Distinguish between dot notation keys and actual dotted keys -const ambiguous = { - 'a.b': 1, // Actual key 'a.b' - a: { b: 2, c: 3 }, // Nested object -}; -const dotKey = pick(ambiguous, 'a.b'); -// Result: { 'a.b': 1 } (actual key takes priority) -``` - -`null` or `undefined` are treated as empty objects. - -```typescript -import { pick } from 'es-toolkit/compat'; - -pick(null, ['a', 'b']); // {} -pick(undefined, ['a', 'b']); // {} -``` - -#### Parameters - -- `object` (`T | null | undefined`): The object to select properties from. -- `...props` (`Array>`): The property keys to select. Can specify single keys, arrays of keys, or deep key paths. - -#### Returns - -(`Pick | Partial`): Returns a new object containing only the specified properties. diff --git a/docs/reference/compat/object/pickBy.md b/docs/reference/compat/object/pickBy.md deleted file mode 100644 index 36620fcaf..000000000 --- a/docs/reference/compat/object/pickBy.md +++ /dev/null @@ -1,86 +0,0 @@ -# pickBy (Lodash compatibility) - -::: warning Use `pickBy` from `es-toolkit` - -This `pickBy` function is relatively slow due to array-like object checking, `iteratee` conversion, and key transformation processes. - -Use the faster and more modern [`pickBy`](../../object/pickBy.md) from `es-toolkit` instead. - -::: - -Creates a new object selecting only properties for which the predicate function returns true. - -```typescript -const result = pickBy(obj, predicate); -``` - -## Usage - -### `pickBy(object, predicate)` - -Executes a predicate function for each property of the object and creates a new object containing only properties for which the predicate returns true. Useful for dynamically selecting properties based on conditions. - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -// Select only values of specific type -const data = { a: 1, b: 'keep', c: 3, d: 'select' }; -const strings = pickBy(data, value => typeof value === 'string'); -// Result: { b: 'keep', d: 'select' } - -// Select properties based on condition -const user = { id: 1, name: 'John', age: 0, active: true, email: '' }; -const validData = pickBy(user, value => Boolean(value)); -// Result: { id: 1, name: 'John', active: true } (only truthy values) - -// Filter by key name -const settings = { userSetting: true, adminSetting: false, debugMode: true }; -const userOnly = pickBy(settings, (value, key) => key.startsWith('user')); -// Result: { userSetting: true } - -// Select only number properties -const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; -const numbersOnly = pickBy(mixed, value => typeof value === 'number'); -// Result: { num1: 42, num2: 0 } - -// Can also be used with arrays -const arr = [1, 2, 3, 4, 5]; -const evens = pickBy(arr, value => value % 2 === 0); -// Result: { '1': 2, '3': 4 } (indices and values of even numbers) - -// Utilize value, key, and original object -const scores = { math: 90, science: 75, english: 85, art: 60 }; -const highScores = pickBy(scores, (value, key, obj) => { - const average = Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length; - return value > average; -}); -// Result: { math: 90, english: 85 } -``` - -When called without a predicate function, it selects only truthy values. - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -const data = { a: 1, b: '', c: 0, d: 'hello', e: null, f: true }; -const truthyValues = pickBy(data); -// Result: { a: 1, d: 'hello', f: true } -``` - -`null` or `undefined` are treated as empty objects. - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -pickBy(null, () => true); // {} -pickBy(undefined, () => true); // {} -``` - -#### Parameters - -- `object` (`Record | Record | object | null | undefined`): The source object to filter. -- `predicate` (`ValueKeyIterateeTypeGuard | ValueKeyIteratee | ValueKeyIteratee`, optional): The predicate function to execute for each property. Properties for which this returns true are selected. Defaults to the `identity` function. - -#### Returns - -(`Record | Record | Partial`): Returns a new object consisting of properties that match the condition. diff --git a/docs/reference/compat/predicate/isArrayBuffer.md b/docs/reference/compat/predicate/isArrayBuffer.md deleted file mode 100644 index ad0d99c1e..000000000 --- a/docs/reference/compat/predicate/isArrayBuffer.md +++ /dev/null @@ -1,46 +0,0 @@ -# isArrayBuffer (Lodash Compatibility) - -::: warning Use es-toolkit's [isArrayBuffer](../../predicate/isArrayBuffer.md) - -This `isArrayBuffer` function operates slowly due to complex handling for Lodash compatibility. - -Instead, use the faster and modern [isArrayBuffer](../../predicate/isArrayBuffer.md) from `es-toolkit`. - -::: - -Checks if a value is an ArrayBuffer. - -```typescript -const result = isArrayBuffer(value); -``` - -## Usage - -### `isArrayBuffer(value)` - -Use `isArrayBuffer` when you want to type-safely check if a value is an ArrayBuffer. It also works as a type guard in TypeScript. - -```typescript -import { isArrayBuffer } from 'es-toolkit/compat'; - -// ArrayBuffer check -const buffer = new ArrayBuffer(16); -isArrayBuffer(buffer); // true - -// Other types return false -isArrayBuffer(new Array()); // false -isArrayBuffer(new Map()); // false -isArrayBuffer({}); // false -isArrayBuffer('hello'); // false -isArrayBuffer(123); // false -isArrayBuffer(null); // false -isArrayBuffer(undefined); // false -``` - -#### Parameters - -- `value` (`unknown`): The value to check if it's an ArrayBuffer. - -#### Returns - -(`value is ArrayBuffer`): Returns `true` if the value is an ArrayBuffer, otherwise `false`. diff --git a/docs/reference/compat/predicate/isBuffer.md b/docs/reference/compat/predicate/isBuffer.md deleted file mode 100644 index d0acfec2a..000000000 --- a/docs/reference/compat/predicate/isBuffer.md +++ /dev/null @@ -1,43 +0,0 @@ -# isBuffer (Lodash Compatibility) - -::: warning Use es-toolkit's [isBuffer](../../predicate/isBuffer.md) instead -This `isBuffer` function operates slowly due to complex processing for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isBuffer](../../predicate/isBuffer.md) instead. -::: - -Checks if a value is a Buffer instance. - -```typescript -const result = isBuffer(value); -``` - -## Usage - -### `isBuffer(value)` - -Use `isBuffer` when you want to type-safely check if a value is a Buffer instance. It's useful when working with Buffer objects in Node.js environments. It also works as a type guard in TypeScript. - -```typescript -import { isBuffer } from 'es-toolkit/compat'; - -// Check Buffer instance -const buffer = Buffer.from('hello'); -isBuffer(buffer); // true - -// Other types return false -isBuffer('hello'); // false -isBuffer([1, 2, 3]); // false -isBuffer(new Uint8Array([1, 2, 3])); // false -isBuffer({}); // false -isBuffer(null); // false -isBuffer(undefined); // false -``` - -#### Parameters - -- `value` (`unknown`): The value to check if it's a Buffer instance. - -#### Returns - -(`boolean`): Returns `true` if the value is a Buffer instance, `false` otherwise. diff --git a/docs/reference/compat/predicate/isDate.md b/docs/reference/compat/predicate/isDate.md deleted file mode 100644 index a4712f04a..000000000 --- a/docs/reference/compat/predicate/isDate.md +++ /dev/null @@ -1,46 +0,0 @@ -# isDate (Lodash Compatibility) - -::: warning Use es-toolkit's [isDate](../../predicate/isDate.md) instead -This `isDate` function operates slowly due to complex processing for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isDate](../../predicate/isDate.md) instead. -::: - -Checks if a value is a Date object. - -```typescript -const result = isDate(value); -``` - -## Usage - -### `isDate(value)` - -Use `isDate` when you want to type-safely check if a value is a Date object. It also works as a type guard in TypeScript. - -```typescript -import { isDate } from 'es-toolkit/compat'; - -// Check Date object -const date = new Date(); -isDate(date); // true - -// Invalid Date is also recognized as a Date object -const invalidDate = new Date('invalid'); -isDate(invalidDate); // true - -// Other types return false -isDate('2024-01-01'); // false -isDate(1640995200000); // false -isDate({}); // false -isDate(null); // false -isDate(undefined); // false -``` - -#### Parameters - -- `value` (`unknown`): The value to check if it's a Date object. - -#### Returns - -(`value is Date`): Returns `true` if the value is a Date object, `false` otherwise. diff --git a/docs/reference/compat/predicate/isEqual.md b/docs/reference/compat/predicate/isEqual.md deleted file mode 100644 index 3d1d630ae..000000000 --- a/docs/reference/compat/predicate/isEqual.md +++ /dev/null @@ -1,84 +0,0 @@ -# isEqual (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isEqual](../../predicate/isEqual.md) - -This `isEqual` function operates slowly due to complex handling for Lodash compatibility. - -Instead, use the faster and modern [isEqual](../../predicate/isEqual.md) from `es-toolkit`. - -::: - -Performs a deep comparison between two values to determine if they are equal. - -```typescript -const result = isEqual(value1, value2); -``` - -## Usage - -### `isEqual(a, b)` - -Use `isEqual` when you want to perform a deep comparison between two values. It compares complex types like Date, RegExp, objects, and arrays by their content. - -```typescript -import { isEqual } from 'es-toolkit/compat'; - -// Basic type comparison -isEqual(1, 1); // true -isEqual('hello', 'hello'); // true -isEqual(true, true); // true - -// Object deep comparison -isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true -isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true -isEqual({ a: 1 }, { a: 1, b: undefined }); // false - -// Array deep comparison -isEqual([1, 2, 3], [1, 2, 3]); // true -isEqual([1, [2, 3]], [1, [2, 3]]); // true - -// Date object comparison -isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true -isEqual(new Date('2020-01-01'), new Date('2020-01-02')); // false - -// RegExp object comparison -isEqual(/abc/g, /abc/g); // true -isEqual(/abc/g, /abc/i); // false -``` - -It also recursively compares nested objects and arrays. - -```typescript -import { isEqual } from 'es-toolkit/compat'; - -const obj1 = { - user: { - name: 'John', - details: { - age: 30, - hobbies: ['reading', 'gaming'], - }, - }, -}; - -const obj2 = { - user: { - name: 'John', - details: { - age: 30, - hobbies: ['reading', 'gaming'], - }, - }, -}; - -isEqual(obj1, obj2); // true -``` - -#### Parameters - -- `a` (`unknown`): The first value to compare. -- `b` (`unknown`): The second value to compare. - -#### Returns - -(`boolean`): Returns `true` if the values are equal, otherwise `false`. diff --git a/docs/reference/compat/predicate/isEqualWith.md b/docs/reference/compat/predicate/isEqualWith.md deleted file mode 100644 index d1c518c6e..000000000 --- a/docs/reference/compat/predicate/isEqualWith.md +++ /dev/null @@ -1,92 +0,0 @@ -# isEqualWith (Lodash Compatibility) - -::: warning Use es-toolkit's [isEqualWith](../../predicate/isEqualWith.md) instead -This `isEqualWith` function operates slowly due to complex processing for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isEqualWith](../../predicate/isEqualWith.md) instead. -::: - -Checks if two values are equal using a custom comparison function. - -```typescript -const result = isEqualWith(a, b, customizer); -``` - -## Usage - -### `isEqualWith(a, b, areValuesEqual?)` - -Deeply compares two values using a custom comparison function. If the custom function returns a boolean value, that result is used. If it returns `undefined`, the default equality comparison is used. - -The custom comparison function is also used when comparing values inside complex structures like objects, arrays, Map, Set, etc., ensuring deep comparison. - -```typescript -import { isEqualWith } from 'es-toolkit/compat'; - -// Case-insensitive string comparison -const customizer = (a: any, b: any) => { - if (typeof a === 'string' && typeof b === 'string') { - return a.toLowerCase() === b.toLowerCase(); - } -}; - -isEqualWith('Hello', 'hello', customizer); // true -isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true - -// Compare numbers by absolute value -const absCustomizer = (a: any, b: any) => { - if (typeof a === 'number' && typeof b === 'number') { - return Math.abs(a) === Math.abs(b); - } -}; - -isEqualWith([-1, 2], [1, -2], absCustomizer); // true - -// Complex object comparison -const obj1 = { - name: 'JOHN', - details: { age: 30, city: 'NYC' }, -}; -const obj2 = { - name: 'john', - details: { age: 30, city: 'nyc' }, -}; - -isEqualWith(obj1, obj2, customizer); // true -``` - -Special handling for Map and Set: - -```typescript -import { isEqualWith } from 'es-toolkit/compat'; - -const customizer = (a: any, b: any) => { - if (typeof a === 'string' && typeof b === 'string') { - return a.toLowerCase() === b.toLowerCase(); - } -}; - -const map1 = new Map([['KEY', 'value']]); -const map2 = new Map([['key', 'value']]); -isEqualWith(map1, map2, customizer); // true - -const set1 = new Set(['HELLO']); -const set2 = new Set(['hello']); -isEqualWith(set1, set2, customizer); // true -``` - -#### Parameters - -- `a` (`any`): The first value to compare. -- `b` (`any`): The second value to compare. -- `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): The custom comparison function. - - `x`: Value from the first object `a` - - `y`: Value from the second object `b` - - `property`: The property key used to get `x` and `y` - - `xParent`: The parent object of the first value `x` - - `yParent`: The parent object of the second value `y` - - `stack`: Internal stack (Map) for handling circular references - -#### Returns - -(`boolean`): Returns `true` if the values are equal according to the custom function, `false` otherwise. diff --git a/docs/reference/compat/predicate/isError.md b/docs/reference/compat/predicate/isError.md deleted file mode 100644 index 9ea476f81..000000000 --- a/docs/reference/compat/predicate/isError.md +++ /dev/null @@ -1,47 +0,0 @@ -# isError (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isError](../../predicate/isError.md) instead -This `isError` function operates slowly due to complex handling for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isError](../../predicate/isError.md) instead. -::: - -Checks if a value is an Error object. - -```typescript -const result = isError(value); -``` - -## Usage - -### `isError(value)` - -Use `isError` when you want to type-safely check if a value is an Error object. It also works as a type guard in TypeScript. - -```typescript -import { isError } from 'es-toolkit/compat'; - -// Error object checking -isError(new Error()); // true -isError(new TypeError('Type error')); // true -isError(new ReferenceError('Reference error')); // true - -// Custom errors that inherit from Error -class CustomError extends Error {} -isError(new CustomError()); // true - -// Other types return false -isError('Error'); // false -isError({ name: 'Error', message: 'Something went wrong' }); // false -isError({}); // false -isError(null); // false -isError(undefined); // false -``` - -#### Parameters - -- `value` (`unknown`): The value to check if it's an Error object. - -#### Returns - -(`value is Error`): Returns `true` if the value is an Error object, `false` otherwise. diff --git a/docs/reference/compat/predicate/isFunction.md b/docs/reference/compat/predicate/isFunction.md deleted file mode 100644 index 47680ef14..000000000 --- a/docs/reference/compat/predicate/isFunction.md +++ /dev/null @@ -1,52 +0,0 @@ -# isFunction (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isFunction](../../predicate/isFunction.md) instead -This `isFunction` function operates slowly due to complex handling for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isFunction](../../predicate/isFunction.md) instead. -::: - -Checks if a value is a function. - -```typescript -const result = isFunction(value); -``` - -## Usage - -### `isFunction(value)` - -Use `isFunction` when you want to type-safely check if a value is a function. It also works as a type guard in TypeScript. - -```typescript -import { isFunction } from 'es-toolkit/compat'; - -// Regular functions -isFunction(function () {}); // true -isFunction(() => {}); // true - -// Built-in functions and constructors -isFunction(Array.prototype.slice); // true -isFunction(Proxy); // true -isFunction(Int8Array); // true - -// Async functions and generator functions -isFunction(async function () {}); // true -isFunction(function* () {}); // true - -// Other types return false -isFunction('function'); // false -isFunction({}); // false -isFunction([]); // false -isFunction(null); // false -isFunction(undefined); // false -isFunction(123); // false -``` - -#### Parameters - -- `value` (`unknown`): The value to check if it's a function. - -#### Returns - -(`value is (...args: any[]) => any`): Returns `true` if the value is a function, `false` otherwise. diff --git a/docs/reference/compat/predicate/isLength.md b/docs/reference/compat/predicate/isLength.md deleted file mode 100644 index f4e24a4cf..000000000 --- a/docs/reference/compat/predicate/isLength.md +++ /dev/null @@ -1,63 +0,0 @@ -# isLength (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isLength](../../predicate/isLength.md) instead -This `isLength` function operates slowly due to complex handling for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isLength](../../predicate/isLength.md) instead. -::: - -Checks if a value is a valid length. - -```typescript -const result = isLength(value); -``` - -## Usage - -### `isLength(value)` - -Use `isLength` when you want to check if a value is a valid length. A valid length is a number type, non-negative integer, and below JavaScript's maximum safe integer (`Number.MAX_SAFE_INTEGER`). It also works as a type guard in TypeScript. - -```typescript -import { isLength } from 'es-toolkit/compat'; - -// Valid lengths -isLength(0); // true -isLength(42); // true -isLength(100); // true -isLength(Number.MAX_SAFE_INTEGER); // true - -// Invalid lengths -isLength(-1); // false (negative) -isLength(1.5); // false (not an integer) -isLength(Number.MAX_SAFE_INTEGER + 1); // false (exceeds safe range) -isLength('3'); // false (string) -isLength(null); // false -isLength(undefined); // false -isLength({}); // false -isLength([]); // false -``` - -It's useful for validating the length property of arrays or strings. - -```typescript -import { isLength } from 'es-toolkit/compat'; - -function validateArrayLength(arr: any[]) { - if (isLength(arr.length)) { - console.log(`Array length ${arr.length} is valid`); - return true; - } - return false; -} - -validateArrayLength([1, 2, 3]); // "Array length 3 is valid" -``` - -#### Parameters - -- `value` (`any`): The value to check if it's a valid length. - -#### Returns - -(`boolean`): Returns `true` if the value is a valid length, `false` otherwise. diff --git a/docs/reference/compat/predicate/isMap.md b/docs/reference/compat/predicate/isMap.md deleted file mode 100644 index f309aa37e..000000000 --- a/docs/reference/compat/predicate/isMap.md +++ /dev/null @@ -1,63 +0,0 @@ -# isMap (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isMap](../../predicate/isMap.md) instead - -This `isMap` function operates slowly due to complex handling for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isMap](../../predicate/isMap.md) instead. - -::: - -Checks if a value is a Map. - -```typescript -const result = isMap(value); -``` - -## Usage - -### `isMap(value)` - -Use `isMap` when you want to type-safely check if a value is a Map. It also works as a type guard in TypeScript. - -```typescript -import { isMap } from 'es-toolkit/compat'; - -// Map checking -const map = new Map(); -isMap(map); // true - -// Other types return false -isMap(new Set()); // false -isMap(new WeakMap()); // false -isMap({}); // false -isMap([]); // false -isMap('map'); // false -isMap(123); // false -isMap(null); // false -isMap(undefined); // false -``` - -It also distinguishes from other similar collections. - -```typescript -import { isMap } from 'es-toolkit/compat'; - -// Map vs Set vs WeakMap -isMap(new Map([['key', 'value']])); // true -isMap(new Set(['value'])); // false -isMap(new WeakMap()); // false - -// Map vs regular objects -isMap({}); // false -isMap({ key: 'value' }); // false -isMap(Object.create(null)); // false -``` - -#### Parameters - -- `value` (`unknown`): The value to check if it's a Map. - -#### Returns - -(`value is Map`): Returns `true` if the value is a Map, `false` otherwise. diff --git a/docs/reference/compat/predicate/isNil.md b/docs/reference/compat/predicate/isNil.md deleted file mode 100644 index 2171b96de..000000000 --- a/docs/reference/compat/predicate/isNil.md +++ /dev/null @@ -1,62 +0,0 @@ -# isNil (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isNil](../../predicate/isNil.md) instead - -This `isNil` function operates slowly due to complex handling for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isNil](../../predicate/isNil.md) instead. - -::: - -Checks if a value is `null` or `undefined`. - -```typescript -const result = isNil(value); -``` - -## Usage - -### `isNil(x)` - -Use `isNil` when you want to type-safely check if a value is `null` or `undefined`. It also works as a type guard in TypeScript. - -```typescript -import { isNil } from 'es-toolkit/compat'; - -// null and undefined return true -isNil(null); // true -isNil(undefined); // true - -// All other values return false -isNil(0); // false -isNil(''); // false -isNil(false); // false -isNil([]); // false -isNil({}); // false -isNil('hello'); // false -isNil(42); // false -``` - -It distinguishes from values that are truthy but not `null` or `undefined`. - -```typescript -import { isNil } from 'es-toolkit/compat'; - -// Values that are falsy but not null/undefined -isNil(0); // false -isNil(''); // false -isNil(false); // false -isNil(NaN); // false - -// Only null and undefined return true -isNil(null); // true -isNil(undefined); // true -``` - -#### Parameters - -- `x` (`any`): The value to check if it's `null` or `undefined`. - -#### Returns - -(`x is null | undefined`): Returns `true` if the value is `null` or `undefined`, `false` otherwise. diff --git a/docs/reference/compat/predicate/isNull.md b/docs/reference/compat/predicate/isNull.md deleted file mode 100644 index cd4dd1de4..000000000 --- a/docs/reference/compat/predicate/isNull.md +++ /dev/null @@ -1,68 +0,0 @@ -# isNull (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isNull](../../predicate/isNull.md) instead - -This `isNull` function is a Lodash compatibility function, but has the same implementation as the main library. - -Use the faster and more modern `es-toolkit`'s [isNull](../../predicate/isNull.md) instead. - -::: - -Checks if a value is `null`. - -```typescript -const result = isNull(value); -``` - -## Usage - -### `isNull(value)` - -Use `isNull` when you want to type-safely check if a value is exactly `null`. It also works as a type guard in TypeScript. - -```typescript -import { isNull } from 'es-toolkit/compat'; - -// Only null returns true -isNull(null); // true - -// undefined also returns false -isNull(undefined); // false - -// All other values also return false -isNull(0); // false -isNull(''); // false -isNull(false); // false -isNull([]); // false -isNull({}); // false -isNull('null'); // false -isNull(NaN); // false -``` - -You can distinguish between `null` and `undefined`. - -```typescript -import { isNull } from 'es-toolkit/compat'; - -function handleValue(value: string | null | undefined) { - if (isNull(value)) { - console.log('Value is explicitly null'); - } else if (value === undefined) { - console.log('Value is undefined'); - } else { - console.log(`Value exists: ${value}`); - } -} - -handleValue(null); // "Value is explicitly null" -handleValue(undefined); // "Value is undefined" -handleValue('hello'); // "Value exists: hello" -``` - -#### Parameters - -- `value` (`any`): The value to check if it's `null`. - -#### Returns - -(`value is null`): Returns `true` if the value is `null`, `false` otherwise. diff --git a/docs/reference/compat/predicate/isPlainObject.md b/docs/reference/compat/predicate/isPlainObject.md deleted file mode 100644 index eda22d3f2..000000000 --- a/docs/reference/compat/predicate/isPlainObject.md +++ /dev/null @@ -1,85 +0,0 @@ -# isPlainObject (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isPlainObject](../../predicate/isPlainObject.md) instead - -This `isPlainObject` function operates slowly due to complex handling for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isPlainObject](../../predicate/isPlainObject.md) instead. - -::: - -Checks if a value is a plain object. - -```typescript -const result = isPlainObject(object); -``` - -## Usage - -### `isPlainObject(object)` - -Use `isPlainObject` when you want to check if a value is a plain object. A plain object is an object created by the `{}` literal, `new Object()`, or `Object.create(null)`. It also works as a type guard in TypeScript. - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -// Plain objects -isPlainObject({}); // true -isPlainObject(new Object()); // true -isPlainObject(Object.create(null)); // true -isPlainObject({ name: 'John', age: 30 }); // true - -// Not plain objects -isPlainObject([]); // false (array) -isPlainObject(new Date()); // false (Date instance) -isPlainObject(new Map()); // false (Map instance) -isPlainObject(new Set()); // false (Set instance) -isPlainObject(/regex/); // false (regular expression) -isPlainObject(function () {}); // false (function) -isPlainObject(null); // false -isPlainObject(undefined); // false -isPlainObject('object'); // false (string) -isPlainObject(42); // false (number) -``` - -It distinguishes between class instances and plain objects. - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -class Person { - name: string; - constructor(name: string) { - this.name = name; - } -} - -const person = new Person('John'); -const plainObj = { name: 'John' }; - -isPlainObject(person); // false (class instance) -isPlainObject(plainObj); // true (plain object) -``` - -It also correctly handles custom `Symbol.toStringTag` properties. - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -// Writable Symbol.toStringTag -const obj1 = {}; -obj1[Symbol.toStringTag] = 'CustomObject'; -isPlainObject(obj1); // true - -// Read-only Symbol.toStringTag (built-in objects) -const date = new Date(); -isPlainObject(date); // false -``` - -#### Parameters - -- `object` (`any`): The value to check if it's a plain object. - -#### Returns - -(`boolean`): Returns `true` if the value is a plain object, `false` otherwise. diff --git a/docs/reference/compat/predicate/isRegExp.md b/docs/reference/compat/predicate/isRegExp.md deleted file mode 100644 index 0e39d72a3..000000000 --- a/docs/reference/compat/predicate/isRegExp.md +++ /dev/null @@ -1,82 +0,0 @@ -# isRegExp (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isRegExp](../../predicate/isRegExp.md) instead - -This `isRegExp` function is a Lodash compatibility function, but is a simple type check. - -Use the faster and more modern `es-toolkit`'s [isRegExp](../../predicate/isRegExp.md) instead. - -::: - -Checks if a value is a regular expression. - -```typescript -const result = isRegExp(value); -``` - -## Usage - -### `isRegExp(value)` - -Use `isRegExp` when you want to type-safely check if a value is a regular expression. It also works as a type guard in TypeScript. - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// Regular expressions -isRegExp(/abc/); // true -isRegExp(new RegExp('abc')); // true -isRegExp(/[a-z]+/g); // true -isRegExp(/pattern/gi); // true - -// Other types return false -isRegExp('/abc/'); // false (string) -isRegExp('pattern'); // false (string) -isRegExp({}); // false (object) -isRegExp([]); // false (array) -isRegExp(null); // false -isRegExp(undefined); // false -isRegExp(123); // false (number) -``` - -It distinguishes between regex strings and actual regex objects. - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// Regular expression vs regex string -isRegExp(/test/); // true -isRegExp('/test/'); // false -isRegExp('\\d+'); // false -isRegExp('/\\d+/g'); // false - -// Various regex flags -isRegExp(/test/i); // true (case insensitive) -isRegExp(/test/g); // true (global search) -isRegExp(/test/m); // true (multiline) -isRegExp(/test/gim); // true (all flags combined) -``` - -It also recognizes dynamically created regular expressions. - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// Regex created with RegExp constructor -const dynamicRegex = new RegExp('\\d{3}-\\d{4}', 'g'); -isRegExp(dynamicRegex); // true - -// Regex created through strings -const pattern = 'hello'; -const flags = 'gi'; -const regex = new RegExp(pattern, flags); -isRegExp(regex); // true -``` - -#### Parameters - -- `value` (`any`): The value to check if it's a regular expression. - -#### Returns - -(`value is RegExp`): Returns `true` if the value is a regular expression, `false` otherwise. diff --git a/docs/reference/compat/predicate/isSet.md b/docs/reference/compat/predicate/isSet.md deleted file mode 100644 index fc09765c5..000000000 --- a/docs/reference/compat/predicate/isSet.md +++ /dev/null @@ -1,67 +0,0 @@ -# isSet (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isSet](../../predicate/isSet.md) instead - -This `isSet` function is a Lodash compatibility function, but has the same implementation as the main library. - -Use the faster and more modern `es-toolkit`'s [isSet](../../predicate/isSet.md) instead. - -::: - -Checks if a value is a Set. - -```typescript -const result = isSet(value); -``` - -## Usage - -### `isSet(value)` - -Use `isSet` when you want to type-safely check if a value is a Set. It also works as a type guard in TypeScript. - -```typescript -import { isSet } from 'es-toolkit/compat'; - -// Set checking -const set = new Set(); -isSet(set); // true - -// Other types return false -isSet(new Map()); // false -isSet(new WeakSet()); // false -isSet([]); // false -isSet({}); // false -isSet('set'); // false -isSet(123); // false -isSet(null); // false -isSet(undefined); // false -``` - -It also distinguishes from other similar collections. - -```typescript -import { isSet } from 'es-toolkit/compat'; - -// Set vs Map vs WeakSet -isSet(new Set([1, 2, 3])); // true -isSet(new Map([['key', 'value']])); // false -isSet(new WeakSet()); // false - -// Set vs array -isSet(new Set([1, 2, 3])); // true -isSet([1, 2, 3]); // false - -// Set vs regular objects -isSet(new Set()); // true -isSet({}); // false -isSet(Object.create(null)); // false -``` - -#### Parameters - -- `value` (`unknown`): The value to check if it's a Set. - -#### Returns - -(`value is Set`): Returns `true` if the value is a Set, `false` otherwise. diff --git a/docs/reference/compat/predicate/isUndefined.md b/docs/reference/compat/predicate/isUndefined.md deleted file mode 100644 index 7fbd36e05..000000000 --- a/docs/reference/compat/predicate/isUndefined.md +++ /dev/null @@ -1,92 +0,0 @@ -# isUndefined (Lodash Compatibility) - -::: warning Use `es-toolkit`'s [isUndefined](../../predicate/isUndefined.md) instead - -This `isUndefined` function operates slowly due to complex handling for Lodash compatibility. - -Use the faster and more modern `es-toolkit`'s [isUndefined](../../predicate/isUndefined.md) instead. - -::: - -Checks if a value is `undefined`. - -```typescript -const result = isUndefined(value); -``` - -## Usage - -### `isUndefined(x)` - -Use `isUndefined` when you want to type-safely check if a value is exactly `undefined`. It also works as a type guard in TypeScript. - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -// Only undefined returns true -isUndefined(undefined); // true - -// null also returns false -isUndefined(null); // false - -// All other values also return false -isUndefined(0); // false -isUndefined(''); // false -isUndefined(false); // false -isUndefined([]); // false -isUndefined({}); // false -isUndefined('undefined'); // false -isUndefined(NaN); // false -``` - -You can distinguish between `undefined` and `null`. - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -function handleValue(value: string | null | undefined) { - if (isUndefined(value)) { - console.log('Value is undefined'); - } else if (value === null) { - console.log('Value is explicitly null'); - } else { - console.log(`Value exists: ${value}`); - } -} - -handleValue(undefined); // "Value is undefined" -handleValue(null); // "Value is explicitly null" -handleValue('hello'); // "Value exists: hello" -``` - -It's useful for checking undeclared variables or uninitialized properties. - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -const obj: { name?: string; age?: number } = { name: 'John' }; - -if (isUndefined(obj.age)) { - console.log('Age is not set'); - obj.age = 25; // Set default value -} - -// Default value handling for function parameters -function greet(name: string, title?: string) { - if (isUndefined(title)) { - title = 'Mr./Ms.'; - } - console.log(`Hello, ${title} ${name}!`); -} - -greet('Kim'); // "Hello, Mr./Ms. Kim!" -greet('Kim', 'Dr.'); // "Hello, Dr. Kim!" -``` - -#### Parameters - -- `x` (`any`): The value to check if it's `undefined`. - -#### Returns - -(`x is undefined`): Returns `true` if the value is `undefined`, `false` otherwise. diff --git a/docs/reference/compat/string/camelCase.md b/docs/reference/compat/string/camelCase.md deleted file mode 100644 index c639bf92e..000000000 --- a/docs/reference/compat/string/camelCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# camelCase (Lodash compatibility) - -::: warning Use `camelCase` from `es-toolkit` - -This `camelCase` function operates slower due to handling non-string input values and removing contracted apostrophes. - -Instead, use the faster and more modern [camelCase](../../string/camelCase.md) from `es-toolkit`. - -::: - -Converts a string to camel case. - -```typescript -const result = camelCase(str); -``` - -## Usage - -### `camelCase(str)` - -Converts a string to camel case. Camel case is a naming convention where the first word starts with a lowercase letter and subsequent words begin with uppercase letters, all without spaces. - -```typescript -import { camelCase } from 'es-toolkit/compat'; - -camelCase('camelCase'); // 'camelCase' -camelCase('some whitespace'); // 'someWhitespace' -camelCase('hyphen-text'); // 'hyphenText' -camelCase('HTTPRequest'); // 'httpRequest' -``` - -Non-string values are also converted to strings before processing. - -```typescript -import { camelCase } from 'es-toolkit/compat'; - -camelCase(123); // '123' -camelCase(null); // '' -camelCase(undefined); // '' -``` - -#### Parameters - -- `str` (`string | object`, optional): The value to convert to camel case. - -#### Returns - -(`string`): Returns the string converted to camel case. diff --git a/docs/reference/compat/string/capitalize.md b/docs/reference/compat/string/capitalize.md deleted file mode 100644 index 6ac05f505..000000000 --- a/docs/reference/compat/string/capitalize.md +++ /dev/null @@ -1,48 +0,0 @@ -# capitalize (Lodash compatibility) - -::: warning Use `capitalize` from `es-toolkit` - -This `capitalize` function operates slower due to handling non-string input values. - -Instead, use the faster and more modern [capitalize](../../string/capitalize.md) from `es-toolkit`. - -::: - -Converts the first character of a string to uppercase and the remaining characters to lowercase. - -```typescript -const result = capitalize(str); -``` - -## Usage - -### `capitalize(str)` - -Converts the first character of a string to uppercase and the remaining characters to lowercase. This is useful for making the first impression of a word better or formatting it as a title. - -```typescript -import { capitalize } from 'es-toolkit/compat'; - -capitalize('fred'); // 'Fred' -capitalize('FRED'); // 'Fred' -capitalize('fRED'); // 'Fred' -``` - -Empty strings and non-string values can also be handled. - -```typescript -import { capitalize } from 'es-toolkit/compat'; - -capitalize(''); // '' -capitalize(123); // '123' -capitalize(null); // '' -capitalize(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to capitalize. - -#### Returns - -(`string`): Returns the string with the first character capitalized and the remaining characters in lowercase. diff --git a/docs/reference/compat/string/deburr.md b/docs/reference/compat/string/deburr.md deleted file mode 100644 index a6ee95fec..000000000 --- a/docs/reference/compat/string/deburr.md +++ /dev/null @@ -1,47 +0,0 @@ -# deburr (Lodash compatibility) - -::: warning Use `deburr` from `es-toolkit` - -This `deburr` function operates slower due to handling non-string input values. - -Instead, use the faster and more modern [deburr](../../string/deburr.md) from `es-toolkit`. - -::: - -Converts special characters and diacritical marks in a string to ASCII characters. - -```typescript -const result = deburr(str); -``` - -## Usage - -### `deburr(str)` - -Converts special characters and diacritical marks in a string to ASCII characters. This is useful for making multilingual text easier to search or sort. - -```typescript -import { deburr } from 'es-toolkit/compat'; - -deburr('Æthelred'); // 'Aethelred' -deburr('München'); // 'Munchen' -deburr('Crème brûlée'); // 'Creme brulee' -``` - -Non-string values are also converted to strings before processing. - -```typescript -import { deburr } from 'es-toolkit/compat'; - -deburr(123); // '123' -deburr(null); // '' -deburr(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to remove special characters from. - -#### Returns - -(`string`): Returns the string with special characters and diacritical marks converted to ASCII characters. diff --git a/docs/reference/compat/string/escape.md b/docs/reference/compat/string/escape.md deleted file mode 100644 index 722b55ca2..000000000 --- a/docs/reference/compat/string/escape.md +++ /dev/null @@ -1,48 +0,0 @@ -# escape (Lodash compatibility) - -::: warning Use `escape` from `es-toolkit` - -This `escape` function operates slower due to handling non-string input values. - -Instead, use the faster and more modern [escape](../../string/escape.md) from `es-toolkit`. - -::: - -Converts HTML special characters in a string to HTML entities. - -```typescript -const result = escape(str); -``` - -## Usage - -### `escape(str)` - -Converts the characters `&`, `<`, `>`, `"`, `'` in a string to their corresponding HTML entities. This is useful for preventing XSS attacks when inserting text into HTML documents. - -```typescript -import { escape } from 'es-toolkit/compat'; - -escape('This is a
element.'); // 'This is a <div> element.' -escape('This is a "quote"'); // 'This is a "quote"' -escape("This is a 'quote'"); // 'This is a 'quote'' -escape('This is a & symbol'); // 'This is a & symbol' -``` - -Non-string values are also converted to strings before processing. - -```typescript -import { escape } from 'es-toolkit/compat'; - -escape(123); // '123' -escape(null); // '' -escape(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to escape HTML special characters. - -#### Returns - -(`string`): Returns the string with HTML special characters converted to entities. diff --git a/docs/reference/compat/string/escapeRegExp.md b/docs/reference/compat/string/escapeRegExp.md deleted file mode 100644 index 1c5ad53e1..000000000 --- a/docs/reference/compat/string/escapeRegExp.md +++ /dev/null @@ -1,49 +0,0 @@ -# escapeRegExp (Lodash compatibility) - -::: warning Use `escapeRegExp` from `es-toolkit` - -This `escapeRegExp` function operates slower due to handling non-string input values. - -Instead, use the faster and more modern [escapeRegExp](../../string/escapeRegExp.md) from `es-toolkit`. - -::: - -Escapes regular expression special characters in a string. - -```typescript -const result = escapeRegExp(str); -``` - -## Usage - -### `escapeRegExp(str)` - -Escapes regular expression special characters `^`, `$`, `\`, `.`, `*`, `+`, `?`, `(`, `)`, `[`, `]`, `{`, `}`, `|` in a string. This is useful when you want to treat a string literally when dynamically creating regular expressions. - -```typescript -import { escapeRegExp } from 'es-toolkit/compat'; - -escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); -// '\\[es-toolkit\\]\\(https://es-toolkit\\.dev/\\)' - -escapeRegExp('$^{}.+*?()[]|\\'); -// '\\$\\^\\{\\}\\.\\+\\*\\?\\(\\)\\[\\]\\|\\\\' -``` - -Non-string values are also converted to strings before processing. - -```typescript -import { escapeRegExp } from 'es-toolkit/compat'; - -escapeRegExp(123); // '123' -escapeRegExp(null); // '' -escapeRegExp(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to escape regular expression special characters. - -#### Returns - -(`string`): Returns the string with regular expression special characters escaped. diff --git a/docs/reference/compat/string/kebabCase.md b/docs/reference/compat/string/kebabCase.md deleted file mode 100644 index fe3d501ea..000000000 --- a/docs/reference/compat/string/kebabCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# kebabCase (Lodash compatibility) - -::: warning Use `kebabCase` from `es-toolkit` - -This `kebabCase` function operates slower due to handling non-string input values and removing contracted apostrophes. - -Instead, use the faster and more modern [kebabCase](../../string/kebabCase.md) from `es-toolkit`. - -::: - -Converts a string to kebab case. - -```typescript -const result = kebabCase(str); -``` - -## Usage - -### `kebabCase(str)` - -Converts a string to kebab case. Kebab case is a naming convention where each word is written in lowercase and connected with a dash (-) character. It's commonly used in URLs and CSS class names. - -```typescript -import { kebabCase } from 'es-toolkit/compat'; - -kebabCase('camelCase'); // 'camel-case' -kebabCase('some whitespace'); // 'some-whitespace' -kebabCase('hyphen-text'); // 'hyphen-text' -kebabCase('HTTPRequest'); // 'http-request' -``` - -Non-string values are also converted to strings before processing. - -```typescript -import { kebabCase } from 'es-toolkit/compat'; - -kebabCase(123); // '123' -kebabCase(null); // '' -kebabCase(undefined); // '' -``` - -#### Parameters - -- `str` (`string | object`, optional): The value to convert to kebab case. - -#### Returns - -(`string`): Returns the string converted to kebab case. diff --git a/docs/reference/compat/string/lowerCase.md b/docs/reference/compat/string/lowerCase.md deleted file mode 100644 index 23145eb1f..000000000 --- a/docs/reference/compat/string/lowerCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# lowerCase (Lodash compatibility) - -::: warning Use `lowerCase` from `es-toolkit` - -This `lowerCase` function operates slower due to handling non-string input values and removing contracted apostrophes. - -Instead, use the faster and more modern [lowerCase](../../string/lowerCase.md) from `es-toolkit`. - -::: - -Converts a string to lowercase words separated by spaces. - -```typescript -const result = lowerCase(str); -``` - -## Usage - -### `lowerCase(str)` - -Converts a string to lowercase words separated by spaces. Each word is converted to lowercase and connected with space characters. This is useful for creating human-readable text. - -```typescript -import { lowerCase } from 'es-toolkit/compat'; - -lowerCase('camelCase'); // 'camel case' -lowerCase('some whitespace'); // 'some whitespace' -lowerCase('hyphen-text'); // 'hyphen text' -lowerCase('HTTPRequest'); // 'http request' -``` - -Non-string values are also converted to strings before processing. - -```typescript -import { lowerCase } from 'es-toolkit/compat'; - -lowerCase(123); // '123' -lowerCase(null); // '' -lowerCase(undefined); // '' -``` - -#### Parameters - -- `str` (`string | object`, optional): The value to convert to lowercase format. - -#### Returns - -(`string`): Returns the string with lowercase words separated by spaces. diff --git a/docs/reference/compat/string/lowerFirst.md b/docs/reference/compat/string/lowerFirst.md deleted file mode 100644 index fd01f9602..000000000 --- a/docs/reference/compat/string/lowerFirst.md +++ /dev/null @@ -1,48 +0,0 @@ -# lowerFirst (Lodash compatibility) - -::: warning Use `lowerFirst` from `es-toolkit` - -This `lowerFirst` function operates slower due to handling non-string input values. - -Instead, use the faster and more modern [lowerFirst](../../string/lowerFirst.md) from `es-toolkit`. - -::: - -Converts the first character of a string to lowercase. - -```typescript -const result = lowerFirst(str); -``` - -## Usage - -### `lowerFirst(str)` - -Converts the first character of a string to lowercase. The remaining characters are kept as is. This is useful for creating camelCase variable names or when you only want to lowercase the first character. - -```typescript -import { lowerFirst } from 'es-toolkit/compat'; - -lowerFirst('fred'); // 'fred' -lowerFirst('Fred'); // 'fred' -lowerFirst('FRED'); // 'fRED' -lowerFirst(''); // '' -``` - -Non-string values are also converted to strings before processing. - -```typescript -import { lowerFirst } from 'es-toolkit/compat'; - -lowerFirst(123); // '123' -lowerFirst(null); // '' -lowerFirst(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to convert the first character to lowercase. - -#### Returns - -(`string`): Returns the string with the first character converted to lowercase. diff --git a/docs/reference/compat/string/pad.md b/docs/reference/compat/string/pad.md deleted file mode 100644 index e439da528..000000000 --- a/docs/reference/compat/string/pad.md +++ /dev/null @@ -1,60 +0,0 @@ -# pad (Lodash compatibility) - -::: warning Use `pad` from `es-toolkit` - -This `pad` function operates slower due to handling `null` or `undefined`. - -Instead, use the faster and more modern [pad](../../string/pad.md) from `es-toolkit`. - -::: - -Pads a string on both sides with padding characters to reach the specified length. - -```typescript -const padded = pad(str, length, chars); -``` - -## Usage - -### `pad(str, length, chars)` - -Use `pad` when you want to pad a string on both sides to match a desired length. If the padding characters don't divide evenly, extra characters are placed on the right. - -```typescript -import { pad } from 'es-toolkit/compat'; - -// Pad with default spaces -pad('abc', 8); -// Returns: ' abc ' - -// Pad with specified characters -pad('abc', 8, '_-'); -// Returns: '_-abc_-_' - -// Return as is if already long enough -pad('abc', 3); -// Returns: 'abc' - -// Return as is if length is shorter -pad('abc', 2); -// Returns: 'abc' -``` - -`null` or `undefined` are treated as empty strings. - -```typescript -import { pad } from 'es-toolkit/compat'; - -pad(null, 5); // ' ' -pad(undefined, 3, '*'); // '***' -``` - -#### Parameters - -- `str` (`string`, optional): The string to pad. -- `length` (`number`, optional): The target length. Defaults to `0`. -- `chars` (`string`, optional): The characters to use for padding. Defaults to space `' '`. - -#### Returns - -(`string`): Returns the string padded to the specified length. diff --git a/docs/reference/compat/string/snakeCase.md b/docs/reference/compat/string/snakeCase.md deleted file mode 100644 index 6b5229ccb..000000000 --- a/docs/reference/compat/string/snakeCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# snakeCase (Lodash compatibility) - -::: warning Use `snakeCase` from `es-toolkit` - -This `snakeCase` function operates slowly due to normalization logic for handling `null` or `undefined`. - -Instead, use the faster and more modern [snakeCase](../../string/snakeCase.md) from `es-toolkit`. - -::: - -Converts a string to snake case. - -```typescript -const snakeCased = snakeCase(str); -``` - -## Usage - -### `snakeCase(str)` - -Use `snakeCase` when you want to convert a string to snake*case. Snake case is a naming convention where each word is written in lowercase and connected with underscores (*). - -```typescript -import { snakeCase } from 'es-toolkit/compat'; - -// Convert camel case -snakeCase('camelCase'); -// Returns: 'camel_case' - -// Convert space-separated string -snakeCase('some whitespace'); -// Returns: 'some_whitespace' - -// Convert hyphen-separated string -snakeCase('hyphen-text'); -// Returns: 'hyphen_text' - -// Handle consecutive uppercase letters -snakeCase('HTTPRequest'); -// Returns: 'http_request' -``` - -`null` or `undefined` are treated as empty strings. - -```typescript -import { snakeCase } from 'es-toolkit/compat'; - -snakeCase(null); // '' -snakeCase(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to convert to snake case. - -#### Returns - -(`string`): Returns the converted string in snake case. diff --git a/docs/reference/compat/string/startCase.md b/docs/reference/compat/string/startCase.md deleted file mode 100644 index a2af12fed..000000000 --- a/docs/reference/compat/string/startCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# startCase (Lodash compatibility) - -::: warning Use `startCase` from `es-toolkit` - -This `startCase` function runs slower due to normalization logic for handling `null` or `undefined`. - -Instead, use the faster and more modern [startCase](../../string/startCase.md) from `es-toolkit`. - -::: - -Converts a string to start case. - -```typescript -const startCased = startCase(str); -``` - -## Usage - -### `startCase(str)` - -Use `startCase` when you want to convert a string to Start Case. Start Case is a naming convention where the first letter of each word is capitalized and separated by spaces. - -```typescript -import { startCase } from 'es-toolkit/compat'; - -// Convert regular string -startCase('hello world'); -// Returns: 'Hello World' - -// Keep words that are already uppercase -startCase('HELLO WORLD'); -// Returns: 'HELLO WORLD' - -// Convert hyphen-separated string -startCase('hello-world'); -// Returns: 'Hello World' - -// Convert underscore-separated string -startCase('hello_world'); -// Returns: 'Hello World' -``` - -`null` or `undefined` are treated as empty strings. - -```typescript -import { startCase } from 'es-toolkit/compat'; - -startCase(null); // '' -startCase(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to convert to start case. - -#### Returns - -(`string`): Returns the start case converted string. diff --git a/docs/reference/compat/string/trim.md b/docs/reference/compat/string/trim.md deleted file mode 100644 index 91c7ab85e..000000000 --- a/docs/reference/compat/string/trim.md +++ /dev/null @@ -1,55 +0,0 @@ -# trim (Lodash Compatibility) - -::: warning Use `trim` from `es-toolkit` - -This `trim` function operates slowly due to handling `null` or `undefined` and array-type `chars`. - -Use the faster and more modern [trim](../../string/trim.md) from `es-toolkit` instead. - -::: - -Removes leading and trailing whitespace or specified characters from a string. - -```typescript -const trimmed = trim(str, chars); -``` - -## Usage - -### `trim(str, chars)` - -Use `trim` when you want to remove whitespace or specific characters from the beginning and end of a string. If `chars` is not specified, only leading and trailing whitespace will be removed. - -```typescript -import { trim } from 'es-toolkit/compat'; - -// Remove leading and trailing whitespace -trim(' hello '); -// Returns: 'hello' - -// Remove specified characters -trim('--hello--', '-'); -// Returns: 'hello' - -// Remove multiple characters with an array -trim('##hello##', ['#', 'o']); -// Returns: 'hell' -``` - -`null` or `undefined` is treated as an empty string. - -```typescript -import { trim } from 'es-toolkit/compat'; - -trim(null); // '' -trim(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to trim. -- `chars` (`string`, optional): The characters to remove. If not specified, whitespace will be removed. - -#### Returns - -(`string`): Returns the string with specified characters removed from the beginning and end. diff --git a/docs/reference/compat/string/trimEnd.md b/docs/reference/compat/string/trimEnd.md deleted file mode 100644 index b477d5de0..000000000 --- a/docs/reference/compat/string/trimEnd.md +++ /dev/null @@ -1,55 +0,0 @@ -# trimEnd (Lodash Compatibility) - -::: warning Use `trimEnd` from `es-toolkit` - -This `trimEnd` function operates slowly due to handling `null` or `undefined` and parameter order changes. - -Use the faster and more modern [trimEnd](../../string/trimEnd.md) from `es-toolkit` instead. - -::: - -Removes trailing whitespace or specified characters from a string. - -```typescript -const trimmed = trimEnd(str, chars); -``` - -## Usage - -### `trimEnd(str, chars)` - -Use `trimEnd` when you want to remove whitespace or specific characters from the end of a string. If `chars` is not specified, only trailing whitespace will be removed. - -```typescript -import { trimEnd } from 'es-toolkit/compat'; - -// Remove trailing whitespace -trimEnd(' abc '); -// Returns: ' abc' - -// Remove specified characters -trimEnd('-_-abc-_-', '_-'); -// Returns: '-_-abc' - -// Only applies to the end of the string -trimEnd('abc', 'a'); -// Returns: 'abc' -``` - -`null` or `undefined` is treated as an empty string. - -```typescript -import { trimEnd } from 'es-toolkit/compat'; - -trimEnd(null); // '' -trimEnd(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to trim from the end. -- `chars` (`string`, optional): The characters to remove. If not specified, whitespace will be removed. - -#### Returns - -(`string`): Returns the string with specified characters removed from the end. diff --git a/docs/reference/compat/string/trimStart.md b/docs/reference/compat/string/trimStart.md deleted file mode 100644 index d0e5ad99d..000000000 --- a/docs/reference/compat/string/trimStart.md +++ /dev/null @@ -1,55 +0,0 @@ -# trimStart (Lodash Compatibility) - -::: warning Use `trimStart` from `es-toolkit` - -This `trimStart` function operates slowly due to handling `null` or `undefined` and parameter order changes. - -Use the faster and more modern [trimStart](../../string/trimStart.md) from `es-toolkit` instead. - -::: - -Removes leading whitespace or specified characters from a string. - -```typescript -const trimmed = trimStart(str, chars); -``` - -## Usage - -### `trimStart(str, chars)` - -Use `trimStart` when you want to remove whitespace or specific characters from the beginning of a string. If `chars` is not specified, only leading whitespace will be removed. - -```typescript -import { trimStart } from 'es-toolkit/compat'; - -// Remove leading whitespace -trimStart(' abc '); -// Returns: 'abc ' - -// Remove specified characters -trimStart('-_-abc-_-', '_-'); -// Returns: 'abc-_-' - -// Only applies to the beginning of the string -trimStart('abc', 'c'); -// Returns: 'abc' -``` - -`null` or `undefined` is treated as an empty string. - -```typescript -import { trimStart } from 'es-toolkit/compat'; - -trimStart(null); // '' -trimStart(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to trim from the beginning. -- `chars` (`string`, optional): The characters to remove. If not specified, whitespace will be removed. - -#### Returns - -(`string`): Returns the string with specified characters removed from the beginning. diff --git a/docs/reference/compat/string/unescape.md b/docs/reference/compat/string/unescape.md deleted file mode 100644 index 729470587..000000000 --- a/docs/reference/compat/string/unescape.md +++ /dev/null @@ -1,58 +0,0 @@ -# unescape (Lodash Compatibility) - -::: warning Use `unescape` from `es-toolkit` - -This `unescape` function operates slowly due to conversion logic for handling `null` or `undefined`. - -Use the faster and more modern [unescape](../../string/unescape.md) from `es-toolkit` instead. - -::: - -Converts HTML entities to their original characters. - -```typescript -const unescaped = unescape(str); -``` - -## Usage - -### `unescape(str)` - -Use `unescape` when you want to convert HTML entities `&`, `<`, `>`, `"`, `'` back to their original characters. This is the reverse operation of the `escape` function. - -```typescript -import { unescape } from 'es-toolkit/compat'; - -// Unescape HTML tags -unescape('This is a <div> element.'); -// Returns: 'This is a
element.' - -// Unescape quotes -unescape('This is a "quote"'); -// Returns: 'This is a "quote"' - -// Unescape apostrophes -unescape('This is a 'quote''); -// Returns: 'This is a 'quote'' - -// Unescape ampersands -unescape('This is a & symbol'); -// Returns: 'This is a & symbol' -``` - -`null` or `undefined` is treated as an empty string. - -```typescript -import { unescape } from 'es-toolkit/compat'; - -unescape(null); // '' -unescape(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to unescape. - -#### Returns - -(`string`): Returns the string with HTML entities converted to their original characters. diff --git a/docs/reference/compat/string/upperCase.md b/docs/reference/compat/string/upperCase.md deleted file mode 100644 index 08d6f5235..000000000 --- a/docs/reference/compat/string/upperCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# upperCase (Lodash Compatibility) - -::: warning Use `upperCase` from `es-toolkit` - -This `upperCase` function operates slowly due to normalization logic for handling `null` or `undefined`. - -Use the faster and more modern [upperCase](../../string/upperCase.md) from `es-toolkit` instead. - -::: - -Converts a string to upper case. - -```typescript -const upperCased = upperCase(str); -``` - -## Usage - -### `upperCase(str)` - -Use `upperCase` when you want to convert a string to upper case (UPPER CASE). Upper case is a naming convention where each word is written in uppercase and connected with spaces. - -```typescript -import { upperCase } from 'es-toolkit/compat'; - -// Convert camel case -upperCase('camelCase'); -// Returns: 'CAMEL CASE' - -// Convert space-separated string -upperCase('some whitespace'); -// Returns: 'SOME WHITESPACE' - -// Convert hyphen-separated string -upperCase('hyphen-text'); -// Returns: 'HYPHEN TEXT' - -// When uppercase letters appear consecutively -upperCase('HTTPRequest'); -// Returns: 'HTTP REQUEST' -``` - -`null` or `undefined` is treated as an empty string. - -```typescript -import { upperCase } from 'es-toolkit/compat'; - -upperCase(null); // '' -upperCase(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to convert to upper case. - -#### Returns - -(`string`): Returns the string converted to upper case. diff --git a/docs/reference/compat/string/upperFirst.md b/docs/reference/compat/string/upperFirst.md deleted file mode 100644 index 21934b267..000000000 --- a/docs/reference/compat/string/upperFirst.md +++ /dev/null @@ -1,54 +0,0 @@ -# upperFirst (Lodash Compatibility) - -::: warning Use `upperFirst` from `es-toolkit` - -This `upperFirst` function operates slowly due to conversion logic for handling `null` or `undefined`. - -Use the faster and more modern [upperFirst](../../string/upperFirst.md) from `es-toolkit` instead. - -::: - -Converts the first character of a string to uppercase. - -```typescript -const upperCased = upperFirst(str); -``` - -## Usage - -### `upperFirst(str)` - -Use `upperFirst` when you want to capitalize only the first character of a string. The remaining characters stay unchanged. - -```typescript -import { upperFirst } from 'es-toolkit/compat'; - -// String starting with lowercase -upperFirst('fred'); -// Returns: 'Fred' - -// String already starting with uppercase -upperFirst('Fred'); -// Returns: 'Fred' - -// All uppercase string -upperFirst('FRED'); -// Returns: 'FRED' -``` - -`null` or `undefined` is treated as an empty string. - -```typescript -import { upperFirst } from 'es-toolkit/compat'; - -upperFirst(null); // '' -upperFirst(undefined); // '' -``` - -#### Parameters - -- `str` (`string`, optional): The string to convert the first character to uppercase. - -#### Returns - -(`string`): Returns the string with the first character converted to uppercase. diff --git a/docs/reference/compat/string/words.md b/docs/reference/compat/string/words.md deleted file mode 100644 index 56f9ce040..000000000 --- a/docs/reference/compat/string/words.md +++ /dev/null @@ -1,69 +0,0 @@ -# words (Lodash Compatibility) - -::: warning Use `words` from `es-toolkit` - -This `words` function operates slowly due to handling `null` or `undefined` and complex Unicode support. - -Use the faster and more modern [words](../../string/words.md) from `es-toolkit` instead. - -::: - -Splits a string into an array of words. - -```typescript -const wordArray = words(str, pattern); -``` - -## Usage - -### `words(str, pattern)` - -Use `words` when you want to split a string into words. By default, it recognizes English letters, numbers, emojis, etc., to extract words. - -```typescript -import { words } from 'es-toolkit/compat'; - -// Basic word extraction -words('fred, barney, & pebbles'); -// Returns: ['fred', 'barney', 'pebbles'] - -// Extract words from camel case -words('camelCaseWord'); -// Returns: ['camel', 'Case', 'Word'] - -// String with numbers -words('hello123world'); -// Returns: ['hello', '123', 'world'] -``` - -You can also extract words using a custom pattern. - -```typescript -import { words } from 'es-toolkit/compat'; - -// Extract words using regex -words('hello world', /\w+/g); -// Returns: ['hello', 'world'] - -// Use string pattern -words('one-two-three', '-'); -// Returns: ['-'] -``` - -`null` or `undefined` is treated as an empty array. - -```typescript -import { words } from 'es-toolkit/compat'; - -words(null); // [] -words(undefined); // [] -``` - -#### Parameters - -- `str` (`string`, optional): The string to split into words. -- `pattern` (`RegExp | string`, optional): The pattern to match words. Defaults to a built-in Unicode word pattern. - -#### Returns - -(`string[]`): Returns an array of extracted words. diff --git a/docs/vercel.json b/docs/vercel.json index ad003ec4a..44d41a8af 100644 --- a/docs/vercel.json +++ b/docs/vercel.json @@ -4,5 +4,31 @@ "deploymentEnabled": { "main": false } - } + }, + "redirects": [ + { "source": "/compatibility.html", "destination": "/compat/intro.html", "permanent": false }, + { "source": "/ko/compatibility.html", "destination": "/ko/compat/intro.html", "permanent": false }, + { "source": "/ja/compatibility.html", "destination": "/ja/compat/intro.html", "permanent": false }, + { "source": "/zh_hans/compatibility.html", "destination": "/zh_hans/compat/intro.html", "permanent": false }, + { + "source": "/reference/compat/:path*.html", + "destination": "/compat/reference/:path*.html", + "permanent": false + }, + { + "source": "/ko/reference/compat/:path*.html", + "destination": "/ko/compat/reference/:path*.html", + "permanent": false + }, + { + "source": "/ja/reference/compat/:path*.html", + "destination": "/ja/compat/reference/:path*.html", + "permanent": false + }, + { + "source": "/zh_hans/reference/compat/:path*.html", + "destination": "/zh_hans/compat/reference/:path*.html", + "permanent": false + } + ] } diff --git a/docs/zh_hans/compat/intro.md b/docs/zh_hans/compat/intro.md new file mode 100644 index 000000000..0f5df1ba2 --- /dev/null +++ b/docs/zh_hans/compat/intro.md @@ -0,0 +1,66 @@ +# es-toolkit/compat + +`es-toolkit/compat` 提供与 [Lodash](https://lodash.com) 完全一致的接口和行为。它的目标是让你保留现有 Lodash 代码的调用方式,逐步迁移到 `es-toolkit`。 + +如果你的项目本来就不使用 Lodash,请使用 [`es-toolkit`](/zh_hans/intro)。 + +::: tip ✅ 自 v1.39.3 起保证与 Lodash 100% 兼容 +`es-toolkit/compat` 直接通过 Lodash 自身的测试代码。行为完全相同,但更小、更快。 +::: + +```ts +// 与 lodash 相同的调用方式,可以直接在 es-toolkit/compat 中使用 +import { chunk } from 'es-toolkit/compat'; + +chunk([1, 2, 3, 4], 0); +// 返回 [],与 lodash 相同。 +``` + +## 迁移流程 + +从现有代码中移除 Lodash 时,推荐按以下顺序操作: + +1. 将 `lodash` / `lodash-es` 的 import 路径替换为 `es-toolkit/compat`。调用代码可以保持不变。 +2. 慢慢整理调用代码,并将 import 切换为 [`es-toolkit`](/zh_hans/intro)。完成迁移后,你将获得更小的包体积和更快的运行速度。 + +## 与 `es-toolkit` 的区别 + +- **API 形态**:与 Lodash 1:1 一致,包括隐式类型转换、多种参数形态以及已弃用的辅助函数。[`es-toolkit`](/zh_hans/intro) 只暴露类型安全的现代形态。 +- **包体积与性能**:比 [`es-toolkit`](/zh_hans/intro) 稍大、稍慢,因为内部包含了与 Lodash 对齐行为所需的额外处理。 +- **已弃用函数**:Lodash 中已弃用的函数仍保留在 `compat` 中以保持兼容,但不会加入 [`es-toolkit`](/zh_hans/intro)。建议在迁移过程中一并清理。 + +各函数的详细文档请参见 [兼容性参考](/zh_hans/compat/reference/array/castArray)。 + +## 设计原则 + +::: info +设计原则可能会有所变化。 +::: + +`es-toolkit/compat` 的目标是为以下功能提供与 `lodash` 100% 相同的实现: + +- 在 lodash 中作为测试用例编写的功能。 +- 可以从 `@types/lodash` 或 `@types/lodash-es` 类型推断的功能。 +- 在将代码从 lodash 迁移到 es-toolkit 时识别出的功能差异(请将这些差异报告到我们的[问题页面](https://github.com/toss/es-toolkit/issues))。 + +但是,以下内容超出 `es-toolkit/compat` 的范围: + +- 隐式类型转换,例如将空字符串转换为零或 false。 +- 针对特定类型数组具有专门实现的函数,如 [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq)。 +- 处理修改了内置对象(如 `Array.prototype`)原型的情况。 +- 处理 JavaScript Realm 的情况。 +- 通过 "Seq" 方法支持的方法链。 + +## 实现状态 + +::: info +以下表情符号表示每个功能的状态: + +- ✅: 已完成(功能已完全实现,并通过 lodash 测试代码的所有测试。) +- 📝: 审查中(功能已实现,但尚未通过 lodash 测试代码进行测试。) +- ❌: 未实现(该功能尚未实现。) + +即使一个功能被标记为"审查中",它可能已经在审查中以确保与 lodash 完全匹配,并且可能已经提供了相同的功能。 +::: + + diff --git a/docs/zh_hans/reference/compat/array/castArray.md b/docs/zh_hans/compat/reference/array/castArray.md similarity index 100% rename from docs/zh_hans/reference/compat/array/castArray.md rename to docs/zh_hans/compat/reference/array/castArray.md diff --git a/docs/zh_hans/compat/reference/array/chunk.md b/docs/zh_hans/compat/reference/array/chunk.md new file mode 100644 index 000000000..6606093bb --- /dev/null +++ b/docs/zh_hans/compat/reference/array/chunk.md @@ -0,0 +1,70 @@ +# chunk(Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [`chunk`](../../../reference/array/chunk.md) + +此 `chunk` 函数由于处理 `null`、`undefined` 和默认 `size` 值等原因运行较慢。 + +请使用 `es-toolkit` 中更快、更现代的 [chunk](../../../reference/array/chunk.md) 实现。 + +::: + +将数组划分为指定大小的较小数组。 + +```typescript +const chunked = chunk(arr, size); +``` + +## 用法 + +### `chunk(arr, size?)` + +当你想要将一个长数组分割成多个相同大小的较小数组时,使用 `chunk`。如果数组不能被均匀分割,最后一个数组将包含剩余的元素。 + +```typescript +import { chunk } from 'es-toolkit/compat'; + +// 将数字数组分成大小为 2 的块。 +chunk([1, 2, 3, 4], 2); +// 返回值:[[1, 2], [3, 4]] + +// 将字符串数组分成大小为 3 的块。 +chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); +// 返回值:[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] + +// 当不能均匀分割时 +chunk([1, 2, 3, 4, 5], 2); +// 返回值:[[1, 2], [3, 4], [5]] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { chunk } from 'es-toolkit/compat'; + +chunk(null, 2); +// 返回值:[] + +chunk(undefined, 2); +// 返回值:[] +``` + +如果大小为 0 或负数,返回空数组。 + +```typescript +import { chunk } from 'es-toolkit/compat'; + +chunk([1, 2, 3], 0); +// 返回值:[] + +chunk([1, 2, 3], -1); +// 返回值:[] +``` + +#### 参数 + +- `arr` (`ArrayLike | null | undefined`): 要划分的数组。 +- `size` (`number`, 可选): 每个较小数组的大小。默认值为 `1`。 + +#### 返回值 + +(`T[][]`): 返回按大小 `size` 划分的二维数组。 diff --git a/docs/zh_hans/compat/reference/array/compact.md b/docs/zh_hans/compat/reference/array/compact.md new file mode 100644 index 000000000..31b4293fa --- /dev/null +++ b/docs/zh_hans/compat/reference/array/compact.md @@ -0,0 +1,77 @@ +# compact(Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [`compact`](../../../reference/array/compact.md) + +此 `compact` 函数由于处理 `null` 和 `undefined` 值、`size` 默认值处理等原因运行较慢。 + +请使用 `es-toolkit` 中更快、更现代的 [compact](../../../reference/array/compact.md) 实现。 + +::: + +从数组中移除假值。 + +```typescript +const compacted = compact(arr); +``` + +## 用法 + +### `compact(arr)` + +当你想要从数组中移除像 `false`、`null`、`0`、`""`、`undefined` 和 `NaN` 这样的假值时,使用 `compact`。 + +```typescript +import { compact } from 'es-toolkit/compat'; + +// 移除假值 +compact([0, 1, false, 2, '', 3]); +// Returns: [1, 2, 3] + +compact(['a', null, 'b', undefined, 'c', NaN]); +// Returns: ['a', 'b', 'c'] + +// 也会移除 bigint 0 +compact([0n, 1n, false, 2n]); +// Returns: [1n, 2n] + +// 处理空数组 +compact([]); +// Returns: [] + +// 当所有值都是假值时 +compact([false, null, 0, '', undefined, NaN]); +// Returns: [] +``` + +真值会保持原样。 + +```typescript +import { compact } from 'es-toolkit/compat'; + +compact([1, 'hello', true, {}, []]); +// Returns: [1, 'hello', true, {}, []] + +// 非零数字 +compact([0, -1, 2, -3]); +// Returns: [-1, 2, -3] +``` + +`null` 或 `undefined` 数组被视为空数组。 + +```typescript +import { compact } from 'es-toolkit/compat'; + +compact(null); +// Returns: [] + +compact(undefined); +// Returns: [] +``` + +#### 参数 + +- `arr` (`ArrayLike | null | undefined`): 要压缩的数组。 + +#### 返回值 + +(`T[]`): 返回移除假值后的新数组。 diff --git a/docs/zh_hans/reference/compat/array/concat.md b/docs/zh_hans/compat/reference/array/concat.md similarity index 100% rename from docs/zh_hans/reference/compat/array/concat.md rename to docs/zh_hans/compat/reference/array/concat.md diff --git a/docs/zh_hans/compat/reference/array/countBy.md b/docs/zh_hans/compat/reference/array/countBy.md new file mode 100644 index 000000000..c0423930b --- /dev/null +++ b/docs/zh_hans/compat/reference/array/countBy.md @@ -0,0 +1,88 @@ +# countBy(Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `countBy` + +此 `countBy` 函数由于复杂的转换函数处理和类型转换而运行较慢。 + +请使用 `es-toolkit` 中更快、更现代的 [countBy](../../../reference/array/countBy.md)。 + +::: + +根据条件对数组或对象的元素进行分类并计算每个分类的数量。 + +```typescript +const counts = countBy(collection, iteratee); +``` + +## 用法 + +### `countBy(collection, iteratee?)` + +当你想要按某个标准对数组或对象的每个元素进行分组,并计算每个组中有多少个元素时,使用 `countBy`。迭代函数返回的值将成为键,该键对应的元素数量将成为值。 + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// 按向下取整对数字分组 +countBy([6.1, 4.2, 6.3], Math.floor); +// Returns: { '4': 1, '6': 2 } + +// 按长度对字符串分组 +countBy(['one', 'two', 'three'], 'length'); +// Returns: { '3': 2, '5': 1 } + +// 按年龄段对用户分组 +const users = [ + { name: 'Alice', age: 25 }, + { name: 'Bob', age: 35 }, + { name: 'Charlie', age: 25 }, +]; +countBy(users, user => Math.floor(user.age / 10) * 10); +// Returns: { '20': 2, '30': 1 } +``` + +也可以处理对象。 + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// 按类型对对象的值进行分类 +const obj = { a: 1, b: 'string', c: 2, d: 'text' }; +countBy(obj, value => typeof value); +// Returns: { 'number': 2, 'string': 2 } +``` + +不使用迭代函数时,会按值本身分组。 + +```typescript +import { countBy } from 'es-toolkit/compat'; + +// 按值本身分组 +countBy([1, 2, 1, 3, 2, 1]); +// Returns: { '1': 3, '2': 2, '3': 1 } + +// 按布尔值分组 +countBy([true, false, true, true]); +// Returns: { 'true': 3, 'false': 1 } +``` + +`null` 或 `undefined` 集合返回空对象。 + +```typescript +import { countBy } from 'es-toolkit/compat'; + +countBy(null); +// Returns: {} + +countBy(undefined); +// Returns: {} +``` + +#### 参数 + +- `collection` (`ArrayLike | object | null | undefined`): 要处理的数组或对象。 +- `iteratee` (`ValueIteratee`, 可选): 决定每个元素分组标准的函数。可以使用函数、属性名或部分对象。 + +#### 返回值 + +(`Record`): 返回包含每个组的键和该组元素数量的对象。 diff --git a/docs/zh_hans/compat/reference/array/difference.md b/docs/zh_hans/compat/reference/array/difference.md new file mode 100644 index 000000000..77c9a4058 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/difference.md @@ -0,0 +1,94 @@ +# difference(Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `difference` + +此 `difference` 函数由于处理 `null` 和 `undefined`、多个数组参数处理而变得复杂。 + +请使用 `es-toolkit` 中更快、更现代的 [difference](../../../reference/array/difference.md)。 + +::: + +从第一个数组中排除其他数组的值,求差集。 + +```typescript +const result = difference(arr, ...values); +``` + +## 用法 + +### `difference(arr, ...values)` + +当你想要从第一个数组中删除所有包含在其余数组中的值时,使用 `difference`。顺序保持第一个数组的顺序。 + +```typescript +import { difference } from 'es-toolkit/compat'; + +// 基本用法 +const array1 = [1, 2, 3, 4, 5]; +const array2 = [2, 4]; +const array3 = [5, 6]; +difference(array1, array2, array3); +// Returns: [1, 3] + +// 字符串数组 +difference(['a', 'b', 'c'], ['b'], ['c', 'd']); +// Returns: ['a'] + +// 处理重复值 +difference([1, 2, 2, 3], [2]); +// Returns: [1, 3] +``` + +也可以处理空数组或空差集。 + +```typescript +import { difference } from 'es-toolkit/compat'; + +// 与空数组的差集 +difference([1, 2, 3], []); +// Returns: [1, 2, 3] + +// 所有值都被排除的情况 +difference([1, 2, 3], [1, 2, 3]); +// Returns: [] + +// 没有重叠值的情况 +difference([1, 2], [3, 4]); +// Returns: [1, 2] +``` + +`null` 或 `undefined` 数组被视为空数组。 + +```typescript +import { difference } from 'es-toolkit/compat'; + +difference(null, [1, 2]); +// Returns: [] + +difference(undefined, [1, 2]); +// Returns: [] + +difference([1, 2, 3], null, undefined); +// Returns: [1, 2, 3] (null和undefined被忽略) +``` + +也支持类数组对象。 + +```typescript +import { difference } from 'es-toolkit/compat'; + +// 类数组对象 +const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; +const arrayLike2 = { 0: 2, 1: 4, length: 2 }; +difference(arrayLike1, arrayLike2); +// Returns: [1, 3] +``` + +#### 参数 + +- `arr` (`ArrayLike | null | undefined`): 求差集的基准数组。 +- `values` (`...ArrayLike[]`): 包含要排除的值的数组。 + +#### 返回值 + +(`T[]`): 返回从第一个数组中排除其他数组值的新数组。 diff --git a/docs/zh_hans/compat/reference/array/differenceBy.md b/docs/zh_hans/compat/reference/array/differenceBy.md new file mode 100644 index 000000000..30cf06be6 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/differenceBy.md @@ -0,0 +1,88 @@ +# differenceBy(Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `differenceBy` + +此 `differenceBy` 函数由于复杂的参数处理和迭代器转换而运行较慢。 + +请使用 `es-toolkit` 中更快、更现代的 [differenceBy](../../../reference/array/differenceBy.md)。 + +::: + +根据迭代函数转换的值,从第一个数组中排除其他数组的元素,求差集。 + +```typescript +const result = differenceBy(array, ...values, iteratee); +``` + +## 用法 + +### `differenceBy(array, ...values, iteratee)` + +当你想要将第一个数组的每个元素和要排除的数组的元素通过迭代函数转换后,删除产生相同值的元素时,使用 `differenceBy`。在对象数组中按特定属性值或转换值进行比较时很有用。 + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// 按向下取整比较 +differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); +// Returns: [1.2] (因为Math.floor(2.1) === Math.floor(2.3),所以排除2.1) + +// 按字符串长度比较 +differenceBy(['one', 'two', 'three'], ['four', 'eight'], 'length'); +// Returns: ['one', 'two'] (因为three和eight长度相同,所以排除three) + +// 按对象属性比较 +const users1 = [ + { id: 1, name: 'Alice' }, + { id: 2, name: 'Bob' }, +]; +const users2 = [{ id: 1, name: 'Different Alice' }]; +differenceBy(users1, users2, 'id'); +// Returns: [{ id: 2, name: 'Bob' }] (排除id为1的对象) +``` + +可以一次排除多个数组。 + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// 从多个数组中排除 +differenceBy([2.1, 1.2, 3.5], [2.3], [1.4], [3.2], Math.floor); +// Returns: [] (所有元素都被排除) + +// 按长度比较字符串数组 +differenceBy(['a', 'bb', 'ccc'], ['x'], ['yy'], ['zzz'], 'length'); +// Returns: [] (长度1、2、3都被排除) +``` + +没有迭代函数时,像普通 `difference` 一样工作。 + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +// 不使用迭代函数 +differenceBy([1, 2, 3], [2, 4]); +// Returns: [1, 3] +``` + +`null` 或 `undefined` 数组被视为空数组。 + +```typescript +import { differenceBy } from 'es-toolkit/compat'; + +differenceBy(null, [1, 2], Math.floor); +// Returns: [] + +differenceBy(undefined, [1, 2], x => x); +// Returns: [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 求差集的基准数组。 +- `values` (`...ArrayLike[]`): 包含要排除的值的数组。 +- `iteratee` (`ValueIteratee`): 将每个元素转换为比较值的函数。可以使用函数、属性名或部分对象。 + +#### 返回值 + +(`T[]`): 返回根据迭代函数转换的值排除元素后的新数组。 diff --git a/docs/zh_hans/compat/reference/array/differenceWith.md b/docs/zh_hans/compat/reference/array/differenceWith.md new file mode 100644 index 000000000..13ba91dc3 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/differenceWith.md @@ -0,0 +1,79 @@ +# differenceWith(Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `differenceWith` + +此 `differenceWith` 函数由于处理 `null` 和 `undefined`、多个数组处理、`ArrayLike` 类型处理等而运行较慢。 + +请使用 `es-toolkit` 中更快、更现代的 [differenceWith](../../../reference/array/differenceWith.md)。 + +::: + +使用比较函数从第一个数组中删除其他数组中包含的元素。 + +```typescript +const result = differenceWith(array, ...values, comparator); +``` + +## 用法 + +### `differenceWith(array, ...values, comparator)` + +当你想要用比较函数比较每个元素来求差时,使用 `differenceWith`。最后一个参数成为比较函数。 + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +// 按id比较对象 +const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; +const others = [{ id: 2 }]; +const comparator = (a, b) => a.id === b.id; + +differenceWith(objects, others, comparator); +// Returns: [{ id: 1 }, { id: 3 }] + +// 一次排除多个数组 +const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]; +const values1 = [{ id: 2 }]; +const values2 = [{ id: 3 }]; + +differenceWith(array, values1, values2, comparator); +// Returns: [{ id: 1 }, { id: 4 }] +``` + +不提供比较函数时,像普通 `difference` 一样工作。 + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +// 不使用比较函数时进行普通比较 +differenceWith([1, 2, 3], [2], [3]); +// Returns: [1] +``` + +也可以使用复杂的比较逻辑。 + +```typescript +import { differenceWith } from 'es-toolkit/compat'; + +const users = [ + { name: 'alice', age: 25 }, + { name: 'bob', age: 30 }, + { name: 'charlie', age: 35 }, +]; +const excludeUsers = [{ name: 'bob', age: 25 }]; // 不同的年龄 + +// 只按名称比较 +const compareByName = (a, b) => a.name === b.name; +differenceWith(users, excludeUsers, compareByName); +// Returns: [{ name: 'alice', age: 25 }, { name: 'charlie', age: 35 }] +// bob被排除(即使年龄不同,名称相同) +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 求差的基准数组。 +- `...values` (`Array>` + `(a: T, b: T) => boolean`): 包含要排除的元素的数组,最后是比较函数。 + +#### 返回值 + +(`T[]`): 返回使用比较函数从第一个数组中删除其余数组元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/drop.md b/docs/zh_hans/compat/reference/array/drop.md new file mode 100644 index 000000000..b18242c8a --- /dev/null +++ b/docs/zh_hans/compat/reference/array/drop.md @@ -0,0 +1,97 @@ +# drop (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `drop` + +此 `drop` 函数由于处理 `null` 或 `undefined`、`toInteger` 转换等原因而表现复杂。 + +请改用更快、更现代的 `es-toolkit` 的 [`drop`](../../../reference/array/drop.md)。 + +::: + +从数组的开头删除指定数量的元素。 + +```typescript +const result = drop(array, n); +``` + +## 用法 + +### `drop(array, n?)` + +当您想从数组的开头删除几个元素并获取其余元素时,使用 `drop`。默认情况下,它会删除第一个元素。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 基本用法(删除第一个元素) +drop([1, 2, 3, 4, 5]); +// 返回: [2, 3, 4, 5] + +// 删除前 2 个元素 +drop([1, 2, 3, 4, 5], 2); +// 返回: [3, 4, 5] + +// 删除前 3 个元素 +drop(['a', 'b', 'c', 'd'], 3); +// 返回: ['d'] +``` + +指定 0 或负数时,返回原始数组。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 删除 0 个元素 +drop([1, 2, 3], 0); +// 返回: [1, 2, 3] + +// 指定负数 +drop([1, 2, 3], -1); +// 返回: [1, 2, 3] +``` + +指定大于数组的数字时,返回空数组。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 指定大于数组大小的数字 +drop([1, 2, 3], 5); +// 返回: [] + +// 从空数组中删除 +drop([], 1); +// 返回: [] +``` + +`null` 或 `undefined` 数组被视为空数组。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +drop(null, 1); +// 返回: [] + +drop(undefined, 2); +// 返回: [] +``` + +也支持类数组对象。 + +```typescript +import { drop } from 'es-toolkit/compat'; + +// 类数组对象 +const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; +drop(arrayLike, 1); +// 返回: ['b', 'c'] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要删除元素的数组。 +- `n` (`number`, 可选): 要删除的元素数量。默认为 `1`。 + +#### 返回值 + +(`T[]`): 返回从开头删除指定数量元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/dropRight.md b/docs/zh_hans/compat/reference/array/dropRight.md new file mode 100644 index 000000000..c18dcacf7 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/dropRight.md @@ -0,0 +1,55 @@ +# dropRight (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `dropRight` + +此 `dropRight` 函数由于处理 `null` 或 `undefined`、`guard` 参数处理、`toInteger` 转换等原因而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`dropRight`](../../../reference/array/dropRight.md)。 + +::: + +从数组的末尾删除指定数量的元素,返回一个新数组。 + +```typescript +const result = dropRight(array, itemsCount); +``` + +## 用法 + +### `dropRight(array, itemsCount)` + +当您想从数组的末尾删除特定数量的元素并创建一个包含剩余元素的新数组时,使用 `dropRight`。 + +```typescript +import { dropRight } from 'es-toolkit/compat'; + +// 从数字数组中删除末尾的 2 个元素。 +dropRight([1, 2, 3, 4, 5], 2); +// 返回: [1, 2, 3] + +// 从字符串数组中删除末尾的 1 个元素。 +dropRight(['a', 'b', 'c'], 1); +// 返回: ['a', 'b'] + +// 如果未指定要删除的数量,则使用默认值 1。 +dropRight([1, 2, 3]); +// 返回: [1, 2] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { dropRight } from 'es-toolkit/compat'; + +dropRight(null, 2); // [] +dropRight(undefined, 2); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要删除元素的数组。 +- `itemsCount` (`number`, 可选): 要从数组末尾删除的元素数量。默认为 `1`。 + +#### 返回值 + +(`T[]`): 返回从末尾删除 `itemsCount` 个元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/dropRightWhile.md b/docs/zh_hans/compat/reference/array/dropRightWhile.md new file mode 100644 index 000000000..5897a5f6e --- /dev/null +++ b/docs/zh_hans/compat/reference/array/dropRightWhile.md @@ -0,0 +1,65 @@ +# dropRightWhile (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `dropRightWhile` + +此 `dropRightWhile` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等原因而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`dropRightWhile`](../../../reference/array/dropRightWhile.md)。 + +::: + +根据条件函数从数组的末尾删除元素。 + +```typescript +const result = dropRightWhile(array, predicate); +``` + +## 用法 + +### `dropRightWhile(array, predicate)` + +当您想从数组的末尾连续删除满足特定条件的元素时,使用 `dropRightWhile`。当条件函数返回 `false` 时停止删除。 + +```typescript +import { dropRightWhile } from 'es-toolkit/compat'; + +// 使用函数作为条件。 +const users = [ + { user: 'barney', active: true }, + { user: 'fred', active: false }, + { user: 'pebbles', active: false }, +]; + +dropRightWhile(users, user => !user.active); +// 返回: [{ user: 'barney', active: true }] + +// 使用对象模式进行匹配。 +dropRightWhile(users, { user: 'pebbles', active: false }); +// 返回: [{ user: 'barney', active: true }, { user: 'fred', active: false }] + +// 以数组形式指定属性和值。 +dropRightWhile(users, ['active', false]); +// 返回: [{ user: 'barney', active: true }] + +// 通过属性名检查条件。 +dropRightWhile(users, 'active'); +// 返回: [{ user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { dropRightWhile } from 'es-toolkit/compat'; + +dropRightWhile(null, x => x > 0); // [] +dropRightWhile(undefined, x => x > 0); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要删除元素的数组。 +- `predicate` (`ListIteratee`, 可选): 应用于每个元素的条件函数。可以接受函数、对象模式、数组模式或属性名。 + +#### 返回值 + +(`T[]`): 返回从第一个不满足条件的元素开始的新数组。 diff --git a/docs/zh_hans/compat/reference/array/dropWhile.md b/docs/zh_hans/compat/reference/array/dropWhile.md new file mode 100644 index 000000000..d2aad405b --- /dev/null +++ b/docs/zh_hans/compat/reference/array/dropWhile.md @@ -0,0 +1,67 @@ +# dropWhile (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `dropWhile` + +此 `dropWhile` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等原因而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`dropWhile`](../../../reference/array/dropWhile.md)。 + +::: + +根据条件函数从数组的开头删除元素。 + +```typescript +const result = dropWhile(array, predicate); +``` + +## 用法 + +### `dropWhile(array, predicate)` + +当您想从数组的开头连续删除满足特定条件的元素时,使用 `dropWhile`。当条件函数返回 `false` 时停止删除。 + +```typescript +import { dropWhile } from 'es-toolkit/compat'; + +// 使用函数作为条件。 +dropWhile([1, 2, 3, 4, 5], n => n < 3); +// 返回: [3, 4, 5] + +// 使用对象模式进行匹配。 +const users = [ + { name: 'alice', active: false }, + { name: 'bob', active: false }, + { name: 'charlie', active: true }, +]; + +dropWhile(users, { active: false }); +// 返回: [{ name: 'charlie', active: true }] + +// 以数组形式指定属性和值。 +dropWhile(users, ['active', false]); +// 返回: [{ name: 'charlie', active: true }] + +// 通过属性名检查条件。 +const items = [{ visible: false }, { visible: false }, { visible: true }]; + +dropWhile(items, 'visible'); +// 返回: [{ visible: false }, { visible: false }, { visible: true }] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { dropWhile } from 'es-toolkit/compat'; + +dropWhile(null, x => x > 0); // [] +dropWhile(undefined, x => x > 0); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要删除元素的数组。 +- `predicate` (`ListIteratee`, 可选): 应用于每个元素的条件函数。可以接受函数、对象模式、数组模式或属性名。默认为 `identity`。 + +#### 返回值 + +(`T[]`): 返回从第一个不满足条件的元素开始的新数组。 diff --git a/docs/zh_hans/reference/compat/array/each.md b/docs/zh_hans/compat/reference/array/each.md similarity index 100% rename from docs/zh_hans/reference/compat/array/each.md rename to docs/zh_hans/compat/reference/array/each.md diff --git a/docs/zh_hans/compat/reference/array/eachRight.md b/docs/zh_hans/compat/reference/array/eachRight.md new file mode 100644 index 000000000..49edc5507 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/eachRight.md @@ -0,0 +1,58 @@ +# eachRight (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `forEachRight` + +此 `eachRight` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等原因而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`forEachRight`](../../../reference/array/forEachRight.md)。 + +::: + +对数组或对象的每个元素从右到左执行迭代操作。 + +```typescript +const result = eachRight(collection, iteratee); +``` + +## 用法 + +### `eachRight(collection, iteratee)` + +从右到左遍历数组、对象或字符串的每个元素并执行给定的函数。对于数组,从最后一个索引开始逆序迭代;对于对象,以逆序遍历可枚举属性。 + +```typescript +import { eachRight } from 'es-toolkit/compat'; + +// 逆序遍历数组 +eachRight([1, 2, 3], (value, index) => console.log(value, index)); +// 日志: 3 2, 2 1, 1 0 + +// 逆序遍历对象 +eachRight({ a: 1, b: 2 }, (value, key) => console.log(key, value)); +// 日志: 'b' 2, 'a' 1 + +// 逆序遍历字符串 +eachRight('hello', (char, index) => console.log(char, index)); +// 日志: 'o' 4, 'l' 3, 'l' 2, 'e' 1, 'h' 0 +``` + +如果函数返回 `false`,则停止迭代。 + +```typescript +import { eachRight } from 'es-toolkit/compat'; + +eachRight([1, 2, 3, 4], value => { + console.log(value); + return value !== 2; // 在 2 处停止 +}); +// 日志: 4, 3, 2 +``` + +#### 参数 + +- `collection` (`ArrayLike | Record | string | null | undefined`): 要遍历的集合。 +- `iteratee` (`(item: any, index: any, collection: any) => unknown`, 可选): 对每个元素执行的函数。默认为 `identity` 函数。 + +#### 返回值 + +(`ArrayLike | Record | string | null | undefined`): 返回原始集合。 diff --git a/docs/zh_hans/reference/compat/array/every.md b/docs/zh_hans/compat/reference/array/every.md similarity index 100% rename from docs/zh_hans/reference/compat/array/every.md rename to docs/zh_hans/compat/reference/array/every.md diff --git a/docs/zh_hans/compat/reference/array/fill.md b/docs/zh_hans/compat/reference/array/fill.md new file mode 100644 index 000000000..9230ad4c9 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/fill.md @@ -0,0 +1,82 @@ +# fill (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `fill` + +此 `fill` 函数由于处理 `null` 或 `undefined`、支持类数组对象等原因而表现复杂。 + +请改用更快、更现代的 `es-toolkit` 的 [`fill`](../../../reference/array/fill.md)。 + +::: + +用指定的值填充数组的元素。 + +```typescript +const result = fill(array, value, start, end); +``` + +## 用法 + +### `fill(array, value, start?, end?)` + +当您想用相同的值填充数组的特定范围或整个数组时,使用 `fill`。它会直接修改原始数组。 + +```typescript +import { fill } from 'es-toolkit/compat'; + +// 填充整个数组 +const arr1 = [1, 2, 3]; +fill(arr1, 'a'); +// 返回: ['a', 'a', 'a'] + +// 填充特定范围 +const arr2 = [1, 2, 3, 4, 5]; +fill(arr2, '*', 1, 4); +// 返回: [1, '*', '*', '*', 5] + +// 使用负数索引 +const arr3 = [1, 2, 3, 4, 5]; +fill(arr3, 'x', -3, -1); +// 返回: [1, 2, 'x', 'x', 5] +``` + +也支持类数组对象。 + +```typescript +import { fill } from 'es-toolkit/compat'; + +const arrayLike = { 0: 1, 1: 2, 2: 3, length: 3 }; +fill(arrayLike, 'a', 1, 2); +// 返回: { 0: 1, 1: 'a', 2: 3, length: 3 } +``` + +`null` 或 `undefined` 数组被视为空数组。 + +```typescript +import { fill } from 'es-toolkit/compat'; + +fill(null, 'a'); +// 返回: [] + +fill(undefined, 'a'); +// 返回: [] +``` + +字符串是只读的,因此按原样返回。 + +```typescript +import { fill } from 'es-toolkit/compat'; + +fill('abc', 'x'); +// 返回: 'abc' (未修改) +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要填充的数组。 +- `value` (`U`): 用于填充数组的值。 +- `start` (`number`, 可选): 起始位置。默认为 `0`。 +- `end` (`number`, 可选): 结束位置(不包括)。默认为 `array.length`。 + +#### 返回值 + +(`ArrayLike`): 返回用值填充的数组。 diff --git a/docs/zh_hans/reference/compat/array/filter.md b/docs/zh_hans/compat/reference/array/filter.md similarity index 100% rename from docs/zh_hans/reference/compat/array/filter.md rename to docs/zh_hans/compat/reference/array/filter.md diff --git a/docs/zh_hans/reference/compat/array/find.md b/docs/zh_hans/compat/reference/array/find.md similarity index 100% rename from docs/zh_hans/reference/compat/array/find.md rename to docs/zh_hans/compat/reference/array/find.md diff --git a/docs/zh_hans/reference/compat/array/findIndex.md b/docs/zh_hans/compat/reference/array/findIndex.md similarity index 100% rename from docs/zh_hans/reference/compat/array/findIndex.md rename to docs/zh_hans/compat/reference/array/findIndex.md diff --git a/docs/zh_hans/reference/compat/array/findLast.md b/docs/zh_hans/compat/reference/array/findLast.md similarity index 100% rename from docs/zh_hans/reference/compat/array/findLast.md rename to docs/zh_hans/compat/reference/array/findLast.md diff --git a/docs/zh_hans/reference/compat/array/findLastIndex.md b/docs/zh_hans/compat/reference/array/findLastIndex.md similarity index 100% rename from docs/zh_hans/reference/compat/array/findLastIndex.md rename to docs/zh_hans/compat/reference/array/findLastIndex.md diff --git a/docs/zh_hans/compat/reference/array/first.md b/docs/zh_hans/compat/reference/array/first.md new file mode 100644 index 000000000..2863b3631 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/first.md @@ -0,0 +1,78 @@ +# first (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `head` + +此 `first` 函数由于处理 `null` 或 `undefined` 和类数组对象转换而运行较慢。`es-toolkit` 的 `head` 函数没有这些额外处理,运行更快、更简单。 + +请改用更快、更现代的 `es-toolkit` 的 [head](../../../reference/array/head.md)。 + +::: + +返回数组的第一个元素。 + +```typescript +const firstElement = first(array); +``` + +## 用法 + +### `first(array)` + +当您想要获取数组的第一个元素时使用 `first`。如果数组为空或为 `null` 或 `undefined`,则返回 `undefined`。 + +```typescript +import { first } from 'es-toolkit/compat'; + +// 从常规数组获取第一个元素 +first([1, 2, 3]); +// Returns: 1 + +// 从字符串数组获取第一个元素 +first(['a', 'b', 'c']); +// Returns: 'a' + +// 空数组 +first([]); +// Returns: undefined +``` + +`null` 或 `undefined` 返回 `undefined`。 + +```typescript +import { first } from 'es-toolkit/compat'; + +first(null); // undefined +first(undefined); // undefined +``` + +可用于类数组对象。 + +```typescript +import { first } from 'es-toolkit/compat'; + +const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; +first(arrayLike); +// Returns: 'a' + +// 字符串也被视为数组 +first('hello'); +// Returns: 'h' +``` + +对于类型保证的元组,返回确切的类型。 + +```typescript +import { first } from 'es-toolkit/compat'; + +const tuple = [1, 'two', true] as const; +first(tuple); +// Returns: 1 (类型推断为 1) +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要获取第一个元素的数组。 + +#### 返回值 + +(`T | undefined`): 返回数组的第一个元素。如果数组为空或无效,则返回 `undefined`。 diff --git a/docs/zh_hans/compat/reference/array/flatMap.md b/docs/zh_hans/compat/reference/array/flatMap.md new file mode 100644 index 000000000..1f5357b13 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/flatMap.md @@ -0,0 +1,77 @@ +# flatMap (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `flatMap` + +此 `flatMap` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等而运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [flatMap](../../../reference/array/flatMap.md)。 + +::: + +对每个元素应用函数并展平结果。 + +```typescript +const result = flatMap(collection, iteratee); +``` + +## 用法 + +### `flatMap(collection, iteratee)` + +对集合的每个元素应用迭代函数并返回展平一层的数组。支持数组、对象和字符串,可以使用各种形式的迭代器。 + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +// 对数组应用函数 +function duplicate(n) { + return [n, n]; +} +flatMap([1, 2], duplicate); +// 结果: [1, 1, 2, 2] + +// 对对象应用函数 +const obj = { a: 1, b: 2 }; +flatMap(obj, (value, key) => [key, value]); +// 结果: ['a', 1, 'b', 2] + +// 使用字符串属性映射 +const users = [ + { user: 'barney', hobbies: ['hiking', 'coding'] }, + { user: 'fred', hobbies: ['reading'] }, +]; +flatMap(users, 'hobbies'); +// 结果: ['hiking', 'coding', 'reading'] +``` + +不使用迭代器时将值展平一层。 + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +const obj = { a: [1, 2], b: [3, 4] }; +flatMap(obj); +// 结果: [1, 2, 3, 4] +``` + +也可以使用部分对象进行条件映射。 + +```typescript +import { flatMap } from 'es-toolkit/compat'; + +const users = [ + { user: 'barney', age: 36, active: true }, + { user: 'fred', age: 40, active: false }, +]; +flatMap(users, { active: false }); +// 结果: [false, true] (active 为 false 的元素的匹配结果) +``` + +#### 参数 + +- `collection` (`object | null | undefined`): 要迭代的集合。可以是数组、对象或字符串。 +- `iteratee` (`ListIterator | ObjectIterator | string | object`, 可选): 应用于每个元素的迭代器。可以是函数、属性名或部分对象。 + +#### 返回值 + +(`any[]`): 返回映射后展平一层的新数组。 diff --git a/docs/zh_hans/compat/reference/array/flatMapDeep.md b/docs/zh_hans/compat/reference/array/flatMapDeep.md new file mode 100644 index 000000000..ff115b33c --- /dev/null +++ b/docs/zh_hans/compat/reference/array/flatMapDeep.md @@ -0,0 +1,77 @@ +# flatMapDeep (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [`flatMapDeep`](../../../reference/array/flatMapDeep.md) + +此 `flatMapDeep` 函数由于复杂的集合类型处理和深度展平逻辑而运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [flatMapDeep](../../../reference/array/flatMapDeep.md)。 + +::: + +对每个元素应用函数并递归展平结果。 + +```typescript +const result = flatMapDeep(collection, iteratee); +``` + +## 用法 + +### `flatMapDeep(collection, iteratee)` + +对集合的每个元素应用迭代函数并返回展平到无限深度的数组。所有嵌套的数组结构都将被展平为一维数组。 + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +// 对数组应用函数并深度展平 +function duplicate(n) { + return [[[n, n]]]; +} +flatMapDeep([1, 2], duplicate); +// 结果: [1, 1, 2, 2] + +// 对对象应用函数并深度展平 +const obj = { a: 1, b: 2 }; +flatMapDeep(obj, (value, key) => [[[key, value]]]); +// 结果: ['a', 1, 'b', 2] + +// 使用字符串属性映射并深度展平 +const users = [ + { user: 'barney', hobbies: [['hiking', 'coding']] }, + { user: 'fred', hobbies: [['reading']] }, +]; +flatMapDeep(users, 'hobbies'); +// 结果: ['hiking', 'coding', 'reading'] +``` + +不使用迭代器时递归展平值。 + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +const obj = { a: [[1, 2]], b: [[[3]]] }; +flatMapDeep(obj); +// 结果: [1, 2, 3] +``` + +也可以使用部分对象进行条件映射。 + +```typescript +import { flatMapDeep } from 'es-toolkit/compat'; + +const users = [ + { user: 'barney', active: [true, false] }, + { user: 'fred', active: [false] }, +]; +flatMapDeep(users, { active: [false] }); +// 结果: [true, true] (active 数组包含 [false] 的元素的匹配结果) +``` + +#### 参数 + +- `collection` (`object | null | undefined`): 要迭代的集合。可以是数组、对象或字符串。 +- `iteratee` (`ListIterator | ObjectIterator | string | object`, 可选): 应用于每个元素的迭代器。可以是函数、属性名或部分对象。 + +#### 返回值 + +(`any[]`): 返回映射后递归展平的新数组。 diff --git a/docs/zh_hans/compat/reference/array/flatMapDepth.md b/docs/zh_hans/compat/reference/array/flatMapDepth.md new file mode 100644 index 000000000..e482b1e9d --- /dev/null +++ b/docs/zh_hans/compat/reference/array/flatMapDepth.md @@ -0,0 +1,79 @@ +# flatMapDepth (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [flatMap](../../../reference/array/flatMap.md) + +此 `flatMapDepth` 函数为了 Lodash 兼容性支持各种形式的迭代器和处理 `null` 或 `undefined`,实现较为复杂。主库中的 `flatMap` 函数仅支持简单的函数迭代器,因此运行更快。 + +请改用更快、更现代的 `es-toolkit` 的 [flatMap](../../../reference/array/flatMap.md)。 + +::: + +使用迭代函数转换数组的每个元素并展平到指定深度。 + +```typescript +const result = flatMapDepth(collection, iteratee, depth); +``` + +## 用法 + +### `flatMapDepth(collection, iteratee, depth)` + +使用给定函数转换数组或对象的每个元素,然后将结果展平到指定深度并返回新数组。当您想将嵌套的数组结构仅展平到所需深度时很有用。 + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +// 转换数组并展平到深度2 +flatMapDepth([1, 2], n => [[n, n]], 2); +// => [1, 1, 2, 2] + +// 限制为深度1时不会完全展平 +flatMapDepth([1, 2], n => [[n, n]], 1); +// => [[1, 1], [2, 2]] + +// 从对象提取值并展平 +const users = [ + { user: 'barney', hobbies: [['hiking'], ['coding']] }, + { user: 'fred', hobbies: [['reading']] }, +]; +flatMapDepth(users, 'hobbies', 2); +// => ['hiking', 'coding', 'reading'] +``` + +此函数支持各种形式的迭代器。 + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +// 使用函数转换 +flatMapDepth([1, 2, 3], n => [[n, n]], 2); + +// 按属性名提取值 +const objects = [{ items: [['a'], ['b']] }, { items: [['c']] }]; +flatMapDepth(objects, 'items', 2); +// => ['a', 'b', 'c'] + +// 使用对象部分匹配 +const users = [{ active: [[true], [false]] }, { active: [[false]] }]; +flatMapDepth(users, { active: [[false]] }, 2); +// => [true, true] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { flatMapDepth } from 'es-toolkit/compat'; + +flatMapDepth(null, n => [n], 1); // => [] +flatMapDepth(undefined, n => [n], 1); // => [] +``` + +#### 参数 + +- `collection` (`ArrayLike | Record | Record | object | null | undefined`): 要迭代的数组或对象。 +- `iteratee` (`((value: T, index: number, collection: any) => any) | string | object`, 可选): 对每个元素执行的转换函数或属性名。默认为 `identity`。 +- `depth` (`number`, 可选): 要展平的最大深度。默认为 `1`。 + +#### 返回值 + +(`T[]`): 返回使用迭代器转换后展平到指定深度的新数组。 diff --git a/docs/zh_hans/compat/reference/array/flatten.md b/docs/zh_hans/compat/reference/array/flatten.md new file mode 100644 index 000000000..71768e1d0 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/flatten.md @@ -0,0 +1,69 @@ +# flatten (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `flatten` + +此 `flatten` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等而运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [flatten](../../../reference/array/flatten.md)。 + +::: + +将数组展平一层。 + +```typescript +const result = flatten(array, depth); +``` + +## 用法 + +### `flatten(value, depth)` + +按指定深度展平嵌套数组。默认情况下只展平一层,并且还支持 Arguments 对象和具有 Symbol.isConcatSpreadable 的对象。 + +```typescript +import { flatten } from 'es-toolkit/compat'; + +// 基本展平(一层) +flatten([1, [2, [3, [4]], 5]]); +// 结果: [1, 2, [3, [4]], 5] + +// 指定深度 +flatten([1, [2, [3, [4]], 5]], 2); +// 结果: [1, 2, 3, [4], 5] + +// 支持 Arguments 对象 +function example() { + return flatten(arguments); +} +example(1, [2, 3], [[4]]); +// 结果: [1, 2, 3, [4]] +``` + +空数组、null 或 undefined 返回空数组。 + +```typescript +import { flatten } from 'es-toolkit/compat'; + +flatten(null); // [] +flatten(undefined); // [] +flatten([]); // [] +``` + +具有 Symbol.isConcatSpreadable 的对象也像数组一样被展平。 + +```typescript +import { flatten } from 'es-toolkit/compat'; + +const spreadable = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true }; +flatten([1, spreadable, 3]); +// 结果: [1, 'a', 'b', 3] +``` + +#### 参数 + +- `value` (`ArrayLike | null | undefined`): 要展平的数组。 +- `depth` (`number`, 可选): 要展平的最大深度。默认为 `1`。 + +#### 返回值 + +(`T[]`): 返回新的展平数组。 diff --git a/docs/zh_hans/compat/reference/array/flattenDeep.md b/docs/zh_hans/compat/reference/array/flattenDeep.md new file mode 100644 index 000000000..6dfd2bbb3 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/flattenDeep.md @@ -0,0 +1,64 @@ +# flattenDeep (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `flattenDeep` + +此 `flattenDeep` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等而运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [flattenDeep](../../../reference/array/flattenDeep.md)。 + +::: + +完全展平数组。 + +```typescript +const result = flattenDeep(array); +``` + +## 用法 + +### `flattenDeep(value)` + +在所有深度递归展平嵌套数组。移除所有嵌套级别,返回完全展平的一维数组。 + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +// 完全展平深层嵌套数组 +flattenDeep([1, [2, [3, [4]], 5]]); +// 结果: [1, 2, 3, 4, 5] + +// 完全展平复杂嵌套结构 +flattenDeep([1, [2, [3, [[[[4]]]]], 5]]); +// 结果: [1, 2, 3, 4, 5] + +// 支持混合类型 +flattenDeep(['a', ['b', ['c', [['d']]]]]); +// 结果: ['a', 'b', 'c', 'd'] +``` + +空数组、null 或 undefined 返回空数组。 + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +flattenDeep(null); // [] +flattenDeep(undefined); // [] +flattenDeep([]); // [] +``` + +已经展平的数组按原样复制。 + +```typescript +import { flattenDeep } from 'es-toolkit/compat'; + +flattenDeep([1, 2, 3, 4, 5]); +// 结果: [1, 2, 3, 4, 5] +``` + +#### 参数 + +- `value` (`ListOfRecursiveArraysOrValues | null | undefined`): 要完全展平的数组。 + +#### 返回值 + +(`Array`): 返回移除所有嵌套的完全展平的新数组。 diff --git a/docs/zh_hans/compat/reference/array/flattenDepth.md b/docs/zh_hans/compat/reference/array/flattenDepth.md new file mode 100644 index 000000000..ce4a3120b --- /dev/null +++ b/docs/zh_hans/compat/reference/array/flattenDepth.md @@ -0,0 +1,55 @@ +# flattenDepth (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `flatten` + +此 `flattenDepth` 函数由于处理 `null` 或 `undefined` 而运行较慢。`es-toolkit` 的 `flatten` 函数没有这些额外处理,运行更快、更简单。 + +请改用更快、更现代的 `es-toolkit` 的 [flatten](../../../reference/array/flatten.md)。 + +::: + +将数组展平到指定深度。 + +```typescript +const flattened = flattenDepth(array, depth); +``` + +## 用法 + +### `flattenDepth(array, depth)` + +当您想将嵌套数组展平到所需深度时使用 `flattenDepth`。指定深度后,它只会将嵌套数组展平到该深度。 + +```typescript +import { flattenDepth } from 'es-toolkit/compat'; + +// 展平到深度1 +flattenDepth([1, [2, [3, [4]], 5]], 1); +// Returns: [1, 2, [3, [4]], 5] + +// 展平到深度2 +flattenDepth([1, [2, [3, [4]], 5]], 2); +// Returns: [1, 2, 3, [4], 5] + +// 如果未指定深度,默认为1 +flattenDepth([1, [2, [3, [4]], 5]]); +// Returns: [1, 2, [3, [4]], 5] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { flattenDepth } from 'es-toolkit/compat'; + +flattenDepth(null, 2); // [] +flattenDepth(undefined, 2); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要展平的数组。 +- `depth` (`number`, 可选): 要展平的最大深度。默认为 `1`。 + +#### 返回值 + +(`T[]`): 返回展平到指定深度的新数组。 diff --git a/docs/zh_hans/reference/compat/array/forEach.md b/docs/zh_hans/compat/reference/array/forEach.md similarity index 100% rename from docs/zh_hans/reference/compat/array/forEach.md rename to docs/zh_hans/compat/reference/array/forEach.md diff --git a/docs/zh_hans/compat/reference/array/forEachRight.md b/docs/zh_hans/compat/reference/array/forEachRight.md new file mode 100644 index 000000000..c61342c0a --- /dev/null +++ b/docs/zh_hans/compat/reference/array/forEachRight.md @@ -0,0 +1,75 @@ +# forEachRight (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `forEachRight` + +此 `forEachRight` 函数由于处理 `null` 或 `undefined`、处理 `ArrayLike` 类型、支持各种条件函数形式等原因运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [forEachRight](../../../reference/array/forEachRight.md)。 + +::: + +从右到左遍历数组或对象的元素,并对每个元素执行函数。 + +```typescript +forEachRight(collection, callback); +``` + +## 用法 + +### `forEachRight(collection, callback)` + +从右到左顺序遍历数组、对象或字符串,并对每个元素执行回调函数。如果回调返回 `false`,则停止遍历。 + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +// 逆序遍历数组 +forEachRight([1, 2, 3], (value, index) => { + console.log(value, index); +}); +// 输出: 3 2, 2 1, 1 0 + +// 逆序遍历字符串 +forEachRight('abc', (char, index) => { + console.log(char, index); +}); +// 输出: 'c' 2, 'b' 1, 'a' 0 + +// 逆序遍历对象 +forEachRight({ a: 1, b: 2, c: 3 }, (value, key) => { + console.log(value, key); +}); +// 输出: 3 'c', 2 'b', 1 'a' +``` + +`null` 或 `undefined` 按原样返回。 + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +forEachRight(null, value => console.log(value)); // null +forEachRight(undefined, value => console.log(value)); // undefined +``` + +如果回调返回 `false`,则停止遍历。 + +```typescript +import { forEachRight } from 'es-toolkit/compat'; + +forEachRight([1, 2, 3, 4], value => { + console.log(value); + if (value === 2) { + return false; // 停止遍历 + } +}); +// 输出: 4, 3, 2 +``` + +#### 参数 + +- `collection` (`ArrayLike | Record | string | null | undefined`): 要遍历的集合。可以是数组、对象、字符串或 null/undefined。 +- `callback` (`(item: any, index: any, arr: any) => unknown`, 选择): 对每个元素执行的函数。返回 `false` 以停止遍历。默认值是 `identity` 函数。 + +#### 返回值 + +(`ArrayLike | Record | string | null | undefined`): 按原样返回原始集合。 diff --git a/docs/zh_hans/compat/reference/array/groupBy.md b/docs/zh_hans/compat/reference/array/groupBy.md new file mode 100644 index 000000000..5540bc9ab --- /dev/null +++ b/docs/zh_hans/compat/reference/array/groupBy.md @@ -0,0 +1,79 @@ +# groupBy (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [groupBy](../../../reference/array/groupBy.md) + +此 `groupBy` 函数由于处理 `null` 或 `undefined`、对象支持、复杂类型处理等原因运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [groupBy](../../../reference/array/groupBy.md)。 + +::: + +根据给定条件将数组或对象的元素分组。 + +```typescript +const grouped = groupBy(collection, iteratee); +``` + +## 用法 + +### `groupBy(collection, iteratee)` + +根据给定的条件函数对数组或对象的每个元素进行分组,并返回按组分类的对象。条件可以以各种形式提供,如函数、属性名、部分对象等。 + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +// 按函数分组 +const array = [6.1, 4.2, 6.3]; +const result = groupBy(array, Math.floor); +// result 为 { '4': [4.2], '6': [6.1, 6.3] } + +// 按属性名分组 +const users = [ + { name: 'john', age: 30 }, + { name: 'jane', age: 25 }, + { name: 'bob', age: 30 }, +]; +const byAge = groupBy(users, 'age'); +// byAge 为 { '25': [{ name: 'jane', age: 25 }], '30': [{ name: 'john', age: 30 }, { name: 'bob', age: 30 }] } + +// 从对象分组 +const obj = { a: 6.1, b: 4.2, c: 6.3 }; +const groupedObj = groupBy(obj, Math.floor); +// groupedObj 为 { '4': [4.2], '6': [6.1, 6.3] } +``` + +`null` 或 `undefined` 被视为空对象。 + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +groupBy(null, x => x); // {} +groupBy(undefined, x => x); // {} +``` + +也可以按部分对象或属性-值对进行分组。 + +```typescript +import { groupBy } from 'es-toolkit/compat'; + +const products = [ + { category: 'fruit', name: 'apple' }, + { category: 'fruit', name: 'banana' }, + { category: 'vegetable', name: 'carrot' }, +]; + +// 按部分对象分组 +const byCategory = groupBy(products, { category: 'fruit' }); +// 按属性-值对分组 +const byName = groupBy(products, ['name', 'apple']); +``` + +#### 参数 + +- `collection` (`ArrayLike | Record | null | undefined`): 要分组的数组或对象。 +- `iteratee` (`Function | PropertyKey | Array | Object`, 选择): 分组条件。可以是函数、属性名、属性-值对或部分对象。默认值是 `identity` 函数。 + +#### 返回值 + +(`Record`): 返回一个对象,其中每个键是组的条件值,值是属于该组的元素数组。 diff --git a/docs/zh_hans/compat/reference/array/head.md b/docs/zh_hans/compat/reference/array/head.md new file mode 100644 index 000000000..388801826 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/head.md @@ -0,0 +1,61 @@ +# head (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [head](../../../reference/array/head.md) + +此 `head` 函数由于 `ArrayLike` 对象处理和数组转换过程而运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [head](../../../reference/array/head.md)。 + +::: + +返回数组的第一个元素。 + +```typescript +const firstElement = head(array); +``` + +## 用法 + +### `head(array)` + +返回数组或类数组对象的第一个元素。如果数组为空或无效,则返回 `undefined`。 + +```typescript +import { head } from 'es-toolkit/compat'; + +// 数字数组的第一个元素 +const numbers = [1, 2, 3, 4]; +const first = head(numbers); +// first 为 1 + +// 字符串数组的第一个元素 +const strings = ['a', 'b', 'c']; +const firstChar = head(strings); +// firstChar 为 'a' + +// 类数组对象 +const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; +const firstItem = head(arrayLike); +// firstItem 为 'x' +``` + +空数组或无效输入返回 `undefined`。 + +```typescript +import { head } from 'es-toolkit/compat'; + +const emptyArray: number[] = []; +const noElement = head(emptyArray); +// noElement 为 undefined + +head(null); // undefined +head(undefined); // undefined +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要获取第一个元素的数组或类数组对象。 + +#### 返回值 + +(`T | undefined`): 返回数组的第一个元素,如果数组为空或无效,则返回 `undefined`。 diff --git a/docs/zh_hans/reference/compat/array/includes.md b/docs/zh_hans/compat/reference/array/includes.md similarity index 100% rename from docs/zh_hans/reference/compat/array/includes.md rename to docs/zh_hans/compat/reference/array/includes.md diff --git a/docs/zh_hans/reference/compat/array/indexOf.md b/docs/zh_hans/compat/reference/array/indexOf.md similarity index 100% rename from docs/zh_hans/reference/compat/array/indexOf.md rename to docs/zh_hans/compat/reference/array/indexOf.md diff --git a/docs/zh_hans/compat/reference/array/initial.md b/docs/zh_hans/compat/reference/array/initial.md new file mode 100644 index 000000000..09cc8e036 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/initial.md @@ -0,0 +1,65 @@ +# initial (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [initial](../../../reference/array/initial.md) + +此 `initial` 函数由于 `ArrayLike` 对象处理和数组转换过程而运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [initial](../../../reference/array/initial.md)。 + +::: + +返回一个新数组,其中包含数组中除最后一个元素外的所有元素。 + +```typescript +const result = initial(array); +``` + +## 用法 + +### `initial(array)` + +返回一个新数组,其中包含数组或类数组对象中除最后一个元素外的所有元素。如果数组为空或只有一个元素,则返回空数组。 + +```typescript +import { initial } from 'es-toolkit/compat'; + +// 从数字数组中排除最后一个元素 +const numbers = [1, 2, 3, 4]; +const result = initial(numbers); +// result 为 [1, 2, 3] + +// 从字符串数组中排除最后一个元素 +const strings = ['a', 'b', 'c', 'd']; +const withoutLast = initial(strings); +// withoutLast 为 ['a', 'b', 'c'] + +// 类数组对象 +const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; +const items = initial(arrayLike); +// items 为 ['x', 'y'] +``` + +空数组或无效输入返回空数组。 + +```typescript +import { initial } from 'es-toolkit/compat'; + +const emptyArray: number[] = []; +const result = initial(emptyArray); +// result 为 [] + +const singleItem = [42]; +const onlyOne = initial(singleItem); +// onlyOne 为 [] + +initial(null); // [] +initial(undefined); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要排除最后一个元素的数组或类数组对象。 + +#### 返回值 + +(`T[]`): 返回排除最后一个元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/intersection.md b/docs/zh_hans/compat/reference/array/intersection.md new file mode 100644 index 000000000..cc0f6af07 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/intersection.md @@ -0,0 +1,80 @@ +# intersection (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [intersection](../../../reference/array/intersection.md) + +此 `intersection` 函数由于处理 `null` 或 `undefined`、多数组支持、去重过程等原因运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [intersection](../../../reference/array/intersection.md)。 + +::: + +查找多个数组的交集。 + +```typescript +const result = intersection(...arrays); +``` + +## 用法 + +### `intersection(...arrays)` + +查找在所有数组中都存在的元素,并将它们作为新数组返回。结果已去重并保持第一个数组的顺序。 + +```typescript +import { intersection } from 'es-toolkit/compat'; + +// 两个数组的交集 +const array1 = [1, 2, 3, 4]; +const array2 = [2, 3, 5, 6]; +const result = intersection(array1, array2); +// result 为 [2, 3] + +// 三个数组的交集 +const array3 = [3, 4, 7, 8]; +const multiResult = intersection(array1, array2, array3); +// multiResult 为 [3] + +// 字符串数组 +const strings1 = ['a', 'b', 'c']; +const strings2 = ['b', 'c', 'd']; +const stringResult = intersection(strings1, strings2); +// stringResult 为 ['b', 'c'] + +// 类数组对象 +const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; +const arrayLike2 = { 0: 2, 1: 3, 2: 4, length: 3 }; +const likeResult = intersection(arrayLike1, arrayLike2); +// likeResult 为 [2, 3] +``` + +`null` 或 `undefined` 数组被视为空数组。 + +```typescript +import { intersection } from 'es-toolkit/compat'; + +const array1 = [1, 2, 3]; +const result1 = intersection(array1, null); +// result1 为 [] + +const result2 = intersection(null, undefined); +// result2 为 [] +``` + +重复元素会从结果中删除。 + +```typescript +import { intersection } from 'es-toolkit/compat'; + +const array1 = [1, 1, 2, 3]; +const array2 = [1, 2, 2, 4]; +const result = intersection(array1, array2); +// result 为 [1, 2](已去重) +``` + +#### 参数 + +- `...arrays` (`Array | null | undefined>`): 要查找交集的数组。也允许类数组对象、null 或 undefined。 + +#### 返回值 + +(`T[]`): 返回在所有数组中都存在的元素的新数组。已去重并遵循第一个数组的顺序。 diff --git a/docs/zh_hans/compat/reference/array/intersectionBy.md b/docs/zh_hans/compat/reference/array/intersectionBy.md new file mode 100644 index 000000000..ab85da395 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/intersectionBy.md @@ -0,0 +1,93 @@ +# intersectionBy (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [intersectionBy](../../../reference/array/intersectionBy.md) + +此 `intersectionBy` 函数由于复杂的条件处理、多数组支持、属性路径解析等原因运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [intersectionBy](../../../reference/array/intersectionBy.md)。 + +::: + +使用给定的条件函数查找多个数组的交集。 + +```typescript +const result = intersectionBy(...arrays, iteratee); +``` + +## 用法 + +### `intersectionBy(...arrays, iteratee)` + +根据给定条件函数转换后的值,查找多个数组的交集。条件可以以各种形式提供,如函数、属性名、部分对象等。 + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +// 按函数查找交集 +const array1 = [2.1, 1.2]; +const array2 = [2.3, 3.4]; +const result = intersectionBy(array1, array2, Math.floor); +// result 为 [2.1](基于 Math.floor,2 是共同的) + +// 按属性查找交集 +const users1 = [ + { id: 1, name: 'john' }, + { id: 2, name: 'jane' }, +]; +const users2 = [ + { id: 2, name: 'jane' }, + { id: 3, name: 'bob' }, +]; +const byId = intersectionBy(users1, users2, 'id'); +// byId 为 [{ id: 2, name: 'jane' }] + +// 三个数组的交集 +const array3 = [2.5, 4.1]; +const multiResult = intersectionBy(array1, array2, array3, Math.floor); +// multiResult 为 [2.1] + +// 类数组对象 +const arrayLike1 = { 0: { x: 1 }, 1: { x: 2 }, length: 2 }; +const arrayLike2 = { 0: { x: 2 }, 1: { x: 3 }, length: 2 }; +const byProperty = intersectionBy(arrayLike1, arrayLike2, 'x'); +// byProperty 为 [{ x: 2 }] +``` + +`null` 或 `undefined` 数组被视为空数组。 + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +const array1 = [{ x: 1 }, { x: 2 }]; +const result = intersectionBy(array1, null, 'x'); +// result 为 [] +``` + +也可以使用部分对象或属性-值对指定条件。 + +```typescript +import { intersectionBy } from 'es-toolkit/compat'; + +const products1 = [ + { category: 'fruit', name: 'apple' }, + { category: 'vegetable', name: 'carrot' }, +]; +const products2 = [ + { category: 'fruit', name: 'banana' }, + { category: 'meat', name: 'beef' }, +]; + +// 使用部分对象指定条件 +const byCategory = intersectionBy(products1, products2, { category: 'fruit' }); +// 使用属性-值对指定条件 +const byCategoryPair = intersectionBy(products1, products2, ['category', 'fruit']); +``` + +#### 参数 + +- `...arrays` (`Array | null | undefined>`): 要查找交集的数组。 +- `iteratee` (`Function | PropertyKey | Array | Object`): 转换每个元素的条件。可以是函数、属性名、属性-值对或部分对象。 + +#### 返回值 + +(`T[]`): 返回基于转换值在所有数组中都存在的元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/intersectionWith.md b/docs/zh_hans/compat/reference/array/intersectionWith.md new file mode 100644 index 000000000..debb44b56 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/intersectionWith.md @@ -0,0 +1,64 @@ +# intersectionWith (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [intersectionWith](../../../reference/array/intersectionWith.md) + +此 `intersectionWith` 函数由于处理 `null` 或 `undefined`、支持各种重载等原因运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [intersectionWith](../../../reference/array/intersectionWith.md)。 + +::: + +使用自定义比较函数创建在所有数组中找到的共同元素的数组。 + +```typescript +const result = intersectionWith(array, ...otherArrays, comparator); +``` + +## 用法 + +### `intersectionWith(array, ...otherArrays, comparator)` + +使用自定义比较函数查找第一个数组与其余数组的交集。比较函数确定元素是否相等,只返回在所有数组中找到的元素。 + +```typescript +import { intersectionWith } from 'es-toolkit/compat'; + +const objects = [ + { id: 1, name: 'john' }, + { id: 2, name: 'jane' }, +]; +const others = [ + { id: 1, name: 'john' }, + { id: 3, name: 'joe' }, +]; + +intersectionWith(objects, others, (a, b) => a.id === b.id); +// => [{ id: 1, name: 'john' }] + +// 您可以与多个数组进行比较 +const array1 = [{ x: 1 }, { x: 2 }]; +const array2 = [{ x: 1 }, { x: 3 }]; +const array3 = [{ x: 1 }, { x: 4 }]; + +intersectionWith(array1, array2, array3, (a, b) => a.x === b.x); +// => [{ x: 1 }] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { intersectionWith } from 'es-toolkit/compat'; + +intersectionWith(null, [1, 2], (a, b) => a === b); // [] +intersectionWith([1, 2], undefined, (a, b) => a === b); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要比较的第一个数组。 +- `...otherArrays` (`Array | ((a: T, b: T | U) => boolean)>`): 要比较的其他数组和作为最后一个元素的比较函数。 +- `comparator` (`(a: T, b: T | U) => boolean`): 确定两个元素是否相等的函数。 + +#### 返回值 + +(`T[]`): 返回在所有数组中共同找到的元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/invokeMap.md b/docs/zh_hans/compat/reference/array/invokeMap.md similarity index 100% rename from docs/zh_hans/reference/compat/array/invokeMap.md rename to docs/zh_hans/compat/reference/array/invokeMap.md diff --git a/docs/zh_hans/reference/compat/array/join.md b/docs/zh_hans/compat/reference/array/join.md similarity index 100% rename from docs/zh_hans/reference/compat/array/join.md rename to docs/zh_hans/compat/reference/array/join.md diff --git a/docs/zh_hans/compat/reference/array/keyBy.md b/docs/zh_hans/compat/reference/array/keyBy.md new file mode 100644 index 000000000..f1f20b658 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/keyBy.md @@ -0,0 +1,64 @@ +# keyBy (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [keyBy](../../../reference/array/keyBy.md) + +由于需要处理 `null` 或 `undefined`、各种参数类型等,这个 `keyBy` 函数运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [keyBy](../../../reference/array/keyBy.md)。 + +::: + +将集合的元素按指定键组织成对象。 + +```typescript +const result = keyBy(collection, iteratee); +``` + +## 用法 + +### `keyBy(collection, iteratee)` + +使用指定的键生成函数或属性名将数组或对象的每个元素组织成对象。如果有多个元素具有相同的键,则使用最后一个元素。 + +```typescript +import { keyBy } from 'es-toolkit/compat'; + +// 通过属性名生成键 +const array = [ + { dir: 'left', code: 97 }, + { dir: 'right', code: 100 }, +]; + +keyBy(array, 'dir'); +// => { left: { dir: 'left', code: 97 }, right: { dir: 'right', code: 100 } } + +// 使用函数生成键 +keyBy(array, o => String.fromCharCode(o.code)); +// => { a: { dir: 'left', code: 97 }, d: { dir: 'right', code: 100 } } + +// 也可以用于对象 +const obj = { + a: { id: 1, name: 'john' }, + b: { id: 2, name: 'jane' }, +}; +keyBy(obj, 'name'); +// => { john: { id: 1, name: 'john' }, jane: { id: 2, name: 'jane' } } +``` + +`null` 或 `undefined` 被视为空对象。 + +```typescript +import { keyBy } from 'es-toolkit/compat'; + +keyBy(null, 'id'); // {} +keyBy(undefined, 'id'); // {} +``` + +#### 参数 + +- `collection` (`ArrayLike | null | undefined`): 要按键组织的数组或对象。 +- `iteratee` (`ValueIterateeCustom`, 可选): 用于生成键的函数或属性名。如果省略,则使用元素本身作为键。 + +#### 返回值 + +(`Record`): 返回一个新对象,其中每个元素映射到生成的键。 diff --git a/docs/zh_hans/compat/reference/array/last.md b/docs/zh_hans/compat/reference/array/last.md new file mode 100644 index 000000000..b215bb6ea --- /dev/null +++ b/docs/zh_hans/compat/reference/array/last.md @@ -0,0 +1,79 @@ +# last (Lodash兼容性) + +::: warning 使用`es-toolkit`的[last](../../../reference/array/last.md) + +此`last`函数由于处理`null`或`undefined`而变得复杂。 + +请使用更快、更现代的`es-toolkit`的[last](../../../reference/array/last.md)。 + +::: + +返回数组的最后一个元素。 + +```typescript +const lastElement = last(array); +``` + +## 用法 + +### `last(array)` + +当您想获取数组的最后一个元素时使用`last`。如果数组为空,则返回`undefined`。 + +```typescript +import { last } from 'es-toolkit/compat'; + +// 数字数组的最后一个元素 +last([1, 2, 3, 4, 5]); +// Returns: 5 + +// 字符串数组的最后一个元素 +last(['a', 'b', 'c']); +// Returns: 'c' + +// 对象数组的最后一个元素 +const users = [{ name: 'Alice' }, { name: 'Bob' }]; +last(users); +// Returns: { name: 'Bob' } +``` + +空数组或`null`、`undefined`返回`undefined`。 + +```typescript +import { last } from 'es-toolkit/compat'; + +// 空数组 +last([]); +// Returns: undefined + +// null数组 +last(null); +// Returns: undefined + +// undefined数组 +last(undefined); +// Returns: undefined +``` + +也支持类数组对象。 + +```typescript +import { last } from 'es-toolkit/compat'; + +// 类数组对象 +const arrayLike = { 0: 'first', 1: 'second', length: 2 }; +last(arrayLike); +// Returns: 'second' + +// 字符串也是类数组对象 +last('hello'); +// Returns: 'o' +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要获取最后一个元素的数组。 + +#### 返回值 + +(`T | undefined`): 返回数组的最后一个元素,如果数组为空、`null`或`undefined`,则返回`undefined`。 diff --git a/docs/zh_hans/reference/compat/array/lastIndexOf.md b/docs/zh_hans/compat/reference/array/lastIndexOf.md similarity index 100% rename from docs/zh_hans/reference/compat/array/lastIndexOf.md rename to docs/zh_hans/compat/reference/array/lastIndexOf.md diff --git a/docs/zh_hans/reference/compat/array/map.md b/docs/zh_hans/compat/reference/array/map.md similarity index 100% rename from docs/zh_hans/reference/compat/array/map.md rename to docs/zh_hans/compat/reference/array/map.md diff --git a/docs/zh_hans/reference/compat/array/nth.md b/docs/zh_hans/compat/reference/array/nth.md similarity index 100% rename from docs/zh_hans/reference/compat/array/nth.md rename to docs/zh_hans/compat/reference/array/nth.md diff --git a/docs/zh_hans/compat/reference/array/orderBy.md b/docs/zh_hans/compat/reference/array/orderBy.md new file mode 100644 index 000000000..1344e04e2 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/orderBy.md @@ -0,0 +1,82 @@ +# orderBy (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [orderBy](../../../reference/array/orderBy.md) + +由于需要处理 `null` 或 `undefined`、复杂路径导航和各种排序条件,这个 `orderBy` 函数运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [orderBy](../../../reference/array/orderBy.md)。 + +::: + +按多个条件对集合的元素进行排序。 + +```typescript +const result = orderBy(collection, criteria, orders); +``` + +## 用法 + +### `orderBy(collection, criteria, orders)` + +根据指定的条件和排序顺序对数组或对象的元素进行排序。您可以使用多个条件,并为每个条件指定升序 (`'asc'`) 或降序 (`'desc'`) 排序。 + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +const users = [ + { name: 'fred', age: 48 }, + { name: 'barney', age: 34 }, + { name: 'fred', age: 40 }, + { name: 'barney', age: 36 }, +]; + +// 按名称升序、年龄降序排序 +orderBy(users, ['name', 'age'], ['asc', 'desc']); +// => [ +// { name: 'barney', age: 36 }, +// { name: 'barney', age: 34 }, +// { name: 'fred', age: 48 }, +// { name: 'fred', age: 40 } +// ] + +// 使用函数指定排序条件 +orderBy(users, [user => user.name, user => user.age], ['asc', 'desc']); +// => 与上面相同的结果 + +// 按单个条件排序 +orderBy(users, 'age', 'desc'); +// => [{ name: 'fred', age: 48 }, { name: 'fred', age: 40 }, ...] +``` + +对于对象,对值进行排序。 + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +const obj = { + a: { name: 'fred', age: 48 }, + b: { name: 'barney', age: 34 }, +}; + +orderBy(obj, 'age', 'desc'); +// => [{ name: 'fred', age: 48 }, { name: 'barney', age: 34 }] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { orderBy } from 'es-toolkit/compat'; + +orderBy(null, 'name'); // [] +orderBy(undefined, 'age'); // [] +``` + +#### 参数 + +- `collection` (`ArrayLike | object | null | undefined`): 要排序的数组或对象。 +- `criteria` (`Criterion | Array>`, 可选): 排序条件。可以使用属性名称、属性路径、函数等。默认为 `[null]`。 +- `orders` (`unknown | unknown[]`, 可选): 每个条件的排序顺序。可以使用 `'asc'`(升序)、`'desc'`(降序)、`true`(升序)、`false`(降序)。默认为 `[]`。 + +#### 返回值 + +(`T[]`): 返回一个新的已排序数组。 diff --git a/docs/zh_hans/compat/reference/array/partition.md b/docs/zh_hans/compat/reference/array/partition.md new file mode 100644 index 000000000..608e55c8b --- /dev/null +++ b/docs/zh_hans/compat/reference/array/partition.md @@ -0,0 +1,89 @@ +# partition (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [partition](../../../reference/array/partition.md) + +由于需要处理 `null` 或 `undefined` 和各种条件类型,这个 `partition` 函数运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [partition](../../../reference/array/partition.md)。 + +::: + +根据条件将集合的元素分成两组。 + +```typescript +const [truthy, falsy] = partition(collection, predicate); +``` + +## 用法 + +### `partition(collection, predicate)` + +根据给定的条件函数将数组或对象的元素分成两组。第一组包含条件为真的元素,第二组包含条件为假的元素。 + +```typescript +import { partition } from 'es-toolkit/compat'; + +// 将数字数组分成偶数和奇数 +partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); +// => [[2, 4, 6], [1, 3, 5]] + +// 使用属性名称指定条件 +const users = [ + { name: 'john', active: true }, + { name: 'jane', active: false }, + { name: 'bob', active: true }, +]; + +partition(users, 'active'); +// => [ +// [{ name: 'john', active: true }, { name: 'bob', active: true }], +// [{ name: 'jane', active: false }] +// ] + +// 使用对象条件过滤 +partition(users, { active: true }); +// => [ +// [{ name: 'john', active: true }, { name: 'bob', active: true }], +// [{ name: 'jane', active: false }] +// ] + +// 使用数组条件过滤 +partition(users, ['name', 'john']); +// => [ +// [{ name: 'john', active: true }], +// [{ name: 'jane', active: false }, { name: 'bob', active: true }] +// ] +``` + +对于对象,分割值。 + +```typescript +import { partition } from 'es-toolkit/compat'; + +const obj = { + a: { score: 90 }, + b: { score: 40 }, + c: { score: 80 }, +}; + +partition(obj, item => item.score >= 80); +// => [[{ score: 90 }, { score: 80 }], [{ score: 40 }]] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { partition } from 'es-toolkit/compat'; + +partition(null, x => x > 0); // [[], []] +partition(undefined, 'active'); // [[], []] +``` + +#### 参数 + +- `collection` (`ArrayLike | T | null | undefined`): 要分割的数组或对象。 +- `predicate` (`((value: T) => unknown) | Partial | [PropertyKey, any] | PropertyKey`, 可选): 测试每个元素的条件。可以是函数、部分对象、属性-值数组或属性名称。默认为 `identity`。 + +#### 返回值 + +(`[T[], T[]]`): 返回一个数组,包含满足条件的元素数组和不满足条件的元素数组。 diff --git a/docs/zh_hans/compat/reference/array/pull.md b/docs/zh_hans/compat/reference/array/pull.md new file mode 100644 index 000000000..ff9670b72 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/pull.md @@ -0,0 +1,44 @@ +# pull (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [pull](../../../reference/array/pull.md) + +此 `pull` 函数用于 Lodash 兼容性,由于更复杂的类型处理和重载而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [pull](../../../reference/array/pull.md)。 + +::: + +从数组中删除所有指定的值。 + +```typescript +const result = pull(array, ...valuesToRemove); +``` + +## 用法 + +### `pull(array, ...valuesToRemove)` + +从数组中删除所有指定的值并修改原始数组。通过直接修改原始数组而不是复制它可以节省内存。 + +```typescript +import { pull } from 'es-toolkit/compat'; + +// 从数字数组中删除特定值 +const numbers = [1, 2, 3, 2, 4, 2, 5]; +pull(numbers, 2, 3); +console.log(numbers); // [1, 4, 5] + +// 从字符串数组中删除特定值 +const fruits = ['apple', 'banana', 'apple', 'cherry']; +pull(fruits, 'apple'); +console.log(fruits); // ['banana', 'cherry'] +``` + +#### 参数 + +- `array` (`T[]`): 要修改的数组。 +- `...valuesToRemove` (`T[]`): 要从数组中删除的值。 + +#### 返回值 + +(`T[]`): 返回修改后的原始数组。 diff --git a/docs/zh_hans/reference/compat/array/pullAll.md b/docs/zh_hans/compat/reference/array/pullAll.md similarity index 100% rename from docs/zh_hans/reference/compat/array/pullAll.md rename to docs/zh_hans/compat/reference/array/pullAll.md diff --git a/docs/zh_hans/reference/compat/array/pullAllBy.md b/docs/zh_hans/compat/reference/array/pullAllBy.md similarity index 100% rename from docs/zh_hans/reference/compat/array/pullAllBy.md rename to docs/zh_hans/compat/reference/array/pullAllBy.md diff --git a/docs/zh_hans/reference/compat/array/pullAllWith.md b/docs/zh_hans/compat/reference/array/pullAllWith.md similarity index 100% rename from docs/zh_hans/reference/compat/array/pullAllWith.md rename to docs/zh_hans/compat/reference/array/pullAllWith.md diff --git a/docs/zh_hans/compat/reference/array/pullAt.md b/docs/zh_hans/compat/reference/array/pullAt.md new file mode 100644 index 000000000..cad16d3d5 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/pullAt.md @@ -0,0 +1,57 @@ +# pullAt (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [pullAt](../../../reference/array/pullAt.md) + +由于复杂的类型处理和重载,这个 `pullAt` 函数运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [pullAt](../../../reference/array/pullAt.md)。 + +::: + +从数组中删除指定索引处的元素并返回已删除的元素。 + +```typescript +const removed = pullAt(array, ...indexes); +``` + +## 用法 + +### `pullAt(array, ...indexes)` + +从数组中删除指定索引处的元素并返回已删除元素的数组。原始数组会被修改。 + +```typescript +import { pullAt } from 'es-toolkit/compat'; + +// 通过单个索引删除 +const array = [1, 2, 3, 4, 5]; +const removed = pullAt(array, 1, 3); +console.log(array); // [1, 3, 5] +console.log(removed); // [2, 4] + +// 通过索引数组删除 +const colors = ['red', 'green', 'blue', 'yellow']; +const removedColors = pullAt(colors, [0, 2]); +console.log(colors); // ['green', 'yellow'] +console.log(removedColors); // ['red', 'blue'] +``` + +不存在的索引被视为 `undefined`。 + +```typescript +import { pullAt } from 'es-toolkit/compat'; + +const numbers = [10, 20, 30]; +const removed = pullAt(numbers, 1, 5); +console.log(numbers); // [10, 30] +console.log(removed); // [20, undefined] +``` + +#### 参数 + +- `array` (`ArrayLike`): 要修改的数组。 +- `...indexes` (`Array`): 要删除的元素的索引。可以传递单个数字或数字数组。 + +#### 返回值 + +(`ArrayLike`): 返回已删除元素的数组。 diff --git a/docs/zh_hans/reference/compat/array/reduce.md b/docs/zh_hans/compat/reference/array/reduce.md similarity index 100% rename from docs/zh_hans/reference/compat/array/reduce.md rename to docs/zh_hans/compat/reference/array/reduce.md diff --git a/docs/zh_hans/reference/compat/array/reduceRight.md b/docs/zh_hans/compat/reference/array/reduceRight.md similarity index 100% rename from docs/zh_hans/reference/compat/array/reduceRight.md rename to docs/zh_hans/compat/reference/array/reduceRight.md diff --git a/docs/zh_hans/reference/compat/array/reject.md b/docs/zh_hans/compat/reference/array/reject.md similarity index 100% rename from docs/zh_hans/reference/compat/array/reject.md rename to docs/zh_hans/compat/reference/array/reject.md diff --git a/docs/zh_hans/compat/reference/array/remove.md b/docs/zh_hans/compat/reference/array/remove.md new file mode 100644 index 000000000..9a3403efe --- /dev/null +++ b/docs/zh_hans/compat/reference/array/remove.md @@ -0,0 +1,70 @@ +# remove (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `remove` + +此 `remove` 函数为了 Lodash 兼容性支持各种形式的谓词,因此实现较为复杂。主库中的 `remove` 函数仅支持简单的函数谓词,因此运行更快。 + +请改用更快、更现代的 `es-toolkit` 的 [remove](../../../reference/array/remove.md)。 + +::: + +从数组中删除匹配条件的元素并返回被删除的元素。 + +```typescript +const removedElements = remove(array, predicate); +``` + +## 用法 + +### `remove(array, predicate)` + +遍历数组并从原始数组中删除满足给定条件的元素,将删除的元素作为新数组返回。请注意,原始数组会被直接修改。 + +```typescript +import { remove } from 'es-toolkit/compat'; + +// 使用函数条件删除 +const numbers = [1, 2, 3, 4, 5]; +const evens = remove(numbers, n => n % 2 === 0); +console.log(numbers); // => [1, 3, 5] +console.log(evens); // => [2, 4] + +// 使用部分对象匹配删除 +const objects = [{ a: 1 }, { a: 2 }, { a: 3 }]; +const removed = remove(objects, { a: 1 }); +console.log(objects); // => [{ a: 2 }, { a: 3 }] +console.log(removed); // => [{ a: 1 }] + +// 使用属性-值对删除 +const items = [{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }]; +const cherries = remove(items, ['name', 'cherry']); +console.log(items); // => [{ name: 'apple' }, { name: 'banana' }] +console.log(cherries); // => [{ name: 'cherry' }] +``` + +此函数支持各种形式的谓词。 + +```typescript +import { remove } from 'es-toolkit/compat'; + +// 使用函数条件 +remove(users, user => user.active === false); + +// 部分对象匹配 +remove(users, { status: 'inactive' }); + +// 属性-值数组 +remove(users, ['type', 'guest']); + +// 按属性名检查真值 +remove(users, 'isDeleted'); +``` + +#### 参数 + +- `array` (`ArrayLike`): 要修改的数组。 +- `predicate` (`((value: T, index: number, array: ArrayLike) => boolean) | Partial | [keyof T, unknown] | keyof T`, 可选): 对每个元素执行的条件。默认为 `identity`。 + +#### 返回值 + +(`T[]`): 返回由因匹配条件而被删除的元素组成的新数组。 diff --git a/docs/zh_hans/reference/compat/array/reverse.md b/docs/zh_hans/compat/reference/array/reverse.md similarity index 100% rename from docs/zh_hans/reference/compat/array/reverse.md rename to docs/zh_hans/compat/reference/array/reverse.md diff --git a/docs/zh_hans/compat/reference/array/sample.md b/docs/zh_hans/compat/reference/array/sample.md new file mode 100644 index 000000000..30b49cd41 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/sample.md @@ -0,0 +1,54 @@ +# sample(Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [sample](../../../reference/array/sample.md) + +此 `sample` 函数由于 `null` 或 `undefined` 处理、对象值处理等原因运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [sample](../../../reference/array/sample.md)。 + +::: + +从数组或对象中获取一个随机元素。 + +```typescript +const randomItem = sample(collection); +``` + +## 用法 + +### `sample(collection)` + +当需要从数组或对象中选择一个随机元素时,使用 `sample`。对于数组,返回一个随机元素,对于对象,返回一个随机值。 + +```typescript +import { sample } from 'es-toolkit/compat'; + +// 从数组中获取随机元素 +sample([1, 2, 3, 4, 5]); +// 返回1到5之间的随机数字 + +// 从对象中获取随机值 +sample({ a: 1, b: 2, c: 3 }); +// 返回1、2、3中的随机值 + +// 也可以处理字符串 +sample('hello'); +// 返回 'h'、'e'、'l'、'l'、'o' 中的随机字符 +``` + +`null` 或 `undefined` 返回 `undefined`。 + +```typescript +import { sample } from 'es-toolkit/compat'; + +sample(null); // undefined +sample(undefined); // undefined +``` + +#### 参数 + +- `collection` (`ArrayLike | Record | null | undefined`):要采样的数组或对象。 + +#### 返回值 + +(`T | string | undefined`):返回从数组或对象中随机选择的元素。如果集合为空或为 `null`、`undefined`,则返回 `undefined`。 diff --git a/docs/zh_hans/compat/reference/array/sampleSize.md b/docs/zh_hans/compat/reference/array/sampleSize.md new file mode 100644 index 000000000..6842509fd --- /dev/null +++ b/docs/zh_hans/compat/reference/array/sampleSize.md @@ -0,0 +1,54 @@ +# sampleSize(Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [sampleSize](../../../reference/array/sampleSize.md) + +此 `sampleSize` 函数由于 `null` 或 `undefined` 处理、对象支持、默认值处理等原因运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [sampleSize](../../../reference/array/sampleSize.md)。 + +::: + +从数组或对象中随机选择指定数量的元素。 + +```typescript +const sampled = sampleSize(collection, size); +``` + +## 用法 + +### `sampleSize(collection, size?)` + +当需要从数组或对象中随机选择元素时,使用 `sampleSize`。它使用 Floyd 算法进行高效的无重复采样。 + +```typescript +import { sampleSize } from 'es-toolkit/compat'; + +// 从数组中随机选择3个元素。 +sampleSize([1, 2, 3, 4, 5], 3); +// 返回值:[2, 4, 5](实际结果可能不同) + +// 从对象中随机选择2个值。 +sampleSize({ a: 1, b: 2, c: 3, d: 4 }, 2); +// 返回值:[2, 4](实际结果可能不同) +``` + +`null` 或 `undefined` 作为空数组处理。 + +```typescript +import { sampleSize } from 'es-toolkit/compat'; + +sampleSize(null, 2); +// 返回值:[] + +sampleSize(undefined, 2); +// 返回值:[] +``` + +#### 参数 + +- `collection` (`Record | Record | T | null | undefined`):要采样的数组或对象。 +- `size` (`number`,可选):要选择的元素数量。默认值为 `1`。 + +#### 返回值 + +(`T[]`):返回由随机选择的元素组成的新数组。 diff --git a/docs/zh_hans/compat/reference/array/shuffle.md b/docs/zh_hans/compat/reference/array/shuffle.md new file mode 100644 index 000000000..183477ecf --- /dev/null +++ b/docs/zh_hans/compat/reference/array/shuffle.md @@ -0,0 +1,60 @@ +# shuffle(Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `shuffle` + +此 `shuffle` 函数为了与 Lodash 兼容而包含额外的处理,运行缓慢。 + +请使用更快、更现代的 `es-toolkit` 的 [shuffle](../../../reference/array/shuffle.md)。 + +::: + +随机打乱数组或对象的元素并返回新数组。 + +```typescript +const result = shuffle(collection); +``` + +## 用法 + +### `shuffle(collection)` + +使用 Fisher-Yates 算法随机打乱数组或对象的元素并返回新数组。不会修改原数组。 + +```typescript +import { shuffle } from 'es-toolkit/compat'; + +// 打乱数字数组 +const numbers = [1, 2, 3, 4, 5]; +const shuffled1 = shuffle(numbers); +// 返回值:例如 [3, 1, 5, 2, 4](每次顺序不同) + +// 打乱字符串数组 +const fruits = ['apple', 'banana', 'cherry', 'date']; +const shuffled2 = shuffle(fruits); +// 返回值:例如 ['cherry', 'apple', 'date', 'banana'] + +// 打乱对象的值 +const obj = { a: 1, b: 2, c: 3, d: 4 }; +const shuffled3 = shuffle(obj); +// 返回值:例如 [3, 1, 4, 2](对象值被随机打乱) +``` + +`null` 或 `undefined` 作为空数组处理。 + +```typescript +import { shuffle } from 'es-toolkit/compat'; + +shuffle(null); +// 返回值:[] + +shuffle(undefined); +// 返回值:[] +``` + +#### 参数 + +- `collection` (`ArrayLike | T | null | undefined`):要打乱的数组或对象。 + +#### 返回值 + +(`T[]`):返回元素被随机打乱的新数组。 diff --git a/docs/zh_hans/reference/compat/array/size.md b/docs/zh_hans/compat/reference/array/size.md similarity index 100% rename from docs/zh_hans/reference/compat/array/size.md rename to docs/zh_hans/compat/reference/array/size.md diff --git a/docs/zh_hans/reference/compat/array/slice.md b/docs/zh_hans/compat/reference/array/slice.md similarity index 100% rename from docs/zh_hans/reference/compat/array/slice.md rename to docs/zh_hans/compat/reference/array/slice.md diff --git a/docs/zh_hans/reference/compat/array/some.md b/docs/zh_hans/compat/reference/array/some.md similarity index 100% rename from docs/zh_hans/reference/compat/array/some.md rename to docs/zh_hans/compat/reference/array/some.md diff --git a/docs/zh_hans/reference/compat/array/sortBy.md b/docs/zh_hans/compat/reference/array/sortBy.md similarity index 100% rename from docs/zh_hans/reference/compat/array/sortBy.md rename to docs/zh_hans/compat/reference/array/sortBy.md diff --git a/docs/zh_hans/reference/compat/array/sortedIndex.md b/docs/zh_hans/compat/reference/array/sortedIndex.md similarity index 100% rename from docs/zh_hans/reference/compat/array/sortedIndex.md rename to docs/zh_hans/compat/reference/array/sortedIndex.md diff --git a/docs/zh_hans/reference/compat/array/sortedIndexBy.md b/docs/zh_hans/compat/reference/array/sortedIndexBy.md similarity index 100% rename from docs/zh_hans/reference/compat/array/sortedIndexBy.md rename to docs/zh_hans/compat/reference/array/sortedIndexBy.md diff --git a/docs/zh_hans/reference/compat/array/sortedIndexOf.md b/docs/zh_hans/compat/reference/array/sortedIndexOf.md similarity index 100% rename from docs/zh_hans/reference/compat/array/sortedIndexOf.md rename to docs/zh_hans/compat/reference/array/sortedIndexOf.md diff --git a/docs/zh_hans/reference/compat/array/sortedLastIndex.md b/docs/zh_hans/compat/reference/array/sortedLastIndex.md similarity index 100% rename from docs/zh_hans/reference/compat/array/sortedLastIndex.md rename to docs/zh_hans/compat/reference/array/sortedLastIndex.md diff --git a/docs/zh_hans/reference/compat/array/sortedLastIndexBy.md b/docs/zh_hans/compat/reference/array/sortedLastIndexBy.md similarity index 100% rename from docs/zh_hans/reference/compat/array/sortedLastIndexBy.md rename to docs/zh_hans/compat/reference/array/sortedLastIndexBy.md diff --git a/docs/zh_hans/reference/compat/array/sortedLastIndexOf.md b/docs/zh_hans/compat/reference/array/sortedLastIndexOf.md similarity index 100% rename from docs/zh_hans/reference/compat/array/sortedLastIndexOf.md rename to docs/zh_hans/compat/reference/array/sortedLastIndexOf.md diff --git a/docs/zh_hans/compat/reference/array/tail.md b/docs/zh_hans/compat/reference/array/tail.md new file mode 100644 index 000000000..024876d74 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/tail.md @@ -0,0 +1,58 @@ +# tail (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [tail](../../../reference/array/tail.md) + +这个 `tail` 函数由于处理 `null` 或 `undefined` 等原因运行较慢。 + +请使用更快且现代的 `es-toolkit` 的 [tail](../../../reference/array/tail.md) 代替。 + +::: + +返回数组中除第一个元素外的所有元素。 + +```typescript +const result = tail(array); +``` + +## 用法 + +### `tail(array)` + +当您想要创建一个包含输入数组中除第一个元素外所有元素的新数组时,使用 `tail`。如果输入数组为空或只有一个元素,则返回空数组。 + +```typescript +import { tail } from 'es-toolkit/compat'; + +// 从数字数组中删除第一个元素。 +tail([1, 2, 3]); +// Returns: [2, 3] + +// 从字符串数组中删除第一个元素。 +tail(['a', 'b', 'c']); +// Returns: ['b', 'c'] + +// 只有一个元素的数组。 +tail([1]); +// Returns: [] + +// 空数组。 +tail([]); +// Returns: [] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { tail } from 'es-toolkit/compat'; + +tail(null); // [] +tail(undefined); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要删除第一个元素的数组。 + +#### 返回值 + +(`T[]`): 返回包含除第一个元素外的所有元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/take.md b/docs/zh_hans/compat/reference/array/take.md new file mode 100644 index 000000000..01e35be2a --- /dev/null +++ b/docs/zh_hans/compat/reference/array/take.md @@ -0,0 +1,56 @@ +# take (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [take](../../../reference/array/take.md) + +这个 `take` 函数由于包含与 Lodash 兼容的额外处理而运行较慢。 + +请使用更快且现代的 `es-toolkit` 的 [take](../../../reference/array/take.md) 代替。 + +::: + +从数组开头获取指定数量的元素并创建一个新数组。 + +```typescript +const result = take([1, 2, 3, 4, 5], 3); +// result 变为 [1, 2, 3]。 +``` + +## 用法 + +### `take(array, count)` + +从数组开头获取指定数量的元素并返回一个新数组。如果 `count` 大于数组长度,则返回整个数组。 + +```typescript +import { take } from 'es-toolkit/compat'; + +// 基本用法 +const numbers = [1, 2, 3, 4, 5]; +const result1 = take(numbers, 3); +// Returns: [1, 2, 3] + +// 请求的数量大于数组长度 +const result2 = take(numbers, 10); +// Returns: [1, 2, 3, 4, 5] (整个数组) + +// 请求 0 个元素 +const result3 = take(numbers, 0); +// Returns: [] + +// 处理空数组 +const result4 = take([], 3); +// Returns: [] + +// 处理负数 +const result5 = take(numbers, -1); +// Returns: [] +``` + +#### 参数 + +- `array` (`T[]`): 要获取元素的数组。 +- `count` (`number`): 要获取的元素数量。默认值为 1。 + +#### 返回值 + +(`T[]`): 包含从开头获取的指定数量元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/takeRight.md b/docs/zh_hans/compat/reference/array/takeRight.md new file mode 100644 index 000000000..35a2fe526 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/takeRight.md @@ -0,0 +1,63 @@ +# takeRight (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [takeRight](../../../reference/array/takeRight.md) + +这个 `takeRight` 函数由于处理 `null` 或 `undefined` 等原因运行较慢。 + +请使用更快且现代的 `es-toolkit` 的 [takeRight](../../../reference/array/takeRight.md) 代替。 + +::: + +从数组末尾获取指定数量的元素。 + +```typescript +const result = takeRight(array, count); +``` + +## 用法 + +### `takeRight(array, count)` + +当您想要从数组末尾获取指定数量的元素来创建新数组时,使用 `takeRight`。如果请求的数量大于数组长度,则返回整个数组。 + +```typescript +import { takeRight } from 'es-toolkit/compat'; + +// 从数字数组中获取末尾的 2 个元素。 +takeRight([1, 2, 3, 4, 5], 2); +// Returns: [4, 5] + +// 从字符串数组中获取末尾的 3 个元素。 +takeRight(['a', 'b', 'c'], 2); +// Returns: ['b', 'c'] + +// 当请求的数量大于数组长度时 +takeRight([1, 2, 3], 5); +// Returns: [1, 2, 3] + +// 请求 0 个元素 +takeRight([1, 2, 3], 0); +// Returns: [] + +// 请求负数 +takeRight([1, 2, 3], -1); +// Returns: [] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { takeRight } from 'es-toolkit/compat'; + +takeRight(null, 2); // [] +takeRight(undefined, 2); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要获取元素的数组。 +- `count` (`number`, 可选): 要获取的元素数量。默认值为 `1`。 + +#### 返回值 + +(`T[]`): 返回包含从末尾获取的指定数量元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/takeRightWhile.md b/docs/zh_hans/compat/reference/array/takeRightWhile.md new file mode 100644 index 000000000..bc9514665 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/takeRightWhile.md @@ -0,0 +1,71 @@ +# takeRightWhile (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [takeRightWhile](../../../reference/array/takeRightWhile.md) + +这个 `takeRightWhile` 函数由于处理 `null` 或 `undefined` 等原因运行较慢。 + +请使用更快且现代的 `es-toolkit` 的 [takeRightWhile](../../../reference/array/takeRightWhile.md) 代替。 + +::: + +在条件满足时从数组末尾获取元素。 + +```typescript +const result = takeRightWhile(array, predicate); +``` + +## 用法 + +### `takeRightWhile(array, predicate)` + +当您想要从数组末尾开始在条件满足时获取元素来创建新数组时,使用 `takeRightWhile`。当条件评估为 false 时停止。 + +```typescript +import { takeRightWhile } from 'es-toolkit/compat'; + +// 使用函数条件 +const numbers = [1, 2, 3, 4, 5]; +takeRightWhile(numbers, x => x > 3); +// Returns: [4, 5] + +// 使用对象属性条件 +const users = [ + { user: 'barney', active: true }, + { user: 'fred', active: false }, + { user: 'pebbles', active: false }, +]; + +takeRightWhile(users, o => !o.active); +// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] + +// 使用部分对象进行条件匹配 +takeRightWhile(users, { active: false }); +// Returns: [{ user: 'pebbles', active: false }] + +// 使用属性-值数组进行条件匹配 +takeRightWhile(users, ['active', false]); +// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] + +// 使用属性名检查真值 +const items = [{ active: false }, { active: true }, { active: true }]; +takeRightWhile(items, 'active'); +// Returns: [{ active: true }, { active: true }] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { takeRightWhile } from 'es-toolkit/compat'; + +takeRightWhile(null, x => x > 0); // [] +takeRightWhile(undefined, x => x > 0); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要处理的数组。 +- `predicate` (`ListIteratee`, 可选): 对每个元素执行的条件。可以是函数、部分对象、属性-值数组或属性名。默认值为恒等函数。 + +#### 返回值 + +(`T[]`): 返回在条件满足时从数组末尾获取的元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/takeWhile.md b/docs/zh_hans/compat/reference/array/takeWhile.md new file mode 100644 index 000000000..b43aed2dc --- /dev/null +++ b/docs/zh_hans/compat/reference/array/takeWhile.md @@ -0,0 +1,71 @@ +# takeWhile (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [takeWhile](../../../reference/array/takeWhile.md) + +这个 `takeWhile` 函数由于处理 `null` 或 `undefined` 等原因运行较慢。 + +请使用更快且现代的 `es-toolkit` 的 [takeWhile](../../../reference/array/takeWhile.md) 代替。 + +::: + +在条件满足时从数组开头获取元素。 + +```typescript +const result = takeWhile(array, predicate); +``` + +## 用法 + +### `takeWhile(array, predicate)` + +当您想要从数组开头开始在条件满足时获取元素来创建新数组时,使用 `takeWhile`。当条件评估为 false 时停止。 + +```typescript +import { takeWhile } from 'es-toolkit/compat'; + +// 使用函数条件 +const numbers = [1, 2, 3, 4, 5]; +takeWhile(numbers, x => x < 3); +// Returns: [1, 2] + +// 使用对象属性条件 +const users = [ + { user: 'barney', active: false }, + { user: 'fred', active: false }, + { user: 'pebbles', active: true }, +]; + +takeWhile(users, o => !o.active); +// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] + +// 使用部分对象进行条件匹配 +takeWhile(users, { active: false }); +// Returns: [{ user: 'barney', active: false }] + +// 使用属性-值数组进行条件匹配 +takeWhile(users, ['active', false]); +// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] + +// 使用属性名检查真值 +const items = [{ active: true }, { active: true }, { active: false }]; +takeWhile(items, 'active'); +// Returns: [{ active: true }, { active: true }] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { takeWhile } from 'es-toolkit/compat'; + +takeWhile(null, x => x > 0); // [] +takeWhile(undefined, x => x > 0); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要处理的数组。 +- `predicate` (`ListIteratee`, 可选): 对每个元素执行的条件。可以是函数、部分对象、属性-值数组或属性名。默认值为恒等函数。 + +#### 返回值 + +(`T[]`): 返回在条件满足时从数组开头获取的元素的新数组。 diff --git a/docs/zh_hans/compat/reference/array/union.md b/docs/zh_hans/compat/reference/array/union.md new file mode 100644 index 000000000..792ebb10e --- /dev/null +++ b/docs/zh_hans/compat/reference/array/union.md @@ -0,0 +1,62 @@ +# union (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [union](../../../reference/array/union.md) + +此 `union` 函数由于复杂的数组处理而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [union](../../../reference/array/union.md)。 + +::: + +从多个数组中创建一个仅包含唯一值的新数组。 + +```typescript +const result = union(...arrays); +``` + +## 用法 + +### `union(...arrays)` + +当您想要合并多个数组并去除重复项以创建仅包含唯一值的新数组时,请使用 `union`。保留每个值首次出现的顺序。 + +```typescript +import { union } from 'es-toolkit/compat'; + +// 合并数字数组 +union([2], [1, 2]); +// 返回: [2, 1] + +// 合并多个数组 +union([2], [1, 2], [2, 3]); +// 返回: [2, 1, 3] + +// 嵌套数组不会被展平 +union([1, 3, 2], [1, [5]], [2, [4]]); +// 返回: [1, 3, 2, [5], [4]] + +// 非数组值会被忽略 +union([0], 3, { '0': 1 }, null, [2, 1]); +// 返回: [0, 2, 1] + +// 类数组对象也会被处理 +union([0], { 0: 'a', length: 1 }, [2, 1]); +// 返回: [0, 'a', 2, 1] +``` + +`null` 或 `undefined` 会被忽略。 + +```typescript +import { union } from 'es-toolkit/compat'; + +union([1, 2], null, undefined, [3, 4]); +// 返回: [1, 2, 3, 4] +``` + +#### 参数 + +- `...arrays` (`Array | null | undefined>`): 要合并的数组。非数组值会被忽略。 + +#### 返回值 + +(`T[]`): 返回一个包含所有数组唯一值的新数组。 diff --git a/docs/zh_hans/compat/reference/array/unionBy.md b/docs/zh_hans/compat/reference/array/unionBy.md new file mode 100644 index 000000000..b304844a9 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/unionBy.md @@ -0,0 +1,66 @@ +# unionBy (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [unionBy](../../../reference/array/unionBy.md) + +此 `unionBy` 函数由于复杂的处理而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [unionBy](../../../reference/array/unionBy.md)。 + +::: + +合并多个数组并根据指定的标准仅保留唯一值。 + +```typescript +const result = unionBy(...arrays, iteratee); +``` + +## 用法 + +### `unionBy(...arrays, iteratee)` + +当您想要合并多个数组并根据给定的标准函数去除重复项以创建仅包含唯一值的新数组时,请使用 `unionBy`。保留每个值首次出现的顺序。 + +```typescript +import { unionBy } from 'es-toolkit/compat'; + +// 通过向下取整比较小数 +unionBy([2.1], [1.2, 2.3], Math.floor); +// 返回: [2.1, 1.2] + +// 通过对象属性比较 +unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); +// 返回: [{ x: 1 }, { x: 2 }] + +// 使用函数比较 +unionBy( + [{ id: 1, name: 'a' }], + [ + { id: 2, name: 'b' }, + { id: 1, name: 'c' }, + ], + item => item.id +); +// 返回: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }] + +// 使用部分对象比较 +unionBy([{ x: 1, y: 1 }], [{ x: 1, y: 2 }], { x: 1 }); +// 返回: [{ x: 1, y: 1 }] +``` + +`null` 或 `undefined` 数组会被忽略。 + +```typescript +import { unionBy } from 'es-toolkit/compat'; + +unionBy([1, 2], null, undefined, [3, 4], x => x); +// 返回: [1, 2, 3, 4] +``` + +#### 参数 + +- `...arrays` (`Array | null | undefined>`): 要合并的数组。 +- `iteratee` (`ValueIteratee`): 确定唯一性的标准。可以是函数、属性名称、部分对象或属性-值数组。 + +#### 返回值 + +(`T[]`): 返回一个根据指定标准去除重复项的唯一值新数组。 diff --git a/docs/zh_hans/compat/reference/array/unionWith.md b/docs/zh_hans/compat/reference/array/unionWith.md new file mode 100644 index 000000000..666428032 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/unionWith.md @@ -0,0 +1,64 @@ +# unionWith (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [unionWith](../../../reference/array/unionWith.md) + +此 `unionWith` 函数由于复杂的处理而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [unionWith](../../../reference/array/unionWith.md)。 + +::: + +合并多个数组并使用比较函数仅保留唯一值。 + +```typescript +const result = unionWith(...arrays, comparator); +``` + +## 用法 + +### `unionWith(...arrays, comparator)` + +当您想要合并多个数组并使用自定义比较函数去除重复项以创建仅包含唯一值的新数组时,请使用 `unionWith`。保留每个值首次出现的顺序。 + +```typescript +import { unionWith } from 'es-toolkit/compat'; + +// 使用自定义比较函数 +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, +]; +const others = [ + { x: 1, y: 1 }, + { x: 1, y: 2 }, +]; + +unionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); +// 返回: [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 1, y: 1 }] + +// 简单的相等性比较 +unionWith([1, 2], [2, 3], (a, b) => a === b); +// 返回: [1, 2, 3] + +// 按字符串长度比较 +unionWith(['ab', 'cd'], ['ef', 'gh', 'ab'], (a, b) => a.length === b.length); +// 返回: ['ab'] +``` + +`null` 或 `undefined` 数组会被忽略。 + +```typescript +import { unionWith } from 'es-toolkit/compat'; + +unionWith([1, 2], null, undefined, [3, 4], (a, b) => a === b); +// 返回: [1, 2, 3, 4] +``` + +#### 参数 + +- `...arrays` (`Array | null | undefined>`): 要合并的数组。 +- `comparator` (`(a: T, b: T) => boolean`): 确定两个值是否相等的比较函数。 + +#### 返回值 + +(`T[]`): 返回一个使用比较函数去除重复项的唯一值新数组。 diff --git a/docs/zh_hans/compat/reference/array/uniq.md b/docs/zh_hans/compat/reference/array/uniq.md new file mode 100644 index 000000000..ae5438153 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/uniq.md @@ -0,0 +1,51 @@ +# uniq (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [uniq](../../../reference/array/uniq.md) + +此 `uniq` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [uniq](../../../reference/array/uniq.md)。 + +::: + +通过从数组中去除重复项来创建一个仅包含唯一元素的新数组。 + +```typescript +const result = uniq([1, 2, 2, 3, 3, 4]); +// result 是 [1, 2, 3, 4]。 +``` + +## 用法 + +### `uniq(array)` + +通过从数组中去除重复项返回一个仅包含唯一元素的新数组。仅保留每个元素的第一次出现,并保留顺序。 + +```typescript +import { uniq } from 'es-toolkit/compat'; + +// 从数字数组中去除重复项 +const numbers = [1, 2, 2, 3, 3, 4, 1]; +const result1 = uniq(numbers); +// 返回: [1, 2, 3, 4] + +// 从字符串数组中去除重复项 +const strings = ['a', 'b', 'b', 'c', 'a']; +const result2 = uniq(strings); +// 返回: ['a', 'b', 'c'] + +// 从对象数组中去除重复项(引用值比较) +const obj1 = { id: 1 }; +const obj2 = { id: 2 }; +const objects = [obj1, obj2, obj1]; +const result3 = uniq(objects); +// 返回: [{ id: 1 }, { id: 2 }] +``` + +#### 参数 + +- `array` (`T[]`): 要处理的数组。 + +#### 返回值 + +(`T[]`): 去除重复项的新数组。 diff --git a/docs/zh_hans/compat/reference/array/uniqBy.md b/docs/zh_hans/compat/reference/array/uniqBy.md new file mode 100644 index 000000000..36bbde273 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/uniqBy.md @@ -0,0 +1,55 @@ +# uniqBy (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [uniqBy](../../../reference/array/uniqBy.md) + +此 `uniqBy` 函数由于处理 `null` 或 `undefined`、复杂参数类型处理等而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [uniqBy](../../../reference/array/uniqBy.md)。 + +::: + +根据转换函数返回的值去除重复项来创建一个唯一元素的新数组。 + +```typescript +const result = uniqBy(array, iteratee); +``` + +## 用法 + +### `uniqBy(array, iteratee)` + +对数组的每个元素应用转换函数,并仅保留转换结果相同的元素中的第一个元素。这在根据对象数组中的特定属性或数字数组中的特定计算结果去除重复项时很有用。 + +```typescript +import { uniqBy } from 'es-toolkit/compat'; + +// 在数字数组中通过 Math.floor 结果去除重复项 +uniqBy([2.1, 1.2, 2.3], Math.floor); +// 返回: [2.1, 1.2] + +// 在对象数组中通过属性去除重复项 +uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); +// 返回: [{ x: 1 }, { x: 2 }] + +// 使用函数去除重复项 +uniqBy([{ name: 'John' }, { name: 'Jane' }, { name: 'John' }], obj => obj.name); +// 返回: [{ name: 'John' }, { name: 'Jane' }] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { uniqBy } from 'es-toolkit/compat'; + +uniqBy(null, Math.floor); // [] +uniqBy(undefined, 'x'); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要去除重复项的数组。 +- `iteratee` (`ValueIteratee`): 要应用于每个元素的转换函数。可以是函数、属性名称、部分对象等。 + +#### 返回值 + +(`T[]`): 返回一个根据转换函数结果去除重复项的新数组。 diff --git a/docs/zh_hans/compat/reference/array/uniqWith.md b/docs/zh_hans/compat/reference/array/uniqWith.md new file mode 100644 index 000000000..6fbe30741 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/uniqWith.md @@ -0,0 +1,60 @@ +# uniqWith (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [uniqWith](../../../reference/array/uniqWith.md) + +此 `uniqWith` 函数由于处理 `null` 或 `undefined`、复杂参数类型处理等而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [uniqWith](../../../reference/array/uniqWith.md)。 + +::: + +使用比较函数去除重复项来创建一个唯一元素的新数组。 + +```typescript +const result = uniqWith(array, comparator); +``` + +## 用法 + +### `uniqWith(array, comparator)` + +使用比较函数比较数组的每个元素来去除重复项。当比较函数返回 `true` 时,两个元素被视为相等,仅保留第一次出现的元素。如果未提供比较函数,默认使用浅相等性比较。 + +```typescript +import { uniqWith } from 'es-toolkit/compat'; + +// 不使用比较函数(浅相等性比较) +uniqWith([1, 2, 2, 3]); +// 返回: [1, 2, 3] + +// 使用自定义比较函数根据奇偶性标准去除重复项 +uniqWith([1, 2, 3, 4], (a, b) => a % 2 === b % 2); +// 返回: [1, 2] + +// 在对象数组中根据属性去除重复项 +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 1, y: 2 }, +]; +uniqWith(objects, (a, b) => a.x === b.x && a.y === b.y); +// 返回: [{ x: 1, y: 2 }, { x: 2, y: 1 }] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { uniqWith } from 'es-toolkit/compat'; + +uniqWith(null); // [] +uniqWith(undefined); // [] +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要去除重复项的数组。 +- `comparator` (`(a: T, b: T) => boolean`, 可选): 比较两个元素是否相等的函数。如果相等则返回 `true`。默认为浅相等性比较。 + +#### 返回值 + +(`T[]`): 返回一个根据比较函数结果去除重复项的新数组。 diff --git a/docs/zh_hans/compat/reference/array/unzip.md b/docs/zh_hans/compat/reference/array/unzip.md new file mode 100644 index 000000000..103d6e28b --- /dev/null +++ b/docs/zh_hans/compat/reference/array/unzip.md @@ -0,0 +1,68 @@ +# unzip (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [unzip](../../../reference/array/unzip.md) + +此 `unzip` 函数由于处理 `null` 或 `undefined`、过滤非数组值等而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [unzip](../../../reference/array/unzip.md)。 + +::: + +将分组数组中相同位置的元素收集到新数组中。 + +```typescript +const result = unzip(array); +``` + +## 用法 + +### `unzip(array)` + +收集嵌套数组中相同索引处的元素并将它们作为新数组返回。执行与 `zip` 函数相反的操作。这在转置矩阵或重组结构化数据时很有用。 + +```typescript +import { unzip } from 'es-toolkit/compat'; + +// 解压混合字符串、布尔值和数字的数组 +const zipped = [ + ['a', true, 1], + ['b', false, 2], +]; +const result = unzip(zipped); +// 返回: [['a', 'b'], [true, false], [1, 2]] + +// 解压数字数组 +const numbers = [ + [1, 4], + [2, 5], + [3, 6], +]; +unzip(numbers); +// 返回: [[1, 2, 3], [4, 5, 6]] + +// 处理不同长度的数组 +const uneven = [ + ['a', 1], + ['b', 2, true], +]; +unzip(uneven); +// 返回: [['a', 'b'], [1, 2], [undefined, true]] +``` + +`null`、`undefined` 或空数组被视为空数组。 + +```typescript +import { unzip } from 'es-toolkit/compat'; + +unzip(null); // [] +unzip(undefined); // [] +unzip([]); // [] +``` + +#### 参数 + +- `array` (`T[][] | ArrayLike> | null | undefined`): 要解压的嵌套数组。每个内部数组中相同位置的元素被收集在一起。 + +#### 返回值 + +(`T[][]`): 返回一个将相同位置的元素收集在一起的新数组。 diff --git a/docs/zh_hans/compat/reference/array/unzipWith.md b/docs/zh_hans/compat/reference/array/unzipWith.md new file mode 100644 index 000000000..f87be970f --- /dev/null +++ b/docs/zh_hans/compat/reference/array/unzipWith.md @@ -0,0 +1,84 @@ +# unzipWith (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `unzipWith` + +此 `unzipWith` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数形式等而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [unzipWith](../../../reference/array/unzipWith.md)。 + +::: + +收集分组数组中相同位置的元素并应用转换函数来创建一个新数组。 + +```typescript +const result = unzipWith(array, iteratee); +``` + +## 用法 + +### `unzipWith(array, iteratee)` + +收集嵌套数组中相同索引处的元素并应用转换函数。类似于 `unzip` 函数,但可以对每个组应用转换函数。如果未提供转换函数,则执行默认的 `unzip` 操作。 + +```typescript +import { unzipWith } from 'es-toolkit/compat'; + +// 将相同位置的元素相加 +unzipWith( + [ + [1, 10, 100], + [2, 20, 200], + ], + (a, b) => a + b +); +// 返回: [3, 30, 300] + +// 不使用转换函数(默认 unzip 操作) +unzipWith([ + [1, 4], + [2, 5], + [3, 6], +]); +// 返回: [[1, 2, 3], [4, 5, 6]] + +// 字符串连接 +unzipWith( + [ + ['a', 'x'], + ['b', 'y'], + ['c', 'z'], + ], + (a, b) => a + b +); +// 返回: ['abc', 'xyz'] + +// 查找最大值 +unzipWith( + [ + [1, 10], + [2, 20], + [3, 5], + ], + Math.max +); +// 返回: [3, 20] +``` + +`null`、`undefined` 或空数组被视为空数组。 + +```typescript +import { unzipWith } from 'es-toolkit/compat'; + +unzipWith(null, (a, b) => a + b); // [] +unzipWith(undefined, (a, b) => a + b); // [] +unzipWith([], (a, b) => a + b); // [] +``` + +#### 参数 + +- `array` (`ArrayLike> | null | undefined`): 要解压的嵌套数组。 +- `iteratee` (`(...values: T[]) => R`, 可选): 要应用于每组元素的转换函数。如果未提供,执行默认的 `unzip` 操作。 + +#### 返回值 + +(`R[]` 或 `T[][]`): 如果提供了转换函数则返回转换结果数组,否则返回解压数组。 diff --git a/docs/zh_hans/compat/reference/array/without.md b/docs/zh_hans/compat/reference/array/without.md new file mode 100644 index 000000000..c0da7867b --- /dev/null +++ b/docs/zh_hans/compat/reference/array/without.md @@ -0,0 +1,49 @@ +# without (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [without](../../../reference/array/without.md) + +此 `without` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [without](../../../reference/array/without.md)。 + +::: + +创建一个从数组中排除指定值的新数组。 + +```typescript +const result = without([1, 2, 3, 4, 5], 2, 4); +// result 是 [1, 3, 5]。 +``` + +## 用法 + +### `without(array, ...values)` + +返回一个从数组中删除指定值的新数组。原始数组不会被修改。 + +```typescript +import { without } from 'es-toolkit/compat'; + +// 从数字数组中删除多个值 +const numbers = [1, 2, 3, 4, 5, 2, 4]; +const result1 = without(numbers, 2, 4); +// 返回: [1, 3, 5] + +// 从字符串数组中删除值 +const fruits = ['apple', 'banana', 'cherry', 'banana']; +const result2 = without(fruits, 'banana'); +// 返回: ['apple', 'cherry'] + +// 处理空数组 +const result3 = without([], 1, 2, 3); +// 返回: [] +``` + +#### 参数 + +- `array` (`T[]`): 要处理的原始数组。 +- `...values` (`T[]`): 要删除的值。 + +#### 返回值 + +(`T[]`): 删除指定值的新数组。 diff --git a/docs/zh_hans/compat/reference/array/xor.md b/docs/zh_hans/compat/reference/array/xor.md new file mode 100644 index 000000000..349d56629 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/xor.md @@ -0,0 +1,61 @@ +# xor (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [xor](../../../reference/array/xor.md) + +此 `xor` 函数由于处理 `null` 或 `undefined`、复杂的重复计算逻辑等而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [xor](../../../reference/array/xor.md)。 + +::: + +创建一个由恰好存在于多个数组中的一个数组中的元素组成的新数组。 + +```typescript +const result = xor(...arrays); +``` + +## 用法 + +### `xor(...arrays)` + +计算多个数组的对称差集。换句话说,返回恰好存在于给定数组中的一个数组中的元素。这在比较两个或多个数组时查找不重叠的唯一元素时很有用。 + +```typescript +import { xor } from 'es-toolkit/compat'; + +// 两个数组的对称差集 +xor([1, 2, 3, 4], [3, 4, 5, 6]); +// 返回: [1, 2, 5, 6] + +// 三个数组的对称差集 +xor([1, 2], [2, 3], [4, 5]); +// 返回: [1, 3, 4, 5] + +// 字符串数组 +xor(['a', 'b'], ['b', 'c']); +// 返回: ['a', 'c'] + +// 仅提供一个数组 +xor([1, 2, 3]); +// 返回: [1, 2, 3] +``` + +`null`、`undefined` 或空数组被忽略,只处理有效数组。 + +```typescript +import { xor } from 'es-toolkit/compat'; + +xor([1, 2], null, [2, 3]); +// 返回: [1, 3] + +xor([], [1, 2], [2, 3]); +// 返回: [1, 3] +``` + +#### 参数 + +- `...arrays` (`Array | null | undefined>`): 要计算对称差集的数组。`null` 或 `undefined` 被忽略。 + +#### 返回值 + +(`T[]`): 返回一个由恰好存在于数组中的一个数组中的元素组成的新数组。 diff --git a/docs/zh_hans/compat/reference/array/xorBy.md b/docs/zh_hans/compat/reference/array/xorBy.md new file mode 100644 index 000000000..dd98b5bed --- /dev/null +++ b/docs/zh_hans/compat/reference/array/xorBy.md @@ -0,0 +1,63 @@ +# xorBy (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [xorBy](../../../reference/array/xorBy.md) + +此 `xorBy` 函数由于处理 `null` 或 `undefined`、复杂的重复计算逻辑等而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [xorBy](../../../reference/array/xorBy.md)。 + +::: + +根据转换函数创建一个由恰好存在于多个数组中的一个数组中的元素组成的新数组。 + +```typescript +const result = xorBy(...arrays, iteratee); +``` + +## 用法 + +### `xorBy(...arrays, iteratee)` + +根据转换函数计算多个数组的对称差集。返回其转换结果恰好存在于数组中的一个数组中的元素。这在根据对象数组中的特定属性或数字数组中的特定计算结果进行比较时很有用。 + +```typescript +import { xorBy } from 'es-toolkit/compat'; + +// 通过 Math.floor 结果计算对称差集 +xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); +// 返回: [1.2, 4.3] + +// 通过对象属性计算对称差集 +xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); +// 返回: [{ x: 2 }] + +// 使用函数计算对称差集 +const users1 = [{ name: 'John', age: 30 }]; +const users2 = [ + { name: 'Jane', age: 25 }, + { name: 'John', age: 30 }, +]; +xorBy(users1, users2, user => user.name); +// 返回: [{ name: 'Jane', age: 25 }] + +// 三个数组的对称差集 +xorBy([1.2, 2.3], [3.4, 4.5], [5.6, 6.7], Math.floor); +// 返回: [1.2, 2.3, 3.4, 4.5, 5.6, 6.7] +``` + +`null` 或 `undefined` 被忽略。 + +```typescript +import { xorBy } from 'es-toolkit/compat'; + +xorBy([2.1, 1.2], null, [4.3, 2.4], Math.floor); +// 返回: [1.2, 4.3] +``` + +#### 参数 + +- `...arrays` (`Array | null | undefined | ValueIteratee>`): 要计算对称差集的数组和末尾的转换函数。可以是函数、属性名称、部分对象等。 + +#### 返回值 + +(`T[]`): 返回一个根据转换函数结果由恰好存在于数组中的一个数组中的元素组成的新数组。 diff --git a/docs/zh_hans/compat/reference/array/xorWith.md b/docs/zh_hans/compat/reference/array/xorWith.md new file mode 100644 index 000000000..85eabab64 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/xorWith.md @@ -0,0 +1,66 @@ +# xorWith (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [xorWith](../../../reference/array/xorWith.md) + +此 `xorWith` 函数由于处理 `null` 或 `undefined`、复杂的重复计算逻辑等而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [xorWith](../../../reference/array/xorWith.md)。 + +::: + +使用比较函数创建一个由恰好存在于多个数组中的一个数组中的元素组成的新数组。 + +```typescript +const result = xorWith(...arrays, comparator); +``` + +## 用法 + +### `xorWith(...arrays, comparator)` + +使用比较函数计算多个数组的对称差集。当比较函数返回 `true` 时,两个元素被视为相等,并返回恰好存在于数组中的一个数组中的元素。这在处理复杂对象或需要自定义比较逻辑时很有用。 + +```typescript +import { xorWith } from 'es-toolkit/compat'; + +// 简单数字比较 +xorWith([1, 2], [2, 3], (a, b) => a === b); +// 返回: [1, 3] + +// 比较对象属性 +const objects = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, +]; +const others = [ + { x: 1, y: 1 }, + { x: 1, y: 2 }, +]; +xorWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); +// 返回: [{ x: 2, y: 1 }, { x: 1, y: 1 }] + +// 三个数组的对称差集 +xorWith([1], [2], [3], (a, b) => a === b); +// 返回: [1, 2, 3] + +// 按字符串长度比较 +xorWith(['hello'], ['world', 'hi'], (a, b) => a.length === b.length); +// 返回: ['hi'] +``` + +如果未提供比较函数,默认使用浅相等性比较。 + +```typescript +import { xorWith } from 'es-toolkit/compat'; + +xorWith([1, 2], [2, 3]); +// 返回: [1, 3] +``` + +#### 参数 + +- `...arrays` (`Array | null | undefined | ((a: T, b: T) => boolean)>`): 要计算对称差集的数组和末尾的比较函数。比较函数应在两个元素相等时返回 `true`。 + +#### 返回值 + +(`T[]`): 返回一个根据比较函数结果由恰好存在于数组中的一个数组中的元素组成的新数组。 diff --git a/docs/zh_hans/compat/reference/array/zip.md b/docs/zh_hans/compat/reference/array/zip.md new file mode 100644 index 000000000..b310de132 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/zip.md @@ -0,0 +1,48 @@ +# zip (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [zip](../../../reference/array/zip.md) + +此 `zip` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [zip](../../../reference/array/zip.md)。 + +::: + +将多个数组组合成一个元组数组。 + +```typescript +const result = zip([1, 2], ['a', 'b']); +// result 是 [[1, 'a'], [2, 'b']]。 +``` + +## 用法 + +### `zip(...arrs)` + +接受多个数组并将每个索引处的元素分组为一个元组来创建一个新数组。如果输入数组的长度不同,结果数组的长度将与最长输入数组的长度相匹配,缺失的元素用 `undefined` 填充。 + +```typescript +import { zip } from 'es-toolkit/compat'; + +const arr1 = [1, 2, 3]; +const arr2 = ['a', 'b', 'c']; +const result = zip(arr1, arr2); +// 返回: [[1, 'a'], [2, 'b'], [3, 'c']] + +// 不同长度的数组 +const arr3 = [true, false]; +const result2 = zip(arr1, arr2, arr3); +// 返回: [[1, 'a', true], [2, 'b', false], [3, 'c', undefined]] + +// 包含空数组 +zip([1, 2], [], ['a', 'b']); +// 返回: [[1, undefined, 'a'], [2, undefined, 'b']] +``` + +#### 参数 + +- `...arrs` (`any[][]`): 要组合的数组。 + +#### 返回值 + +(`any[][]`): 包含输入数组每个索引元素的元组的新数组。 diff --git a/docs/zh_hans/compat/reference/array/zipObject.md b/docs/zh_hans/compat/reference/array/zipObject.md new file mode 100644 index 000000000..6a928e5eb --- /dev/null +++ b/docs/zh_hans/compat/reference/array/zipObject.md @@ -0,0 +1,50 @@ +# zipObject (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [zipObject](../../../reference/array/zipObject.md) + +此 `zipObject` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [zipObject](../../../reference/array/zipObject.md)。 + +::: + +使用两个数组创建一个对象。第一个数组用作属性名称,第二个数组用作相应的值。 + +```typescript +const result = zipObject(keys, values); +``` + +## 用法 + +### `zipObject(keys, values)` + +当您想要从键数组和值数组创建单个对象时,请使用 `zipObject`。它使用第一个数组的元素作为属性名称,第二个数组的元素作为其相应的值。这在处理 API 响应或转换数据时特别有用。 + +```typescript +import { zipObject } from 'es-toolkit/compat'; + +// 基本用法 +const keys = ['a', 'b', 'c']; +const values = [1, 2, 3]; +const result = zipObject(keys, values); +// 返回: { a: 1, b: 2, c: 3 } + +// 不同长度的数组 +const keys2 = ['x', 'y', 'z']; +const values2 = [10, 20]; +const result2 = zipObject(keys2, values2); +// 返回: { x: 10, y: 20, z: undefined } + +// 提供空数组 +const result3 = zipObject([], []); +// 返回: {} +``` + +#### 参数 + +- `keys` (`PropertyKey[]`): 用作属性名称的数组。 +- `values` (`T[]`): 用作属性值的数组。 + +#### 返回值 + +(`Record`): 创建的对象。 diff --git a/docs/zh_hans/reference/compat/array/zipObjectDeep.md b/docs/zh_hans/compat/reference/array/zipObjectDeep.md similarity index 100% rename from docs/zh_hans/reference/compat/array/zipObjectDeep.md rename to docs/zh_hans/compat/reference/array/zipObjectDeep.md diff --git a/docs/zh_hans/compat/reference/array/zipWith.md b/docs/zh_hans/compat/reference/array/zipWith.md new file mode 100644 index 000000000..5d04c4bc0 --- /dev/null +++ b/docs/zh_hans/compat/reference/array/zipWith.md @@ -0,0 +1,47 @@ +# zipWith (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [zipWith](../../../reference/array/zipWith.md) + +此 `zipWith` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [zipWith](../../../reference/array/zipWith.md)。 + +::: + +使用组合函数将多个数组的元素组合成一个新数组。 + +```typescript +const result = zipWith([1, 2], [3, 4], (a, b) => a + b); +// result 是 [4, 6]。 +``` + +## 用法 + +### `zipWith(...arrs, iteratee)` + +接受多个数组并使用提供的函数组合每个索引处的元素来创建一个新数组。如果数组的长度不同,它将处理到最长数组的长度,对于缺失的值传递 `undefined`。 + +```typescript +import { zipWith } from 'es-toolkit/compat'; + +// 将两个数组的元素相加 +const result1 = zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b); +// 返回: [5, 7, 9] + +// 组合三个数组的元素 +const result2 = zipWith([1, 2], [3, 4], [5, 6], (a, b, c) => a + b + c); +// 返回: [9, 12] + +// 不同长度的数组 +const result3 = zipWith([1, 2, 3], [4, 5], (a, b) => (a || 0) + (b || 0)); +// 返回: [5, 7, 3] +``` + +#### 参数 + +- `...arrs` (`any[][]`): 要组合的数组。 +- `iteratee` (`Function`): 组合每个索引处元素的函数。 + +#### 返回值 + +(`any[]`): 应用组合函数的结果组成的新数组。 diff --git a/docs/zh_hans/compat/reference/function/after.md b/docs/zh_hans/compat/reference/function/after.md new file mode 100644 index 000000000..503c1e1a8 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/after.md @@ -0,0 +1,75 @@ +# after (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [`after`](../../../reference/function/after.md) + +由于复杂的类型验证和整数转换处理,此 `after` 函数运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [after](../../../reference/function/after.md)。 + +::: + +创建一个只在被调用指定次数后才执行的函数。 + +```typescript +const restrictedFunction = after(n, func); +``` + +## 用法 + +### `after(n, func)` + +当您想限制函数仅在被调用特定次数后才执行时,请使用 `after`。它在多个异步操作完成后执行回调,或在初始化阶段后激活函数时非常有用。 + +```typescript +import { after } from 'es-toolkit/compat'; + +// 基本用法 +const logAfterThree = after(3, () => { + console.log('从第3次调用开始执行!'); +}); + +logAfterThree(); // 不执行 +logAfterThree(); // 不执行 +logAfterThree(); // 输出 "从第3次调用开始执行!" +logAfterThree(); // 输出 "从第3次调用开始执行!" (继续执行) +``` + +您还可以使用它在所有异步操作完成后执行特定回调。 + +```typescript +import { after } from 'es-toolkit/compat'; + +const tasks = ['task1', 'task2', 'task3']; +const allTasksComplete = after(tasks.length, () => { + console.log('所有任务已完成!'); +}); + +// 每个任务完成时调用 +tasks.forEach(task => { + performAsyncTask(task, () => { + console.log(`${task} 完成`); + allTasksComplete(); // 第3次调用时输出 "所有任务已完成!" + }); +}); +``` + +当传递0或负数时,从第一次调用开始立即执行。 + +```typescript +import { after } from 'es-toolkit/compat'; + +const immediate = after(0, () => console.log('立即执行')); +immediate(); // "立即执行" + +const negative = after(-1, () => console.log('立即执行')); +negative(); // "立即执行" +``` + +#### 参数 + +- `n` (`number`): 函数执行前所需的调用次数。 +- `func` (`TFunc`): 要限制的函数。 + +#### 返回值 + +(`TFunc`): 返回一个新的受限函数,从第 n 次调用开始执行原始函数。 diff --git a/docs/zh_hans/compat/reference/function/ary.md b/docs/zh_hans/compat/reference/function/ary.md new file mode 100644 index 000000000..8797d2414 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/ary.md @@ -0,0 +1,90 @@ +# ary (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [`ary`](../../../reference/function/ary.md) + +由于复杂的参数验证,此 `ary` 函数运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [ary](../../../reference/function/ary.md)。 + +::: + +创建一个限制可接收参数数量的函数。 + +```typescript +const cappedFunction = ary(func, n); +``` + +## 用法 + +### `ary(func, n)` + +当您想限制函数接收的参数数量时,请使用 `ary`。它在安全地使用接收太多参数的函数或在回调函数中忽略不必要的参数时非常有用。 + +```typescript +import { ary } from 'es-toolkit/compat'; + +// 基本用法 +function greet(name, age, city) { + return `你好, ${name}! ${age}岁, 来自${city}。`; +} + +const limitedGreet = ary(greet, 2); +console.log(limitedGreet('张三', 30, '北京', '额外参数')); +// "你好, 张三! 30岁, 来自undefined。" +// 第3个参数之后被忽略 +``` + +与数组方法一起使用时,可以防止不必要的参数传递给回调函数。 + +```typescript +import { ary } from 'es-toolkit/compat'; + +// parseInt接受第二个参数(基数),但map的回调传递3个参数 +const numbers = ['1', '2', '3', '4', '5']; + +// 错误用法 - parseInt将索引作为基数接收 +console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] + +// 使用ary只传递第一个参数 +console.log(numbers.map(ary(parseInt, 1))); // [1, 2, 3, 4, 5] +``` + +可以限制函数只接收所需数量的参数。 + +```typescript +import { ary } from 'es-toolkit/compat'; + +function sum(...args) { + return args.reduce((total, num) => total + num, 0); +} + +const sum0 = ary(sum, 0); +const sum1 = ary(sum, 1); +const sum2 = ary(sum, 2); +const sum3 = ary(sum, 3); + +console.log(sum0(1, 2, 3, 4, 5)); // 0 (无参数) +console.log(sum1(1, 2, 3, 4, 5)); // 1 (仅第一个参数) +console.log(sum2(1, 2, 3, 4, 5)); // 3 (仅前两个参数) +console.log(sum3(1, 2, 3, 4, 5)); // 6 (仅前三个参数) +``` + +当传递负数或 `NaN` 时,会被视为0,所有参数都被忽略。 + +```typescript +import { ary } from 'es-toolkit/compat'; + +const func = (a, b, c) => [a, b, c]; + +console.log(ary(func, -1)(1, 2, 3)); // [] (负数视为0) +console.log(ary(func, NaN)(1, 2, 3)); // [] (NaN视为0) +``` + +#### 参数 + +- `func` (`Function`): 要限制参数数量的函数。 +- `n` (`number`, 可选): 允许的最大参数数量。如果省略,则使用函数的 `length` 属性。 + +#### 返回值 + +(`Function`): 返回一个最多接受 `n` 个参数的新函数。 diff --git a/docs/zh_hans/compat/reference/function/attempt.md b/docs/zh_hans/compat/reference/function/attempt.md new file mode 100644 index 000000000..4ae75224f --- /dev/null +++ b/docs/zh_hans/compat/reference/function/attempt.md @@ -0,0 +1,66 @@ +# attempt (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [`attempt`](../../../reference/util/attempt.md) 函数或 try-catch 块 + +此 `attempt` 函数可能会让人困惑,因为它不区分地返回错误和返回值。 + +请改用更直接和清晰的 [`attempt`](../../../reference/util/attempt.md) 函数或 try-catch 块。 + +::: + +执行函数并在发生错误时返回错误对象的函数。 + +```typescript +const result = attempt(func, ...args); +``` + +## 用法 + +### `attempt(func, ...args)` + +当您想安全地执行函数时使用 `attempt`。在执行可能抛出错误的函数时,它很有用,可以防止程序崩溃并将错误作为返回值处理。 + +```typescript +import { attempt } from 'es-toolkit/compat'; + +// 基本用法 - 成功的情况 +const result = attempt((x, y) => x + y, 2, 3); +console.log(result); // 5 + +// 错误情况 +const errorResult = attempt(() => { + throw new Error('出错了'); +}); +console.log(errorResult); // Error: 出错了 +``` + +以下是与使用 try-catch 块的区别。 + +```typescript +// 使用 attempt +import { attempt } from 'es-toolkit/compat'; + +const result = attempt(riskyFunction, arg1, arg2); +if (result instanceof Error) { + console.log('发生错误:', result.message); +} else { + console.log('结果:', result); +} + +// 使用 try-catch (更直接) +try { + const result = riskyFunction(arg1, arg2); + console.log('结果:', result); +} catch (error) { + console.log('发生错误:', error.message); +} +``` + +#### 参数 + +- `func` (`Function`): 要执行的函数。 +- `args` (`...any[]`): 要传递给函数的参数。 + +#### 返回值 + +(`ReturnType | Error`): 如果函数成功则返回返回值,如果发生错误则返回 Error 对象。 diff --git a/docs/zh_hans/compat/reference/function/before.md b/docs/zh_hans/compat/reference/function/before.md new file mode 100644 index 000000000..6d1d2f2e5 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/before.md @@ -0,0 +1,186 @@ +# before (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [`before`](../../../reference/function/before.md) + +由于复杂的类型验证和整数转换处理,这个 `before` 函数的运行速度较慢。 + +请使用更快、更现代的 `es-toolkit` 的 [before](../../../reference/function/before.md)。 + +::: + +创建一个函数,该函数在指定次数内执行原始函数,之后返回最后一次的结果。 + +```typescript +const limitedFunction = before(n, func); +``` + +## 用法 + +### `before(n, func)` + +当您想要限制函数只执行到特定次数时,请使用 `before`。这对于限制函数调用次数或只在初始设置阶段执行函数时非常有用。 + +```typescript +import { before } from 'es-toolkit/compat'; + +// 基本用法 +let count = 0; +const beforeThree = before(3, () => ++count); + +console.log(beforeThree()); // 1 (第一次调用) +console.log(beforeThree()); // 2 (第二次调用) +console.log(beforeThree()); // 2 (从第三次调用开始返回最后结果) +console.log(beforeThree()); // 2 (继续返回最后结果) +``` + +使用闭包的替代方案: + +```typescript +// 使用 before +const beforeThree = before(3, myFunction); + +// 使用闭包(更简单更快) +function createBefore(limit, callback) { + let callCount = 0; + let lastResult; + + return function (...args) { + if (callCount < limit - 1) { + lastResult = callback.apply(this, args); + callCount++; + } + return lastResult; + }; +} + +const beforeThreeAlternative = createBefore(3, myFunction); +``` + +用作初始化函数: + +```typescript +import { before } from 'es-toolkit/compat'; + +class Database { + constructor() { + this.isInitialized = false; + + // 初始化只执行一次 + this.initialize = before(2, () => { + console.log('正在初始化数据库...'); + this.setupConnection(); + this.isInitialized = true; + return '初始化完成'; + }); + } + + setupConnection() { + // 实际连接设置逻辑 + } + + query(sql) { + const initResult = this.initialize(); + console.log(initResult); // 第一次调用: "初始化完成",之后:相同结果 + + // 查询执行逻辑 + return `执行查询: ${sql}`; + } +} + +const db = new Database(); +db.query('SELECT * FROM users'); // 执行初始化 +db.query('SELECT * FROM products'); // 不执行初始化 +``` + +限制 API 调用: + +```typescript +import { before } from 'es-toolkit/compat'; + +// 最多允许 5 次 API 调用 +const limitedApiCall = before(6, endpoint => { + console.log(`API 调用: ${endpoint}`); + return fetch(endpoint).then(res => res.json()); +}); + +// 前 5 次执行实际的 API 调用 +limitedApiCall('/api/data1'); // 实际调用 +limitedApiCall('/api/data2'); // 实际调用 +limitedApiCall('/api/data3'); // 实际调用 +limitedApiCall('/api/data4'); // 实际调用 +limitedApiCall('/api/data5'); // 实际调用 +limitedApiCall('/api/data6'); // 返回最后结果(不进行 API 调用) +``` + +限制事件监听器: + +```typescript +import { before } from 'es-toolkit/compat'; + +// 最多处理 3 次点击事件 +const limitedClickHandler = before(4, event => { + console.log('处理点击:', event.target.id); + return `处理完成: ${Date.now()}`; +}); + +document.getElementById('button').addEventListener('click', limitedClickHandler); +// 只处理前 3 次点击,之后返回最后结果 +``` + +处理参数和返回值: + +```typescript +import { before } from 'es-toolkit/compat'; + +const limitedCalculator = before(3, (operation, a, b) => { + const result = operation === 'add' ? a + b : a - b; + console.log(`计算: ${a} ${operation} ${b} = ${result}`); + return result; +}); + +console.log(limitedCalculator('add', 5, 3)); // "计算: 5 add 3 = 8",返回: 8 +console.log(limitedCalculator('subtract', 10, 4)); // "计算: 10 subtract 4 = 6",返回: 6 +console.log(limitedCalculator('multiply', 7, 2)); // 不计算,返回: 6(最后结果) +``` + +传递 0 或 1 会使函数不执行: + +```typescript +import { before } from 'es-toolkit/compat'; + +const neverCalled = before(0, () => { + console.log('此函数不会执行'); + return '结果'; +}); + +const onceOnly = before(1, () => { + console.log('此函数也不会执行'); + return '结果'; +}); + +console.log(neverCalled()); // undefined +console.log(onceOnly()); // undefined +``` + +资源清理优化: + +```typescript +import { before } from 'es-toolkit/compat'; + +// 函数引用会自动清理以防止内存泄漏 +const limitedProcessor = before(2, data => { + // 复杂的数据处理 + return processComplexData(data); +}); + +// 第 2 次调用后,原始函数引用被移除(垃圾回收) +``` + +#### 参数 + +- `n` (`number`): 函数执行的最大次数。执行到 n-1 次,从第 n 次调用开始返回最后结果。 +- `func` (`Function`): 要限制的函数。 + +#### 返回值 + +(`Function`): 返回一个新函数,该函数在指定次数内执行原始函数,之后返回最后一次的结果。 diff --git a/docs/zh_hans/reference/compat/function/bind.md b/docs/zh_hans/compat/reference/function/bind.md similarity index 100% rename from docs/zh_hans/reference/compat/function/bind.md rename to docs/zh_hans/compat/reference/function/bind.md diff --git a/docs/zh_hans/reference/compat/function/bindKey.md b/docs/zh_hans/compat/reference/function/bindKey.md similarity index 100% rename from docs/zh_hans/reference/compat/function/bindKey.md rename to docs/zh_hans/compat/reference/function/bindKey.md diff --git a/docs/zh_hans/compat/reference/function/curry.md b/docs/zh_hans/compat/reference/function/curry.md new file mode 100644 index 000000000..d41497e72 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/curry.md @@ -0,0 +1,222 @@ +# curry (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `curry` 或手动闭包 +此 `curry` 函数由于复杂的占位符处理、参数个数验证和参数组合逻辑而运行缓慢。 + +如果不需要占位符,请改用更快的 `es-toolkit` 的 [`curry`](../../../reference/function/curry.md) 或简单闭包。 +::: + +对函数进行柯里化,使其可以一次接受一个参数或一次接受多个参数。 + +```typescript +const curriedFunction = curry(func, arity); +``` + +## 用法 + +### `curry(func, arity)` + +当您想要对函数进行柯里化以便更容易地进行部分应用时,使用 `curry`。它对于逐步提供参数或使用占位符稍后在特定位置提供参数非常有用。 + +```typescript +import { curry } from 'es-toolkit/compat'; + +// 基本用法 +function add(a, b, c) { + return a + b + c; +} + +const curriedAdd = curry(add); + +// 可以用各种方式调用 +console.log(curriedAdd(1)(2)(3)); // 6 +console.log(curriedAdd(1, 2)(3)); // 6 +console.log(curriedAdd(1)(2, 3)); // 6 +console.log(curriedAdd(1, 2, 3)); // 6 +``` + +与主库 curry 的比较: + +```typescript +// compat 版本 (灵活,但较慢) +import { curry } from 'es-toolkit/compat'; +const curriedCompat = curry(add); +curriedCompat(1, 2)(3); // 支持 +curriedCompat(1)(curry.placeholder, 3)(2); // 支持占位符 + +// 主库版本 (更快,但只能一次一个) +import { curry } from 'es-toolkit'; +const curriedMain = curry(add); +curriedMain(1)(2)(3); // 支持 +curriedMain(1, 2)(3); // 不支持 +``` + +使用占位符功能: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function greet(greeting, name, punctuation) { + return `${greeting}, ${name}${punctuation}`; +} + +const curriedGreet = curry(greet); + +// 使用占位符跳过中间参数 +const greetWithExclamation = curriedGreet(curry.placeholder, curry.placeholder, '!'); +console.log(greetWithExclamation('Hello', 'John')); // "Hello, John!" + +const sayHello = curriedGreet('Hello'); +console.log(sayHello(curry.placeholder, '~')('Jane')); // "Hello, Jane~" +``` + +在函数式编程中使用: + +```typescript +import { curry } from 'es-toolkit/compat'; + +// 创建映射函数 +const map = curry((fn, array) => array.map(fn)); +const filter = curry((predicate, array) => array.filter(predicate)); + +const numbers = [1, 2, 3, 4, 5]; + +// 创建可重用的函数 +const double = x => x * 2; +const isEven = x => x % 2 === 0; + +const mapDouble = map(double); +const filterEven = filter(isEven); + +console.log(mapDouble(numbers)); // [2, 4, 6, 8, 10] +console.log(filterEven(numbers)); // [2, 4] + +// 函数组合 +const processNumbers = nums => mapDouble(filterEven(nums)); +console.log(processNumbers(numbers)); // [4, 8] +``` + +配置 API 客户端: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function apiRequest(method, baseUrl, endpoint, options) { + return fetch(`${baseUrl}${endpoint}`, { + method, + ...options, + }); +} + +const curriedApiRequest = curry(apiRequest); + +// 使用默认设置创建专用函数 +const apiGet = curriedApiRequest('GET', 'https://api.example.com'); +const apiPost = curriedApiRequest('POST', 'https://api.example.com'); + +// 包含认证标头 +const authenticatedPost = apiPost(curry.placeholder, { + headers: { Authorization: 'Bearer token123' }, +}); + +// 使用 +apiGet('/users'); // GET https://api.example.com/users +authenticatedPost('/users'); // POST with auth headers +``` + +数学运算函数: + +```typescript +import { curry } from 'es-toolkit/compat'; + +const calculate = curry((operation, a, b) => { + switch (operation) { + case '+': + return a + b; + case '-': + return a - b; + case '*': + return a * b; + case '/': + return a / b; + default: + throw new Error('不支持的操作'); + } +}); + +// 专用操作函数 +const add = calculate('+'); +const subtract = calculate('-'); +const multiply = calculate('*'); + +console.log(add(5, 3)); // 8 +console.log(subtract(10)(4)); // 6 +console.log(multiply(3, 4)); // 12 + +// 使用占位符固定第二个操作数 +const addFive = calculate('+', curry.placeholder, 5); +console.log(addFive(10)); // 15 +``` + +指定参数个数: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function variableArgsFunction(a, b, c, ...rest) { + return [a, b, c, rest]; +} + +// 将参数个数限制为 3 +const curriedFixed = curry(variableArgsFunction, 3); + +console.log(curriedFixed(1)(2)(3)); // [1, 2, 3, []] +console.log(curriedFixed(1, 2)(3)); // [1, 2, 3, []] + +// 不指定参数个数使用 (默认值: function.length) +const curriedDefault = curry(variableArgsFunction); // arity = 3 +``` + +简单的柯里化替代方案: + +```typescript +// 使用 curry +const curriedAdd = curry((a, b, c) => a + b + c); + +// 手动闭包 (更快) +const manualCurry = a => b => c => a + b + c; + +// 两者产生相同的结果 +console.log(curriedAdd(1)(2)(3)); // 6 +console.log(manualCurry(1)(2)(3)); // 6 +``` + +也支持构造函数: + +```typescript +import { curry } from 'es-toolkit/compat'; + +function Person(name, age, city) { + this.name = name; + this.age = age; + this.city = city; +} + +const CurriedPerson = curry(Person); +const SeoulPerson = CurriedPerson(curry.placeholder, curry.placeholder, 'Seoul'); + +const person1 = new SeoulPerson('John', 30); +const person2 = new SeoulPerson('Jane', 25); + +console.log(person1.city); // "Seoul" +console.log(person2.city); // "Seoul" +``` + +#### 参数 + +- `func` (`Function`): 要柯里化的函数。 +- `arity` (`number`, 可选): 函数的参数个数。如果省略,使用 `func.length`。 + +#### 返回值 + +(`Function & { placeholder: symbol }`): 返回柯里化的函数。`placeholder` 属性允许您控制参数位置。 diff --git a/docs/zh_hans/compat/reference/function/curryRight.md b/docs/zh_hans/compat/reference/function/curryRight.md new file mode 100644 index 000000000..972a4887c --- /dev/null +++ b/docs/zh_hans/compat/reference/function/curryRight.md @@ -0,0 +1,242 @@ +# curryRight (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [`curryRight`](../../../reference/function/curryRight.md) 或手动闭包 + +由于复杂的占位符处理、参数数量验证和参数组合逻辑,这个 `curryRight` 函数运行较慢。 + +如果不需要占位符,请使用更快的 `es-toolkit` 的 [`curryRight`](../../../reference/function/curryRight.md) 或简单的闭包。 + +::: + +从右到左柯里化一个函数,创建一个可以一次接受一个或多个参数的函数,从最后一个参数开始。 + +```typescript +const curriedFunction = curryRight(func, arity); +``` + +## 用法 + +### `curryRight(func, arity)` + +当您想要从右到左柯里化一个函数并从最后一个参数开始部分应用参数时,请使用 `curryRight`。与常规的 `curry` 不同,它首先从最后一个参数开始处理。 + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 基本用法 +function subtract(a, b, c) { + return a - b - c; +} + +const curriedSubtract = curryRight(subtract); + +// 从右开始柯里化(从最后一个参数开始) +console.log(curriedSubtract(1)(2)(5)); // 5 - 2 - 1 = 2 +console.log(curriedSubtract(1, 2)(5)); // 5 - 2 - 1 = 2 +console.log(curriedSubtract(1)(2, 5)); // 2 - 5 - 1 = -4 +console.log(curriedSubtract(1, 2, 5)); // 1 - 2 - 5 = -6 +``` + +`curry` 和 `curryRight` 的区别: + +```typescript +import { curry, curryRight } from 'es-toolkit/compat'; + +function divide(a, b, c) { + return a / b / c; +} + +// 常规 curry(从左开始) +const leftCurried = curry(divide); +console.log(leftCurried(12)(3)(2)); // ((12 / 3) / 2) = 2 + +// curryRight(从右开始) +const rightCurried = curryRight(divide); +console.log(rightCurried(2)(3)(12)); // ((12 / 3) / 2) = 2 +// 最后提供的 12 成为第一个参数(a) +``` + +与主库的比较: + +```typescript +// compat 版本(灵活,但较慢) +import { curryRight } from 'es-toolkit/compat'; +const curriedCompat = curryRight(subtract); +curriedCompat(1, 2)(3); // 支持 +curriedCompat(1)(curryRight.placeholder, 3)(2); // 支持占位符 + +// 主库版本(更快,但一次只能一个) +import { curryRight } from 'es-toolkit'; +const curriedMain = curryRight(subtract); +curriedMain(1)(2)(3); // 支持 +curriedMain(1, 2)(3); // 不支持 +``` + +使用占位符功能: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function formatMessage(name, action, time) { + return `${name} 在 ${time} ${action}了`; +} + +const curriedFormat = curryRight(formatMessage); + +// 使用占位符跳过特定位置 +const todayAction = curriedFormat('今天'); +const todayLoginAction = todayAction(curryRight.placeholder, '登录'); + +console.log(todayLoginAction('张三')); +// "张三 在 今天 登录了" + +// 首先固定时间 +const morningFormat = curriedFormat('早上9点'); +console.log(morningFormat('评论', '李四')); +// "李四 在 早上9点 评论了" +``` + +在数组处理中使用: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 从数组末尾获取特定数量的项 +function takeFromEnd(array, count, separator = ', ') { + return array.slice(-count).join(separator); +} + +const curriedTake = curryRight(takeFromEnd); + +// 创建用逗号分隔的函数 +const takeWithComma = curriedTake(', '); + +// 获取最后3项 +const takeLast3 = takeWithComma(3); + +const fruits = ['苹果', '香蕉', '橙子', '葡萄', '猕猴桃']; +console.log(takeLast3(fruits)); // "橙子, 葡萄, 猕猴桃" + +// 使用不同的分隔符 +const takeWithDash = curriedTake(' - '); +console.log(takeWithDash(2, fruits)); // "葡萄 - 猕猴桃" +``` + +在函数组合中使用: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 日志输出函数 +function logWithPrefix(message, level, timestamp) { + return `[${timestamp}] ${level}: ${message}`; +} + +const curriedLog = curryRight(logWithPrefix); + +// 用当前时间固定 +const currentTimeLog = curriedLog(new Date().toISOString()); + +// 按级别创建记录器 +const errorLog = currentTimeLog('ERROR'); +const infoLog = currentTimeLog('INFO'); +const debugLog = currentTimeLog('DEBUG'); + +// 使用 +console.log(errorLog('数据库连接失败')); +console.log(infoLog('服务器已启动')); +console.log(debugLog('正在处理用户请求')); +``` + +函数式编程管道: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +// 数据转换函数 +const mapWith = curryRight((array, fn) => array.map(fn)); +const filterWith = curryRight((array, predicate) => array.filter(predicate)); +const reduceWith = curryRight((array, reducer, initial) => array.reduce(reducer, initial)); + +const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + +// 定义转换函数 +const double = x => x * 2; +const isEven = x => x % 2 === 0; +const sum = (acc, val) => acc + val; + +// 组合管道(右侧优先) +const processNumbers = nums => { + return reduceWith(filterWith(mapWith(nums, double), isEven), sum, 0); +}; + +console.log(processNumbers(numbers)); // 所有数字翻倍,过滤偶数,然后求和 +``` + +API 请求构建器: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function makeRequest(url, method, headers, body) { + return fetch(url, { method, headers, body }); +} + +const curriedRequest = curryRight(makeRequest); + +// 首先设置 body +const withJsonBody = curriedRequest(JSON.stringify({ data: 'test' })); + +// 添加 headers +const withHeaders = withJsonBody({ + 'Content-Type': 'application/json', + Authorization: 'Bearer token123', +}); + +// 设置 POST 方法 +const postRequest = withHeaders('POST'); + +// 最终使用 +postRequest('/api/data') + .then(response => response.json()) + .then(data => console.log(data)); +``` + +手动柯里化替代方案: + +```typescript +// 使用 curryRight +const curriedSubtract = curryRight((a, b, c) => a - b - c); + +// 手动闭包(更快,从右开始) +const manualCurryRight = c => b => a => a - b - c; + +// 两者结果相同 +console.log(curriedSubtract(1)(2)(5)); // 2 +console.log(manualCurryRight(1)(2)(5)); // 2 +``` + +指定参数数量: + +```typescript +import { curryRight } from 'es-toolkit/compat'; + +function variableArgsFunction(a, b, c, ...rest) { + return { a, b, c, rest }; +} + +// 将参数数量限制为3(忽略 rest) +const curriedFixed = curryRight(variableArgsFunction, 3); + +// 从右侧按 c, b, a 的顺序接收 +console.log(curriedFixed(3)(2)(1)); // { a: 1, b: 2, c: 3, rest: [] } +``` + +#### 参数 + +- `func` (`Function`): 要从右到左柯里化的函数。 +- `arity` (`number`, 可选): 函数的参数数量。如果省略,则使用 `func.length`。 + +#### 返回值 + +(`Function & { placeholder: symbol }`): 返回从右到左柯里化的函数。可以使用 `placeholder` 属性控制参数位置。 diff --git a/docs/zh_hans/compat/reference/function/debounce.md b/docs/zh_hans/compat/reference/function/debounce.md new file mode 100644 index 000000000..ec9fb5b05 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/debounce.md @@ -0,0 +1,264 @@ +# debounce (Lodash 兼容) + +::: warning 请使用 `es-toolkit` 的 [`debounce`](../../../reference/function/debounce.md) + +这个 `debounce` 函数由于复杂的 `maxWait` 处理和 Lodash 兼容的选项结构而存在开销。 + +请使用更快、更现代的 `es-toolkit` 的 [`debounce`](../../../reference/function/debounce.md)。 + +::: + +创建一个防抖函数,延迟调用提供的函数,直到自上次调用后经过 `wait` 毫秒。 + +```typescript +const debouncedFunction = debounce(func, wait, options); +``` + +## 用法 + +### `debounce(func, wait, options)` + +当您想要延迟函数调用时,使用 `debounce`。它对于防止搜索输入、滚动事件、按钮点击等中的过度调用很有用。 + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// 基本用法 +const searchFunction = debounce(query => { + console.log('搜索:', query); +}, 300); + +// 仅当在 300ms 内未再次调用时执行 +searchFunction('React'); // 不执行 +searchFunction('Vue'); // 不执行 +searchFunction('Angular'); // 300ms 后输出 "搜索: Angular" +``` + +与主库 debounce 的比较: + +```typescript +// compat 版本(Lodash 兼容,包含 maxWait 等额外选项) +import { debounce } from 'es-toolkit/compat'; +const debouncedCompat = debounce(func, 300, { + leading: true, + trailing: false, + maxWait: 1000 +}); + +// 主库版本(更快、更简单) +import { debounce } from 'es-toolkit'; +const debouncedMain = debounce(func, 300, { + edges: ['leading'] // 使用 edges 而不是 leading/trailing +}); +``` + +leading 和 trailing 选项: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const func = () => console.log('执行了'); + +// leading: true - 首次调用时立即执行 +const leadingDebounce = debounce(func, 1000, { leading: true }); +leadingDebounce(); // 立即输出 "执行了" +leadingDebounce(); // 等待 1 秒 +// 1 秒后没有额外执行 + +// trailing: true(默认) - 最后一次调用后延迟执行 +const trailingDebounce = debounce(func, 1000, { trailing: true }); +trailingDebounce(); // 等待 1 秒 +trailingDebounce(); // 等待 1 秒(取消之前的计时器) +// 1 秒后输出 "执行了" + +// 两者都为 true - 在开始和结束时执行 +const bothDebounce = debounce(func, 1000, { + leading: true, + trailing: true, +}); +bothDebounce(); // 立即输出 "执行了" +bothDebounce(); // 等待 1 秒 +// 1 秒后输出 "执行了"(trailing) +``` + +maxWait 选项: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// 保证至少每 2 秒执行一次 +const debouncedWithMaxWait = debounce(() => console.log('已保存'), 500, { maxWait: 2000 }); + +// 即使快速连续调用,也会每 2 秒执行一次 +setInterval(() => { + debouncedWithMaxWait(); +}, 100); // 每 100ms 调用一次,但每 2 秒输出 "已保存" +``` + +实际搜索示例: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +class SearchComponent { + constructor() { + this.searchInput = document.getElementById('search'); + + // 将用户输入防抖 300ms + this.debouncedSearch = debounce(this.performSearch.bind(this), 300, { + leading: false, // 输入开始时不立即搜索 + trailing: true, // 输入停止后搜索 + }); + + this.searchInput.addEventListener('input', e => { + this.debouncedSearch(e.target.value); + }); + } + + performSearch(query) { + if (query.length < 2) return; + + console.log('API 调用:', query); + // fetch(`/api/search?q=${query}`)... + } +} +``` + +滚动事件优化: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +// 将滚动事件防抖 100ms,但至少每 500ms 执行一次 +const optimizedScrollHandler = debounce( + () => { + const scrollTop = window.pageYOffset; + console.log('滚动位置:', scrollTop); + + // 头部隐藏/显示逻辑 + if (scrollTop > 100) { + document.header.classList.add('hidden'); + } else { + document.header.classList.remove('hidden'); + } + }, + 100, + { maxWait: 500 } +); + +window.addEventListener('scroll', optimizedScrollHandler); +``` + +API 调用限制: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +class AutoSave { + constructor() { + // 防抖 500ms,至少每 5 秒保存一次 + this.debouncedSave = debounce(this.saveToServer.bind(this), 500, { maxWait: 5000 }); + } + + onTextChange(content) { + this.pendingContent = content; + this.debouncedSave(); + } + + saveToServer() { + if (!this.pendingContent) return; + + console.log('保存到服务器:', this.pendingContent); + // fetch('/api/save', { ... }) + + this.pendingContent = null; + } +} +``` + +cancel 和 flush 方法: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const debouncedFunc = debounce(() => { + console.log('执行了'); +}, 1000); + +debouncedFunc(); // 等待 1 秒 + +// 取消待执行的调用 +debouncedFunc.cancel(); + +// 或立即执行 +debouncedFunc(); // 开始等待 1 秒 +debouncedFunc.flush(); // 立即输出 "执行了" 并取消计时器 +``` + +防止重复按钮点击: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const handleSubmit = debounce( + async formData => { + console.log('正在提交表单...'); + try { + const response = await fetch('/api/submit', { + method: 'POST', + body: formData, + }); + console.log('提交完成'); + } catch (error) { + console.error('提交失败:', error); + } + }, + 1000, + { leading: true, trailing: false } // 仅处理第一次点击 +); + +document.getElementById('submit-btn').addEventListener('click', e => { + const formData = new FormData(e.target.form); + handleSubmit(formData); +}); +``` + +调整大小事件处理: + +```typescript +import { debounce } from 'es-toolkit/compat'; + +const handleResize = debounce( + () => { + const width = window.innerWidth; + const height = window.innerHeight; + + console.log('窗口已调整大小:', { width, height }); + + // 重新计算布局 + recalculateLayout(); + }, + 250, + { leading: false, trailing: true } +); + +window.addEventListener('resize', handleResize); + +// 页面卸载时清理 +window.addEventListener('beforeunload', () => { + handleResize.cancel(); +}); +``` + +#### 参数 + +- `func` (`Function`): 要防抖的函数。 +- `wait` (`number`, 可选): 要延迟的毫秒数。默认为 `0`。 +- `options` (`DebounceSettings`, 可选): 选项对象。 + - `leading` (`boolean`): 如果为 `true`,则在延迟开始时执行函数。默认为 `false`。 + - `trailing` (`boolean`): 如果为 `true`,则在延迟结束时执行函数。默认为 `true`。 + - `maxWait` (`number`): 函数执行可以延迟的最大时间。默认为 `Infinity`。 + +#### 返回值 + +(`DebouncedFunc`): 返回防抖函数。它包含 `cancel()` 和 `flush()` 方法。 diff --git a/docs/zh_hans/reference/compat/function/defer.md b/docs/zh_hans/compat/reference/function/defer.md similarity index 100% rename from docs/zh_hans/reference/compat/function/defer.md rename to docs/zh_hans/compat/reference/function/defer.md diff --git a/docs/zh_hans/reference/compat/function/delay.md b/docs/zh_hans/compat/reference/function/delay.md similarity index 100% rename from docs/zh_hans/reference/compat/function/delay.md rename to docs/zh_hans/compat/reference/function/delay.md diff --git a/docs/zh_hans/reference/compat/function/flip.md b/docs/zh_hans/compat/reference/function/flip.md similarity index 100% rename from docs/zh_hans/reference/compat/function/flip.md rename to docs/zh_hans/compat/reference/function/flip.md diff --git a/docs/zh_hans/compat/reference/function/flow.md b/docs/zh_hans/compat/reference/function/flow.md new file mode 100644 index 000000000..ef68459c4 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/flow.md @@ -0,0 +1,87 @@ +# flow (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `flow` +这个 `flow` 函数为了 Lodash 兼容性添加了数组扁平化处理,变得复杂了。 + +建议使用更快、更现代的 `es-toolkit` 的 [flow](../../../reference/function/flow.md)。 +::: + +创建一个新函数,从左到右依次执行给定的函数。 + +```typescript +const combinedFunc = flow(...functions); +``` + +## 用法 + +### `flow(...functions)` + +当您想要创建一个从左到右依次执行多个函数的组合函数时,请使用 `flow`。它对于创建数据转换管道很有用。 + +```typescript +import { flow } from 'es-toolkit/compat'; + +// 基本用法 +function add(x, y) { + return x + y; +} + +function square(n) { + return n * n; +} + +function double(n) { + return n * 2; +} + +// 从左到右执行: double(square(add(x, y))) +const calculate = flow(add, square, double); +console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 + +// 以数组形式传递函数 +const calculate2 = flow([add, square], double); +console.log(calculate2(2, 3)); // 50 + +// 现代替代方案(推荐) +const modernCalculate = (x, y) => double(square(add(x, y))); +console.log(modernCalculate(1, 2)); // 18 + +// 使用管道操作符(未来的 JavaScript) +const pipeCalculate = (x, y) => add(x, y) |> square |> double; + +// 或使用链式模式 +class Calculator { + constructor(value) { + this.value = value; + } + + add(n) { + this.value += n; + return this; + } + + square() { + this.value *= this.value; + return this; + } + + double() { + this.value *= 2; + return this; + } + + valueOf() { + return this.value; + } +} + +const chainedResult = new Calculator(3).square().double().valueOf(); // 18 +``` + +#### 参数 + +- `...functions` (`Array`): 要从左到右执行的函数。也可以以数组形式传递。 + +#### 返回值 + +(`Function`): 返回一个新的组合函数,从左到右依次执行所有函数。 diff --git a/docs/zh_hans/compat/reference/function/flowRight.md b/docs/zh_hans/compat/reference/function/flowRight.md new file mode 100644 index 000000000..5f9c0f739 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/flowRight.md @@ -0,0 +1,65 @@ +# flowRight (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `flowRight` +这个 `flowRight` 函数为了 Lodash 兼容性添加了数组扁平化处理,变得复杂了。 + +建议使用更快、更现代的 `es-toolkit` 的 [flowRight](../../../reference/function/flowRight.md)。 +::: + +创建一个新函数,从右到左依次执行给定的函数。 + +```typescript +const combinedFunc = flowRight(...functions); +``` + +## 用法 + +### `flowRight(...functions)` + +当您想要创建一个从右到左依次执行多个函数的组合函数时,请使用 `flowRight`。它对于创建数据转换管道很有用。 + +```typescript +import { flowRight } from 'es-toolkit/compat'; + +// 基本用法 +function add(x, y) { + return x + y; +} + +function square(n) { + return n * n; +} + +function double(n) { + return n * 2; +} + +// 从右到左执行: double(square(add(x, y))) +const calculate = flowRight(double, square, add); +console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 + +// 以数组形式传递函数 +const calculate2 = flowRight([double, square], add); +console.log(calculate2(2, 3)); // 50 + +// 现代替代方案(推荐) +const modernCalculate = (x, y) => double(square(add(x, y))); +console.log(modernCalculate(1, 2)); // 18 + +// 或使用函数链 +const chainedCalculate = (x, y) => [x, y] + .reduce((acc, val, idx) => idx === 0 ? val : acc + val) + .valueOf() + |> (n => n * n) + |> (n => n * 2); +``` + +通常以与 `flow` 相反的顺序工作。它的工作方式类似于函数组合,因此很直观。 + +#### 参数 + +- `...functions` (`Array`): 要从右到左执行的函数。也可以以数组形式传递。 + +#### 返回值 + +(`Function`): 返回一个新的组合函数,从右到左依次执行所有函数。 diff --git a/docs/zh_hans/compat/reference/function/identity.md b/docs/zh_hans/compat/reference/function/identity.md new file mode 100644 index 000000000..e9b5956db --- /dev/null +++ b/docs/zh_hans/compat/reference/function/identity.md @@ -0,0 +1,62 @@ +# identity (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `identity` +这个 `identity` 函数在 `es-toolkit` 的主库中也有相同功能的函数。它只是简单地返回输入值。 + +建议使用更快、更现代的 `es-toolkit` 的 [identity](../../../reference/function/identity.md)。 +::: + +返回接收到的值。 + +```typescript +const result = identity(value); +``` + +## 用法 + +### `identity(value)` + +当您想要原样返回接收到的值时,请使用 `identity`。它主要用作默认值或占位符函数,在函数式编程中经常使用。 + +```typescript +import { identity } from 'es-toolkit/compat'; + +// 基本用法 +console.log(identity(5)); // 5 +console.log(identity('hello')); // 'hello' +console.log(identity({ key: 'value' })); // { key: 'value' } + +// 与数组的 map 一起使用(值复制) +const numbers = [1, 2, 3, 4, 5]; +const copied = numbers.map(identity); +console.log(copied); // [1, 2, 3, 4, 5] + +// 在过滤中用作默认值 +const values = [1, 0, '', 'hello', null, undefined, false, true]; +const filtered = values.filter(identity); // 只保留真值 +console.log(filtered); // [1, 'hello', true] + +// 用作默认转换函数 +function processData(data, transform = identity) { + return transform(data); +} + +console.log(processData('hello')); // 'hello' +console.log(processData('hello', x => x.toUpperCase())); // 'HELLO' +``` + +在大多数情况下,可以用更简单的箭头函数 `x => x` 替代: + +```typescript +// 使用箭头函数而不是 identity(推荐) +const copied = numbers.map(x => x); +const filtered = values.filter(x => x); +``` + +#### 参数 + +- `value` (`T`): 要返回的值。 + +#### 返回值 + +(`T`): 原样返回接收到的值。 diff --git a/docs/zh_hans/compat/reference/function/memoize.md b/docs/zh_hans/compat/reference/function/memoize.md new file mode 100644 index 000000000..95ca791b0 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/memoize.md @@ -0,0 +1,66 @@ +# memoize (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `memoize` +这个 `memoize` 函数由于 `resolver` 函数的 `null` 检查、`MapCache` 接口的复杂类型处理以及为了 Lodash 兼容性而产生的额外开销,导致运行缓慢。 + +建议使用更快、更现代的 `es-toolkit` 的 [memoize](../../../reference/function/memoize.md)。 +::: + +缓存函数结果,以在使用相同参数调用时提高性能。 + +```typescript +const memoizedFunc = memoize(func, resolver); +``` + +## 用法 + +### `memoize(func, resolver)` + +当您想要缓存函数结果以在使用相同参数调用时重用之前的结果时,请使用 `memoize`。它对于昂贵的计算或 API 调用很有用。 + +```typescript +import { memoize } from 'es-toolkit/compat'; + +// 基本用法 +function expensiveCalculation(n) { + console.log('计算中...', n); + return n * n; +} + +const memoizedCalc = memoize(expensiveCalculation); + +console.log(memoizedCalc(5)); // '计算中... 5', 25 +console.log(memoizedCalc(5)); // 25 (缓存的结果,不计算) +console.log(memoizedCalc(10)); // '计算中... 10', 100 + +// 使用自定义解析器 +function fetchUserData(userId, includeProfile) { + console.log('获取用户数据...', userId, includeProfile); + return { id: userId, profile: includeProfile ? '个人资料数据' : null }; +} + +// 生成考虑所有参数的缓存键 +const memoizedFetch = memoize(fetchUserData, (userId, includeProfile) => { + return `${userId}_${includeProfile}`; +}); + +memoizedFetch(1, true); // '获取用户数据... 1 true' +memoizedFetch(1, true); // 使用缓存的结果 +memoizedFetch(1, false); // '获取用户数据... 1 false' (不同的缓存键) + +// 访问和修改缓存 +console.log(memoizedCalc.cache.get(5)); // 25 +memoizedCalc.cache.set(7, 49); // 手动设置缓存 +console.log(memoizedCalc(7)); // 49 (使用缓存值,不计算) +``` + +在大多数情况下使用基本哈希映射,但根据需要也可以使用自定义缓存实现。 + +#### 参数 + +- `func` (`Function`): 要记忆化的函数。 +- `resolver` (`Function`, 可选): 确定缓存键的函数。如果未提供,使用第一个参数作为键。 + +#### 返回值 + +(`Function & { cache: MapCache }`): 返回记忆化的函数。返回的函数具有 `cache` 属性,可直接访问缓存。 diff --git a/docs/zh_hans/reference/compat/function/negate.md b/docs/zh_hans/compat/reference/function/negate.md similarity index 100% rename from docs/zh_hans/reference/compat/function/negate.md rename to docs/zh_hans/compat/reference/function/negate.md diff --git a/docs/zh_hans/compat/reference/function/noop.md b/docs/zh_hans/compat/reference/function/noop.md new file mode 100644 index 000000000..e1b147ee1 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/noop.md @@ -0,0 +1,60 @@ +# noop (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `noop` + +`es-toolkit` 也有相同行为的 [noop](../../../reference/function/noop.md) 函数。 + +::: + +什么都不做的空函数。 + +```typescript +noop(); +``` + +## 用法 + +### `noop(...args)` + +当您需要一个什么都不做的占位符函数时,使用 `noop`。它通常用作默认值或回调函数。 + +```typescript +import { noop } from 'es-toolkit/compat'; + +// 基本用法 +noop(); // 什么都不做 +noop(1, 2, 3); // 接受参数但什么都不做 + +// 用作默认回调 +function processData(data, callback = noop) { + // 处理数据 + console.log('处理数据中...', data); + + // 调用回调(如果未提供则为 noop) + callback(data); +} + +processData('测试'); // 即使未提供回调也能正常工作 + +// 现代替代方案(推荐) +function modernProcessData(data, callback = () => {}) { + console.log('处理数据中...', data); + callback(data); +} + +// 或使用可选回调 +function processDataOptional(data, callback) { + console.log('处理数据中...', data); + callback?.(data); // 仅在提供回调时调用 +} +``` + +在需要默认值或占位符的情况下很有用,但在现代 JavaScript 中,使用可选链(`?.`)或默认参数更常见。 + +#### 参数 + +- `...args` (`any[]`): 可以接受任何参数,但都会被忽略。 + +#### 返回值 + +(`void`): 不返回任何内容。 diff --git a/docs/zh_hans/reference/compat/function/nthArg.md b/docs/zh_hans/compat/reference/function/nthArg.md similarity index 100% rename from docs/zh_hans/reference/compat/function/nthArg.md rename to docs/zh_hans/compat/reference/function/nthArg.md diff --git a/docs/zh_hans/compat/reference/function/once.md b/docs/zh_hans/compat/reference/function/once.md new file mode 100644 index 000000000..18acf31c9 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/once.md @@ -0,0 +1,56 @@ +# once (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `once` + +这个 `once` 函数与 `es-toolkit` 主库的 [once](../../../reference/function/once.md) 函数具有相同的功能。 + +::: + +限制函数只能被调用一次。 + +```typescript +const limitedFunc = once(func); +``` + +## 用法 + +### `once(func)` + +当您想限制函数只能被调用一次时,使用 `once`。第一次调用后,结果会被缓存并返回相同的值。 + +```typescript +import { once } from 'es-toolkit/compat'; + +// 基本用法 +let count = 0; +const increment = once(() => { + count++; + console.log('计数器递增:', count); + return count; +}); + +increment(); // 输出 '计数器递增: 1',返回 1 +increment(); // 不输出任何内容,返回 1 +increment(); // 不输出任何内容,返回 1 + +// 实用示例 - 初始化函数 +const initialize = once(() => { + console.log('正在初始化应用程序...'); + // 昂贵的初始化操作 + return '初始化完成'; +}); + +// 即使多次调用,初始化也只执行一次 +initialize(); // 输出 '正在初始化应用程序...' +initialize(); // 不输出任何内容 +``` + +在创建昂贵的初始化操作或设置函数时很有用。例如,可以用于数据库连接、API 令牌初始化等。 + +#### 参数 + +- `func` (`Function`): 要限制为只调用一次的函数。 + +#### 返回值 + +(`Function`): 返回一个新函数,该函数只被调用一次。从第二次调用开始,返回第一次调用的结果。 diff --git a/docs/zh_hans/reference/compat/function/overArgs.md b/docs/zh_hans/compat/reference/function/overArgs.md similarity index 100% rename from docs/zh_hans/reference/compat/function/overArgs.md rename to docs/zh_hans/compat/reference/function/overArgs.md diff --git a/docs/zh_hans/compat/reference/function/partial.md b/docs/zh_hans/compat/reference/function/partial.md new file mode 100644 index 000000000..5d27b025c --- /dev/null +++ b/docs/zh_hans/compat/reference/function/partial.md @@ -0,0 +1,59 @@ +# partial (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `partial` + +这个 `partial` 函数由于许多重载和联合类型处理而效率低下。此外,在大多数情况下可以用更简单的箭头函数替代。 + +建议使用更快且更现代的 `es-toolkit` 的 [`partial`](../../../reference/function/partial.md)。 + +::: + +通过预填充参数来创建部分应用的函数。 + +```typescript +const partialFunc = partial(func, ...args); +``` + +## 用法 + +### `partial(func, ...args)` + +当您想通过预填充参数来创建部分应用的函数时,使用 `partial`。主要在参数顺序重要的函数中固定前面的参数时很有用。 + +```typescript +import { partial } from 'es-toolkit/compat'; + +// 基本用法 +function greet(greeting, name, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// 预设第一个参数 +const sayHello = partial(greet, 'Hello'); +sayHello('Alice', '!'); // 'Hello Alice!' + +// 预设多个参数 +const greetAlice = partial(greet, 'Hello', 'Alice'); +greetAlice('!'); // 'Hello Alice!' + +// 使用 placeholder 控制参数顺序 +const greetWithExclamation = partial(greet, partial.placeholder, 'Alice', '!'); +greetWithExclamation('Hi'); // 'Hi Alice!' +``` + +在大多数情况下可以用箭头函数替代: + +```typescript +// 使用箭头函数代替 partial(推荐) +const sayHello = (name, punctuation) => greet('Hello', name, punctuation); +const greetAlice = punctuation => greet('Hello', 'Alice', punctuation); +``` + +#### 参数 + +- `func` (`Function`): 要部分应用的函数。 +- `...args` (`any[]`): 要预填充的参数。使用 `partial.placeholder` 可以控制参数顺序。 + +#### 返回值 + +(`Function`): 返回一个预填充了参数的新函数。 diff --git a/docs/zh_hans/compat/reference/function/partialRight.md b/docs/zh_hans/compat/reference/function/partialRight.md new file mode 100644 index 000000000..1b217e6c0 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/partialRight.md @@ -0,0 +1,59 @@ +# partialRight (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 `partialRight` + +这个 `partialRight` 函数由于许多重载和联合类型处理而效率低下。此外,在大多数情况下可以用更简单的箭头函数替代。 + +建议使用更快且更现代的 `es-toolkit` 的 [`partialRight`](../../../reference/function/partialRight.md)。 + +::: + +通过从右侧预填充参数来创建部分应用的函数。 + +```typescript +const partialFunc = partialRight(func, ...args); +``` + +## 用法 + +### `partialRight(func, ...args)` + +当您想通过从右侧预填充参数来创建部分应用的函数时,使用 `partialRight`。主要在参数顺序重要的函数中固定最后的参数时很有用。 + +```typescript +import { partialRight } from 'es-toolkit/compat'; + +// 基本用法 +function greet(greeting, name, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// 预设最后一个参数 +const greetWithExclamation = partialRight(greet, '!'); +greetWithExclamation('Hello', 'Alice'); // 'Hello Alice!' + +// 预设多个参数 +const sayHiToAlice = partialRight(greet, 'Alice', '!'); +sayHiToAlice('Hi'); // 'Hi Alice!' + +// 使用 placeholder 控制参数顺序 +const greetAliceWithCustom = partialRight(greet, 'Alice', partialRight.placeholder); +greetAliceWithCustom('Hello', '?'); // 'Hello Alice?' +``` + +在大多数情况下可以用箭头函数替代: + +```typescript +// 使用箭头函数代替 partialRight(推荐) +const greetWithExclamation = (greeting, name) => greet(greeting, name, '!'); +const sayHiToAlice = greeting => greet(greeting, 'Alice', '!'); +``` + +#### 参数 + +- `func` (`Function`): 要部分应用的函数。 +- `...args` (`any[]`): 要预填充的参数。使用 `partialRight.placeholder` 可以控制参数顺序。 + +#### 返回值 + +(`Function`): 返回一个从右侧预填充了参数的新函数。 diff --git a/docs/zh_hans/reference/compat/function/rearg.md b/docs/zh_hans/compat/reference/function/rearg.md similarity index 100% rename from docs/zh_hans/reference/compat/function/rearg.md rename to docs/zh_hans/compat/reference/function/rearg.md diff --git a/docs/zh_hans/compat/reference/function/rest.md b/docs/zh_hans/compat/reference/function/rest.md new file mode 100644 index 000000000..e1ae97640 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/rest.md @@ -0,0 +1,54 @@ +# rest (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `rest` + +此 `rest` 函数由于额外的逻辑(如默认值处理和索引验证)可能会导致性能下降。 + +请改用更快、更现代的 `es-toolkit` 的 [rest](../../../reference/function/rest.md)。 + +::: + +创建一个函数,从指定索引开始将剩余参数分组到数组中。 + +```typescript +const restFunc = rest(func, start); +``` + +## 用法 + +### `rest(func, start)` + +当您想通过将指定索引开始的剩余参数分组到数组中来转换函数参数时,请使用 `rest`。它对于创建可变参数函数很有用。 + +```typescript +import { rest } from 'es-toolkit/compat'; + +// 基本用法 - 将最后的参数分组到数组中 +function logMessage(level, message, ...details) { + console.log(`[${level}] ${message}`, details); +} + +const restLogger = rest(logMessage, 2); +restLogger('ERROR', '发生错误', '详细信息 1', '详细信息 2'); +// 内部调用 logMessage('ERROR', '发生错误', [['详细信息 1', '详细信息 2']]) + +// 不同索引的示例 +function process(action, target, ...args) { + return { action, target, args }; +} + +const restProcess = rest(process, 1); +restProcess('update', 'user', 'name', 'John', 'age', 25); +// { action: 'update', target: ['user', 'name', 'John', 'age', 25], args: [] } +``` + +当您想将函数的最后参数作为数组接收时使用它。在现代 JavaScript 中,使用剩余参数语法(`...args`)更为常见。 + +#### 参数 + +- `func` (`Function`): 要转换的函数。 +- `start` (`number`, 可选): 开始将参数分组到数组中的索引。默认值为 `func.length - 1`。 + +#### 返回值 + +(`Function`): 返回一个新函数,从指定索引开始将剩余参数分组到数组中。 diff --git a/docs/zh_hans/reference/compat/function/spread.md b/docs/zh_hans/compat/reference/function/spread.md similarity index 100% rename from docs/zh_hans/reference/compat/function/spread.md rename to docs/zh_hans/compat/reference/function/spread.md diff --git a/docs/zh_hans/compat/reference/function/throttle.md b/docs/zh_hans/compat/reference/function/throttle.md new file mode 100644 index 000000000..67b9138cd --- /dev/null +++ b/docs/zh_hans/compat/reference/function/throttle.md @@ -0,0 +1,52 @@ +# throttle (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `throttle` + +此 `throttle` 函数为了 Lodash 兼容性在内部使用 debounce 函数,使其变得有些复杂。它还具有更复杂的默认值和选项处理。 + +请改用更快、更现代的 `es-toolkit` 的 [throttle](../../../reference/function/throttle.md)。 + +::: + +限制函数调用,使其在指定时间间隔内最多执行一次。 + +```typescript +const throttledFunc = throttle(func, wait, options); +``` + +## 用法 + +### `throttle(func, wait, options)` + +当您想限制函数调用在指定时间间隔内最多执行一次时,请使用 `throttle`。它对于限制事件处理程序或 API 调用的频率很有用。 + +```typescript +import { throttle } from 'es-toolkit/compat'; + +// 基本用法 - 每秒最多执行一次 +const throttledLog = throttle(() => { + console.log('事件发生!'); +}, 1000); + +// 使用选项的示例 +const throttledScroll = throttle(handleScroll, 100, { + leading: true, // 首次调用时立即执行 + trailing: false, // 最后一次调用后不执行 +}); + +window.addEventListener('scroll', throttledScroll); +``` + +在处理快速发生的事件(如滚动或调整大小事件)时,这对于性能至关重要。 + +#### 参数 + +- `func` (`Function`): 要节流的函数。 +- `wait` (`number`, 可选): 等待时间(毫秒)。默认值为 `0`。 +- `options` (`ThrottleSettings`, 可选): 节流选项。 + - `leading` (`boolean`): 是否在首次调用时执行。默认值为 `true`。 + - `trailing` (`boolean`): 是否在最后一次调用后执行。默认值为 `true`。 + +#### 返回值 + +(`DebouncedFunc`): 返回节流函数。您可以使用 `cancel()` 方法取消待处理的执行。 diff --git a/docs/zh_hans/compat/reference/function/unary.md b/docs/zh_hans/compat/reference/function/unary.md new file mode 100644 index 000000000..6aee63435 --- /dev/null +++ b/docs/zh_hans/compat/reference/function/unary.md @@ -0,0 +1,46 @@ +# unary (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `ary` + +此 `unary` 函数是作为 `ary` 函数的特殊情况实现的。如果您需要更多控制,直接使用 `es-toolkit` 的 [ary](../../../reference/function/ary.md) 会更高效。 + +请改用更快、更现代的 `es-toolkit` 的 [ary](../../../reference/function/ary.md)。 + +::: + +限制函数最多接受一个参数。 + +```typescript +const limitedFunc = unary(func); +``` + +## 用法 + +### `unary(func)` + +当您想限制函数最多接受一个参数时,请使用 `unary`。传递的任何额外参数都将被忽略。 + +```typescript +import { unary } from 'es-toolkit/compat'; + +function greet(name, greeting, punctuation) { + return `${greeting} ${name}${punctuation}`; +} + +// 转换为只接受第一个参数的函数 +const greetOne = unary(greet); +greetOne('Alice', 'Hello', '!'); // 与 greet('Alice') 相同 + +// 与数组的 map 函数一起使用时很有用 +const numbers = ['1', '2', '3']; +numbers.map(parseInt); // [1, NaN, NaN] - 意外结果 +numbers.map(unary(parseInt)); // [1, 2, 3] - 正确结果 +``` + +#### 参数 + +- `func` (`(...args: any[]) => any`): 要限制参数的函数。 + +#### 返回值 + +(`(...args: any[]) => any`): 返回最多接受一个参数的新函数。 diff --git a/docs/zh_hans/reference/compat/function/wrap.md b/docs/zh_hans/compat/reference/function/wrap.md similarity index 100% rename from docs/zh_hans/reference/compat/function/wrap.md rename to docs/zh_hans/compat/reference/function/wrap.md diff --git a/docs/zh_hans/reference/compat/math/add.md b/docs/zh_hans/compat/reference/math/add.md similarity index 100% rename from docs/zh_hans/reference/compat/math/add.md rename to docs/zh_hans/compat/reference/math/add.md diff --git a/docs/zh_hans/reference/compat/math/ceil.md b/docs/zh_hans/compat/reference/math/ceil.md similarity index 100% rename from docs/zh_hans/reference/compat/math/ceil.md rename to docs/zh_hans/compat/reference/math/ceil.md diff --git a/docs/zh_hans/compat/reference/math/clamp.md b/docs/zh_hans/compat/reference/math/clamp.md new file mode 100644 index 000000000..65ef47c2a --- /dev/null +++ b/docs/zh_hans/compat/reference/math/clamp.md @@ -0,0 +1,82 @@ +# clamp (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [clamp](../../../reference/math/clamp.md) + +这个 `clamp` 函数由于 NaN 验证和处理会运行较慢。 + +请使用更快、更现代的 `es-toolkit` 的 [clamp](../../../reference/math/clamp.md)。 + +::: + +将数字限制在指定范围内。 + +```typescript +const clamped = clamp(number, lower, upper); +``` + +## 用法 + +### `clamp(number, lower, upper)` + +当您想要将数字限制在指定的最小值和最大值之间时,请使用 `clamp`。 + +```typescript +import { clamp } from 'es-toolkit/compat'; + +// 基本用法 +clamp(3, 2, 4); +// Returns: 3 (在范围内) + +clamp(0, 5, 10); +// Returns: 5 (限制为最小值) + +clamp(15, 5, 10); +// Returns: 10 (限制为最大值) + +// 处理负数 +clamp(-5, -10, -1); +// Returns: -5 + +clamp(-15, -10, -1); +// Returns: -10 (限制为最小值) +``` + +### `clamp(number, upper)` + +如果只提供一个参数,该值将用作最大值。 + +```typescript +import { clamp } from 'es-toolkit/compat'; + +// 只指定最大值 +clamp(5, 3); +// Returns: 3 (限制为最大值) + +clamp(2, 3); +// Returns: 2 (在范围内) + +clamp(1, 5); +// Returns: 1 +``` + +NaN 值被处理为 0。 + +```typescript +import { clamp } from 'es-toolkit/compat'; + +clamp(5, NaN, 10); +// Returns: 5 (NaN 被处理为 0,范围是 0~10) + +clamp(5, 2, NaN); +// Returns: 2 (NaN 被处理为 0,范围是 0~2) +``` + +#### 参数 + +- `number` (`number`): 要限制的数字。 +- `lower` (`number`): 最小值。如果只有第二个参数,则为最大值。 +- `upper` (`number`, 可选): 最大值。 + +#### 返回值 + +(`number`): 返回限制在指定范围内的数字。 diff --git a/docs/zh_hans/reference/compat/math/divide.md b/docs/zh_hans/compat/reference/math/divide.md similarity index 100% rename from docs/zh_hans/reference/compat/math/divide.md rename to docs/zh_hans/compat/reference/math/divide.md diff --git a/docs/zh_hans/reference/compat/math/floor.md b/docs/zh_hans/compat/reference/math/floor.md similarity index 100% rename from docs/zh_hans/reference/compat/math/floor.md rename to docs/zh_hans/compat/reference/math/floor.md diff --git a/docs/zh_hans/compat/reference/math/inRange.md b/docs/zh_hans/compat/reference/math/inRange.md new file mode 100644 index 000000000..9532828d9 --- /dev/null +++ b/docs/zh_hans/compat/reference/math/inRange.md @@ -0,0 +1,101 @@ +# inRange (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [inRange](../../../reference/math/inRange.md) + +这个 `inRange` 函数由于复杂的类型转换和 null/undefined 处理会运行较慢。 + +请使用更快、更现代的 `es-toolkit` 的 [inRange](../../../reference/math/inRange.md)。 + +::: + +检查数字是否在指定范围内。 + +```typescript +const result = inRange(value, minimum, maximum); +``` + +## 用法 + +### `inRange(value, minimum, maximum?)` + +当您想要检查数字是否在特定范围内时,请使用 `inRange`。最小值包含在内,最大值不包含在内。 + +```typescript +import { inRange } from 'es-toolkit/compat'; + +// 基本用法 +inRange(3, 2, 4); +// Returns: true (2 ≤ 3 < 4) + +inRange(1, 2, 5); +// Returns: false (1 < 2) + +inRange(5, 2, 5); +// Returns: false (5 不包含在内) + +// 范围边界值 +inRange(2, 2, 4); +// Returns: true (最小值包含在内) + +inRange(4, 2, 4); +// Returns: false (最大值不包含在内) +``` + +### `inRange(value, maximum)` + +如果只提供两个参数,则处理为从 0 到 maximum 的范围。 + +```typescript +import { inRange } from 'es-toolkit/compat'; + +inRange(3, 5); +// Returns: true (0 ≤ 3 < 5) + +inRange(-1, 5); +// Returns: false (-1 < 0) + +inRange(0, 5); +// Returns: true (0 ≤ 0 < 5) + +inRange(5, 5); +// Returns: false (5 不包含在内) +``` + +如果最小值大于最大值,会自动交换。 + +```typescript +import { inRange } from 'es-toolkit/compat'; + +inRange(3, 5, 2); +// Returns: true (范围变为 2~5,2 ≤ 3 < 5) + +inRange(1, 5, 2); +// Returns: false (1 < 2) +``` + +无效值会被适当转换。 + +```typescript +import { inRange } from 'es-toolkit/compat'; + +// 字符串数字转换 +inRange(3, '2', '4'); +// Returns: true + +// falsy 值被处理为 0 +inRange(1, null, 5); +// Returns: true (null 被处理为 0,范围为 0~5) + +inRange(3, false, 5); +// Returns: true (false 被处理为 0) +``` + +#### 参数 + +- `value` (`number`): 要检查是否在范围内的数字。 +- `minimum` (`number`): 范围的最小值(包含)。如果没有 `maximum`,此值变为最大值。 +- `maximum` (`number`, 可选): 范围的最大值(不包含)。 + +#### 返回值 + +(`boolean`): 如果值在指定范围内返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/math/max.md b/docs/zh_hans/compat/reference/math/max.md similarity index 100% rename from docs/zh_hans/reference/compat/math/max.md rename to docs/zh_hans/compat/reference/math/max.md diff --git a/docs/zh_hans/compat/reference/math/maxBy.md b/docs/zh_hans/compat/reference/math/maxBy.md new file mode 100644 index 000000000..db754e151 --- /dev/null +++ b/docs/zh_hans/compat/reference/math/maxBy.md @@ -0,0 +1,114 @@ +# maxBy (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [maxBy](../../../reference/array/maxBy.md) + +这个 `maxBy` 函数由于 iteratee 函数处理和类型转换会运行较慢。 + +请使用更快、更现代的 `es-toolkit` 的 [maxBy](../../../reference/array/maxBy.md)。 + +::: + +在符合条件的值中查找最大值元素。 + +```typescript +const maxItem = maxBy(array, iteratee); +``` + +## 用法 + +### `maxBy(array, iteratee)` + +在数组中查找函数计算值最大的元素。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +// 对象数组中特定属性最大的元素 +const people = [ + { name: '张三', age: 25 }, + { name: '李四', age: 30 }, + { name: '王五', age: 35 }, +]; + +maxBy(people, person => person.age); +// Returns: { name: '王五', age: 35 } + +// 也可以使用属性名 +maxBy(people, 'age'); +// Returns: { name: '王五', age: 35 } +``` + +用函数转换值来查找最大值。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +maxBy(items, x => x.a); +// Returns: { a: 3 } + +const numbers = [-1, -2, -3]; +maxBy(numbers, x => Math.abs(x)); +// Returns: -3 (绝对值最大的元素) +``` + +通过数组元素访问。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const arrays = [ + [1, 2], + [3, 4], + [0, 5], +]; +maxBy(arrays, 0); // 第一个元素最大的数组 +// Returns: [3, 4] + +maxBy(arrays, 1); // 第二个元素最大的数组 +// Returns: [0, 5] +``` + +查找对象特定属性和值匹配的情况。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +const users = [ + { name: '张三', age: 25, active: true }, + { name: '李四', age: 30, active: false }, + { name: '王五', age: 35, active: true }, +]; + +// active 为 true 的元素中的第一个 +maxBy(users, ['active', true]); +// Returns: { name: '张三', age: 25, active: true } + +// 用对象指定条件 +maxBy(users, { active: true }); +// Returns: { name: '张三', age: 25, active: true } +``` + +空数组返回 undefined。 + +```typescript +import { maxBy } from 'es-toolkit/compat'; + +maxBy([], x => x.a); +// Returns: undefined + +maxBy(null); +// Returns: undefined + +maxBy(undefined); +// Returns: undefined +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要搜索的数组。 +- `iteratee` (`ValueIteratee`, 可选): 应用于每个元素的函数、属性名或条件。 + +#### 返回值 + +(`T | undefined`): 返回符合条件的值最大的元素。如果是空数组则返回 `undefined`。 diff --git a/docs/zh_hans/compat/reference/math/mean.md b/docs/zh_hans/compat/reference/math/mean.md new file mode 100644 index 000000000..5d73fd74e --- /dev/null +++ b/docs/zh_hans/compat/reference/math/mean.md @@ -0,0 +1,76 @@ +# mean (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [mean](../../../reference/math/mean.md) + +这个 `mean` 函数由于类型转换和 null/undefined 处理会运行较慢。 + +请使用更快、更现代的 `es-toolkit` 的 [mean](../../../reference/math/mean.md)。 + +::: + +计算数组的平均值。 + +```typescript +const average = mean(array); +``` + +## 用法 + +### `mean(array)` + +计算数字数组的平均值。 + +```typescript +import { mean } from 'es-toolkit/compat'; + +// 数字数组 +mean([1, 2, 3, 4, 5]); +// Returns: 3 + +mean([10, 20, 30]); +// Returns: 20 + +mean([1.5, 2.5, 3.5]); +// Returns: 2.5 +``` + +空数组返回 NaN。 + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean([]); +// Returns: NaN + +mean(null); +// Returns: NaN + +mean(undefined); +// Returns: NaN +``` + +无效值会被视作 0 并计算。 + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean([1, undefined, 2, null, 3]); +// Returns: 1.2 (1 + 2 + 3) / 5 = 1.2 +``` + +字符串将会被拼接。 + +```typescript +import { mean } from 'es-toolkit/compat'; + +mean(['1', '2', '3']); +// Returns: 41 (123 / 3 = 41) +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 包含要计算平均值的数字数组。 + +#### 返回值 + +(`number`): 返回数组的平均值。如果是空数组则返回 `NaN`。 diff --git a/docs/zh_hans/compat/reference/math/meanBy.md b/docs/zh_hans/compat/reference/math/meanBy.md new file mode 100644 index 000000000..57d6842ec --- /dev/null +++ b/docs/zh_hans/compat/reference/math/meanBy.md @@ -0,0 +1,103 @@ +# meanBy (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [meanBy](../../../reference/math/meanBy.md) + +这个 `meanBy` 函数由于 iteratee 函数处理和类型转换会运行较慢。 + +请使用更快、更现代的 `es-toolkit` 的 [meanBy](../../../reference/math/meanBy.md)。 + +::: + +计算符合条件的值的平均值。 + +```typescript +const average = meanBy(array, iteratee); +``` + +## 用法 + +### `meanBy(array, iteratee)` + +计算数组中每个元素应用函数后结果的平均值。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +// 对象数组中特定属性的平均值 +const people = [ + { name: '张三', age: 25 }, + { name: '李四', age: 30 }, + { name: '王五', age: 35 }, +]; + +meanBy(people, person => person.age); +// Returns: 30 + +// 也可以使用属性名 +meanBy(people, 'age'); +// Returns: 30 +``` + +用函数转换值来计算平均值。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const numbers = [1.5, 2.7, 3.2, 4.8]; +meanBy(numbers, x => Math.floor(x)); +// Returns: 2.5 (1 + 2 + 3 + 4) / 4 + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +meanBy(items, x => x.a); +// Returns: 2 +``` + +通过数组元素访问。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const arrays = [[2], [3], [1]]; +meanBy(arrays, 0); // 第一个元素的平均值 +// Returns: 2 +``` + +只计算对象特定属性和值匹配的情况。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +const users = [ + { name: '张三', age: 25, active: true }, + { name: '李四', age: 30, active: false }, + { name: '王五', age: 35, active: true }, +]; + +// 只有 active 为 true 的人 +meanBy(users, { active: true }); +// Returns: 0.6666666 (active 为 true 的人占总人数的比例) +``` + +空数组返回 NaN。 + +```typescript +import { meanBy } from 'es-toolkit/compat'; + +meanBy([], x => x.a); +// Returns: NaN + +meanBy(null); +// Returns: NaN + +meanBy(undefined); +// Returns: NaN +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要处理的数组。 +- `iteratee` (`ValueIteratee`, 可选): 应用于每个元素的函数、属性名或条件。 + +#### 返回值 + +(`number`): 返回符合条件的值的平均值。如果是空数组则返回 `NaN`。 diff --git a/docs/zh_hans/reference/compat/math/min.md b/docs/zh_hans/compat/reference/math/min.md similarity index 100% rename from docs/zh_hans/reference/compat/math/min.md rename to docs/zh_hans/compat/reference/math/min.md diff --git a/docs/zh_hans/compat/reference/math/minBy.md b/docs/zh_hans/compat/reference/math/minBy.md new file mode 100644 index 000000000..e1367c220 --- /dev/null +++ b/docs/zh_hans/compat/reference/math/minBy.md @@ -0,0 +1,114 @@ +# minBy(Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [minBy](../../../reference/array/minBy.md) + +这个 `minBy` 函数由于 iteratee 函数处理和类型转换会运行较慢。 + +请使用更快、更现代的 `es-toolkit` 的 [minBy](../../../reference/array/minBy.md)。 + +::: + +在满足条件的值中找到最小值元素。 + +```typescript +const minItem = minBy(array, iteratee); +``` + +## 用法 + +### `minBy(array, iteratee)` + +在数组中找到通过函数计算后值最小的元素。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +// 对象数组中特定属性最小的元素 +const people = [ + { name: '张三', age: 25 }, + { name: '李四', age: 30 }, + { name: '王五', age: 35 }, +]; + +minBy(people, person => person.age); +// Returns: { name: '张三', age: 25 } + +// 也可以使用属性名 +minBy(people, 'age'); +// Returns: { name: '张三', age: 25 } +``` + +通过函数转换值来找到最小值。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; +minBy(items, x => x.a); +// Returns: { a: 1 } + +const numbers = [-1, -2, -3]; +minBy(numbers, x => Math.abs(x)); +// Returns: -1 (绝对值最小的元素) +``` + +通过数组元素访问。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const arrays = [ + [1, 2], + [3, 4], + [0, 5], +]; +minBy(arrays, 0); // 第一个元素最小的数组 +// Returns: [0, 5] + +minBy(arrays, 1); // 第二个元素最小的数组 +// Returns: [1, 2] +``` + +查找对象的特定属性和值匹配的情况。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +const users = [ + { name: '张三', age: 25, active: true }, + { name: '李四', age: 30, active: false }, + { name: '王五', age: 35, active: true }, +]; + +// 在 active 为 true 的元素中找到不是第一个的元素 +minBy(users, ['active', true]); +// Returns: { name: '李四', age: 30, active: false } + +// 使用对象指定条件 +minBy(users, { active: true }); +// Returns: { name: '李四', age: 30, active: false } +``` + +空数组返回 undefined。 + +```typescript +import { minBy } from 'es-toolkit/compat'; + +minBy([], x => x.a); +// Returns: undefined + +minBy(null); +// Returns: undefined + +minBy(undefined); +// Returns: undefined +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要搜索的数组。 +- `iteratee` (`ValueIteratee`, 可选): 应用于每个元素的函数、属性名或条件。 + +#### 返回值 + +(`T | undefined`): 返回满足条件的值最小的元素。如果是空数组则返回 `undefined`。 diff --git a/docs/zh_hans/reference/compat/math/multiply.md b/docs/zh_hans/compat/reference/math/multiply.md similarity index 100% rename from docs/zh_hans/reference/compat/math/multiply.md rename to docs/zh_hans/compat/reference/math/multiply.md diff --git a/docs/zh_hans/reference/compat/math/parseInt.md b/docs/zh_hans/compat/reference/math/parseInt.md similarity index 100% rename from docs/zh_hans/reference/compat/math/parseInt.md rename to docs/zh_hans/compat/reference/math/parseInt.md diff --git a/docs/zh_hans/reference/compat/math/random.md b/docs/zh_hans/compat/reference/math/random.md similarity index 100% rename from docs/zh_hans/reference/compat/math/random.md rename to docs/zh_hans/compat/reference/math/random.md diff --git a/docs/zh_hans/compat/reference/math/range.md b/docs/zh_hans/compat/reference/math/range.md new file mode 100644 index 000000000..061c92a12 --- /dev/null +++ b/docs/zh_hans/compat/reference/math/range.md @@ -0,0 +1,99 @@ +# range(Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [range](../../../reference/math/range.md) + +这个 `range` 函数由于复杂的参数处理和类型转换而运行缓慢。 + +请使用更快更现代的 `es-toolkit` 的 [range](../../../reference/math/range.md)。 + +::: + +创建数字范围数组。 + +```typescript +const numbers = range(start, end, step); +``` + +## 用法 + +### `range(end)` + +创建从 0 到 end 以 1 递增的数组。 + +```typescript +import { range } from 'es-toolkit/compat'; + +range(4); +// Returns: [0, 1, 2, 3] + +range(0); +// Returns: [] + +range(-4); +// Returns: [0, -1, -2, -3] +``` + +### `range(start, end)` + +创建从 start 到 end 以 1 递增的数组。 + +```typescript +import { range } from 'es-toolkit/compat'; + +range(1, 5); +// Returns: [1, 2, 3, 4] + +range(5, 1); +// Returns: [5, 4, 3, 2] (自动以 -1 递减) + +range(-2, 3); +// Returns: [-2, -1, 0, 1, 2] +``` + +### `range(start, end, step)` + +创建从 start 到 end 以 step 递增的数组。 + +```typescript +import { range } from 'es-toolkit/compat'; + +range(0, 20, 5); +// Returns: [0, 5, 10, 15] + +range(0, -4, -1); +// Returns: [0, -1, -2, -3] + +range(1, 4, 0); +// Returns: [1, 1, 1] +``` + +小数 step 也可以使用。 + +```typescript +import { range } from 'es-toolkit/compat'; + +range(0, 1, 0.2); +// Returns: [0, 0.2, 0.4, 0.6, 0.8] + +range(1, 0, -0.25); +// Returns: [1, 0.75, 0.5, 0.25] +``` + +用作 iteratee 时通过 guard 对象处理。 + +```typescript +import { range } from 'es-toolkit/compat'; + +[1, 2, 3].map(range); +// Returns: [[0], [0, 1], [0, 1, 2]] +``` + +#### 参数 + +- `start` (`number`): 范围的起始值(包含)。如果没有 `end`,此值将成为 end。 +- `end` (`number`, 可选): 范围的结束值(不包含)。 +- `step` (`number`, 可选): 递增幅度。默认值为 1 或 -1。 + +#### 返回值 + +(`number[]`): 返回指定范围的数字数组。 diff --git a/docs/zh_hans/compat/reference/math/rangeRight.md b/docs/zh_hans/compat/reference/math/rangeRight.md new file mode 100644 index 000000000..64cd544d1 --- /dev/null +++ b/docs/zh_hans/compat/reference/math/rangeRight.md @@ -0,0 +1,99 @@ +# rangeRight(Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [rangeRight](../../../reference/math/rangeRight.md) + +这个 `rangeRight` 函数由于复杂的参数处理和类型转换而运行缓慢。 + +请使用更快更现代的 `es-toolkit` 的 [rangeRight](../../../reference/math/rangeRight.md)。 + +::: + +创建数字范围数组(逆序)。 + +```typescript +const numbers = rangeRight(start, end, step); +``` + +## 用法 + +### `rangeRight(end)` + +创建从 0 到 end 以 1 递增后逆序的数组。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(4); +// Returns: [3, 2, 1, 0] + +rangeRight(0); +// Returns: [] + +rangeRight(-4); +// Returns: [-3, -2, -1, 0] +``` + +### `rangeRight(start, end)` + +创建从 start 到 end 以 1 递增后逆序的数组。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(1, 5); +// Returns: [4, 3, 2, 1] + +rangeRight(5, 1); +// Returns: [2, 3, 4, 5] (自动以 -1 递减后逆序) + +rangeRight(-2, 3); +// Returns: [2, 1, 0, -1, -2] +``` + +### `rangeRight(start, end, step)` + +创建从 start 到 end 以 step 递增后逆序的数组。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(0, 8, 2); +// Returns: [6, 4, 2, 0] + +rangeRight(0, -4, -1); +// Returns: [-3, -2, -1, 0] + +rangeRight(1, 4, 0); +// Returns: [1, 1, 1] +``` + +小数 step 也可以使用。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +rangeRight(0, 1, 0.2); +// Returns: [0.8, 0.6, 0.4, 0.2, 0] + +rangeRight(1, 0, -0.25); +// Returns: [0.25, 0.5, 0.75, 1] +``` + +用作 iteratee 时通过 guard 对象处理。 + +```typescript +import { rangeRight } from 'es-toolkit/compat'; + +[1, 2, 3].map(rangeRight); +// Returns: [[0], [1, 0], [2, 1, 0]] +``` + +#### 参数 + +- `start` (`number`): 范围的起始值(包含)。如果没有 `end`,此值将成为 end。 +- `end` (`number`, 可选): 范围的结束值(不包含)。 +- `step` (`number`, 可选): 递增幅度。默认值为 1 或 -1。 + +#### 返回值 + +(`number[]`): 返回指定范围的数字数组(逆序)。 diff --git a/docs/zh_hans/reference/compat/math/round.md b/docs/zh_hans/compat/reference/math/round.md similarity index 100% rename from docs/zh_hans/reference/compat/math/round.md rename to docs/zh_hans/compat/reference/math/round.md diff --git a/docs/zh_hans/reference/compat/math/subtract.md b/docs/zh_hans/compat/reference/math/subtract.md similarity index 100% rename from docs/zh_hans/reference/compat/math/subtract.md rename to docs/zh_hans/compat/reference/math/subtract.md diff --git a/docs/zh_hans/compat/reference/math/sum.md b/docs/zh_hans/compat/reference/math/sum.md new file mode 100644 index 000000000..771186f2b --- /dev/null +++ b/docs/zh_hans/compat/reference/math/sum.md @@ -0,0 +1,73 @@ +# sum (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [sum](../../../reference/math/sum.md) + +这个 `sum` 函数由于类型转换和 null/undefined 处理会运行较慢。 + +请使用更快、更现代的 `es-toolkit` 的 [sum](../../../reference/math/sum.md)。 + +::: + +将数组的所有值相加。 + +```typescript +const total = sum(array); +``` + +## 用法 + +### `sum(array)` + +将数组中的所有数字相加得到总和。 + +```typescript +import { sum } from 'es-toolkit/compat'; + +// 数字数组 +sum([1, 2, 3]); +// Returns: 6 + +sum([1.5, 2.5, 3]); +// Returns: 7 + +// 空数组 +sum([]); +// Returns: 0 +``` + +BigInt 和字符串也能处理。 + +```typescript +import { sum } from 'es-toolkit/compat'; + +// BigInt 数组 +sum([1n, 2n, 3n]); +// Returns: 6n + +// 字符串数组(连接) +sum(['1', '2']); +// Returns: '12' +``` + +无效值会被忽略。 + +```typescript +import { sum } from 'es-toolkit/compat'; + +sum([1, undefined, 2]); +// Returns: 3 (忽略 undefined) + +sum(null); +// Returns: 0 + +sum(undefined); +// Returns: 0 +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 包含要相加值的数组。 + +#### 返回值 + +(`number`): 返回所有值相加的总和。 diff --git a/docs/zh_hans/compat/reference/math/sumBy.md b/docs/zh_hans/compat/reference/math/sumBy.md new file mode 100644 index 000000000..9794a3af4 --- /dev/null +++ b/docs/zh_hans/compat/reference/math/sumBy.md @@ -0,0 +1,103 @@ +# sumBy(Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [sumBy](../../../reference/math/sumBy.md) + +这个 `sumBy` 函数由于 iteratee 函数处理和类型转换而运行缓慢。 + +请使用更快更现代的 `es-toolkit` 的 [sumBy](../../../reference/math/sumBy.md)。 + +::: + +将满足条件的值相加。 + +```typescript +const total = sumBy(array, iteratee); +``` + +## 用法 + +### `sumBy(array, iteratee)` + +对数组的每个元素应用函数后将结果相加。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +// 数字数组 +sumBy([1, 2, 3], value => value); +// Returns: 6 + +sumBy([1.5, 2.5, 3.5], value => Math.floor(value)); +// Returns: 6 (1 + 2 + 3) + +// 空数组 +sumBy([], value => value); +// Returns: 0 +``` + +### `sumBy(array)` + +不提供函数时直接将数组值相加。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +sumBy([1, 2, 3]); +// Returns: 6 + +sumBy([1n, 2n, 3n]); +// Returns: 6n +``` + +将对象数组中的特定属性相加。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +const people = [ + { name: '张三', age: 25 }, + { name: '李四', age: 30 }, + { name: '王五', age: 35 }, +]; + +sumBy(people, person => person.age); +// Returns: 90 + +// 也可以使用属性名 +sumBy(people, 'age'); +// Returns: 90 +``` + +字符串也会被连接。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +const items = [{ a: '1' }, { a: '2' }]; +sumBy(items, obj => obj.a); +// Returns: '12' +``` + +无效值会被忽略。 + +```typescript +import { sumBy } from 'es-toolkit/compat'; + +sumBy([1, undefined, 2], value => value); +// Returns: 3 (忽略 undefined) + +sumBy(null); +// Returns: 0 + +sumBy(undefined); +// Returns: 0 +``` + +#### 参数 + +- `array` (`ArrayLike | null | undefined`): 要处理的数组。 +- `iteratee` (`((value: T) => number) | string`, 可选): 应用于每个元素的函数或属性名。 + +#### 返回值 + +(`number`): 返回满足条件的值的总和。 diff --git a/docs/zh_hans/reference/compat/object/assign.md b/docs/zh_hans/compat/reference/object/assign.md similarity index 100% rename from docs/zh_hans/reference/compat/object/assign.md rename to docs/zh_hans/compat/reference/object/assign.md diff --git a/docs/zh_hans/reference/compat/object/assignIn.md b/docs/zh_hans/compat/reference/object/assignIn.md similarity index 100% rename from docs/zh_hans/reference/compat/object/assignIn.md rename to docs/zh_hans/compat/reference/object/assignIn.md diff --git a/docs/zh_hans/reference/compat/object/assignInWith.md b/docs/zh_hans/compat/reference/object/assignInWith.md similarity index 100% rename from docs/zh_hans/reference/compat/object/assignInWith.md rename to docs/zh_hans/compat/reference/object/assignInWith.md diff --git a/docs/zh_hans/reference/compat/object/assignWith.md b/docs/zh_hans/compat/reference/object/assignWith.md similarity index 100% rename from docs/zh_hans/reference/compat/object/assignWith.md rename to docs/zh_hans/compat/reference/object/assignWith.md diff --git a/docs/zh_hans/reference/compat/object/at.md b/docs/zh_hans/compat/reference/object/at.md similarity index 100% rename from docs/zh_hans/reference/compat/object/at.md rename to docs/zh_hans/compat/reference/object/at.md diff --git a/docs/zh_hans/compat/reference/object/clone.md b/docs/zh_hans/compat/reference/object/clone.md new file mode 100644 index 000000000..070062225 --- /dev/null +++ b/docs/zh_hans/compat/reference/object/clone.md @@ -0,0 +1,89 @@ +# clone (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `clone` + +这个 `clone` 函数由于处理特殊对象类型的复杂逻辑而相对较慢。 + +请改用 `es-toolkit` 的更快、更现代的 [clone](../../../reference/object/clone.md)。 + +::: + +创建对象的浅拷贝。 + +```typescript +const cloned = clone(value); +``` + +## 用法 + +### `clone(value)` + +当您想要创建值的浅拷贝时,请使用 `clone`。它可以复制各种类型的对象和原始值。 + +```typescript +import { clone } from 'es-toolkit/compat'; + +// 复制原始值 +const num = 42; +const clonedNum = clone(num); +// Returns: 42 (相同的值) + +// 复制数组 +const arr = [1, 2, 3]; +const clonedArr = clone(arr); +// Returns: [1, 2, 3] (新的数组实例) + +// 复制对象 +const obj = { a: 1, b: 'hello' }; +const clonedObj = clone(obj); +// Returns: { a: 1, b: 'hello' } (新的对象实例) + +// 复制Date对象 +const date = new Date('2023-01-01'); +const clonedDate = clone(date); +// Returns: new Date('2023-01-01') (新的Date实例) + +// 复制正则表达式 +const regex = /hello/gi; +regex.lastIndex = 3; +const clonedRegex = clone(regex); +// Returns: /hello/gi with lastIndex = 3 + +// 复制Map +const map = new Map([ + ['a', 1], + ['b', 2], +]); +const clonedMap = clone(map); +// Returns: new Map([['a', 1], ['b', 2]]) + +// 复制Set +const set = new Set([1, 2, 3]); +const clonedSet = clone(set); +// Returns: new Set([1, 2, 3]) +``` + +嵌套对象仅进行浅拷贝。 + +```typescript +import { clone } from 'es-toolkit/compat'; + +const nested = { + a: 1, + b: { + c: 2, + }, +}; +const clonedNested = clone(nested); + +console.log(clonedNested !== nested); // true (不同的对象) +console.log(clonedNested.b === nested.b); // true (嵌套对象具有相同的引用) +``` + +#### 参数 + +- `value` (`T`): 要复制的值。 + +#### 返回值 + +(`T`): 返回复制的值。 diff --git a/docs/zh_hans/compat/reference/object/cloneDeep.md b/docs/zh_hans/compat/reference/object/cloneDeep.md new file mode 100644 index 000000000..2bf72d71f --- /dev/null +++ b/docs/zh_hans/compat/reference/object/cloneDeep.md @@ -0,0 +1,88 @@ +# cloneDeep (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `cloneDeep` + +这个 `cloneDeep` 函数由于处理特殊对象类型的复杂逻辑而相对较慢。 + +请改用 `es-toolkit` 的更快、更现代的 [cloneDeep](../../../reference/object/cloneDeep.md)。 + +::: + +创建对象的深拷贝。 + +```typescript +const cloned = cloneDeep(value); +``` + +## 用法 + +### `cloneDeep(value)` + +当您想要创建值的深拷贝时,请使用 `cloneDeep`。它将嵌套的对象和数组完全复制为新实例。 + +```typescript +import { cloneDeep } from 'es-toolkit/compat'; + +// 复制原始值 +const num = 42; +const clonedNum = cloneDeep(num); +// Returns: 42 (相同的值) + +// 深拷贝数组 +const arr = [1, [2, 3], { a: 4 }]; +const clonedArr = cloneDeep(arr); +clonedArr[1][0] = 99; +console.log(arr[1][0]); // 2 (原始值未更改) +console.log(clonedArr[1][0]); // 99 + +// 深拷贝对象 +const obj = { + a: 1, + b: { + c: 2, + d: { + e: 3, + }, + }, +}; +const clonedObj = cloneDeep(obj); +clonedObj.b.d.e = 99; +console.log(obj.b.d.e); // 3 (原始值未更改) +console.log(clonedObj.b.d.e); // 99 + +// 深拷贝Date对象 +const date = new Date('2023-01-01'); +const clonedDate = cloneDeep(date); +// Returns: new Date('2023-01-01') (新的Date实例) + +// 复杂的嵌套结构 +const complex = { + arr: [1, { nested: true }], + map: new Map([['key', { value: 1 }]]), + set: new Set([{ item: 1 }]), + date: new Date(), +}; +const clonedComplex = cloneDeep(complex); +// 所有嵌套对象都作为完全新的实例被复制 +``` + +循环引用也得到正确处理。 + +```typescript +import { cloneDeep } from 'es-toolkit/compat'; + +const obj = { a: 1 }; +obj.self = obj; // 循环引用 + +const cloned = cloneDeep(obj); +console.log(cloned !== obj); // true +console.log(cloned.self === cloned); // true (保留循环引用) +``` + +#### 参数 + +- `value` (`T`): 要深拷贝的值。 + +#### 返回值 + +(`T`): 返回深拷贝的值。 diff --git a/docs/zh_hans/reference/compat/object/cloneDeepWith.md b/docs/zh_hans/compat/reference/object/cloneDeepWith.md similarity index 100% rename from docs/zh_hans/reference/compat/object/cloneDeepWith.md rename to docs/zh_hans/compat/reference/object/cloneDeepWith.md diff --git a/docs/zh_hans/reference/compat/object/cloneWith.md b/docs/zh_hans/compat/reference/object/cloneWith.md similarity index 100% rename from docs/zh_hans/reference/compat/object/cloneWith.md rename to docs/zh_hans/compat/reference/object/cloneWith.md diff --git a/docs/zh_hans/reference/compat/object/create.md b/docs/zh_hans/compat/reference/object/create.md similarity index 100% rename from docs/zh_hans/reference/compat/object/create.md rename to docs/zh_hans/compat/reference/object/create.md diff --git a/docs/zh_hans/reference/compat/object/defaults.md b/docs/zh_hans/compat/reference/object/defaults.md similarity index 100% rename from docs/zh_hans/reference/compat/object/defaults.md rename to docs/zh_hans/compat/reference/object/defaults.md diff --git a/docs/zh_hans/reference/compat/object/defaultsDeep.md b/docs/zh_hans/compat/reference/object/defaultsDeep.md similarity index 100% rename from docs/zh_hans/reference/compat/object/defaultsDeep.md rename to docs/zh_hans/compat/reference/object/defaultsDeep.md diff --git a/docs/zh_hans/reference/compat/object/extend.md b/docs/zh_hans/compat/reference/object/extend.md similarity index 100% rename from docs/zh_hans/reference/compat/object/extend.md rename to docs/zh_hans/compat/reference/object/extend.md diff --git a/docs/zh_hans/reference/compat/object/extendWith.md b/docs/zh_hans/compat/reference/object/extendWith.md similarity index 100% rename from docs/zh_hans/reference/compat/object/extendWith.md rename to docs/zh_hans/compat/reference/object/extendWith.md diff --git a/docs/zh_hans/compat/reference/object/findKey.md b/docs/zh_hans/compat/reference/object/findKey.md new file mode 100644 index 000000000..ea28d58fa --- /dev/null +++ b/docs/zh_hans/compat/reference/object/findKey.md @@ -0,0 +1,61 @@ +# findKey (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `findKey` + +由于需要处理各种条件类型和兼容性逻辑,此 `findKey` 函数的行为较为复杂。 + +建议使用更快、更现代的 `es-toolkit` 的 [findKey](../../../reference/object/findKey.md)。 + +::: + +查找满足条件的第一个元素的键。 + +```typescript +const key = findKey(obj, predicate); +``` + +## 用法 + +### `findKey(obj, predicate)` + +使用 `findKey` 在对象中查找满足条件的第一个元素的键。可以使用函数、对象、数组、字符串等各种形式的条件。 + +```typescript +import { findKey } from 'es-toolkit/compat'; + +// 使用函数条件查找键 +const users = { + alice: { age: 25, active: true }, + bob: { age: 30, active: false }, + charlie: { age: 35, active: true }, +}; + +findKey(users, user => user.age > 30); +// 返回值: 'charlie' + +// 使用对象条件查找键 +findKey(users, { active: false }); +// 返回值: 'bob' + +// 使用属性路径查找键 +findKey(users, 'active'); +// 返回值: 'alice' +``` + +如果没有匹配的元素,则返回 `undefined`。 + +```typescript +import { findKey } from 'es-toolkit/compat'; + +findKey({ a: 1, b: 2 }, value => value > 5); +// 返回值: undefined +``` + +#### 参数 + +- `obj` (`T | null | undefined`): 要搜索的对象。 +- `predicate` (`ObjectIteratee`, 可选): 应用于每个元素的条件。可以是函数、对象、数组或字符串。 + +#### 返回值 + +(`string | undefined`): 返回满足条件的第一个元素的键。如果没有找到匹配项,则返回 `undefined`。 diff --git a/docs/zh_hans/reference/compat/object/findLastKey.md b/docs/zh_hans/compat/reference/object/findLastKey.md similarity index 100% rename from docs/zh_hans/reference/compat/object/findLastKey.md rename to docs/zh_hans/compat/reference/object/findLastKey.md diff --git a/docs/zh_hans/reference/compat/object/forIn.md b/docs/zh_hans/compat/reference/object/forIn.md similarity index 100% rename from docs/zh_hans/reference/compat/object/forIn.md rename to docs/zh_hans/compat/reference/object/forIn.md diff --git a/docs/zh_hans/reference/compat/object/forInRight.md b/docs/zh_hans/compat/reference/object/forInRight.md similarity index 100% rename from docs/zh_hans/reference/compat/object/forInRight.md rename to docs/zh_hans/compat/reference/object/forInRight.md diff --git a/docs/zh_hans/reference/compat/object/forOwn.md b/docs/zh_hans/compat/reference/object/forOwn.md similarity index 100% rename from docs/zh_hans/reference/compat/object/forOwn.md rename to docs/zh_hans/compat/reference/object/forOwn.md diff --git a/docs/zh_hans/reference/compat/object/forOwnRight.md b/docs/zh_hans/compat/reference/object/forOwnRight.md similarity index 100% rename from docs/zh_hans/reference/compat/object/forOwnRight.md rename to docs/zh_hans/compat/reference/object/forOwnRight.md diff --git a/docs/zh_hans/reference/compat/object/fromPairs.md b/docs/zh_hans/compat/reference/object/fromPairs.md similarity index 100% rename from docs/zh_hans/reference/compat/object/fromPairs.md rename to docs/zh_hans/compat/reference/object/fromPairs.md diff --git a/docs/zh_hans/reference/compat/object/functions.md b/docs/zh_hans/compat/reference/object/functions.md similarity index 100% rename from docs/zh_hans/reference/compat/object/functions.md rename to docs/zh_hans/compat/reference/object/functions.md diff --git a/docs/zh_hans/reference/compat/object/functionsIn.md b/docs/zh_hans/compat/reference/object/functionsIn.md similarity index 100% rename from docs/zh_hans/reference/compat/object/functionsIn.md rename to docs/zh_hans/compat/reference/object/functionsIn.md diff --git a/docs/zh_hans/reference/compat/object/get.md b/docs/zh_hans/compat/reference/object/get.md similarity index 100% rename from docs/zh_hans/reference/compat/object/get.md rename to docs/zh_hans/compat/reference/object/get.md diff --git a/docs/zh_hans/reference/compat/object/has.md b/docs/zh_hans/compat/reference/object/has.md similarity index 100% rename from docs/zh_hans/reference/compat/object/has.md rename to docs/zh_hans/compat/reference/object/has.md diff --git a/docs/zh_hans/reference/compat/object/hasIn.md b/docs/zh_hans/compat/reference/object/hasIn.md similarity index 100% rename from docs/zh_hans/reference/compat/object/hasIn.md rename to docs/zh_hans/compat/reference/object/hasIn.md diff --git a/docs/zh_hans/compat/reference/object/invert.md b/docs/zh_hans/compat/reference/object/invert.md new file mode 100644 index 000000000..26e89c48d --- /dev/null +++ b/docs/zh_hans/compat/reference/object/invert.md @@ -0,0 +1,60 @@ +# invert (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `invert` + +由于 Lodash 兼容性所需的复杂处理,此 `invert` 函数运行较慢。 + +请使用更快、更现代的 `es-toolkit` 的 [`invert`](../../../reference/object/invert.md)。 + +::: + +反转对象的键和值。 + +```typescript +const inverted = invert(object); +``` + +## 用法 + +### `invert(object)` + +当您想要交换对象的键和值时,请使用 `invert`。原始对象的键将成为新对象的值,原始对象的值将成为新对象的键。 + +```typescript +import { invert } from 'es-toolkit/compat'; + +// 基本键值反转 +const object = { a: 1, b: 2, c: 3 }; +invert(object); +// => { '1': 'a', '2': 'b', '3': 'c' } + +// 反转字符串值 +const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' }; +invert(colors); +// => { '#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue' } + +// 混合键和值类型 +const mixed = { a: 1, 2: 'b', c: 3, 4: 'd' }; +invert(mixed); +// => { '1': 'a', 'b': '2', '3': 'c', 'd': '4' } +``` + +当存在重复值时,将使用最后一个键。 + +```typescript +import { invert } from 'es-toolkit/compat'; + +// 存在重复值的情况 +const object = { a: 1, b: 1, c: 2 }; +invert(object); +// => { '1': 'b', '2': 'c' } +// 'a' 被覆盖并丢失 +``` + +#### 参数 + +- `object` (`object`): 要反转的对象。 + +#### 返回值 + +(`Record`): 返回键和值反转后的新对象。 diff --git a/docs/zh_hans/reference/compat/object/invertBy.md b/docs/zh_hans/compat/reference/object/invertBy.md similarity index 100% rename from docs/zh_hans/reference/compat/object/invertBy.md rename to docs/zh_hans/compat/reference/object/invertBy.md diff --git a/docs/zh_hans/reference/compat/object/keys.md b/docs/zh_hans/compat/reference/object/keys.md similarity index 100% rename from docs/zh_hans/reference/compat/object/keys.md rename to docs/zh_hans/compat/reference/object/keys.md diff --git a/docs/zh_hans/reference/compat/object/keysIn.md b/docs/zh_hans/compat/reference/object/keysIn.md similarity index 100% rename from docs/zh_hans/reference/compat/object/keysIn.md rename to docs/zh_hans/compat/reference/object/keysIn.md diff --git a/docs/zh_hans/compat/reference/object/mapKeys.md b/docs/zh_hans/compat/reference/object/mapKeys.md new file mode 100644 index 000000000..6bf57dcb9 --- /dev/null +++ b/docs/zh_hans/compat/reference/object/mapKeys.md @@ -0,0 +1,63 @@ +# mapKeys (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `mapKeys` + +这个 `mapKeys` 函数由于处理 `null` 或 `undefined` 以及 `iteratee` 转换过程而相对较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`mapKeys`](../../../reference/object/mapKeys.md)。 + +::: + +通过转换键来创建新对象,同时保持值不变。 + +```typescript +const result = mapKeys(obj, iteratee); +``` + +## 用法 + +### `mapKeys(object, iteratee)` + +使用 `iteratee` 函数转换对象中的每个键来创建新对象。值保持不变,只修改键。适用于转换或规范化对象键。 + +```typescript +import { mapKeys } from 'es-toolkit/compat'; + +// 为键添加前缀 +const obj = { a: 1, b: 2, c: 3 }; +const result = mapKeys(obj, (value, key) => 'prefix_' + key); +// 结果: { prefix_a: 1, prefix_b: 2, prefix_c: 3 } + +// 将键转换为大写 +const data = { name: 'John', age: 30 }; +const uppercased = mapKeys(data, (value, key) => key.toUpperCase()); +// 结果: { NAME: 'John', AGE: 30 } + +// 将数组索引转换为键 +const arr = ['apple', 'banana', 'orange']; +const indexed = mapKeys(arr, (value, index) => `item_${index}`); +// 结果: { item_0: 'apple', item_1: 'banana', item_2: 'orange' } + +// 通过组合键和值创建新键 +const scores = { math: 90, science: 85, english: 92 }; +const detailed = mapKeys(scores, (value, key) => `${key}_score_${value}`); +// 结果: { math_score_90: 90, science_score_85: 85, english_score_92: 92 } +``` + +`null` 或 `undefined` 被视为空对象。 + +```typescript +import { mapKeys } from 'es-toolkit/compat'; + +mapKeys(null, iteratee); // {} +mapKeys(undefined, iteratee); // {} +``` + +#### 参数 + +- `object` (`ArrayLike | T | null | undefined`): 要转换键的对象或数组。 +- `iteratee` (`ListIteratee | ObjectIteratee`, 可选): 用于转换每个键的函数。默认为 `identity` 函数。 + +#### 返回值 + +(`Record | Record`): 返回一个具有转换后键的新对象。 diff --git a/docs/zh_hans/compat/reference/object/mapValues.md b/docs/zh_hans/compat/reference/object/mapValues.md new file mode 100644 index 000000000..a74445632 --- /dev/null +++ b/docs/zh_hans/compat/reference/object/mapValues.md @@ -0,0 +1,71 @@ +# mapValues (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `mapValues` + +这个 `mapValues` 函数由于处理 `null` 或 `undefined` 以及 `iteratee` 转换过程而相对较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`mapValues`](../../../reference/object/mapValues.md)。 + +::: + +通过转换值来创建新对象,同时保持键不变。 + +```typescript +const result = mapValues(obj, iteratee); +``` + +## 用法 + +### `mapValues(object, iteratee)` + +使用 `iteratee` 函数转换对象中的每个值来创建新对象。键保持不变,只修改值。可以处理字符串、数组和对象。适用于转换或计算数据。 + +```typescript +import { mapValues } from 'es-toolkit/compat'; + +// 转换对象值 +const obj = { a: 1, b: 2, c: 3 }; +const doubled = mapValues(obj, value => value * 2); +// 结果: { a: 2, b: 4, c: 6 } + +// 将字符串转换为大写 +const names = { first: 'john', last: 'doe' }; +const uppercased = mapValues(names, value => value.toUpperCase()); +// 结果: { first: 'JOHN', last: 'DOE' } + +// 转换字符串中的每个字符 +const str = 'abc'; +const charMap = mapValues(str, char => char.toUpperCase()); +// 结果: { '0': 'A', '1': 'B', '2': 'C' } + +// 将数组转换为对象 +const arr = [10, 20, 30]; +const arrMap = mapValues(arr, (value, index) => value + index); +// 结果: { '0': 10, '1': 21, '2': 32 } + +// 使用属性路径提取值 +const users = { + user1: { profile: { name: 'Alice' } }, + user2: { profile: { name: 'Bob' } }, +}; +const userNames = mapValues(users, 'profile.name'); +// 结果: { user1: 'Alice', user2: 'Bob' } +``` + +`null` 或 `undefined` 被视为空对象。 + +```typescript +import { mapValues } from 'es-toolkit/compat'; + +mapValues(null, iteratee); // {} +mapValues(undefined, iteratee); // {} +``` + +#### 参数 + +- `object` (`string | T[] | T | null | undefined`): 要转换值的对象、数组或字符串。 +- `iteratee` (`ValueIteratee`, 可选): 用于转换每个值的函数、属性路径或匹配对象。默认为 `identity` 函数。 + +#### 返回值 + +(`Record | { [P in keyof T]: U } | Record | Record | Partial`): 返回一个具有转换后值的新对象。 diff --git a/docs/zh_hans/compat/reference/object/merge.md b/docs/zh_hans/compat/reference/object/merge.md new file mode 100644 index 000000000..b30be2a4c --- /dev/null +++ b/docs/zh_hans/compat/reference/object/merge.md @@ -0,0 +1,82 @@ +# merge (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `merge` + +这个 `merge` 函数由于内部调用复杂的 `mergeWith` 函数而相对较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`merge`](../../../reference/object/merge.md)。 + +::: + +深度合并多个对象为单个对象。 + +```typescript +const result = merge(target, ...sources); +``` + +## 用法 + +### `merge(object, ...sources)` + +将一个或多个源对象深度合并到目标对象中。嵌套的对象和数组会递归合并。如果源对象的属性是 `undefined`,则不会覆盖目标对象中的现有值。适用于合并对象配置或应用默认值。 + +```typescript +import { merge } from 'es-toolkit/compat'; + +// 基本对象合并 +const target = { a: 1, b: { x: 1, y: 2 } }; +const source = { b: { y: 3, z: 4 }, c: 5 }; +const result = merge(target, source); +// 结果: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } + +// 数组合并 +const obj1 = { arr: [1, 2] }; +const obj2 = { arr: [3, 4] }; +const merged = merge(obj1, obj2); +// 结果: { arr: [3, 4] } (数组被替换) + +// 多个对象合并 +const base = { a: 1 }; +const ext1 = { b: 2 }; +const ext2 = { c: 3 }; +const ext3 = { d: 4 }; +const combined = merge(base, ext1, ext2, ext3); +// 结果: { a: 1, b: 2, c: 3, d: 4 } + +// 嵌套对象合并 +const config = { + api: { url: 'https://api.example.com', timeout: 5000 }, + features: { auth: true }, +}; +const overrides = { + api: { timeout: 10000, retries: 3 }, + features: { analytics: true }, +}; +const finalConfig = merge(config, overrides); +// 结果: { +// api: { url: 'https://api.example.com', timeout: 10000, retries: 3 }, +// features: { auth: true, analytics: true } +// } +``` + +目标对象会被修改,因此如需保留原始对象请使用空对象。 + +```typescript +import { merge } from 'es-toolkit/compat'; + +const original = { a: 1, b: { x: 1 } }; +const source = { b: { y: 2 } }; + +// 保留原始对象 +const result = merge({}, original, source); +// original 未被修改 +``` + +#### 参数 + +- `object` (`any`): 要合并到的目标对象。此对象会被修改。 +- `...sources` (`any[]`): 要合并的源对象。 + +#### 返回值 + +(`any`): 返回合并后的目标对象。 diff --git a/docs/zh_hans/compat/reference/object/mergeWith.md b/docs/zh_hans/compat/reference/object/mergeWith.md new file mode 100644 index 000000000..570e6645b --- /dev/null +++ b/docs/zh_hans/compat/reference/object/mergeWith.md @@ -0,0 +1,94 @@ +# mergeWith (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `mergeWith` + +这个 `mergeWith` 函数由于复杂的类型检查、循环引用处理和特殊对象处理而相对较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`mergeWith`](../../../reference/object/mergeWith.md)。 + +::: + +使用自定义函数控制合并行为,深度合并多个对象。 + +```typescript +const result = mergeWith(target, ...sources, customizer); +``` + +## 用法 + +### `mergeWith(object, ...sources, customizer)` + +将一个或多个源对象深度合并到目标对象中,使用自定义函数控制合并行为。如果自定义函数返回 `undefined`,则使用默认合并逻辑。适用于连接数组或应用特殊合并规则。 + +```typescript +import { mergeWith } from 'es-toolkit/compat'; + +// 数字相加 +const obj1 = { a: 1, b: 2 }; +const obj2 = { b: 3, c: 4 }; +const result = mergeWith(obj1, obj2, (objValue, srcValue) => { + if (typeof objValue === 'number' && typeof srcValue === 'number') { + return objValue + srcValue; + } +}); +// 结果: { a: 1, b: 5, c: 4 } + +// 连接数组 +const arr1 = { items: [1, 2] }; +const arr2 = { items: [3, 4] }; +const merged = mergeWith(arr1, arr2, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return objValue.concat(srcValue); + } +}); +// 结果: { items: [1, 2, 3, 4] } + +// 连接字符串 +const str1 = { message: 'Hello' }; +const str2 = { message: 'World' }; +const combined = mergeWith(str1, str2, (objValue, srcValue, key) => { + if (key === 'message' && typeof objValue === 'string') { + return objValue + ' ' + srcValue; + } +}); +// 结果: { message: 'Hello World' } + +// 多个源对象与自定义函数 +const base = { scores: [80] }; +const quiz1 = { scores: [90] }; +const quiz2 = { scores: [85] }; +const final = mergeWith(base, quiz1, quiz2, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return objValue.concat(srcValue); + } +}); +// 结果: { scores: [80, 90, 85] } +``` + +自定义函数接收各种参数。 + +```typescript +import { mergeWith } from 'es-toolkit/compat'; + +const customizer = (objValue, srcValue, key, object, source, stack) => { + console.log('合并中:', key, objValue, '->', srcValue); + + // 仅对特定键进行自定义 + if (key === 'specialField') { + return `${objValue}_${srcValue}`; + } + + // 返回undefined使用默认合并逻辑 + return undefined; +}; +``` + +#### 参数 + +- `object` (`any`): 要合并到的目标对象。此对象会被修改。 +- `...sources` (`any[]`): 要合并的源对象。 +- `customizer` (`MergeWithCustomizer`): 自定义值分配的函数。格式: `(objValue, srcValue, key, object, source, stack) => any`。 + +#### 返回值 + +(`any`): 返回合并后的目标对象。 diff --git a/docs/zh_hans/compat/reference/object/omit.md b/docs/zh_hans/compat/reference/object/omit.md new file mode 100644 index 000000000..785a2f576 --- /dev/null +++ b/docs/zh_hans/compat/reference/object/omit.md @@ -0,0 +1,82 @@ +# omit (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `omit` + +这个 `omit` 函数由于深拷贝和调用 `unset` 函数而相对较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`omit`](../../../reference/object/omit.md)。 + +::: + +创建一个排除指定键的新对象。 + +```typescript +const result = omit(obj, ...keys); +``` + +## 用法 + +### `omit(object, ...paths)` + +创建一个排除指定键的新对象。支持深层键路径,可以使用数组一次指定多个键。适用于从对象中删除敏感信息或仅选择需要的属性。 + +```typescript +import { omit } from 'es-toolkit/compat'; + +// 删除基本键 +const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }; +const publicUser = omit(user, 'password', 'email'); +// 结果: { id: 1, name: 'John' } + +// 使用数组删除多个键 +const data = { a: 1, b: 2, c: 3, d: 4 }; +const filtered = omit(data, ['a', 'c']); +// 结果: { b: 2, d: 4 } + +// 删除深层键路径 +const nested = { + user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, + admin: true, +}; +const result = omit(nested, 'user.profile.age', 'admin'); +// 结果: { user: { profile: { name: 'John' }, settings: { theme: 'dark' } } } + +// 组合嵌套数组和键 +const complex = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; +const simplified = omit(complex, 'a', ['b', 'c'], 'd.f'); +// 结果: { d: { e: 4 } } +``` + +您可以自由组合数组、字符串和键路径。 + +```typescript +import { omit } from 'es-toolkit/compat'; + +const config = { + api: { url: 'https://api.example.com', key: 'secret', timeout: 5000 }, + ui: { theme: 'dark', language: 'en' }, + debug: true, +}; + +// 以多种方式指定键 +const cleaned = omit(config, 'api.key', ['debug'], 'ui.language'); +// 结果: { api: { url: 'https://api.example.com', timeout: 5000 }, ui: { theme: 'dark' } } +``` + +`null` 或 `undefined` 被视为空对象。 + +```typescript +import { omit } from 'es-toolkit/compat'; + +omit(null, 'key'); // {} +omit(undefined, 'key'); // {} +``` + +#### 参数 + +- `object` (`T | null | undefined`): 要删除键的源对象。 +- `...paths` (`Array>`): 要删除的键。可以指定单个键、键数组或深层键路径。 + +#### 返回值 + +(`Partial`): 返回删除指定键后的新对象。 diff --git a/docs/zh_hans/compat/reference/object/omitBy.md b/docs/zh_hans/compat/reference/object/omitBy.md new file mode 100644 index 000000000..0a941e49d --- /dev/null +++ b/docs/zh_hans/compat/reference/object/omitBy.md @@ -0,0 +1,76 @@ +# omitBy (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `omitBy` + +这个 `omitBy` 函数由于类数组对象检查、`iteratee` 转换和键转换过程而相对较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`omitBy`](../../../reference/object/omitBy.md)。 + +::: + +创建一个新对象,排除断言函数返回true的属性。 + +```typescript +const result = omitBy(obj, predicate); +``` + +## 用法 + +### `omitBy(object, predicate)` + +对对象的每个属性执行断言函数,并创建一个新对象,排除断言返回true的属性。适用于根据条件动态过滤属性。 + +```typescript +import { omitBy } from 'es-toolkit/compat'; + +// 删除特定类型的值 +const data = { a: 1, b: 'remove', c: 3, d: 'keep' }; +const numbers = omitBy(data, value => typeof value === 'string'); +// 结果: { a: 1, c: 3 } + +// 根据条件删除属性 +const user = { id: 1, name: 'John', age: 0, active: false, email: '' }; +const validData = omitBy(user, value => !value); +// 结果: { id: 1, name: 'John' } (删除假值) + +// 按键名过滤 +const settings = { userSetting: true, adminSetting: false, debugMode: true }; +const userOnly = omitBy(settings, (value, key) => key.startsWith('admin')); +// 结果: { userSetting: true, debugMode: true } + +// 仅删除数字属性 +const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; +const noNumbers = omitBy(mixed, value => typeof value === 'number'); +// 结果: { str: 'hello', bool: true, obj: {} } + +// 也可用于数组 +const arr = [1, 2, 3, 4, 5]; +const filtered = omitBy(arr, value => value % 2 === 0); +// 结果: { '0': 1, '2': 3, '4': 5 } (偶数索引处的奇数值) + +// 利用值、键和原始对象 +const scores = { math: 90, science: 75, english: 85, art: 60 }; +const passingGrades = omitBy(scores, (value, key, obj) => { + console.log(`${key}: ${value} (平均: ${Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length})`); + return value < 80; +}); +// 结果: { math: 90, english: 85 } +``` + +`null` 或 `undefined` 被视为空对象。 + +```typescript +import { omitBy } from 'es-toolkit/compat'; + +omitBy(null, () => true); // {} +omitBy(undefined, () => true); // {} +``` + +#### 参数 + +- `object` (`Record | Record | object | null | undefined`): 要过滤的源对象。 +- `predicate` (`ValueKeyIteratee | ValueKeyIteratee`, 可选): 对每个属性执行的断言函数。此函数返回true的属性将被删除。默认为 `identity` 函数。 + +#### 返回值 + +(`Record | Record | Partial`): 返回一个由不满足条件的属性组成的新对象。 diff --git a/docs/zh_hans/compat/reference/object/pick.md b/docs/zh_hans/compat/reference/object/pick.md new file mode 100644 index 000000000..b65a19d99 --- /dev/null +++ b/docs/zh_hans/compat/reference/object/pick.md @@ -0,0 +1,73 @@ +# pick (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `pick` + +这个 `pick` 函数由于复杂的路径处理、调用 `get`/`set` 函数以及处理 `null`/`undefined` 而相对较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`pick`](../../../reference/object/pick.md)。 + +::: + +通过仅选择指定属性来创建新对象。 + +```typescript +const result = pick(obj, ...keys); +``` + +## 用法 + +### `pick(object, ...props)` + +当您想创建一个仅包含对象中所需属性的新对象时,请使用 `pick`。可以使用数组一次传递多个键,或将它们作为单个参数逐个传递。支持深层键路径,因此您也可以选择嵌套属性。 + +```typescript +import { pick } from 'es-toolkit/compat'; + +// 基本用法 +const obj = { a: 1, b: 2, c: 3, d: 4 }; +const result = pick(obj, ['a', 'c']); +// 结果: { a: 1, c: 3 } + +// 作为单个参数传递 +const result2 = pick(obj, 'a', 'c'); +// 结果: { a: 1, c: 3 } + +// 选择深层路径 +const nested = { + user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, + admin: true, +}; +const userInfo = pick(nested, 'user.profile.name', 'admin'); +// 结果: { user: { profile: { name: 'John' } }, admin: true } + +// 混合数组和单个键 +const mixed = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; +const selected = pick(mixed, ['a', 'b'], 'c', 'd.e'); +// 结果: { a: 1, b: 2, c: 3, d: { e: 4 } } + +// 区分点表示法键和实际带点的键 +const ambiguous = { + 'a.b': 1, // 实际键 'a.b' + a: { b: 2, c: 3 }, // 嵌套对象 +}; +const dotKey = pick(ambiguous, 'a.b'); +// 结果: { 'a.b': 1 } (实际键优先) +``` + +`null` 或 `undefined` 被视为空对象。 + +```typescript +import { pick } from 'es-toolkit/compat'; + +pick(null, ['a', 'b']); // {} +pick(undefined, ['a', 'b']); // {} +``` + +#### 参数 + +- `object` (`T | null | undefined`): 要选择属性的对象。 +- `...props` (`Array>`): 要选择的属性键。可以指定单个键、键数组或深层键路径。 + +#### 返回值 + +(`Pick | Partial`): 返回仅包含指定属性的新对象。 diff --git a/docs/zh_hans/compat/reference/object/pickBy.md b/docs/zh_hans/compat/reference/object/pickBy.md new file mode 100644 index 000000000..52615bffd --- /dev/null +++ b/docs/zh_hans/compat/reference/object/pickBy.md @@ -0,0 +1,86 @@ +# pickBy (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `pickBy` + +这个 `pickBy` 函数由于类数组对象检查、`iteratee` 转换和键转换过程而相对较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [`pickBy`](../../../reference/object/pickBy.md)。 + +::: + +创建一个新对象,仅选择断言函数返回true的属性。 + +```typescript +const result = pickBy(obj, predicate); +``` + +## 用法 + +### `pickBy(object, predicate)` + +对对象的每个属性执行断言函数,并创建一个新对象,仅包含断言返回true的属性。适用于根据条件动态选择属性。 + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +// 仅选择特定类型的值 +const data = { a: 1, b: 'keep', c: 3, d: 'select' }; +const strings = pickBy(data, value => typeof value === 'string'); +// 结果: { b: 'keep', d: 'select' } + +// 根据条件选择属性 +const user = { id: 1, name: 'John', age: 0, active: true, email: '' }; +const validData = pickBy(user, value => Boolean(value)); +// 结果: { id: 1, name: 'John', active: true } (仅真值) + +// 按键名过滤 +const settings = { userSetting: true, adminSetting: false, debugMode: true }; +const userOnly = pickBy(settings, (value, key) => key.startsWith('user')); +// 结果: { userSetting: true } + +// 仅选择数字属性 +const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; +const numbersOnly = pickBy(mixed, value => typeof value === 'number'); +// 结果: { num1: 42, num2: 0 } + +// 也可用于数组 +const arr = [1, 2, 3, 4, 5]; +const evens = pickBy(arr, value => value % 2 === 0); +// 结果: { '1': 2, '3': 4 } (偶数的索引和值) + +// 利用值、键和原始对象 +const scores = { math: 90, science: 75, english: 85, art: 60 }; +const highScores = pickBy(scores, (value, key, obj) => { + const average = Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length; + return value > average; +}); +// 结果: { math: 90, english: 85 } +``` + +不带断言函数调用时,仅选择真值。 + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +const data = { a: 1, b: '', c: 0, d: 'hello', e: null, f: true }; +const truthyValues = pickBy(data); +// 结果: { a: 1, d: 'hello', f: true } +``` + +`null` 或 `undefined` 被视为空对象。 + +```typescript +import { pickBy } from 'es-toolkit/compat'; + +pickBy(null, () => true); // {} +pickBy(undefined, () => true); // {} +``` + +#### 参数 + +- `object` (`Record | Record | object | null | undefined`): 要过滤的源对象。 +- `predicate` (`ValueKeyIterateeTypeGuard | ValueKeyIteratee | ValueKeyIteratee`, 可选): 对每个属性执行的断言函数。此函数返回true的属性将被选择。默认为 `identity` 函数。 + +#### 返回值 + +(`Record | Record | Partial`): 返回一个由满足条件的属性组成的新对象。 diff --git a/docs/zh_hans/reference/compat/object/property.md b/docs/zh_hans/compat/reference/object/property.md similarity index 100% rename from docs/zh_hans/reference/compat/object/property.md rename to docs/zh_hans/compat/reference/object/property.md diff --git a/docs/zh_hans/reference/compat/object/propertyOf.md b/docs/zh_hans/compat/reference/object/propertyOf.md similarity index 100% rename from docs/zh_hans/reference/compat/object/propertyOf.md rename to docs/zh_hans/compat/reference/object/propertyOf.md diff --git a/docs/zh_hans/reference/compat/object/result.md b/docs/zh_hans/compat/reference/object/result.md similarity index 100% rename from docs/zh_hans/reference/compat/object/result.md rename to docs/zh_hans/compat/reference/object/result.md diff --git a/docs/zh_hans/reference/compat/object/set.md b/docs/zh_hans/compat/reference/object/set.md similarity index 100% rename from docs/zh_hans/reference/compat/object/set.md rename to docs/zh_hans/compat/reference/object/set.md diff --git a/docs/zh_hans/reference/compat/object/setWith.md b/docs/zh_hans/compat/reference/object/setWith.md similarity index 100% rename from docs/zh_hans/reference/compat/object/setWith.md rename to docs/zh_hans/compat/reference/object/setWith.md diff --git a/docs/zh_hans/reference/compat/object/toDefaulted.md b/docs/zh_hans/compat/reference/object/toDefaulted.md similarity index 100% rename from docs/zh_hans/reference/compat/object/toDefaulted.md rename to docs/zh_hans/compat/reference/object/toDefaulted.md diff --git a/docs/zh_hans/reference/compat/object/toPairs.md b/docs/zh_hans/compat/reference/object/toPairs.md similarity index 100% rename from docs/zh_hans/reference/compat/object/toPairs.md rename to docs/zh_hans/compat/reference/object/toPairs.md diff --git a/docs/zh_hans/reference/compat/object/toPairsIn.md b/docs/zh_hans/compat/reference/object/toPairsIn.md similarity index 100% rename from docs/zh_hans/reference/compat/object/toPairsIn.md rename to docs/zh_hans/compat/reference/object/toPairsIn.md diff --git a/docs/zh_hans/reference/compat/object/transform.md b/docs/zh_hans/compat/reference/object/transform.md similarity index 100% rename from docs/zh_hans/reference/compat/object/transform.md rename to docs/zh_hans/compat/reference/object/transform.md diff --git a/docs/zh_hans/reference/compat/object/unset.md b/docs/zh_hans/compat/reference/object/unset.md similarity index 100% rename from docs/zh_hans/reference/compat/object/unset.md rename to docs/zh_hans/compat/reference/object/unset.md diff --git a/docs/zh_hans/reference/compat/object/update.md b/docs/zh_hans/compat/reference/object/update.md similarity index 100% rename from docs/zh_hans/reference/compat/object/update.md rename to docs/zh_hans/compat/reference/object/update.md diff --git a/docs/zh_hans/reference/compat/object/updateWith.md b/docs/zh_hans/compat/reference/object/updateWith.md similarity index 100% rename from docs/zh_hans/reference/compat/object/updateWith.md rename to docs/zh_hans/compat/reference/object/updateWith.md diff --git a/docs/zh_hans/reference/compat/object/values.md b/docs/zh_hans/compat/reference/object/values.md similarity index 100% rename from docs/zh_hans/reference/compat/object/values.md rename to docs/zh_hans/compat/reference/object/values.md diff --git a/docs/zh_hans/reference/compat/object/valuesIn.md b/docs/zh_hans/compat/reference/object/valuesIn.md similarity index 100% rename from docs/zh_hans/reference/compat/object/valuesIn.md rename to docs/zh_hans/compat/reference/object/valuesIn.md diff --git a/docs/zh_hans/reference/compat/predicate/conforms.md b/docs/zh_hans/compat/reference/predicate/conforms.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/conforms.md rename to docs/zh_hans/compat/reference/predicate/conforms.md diff --git a/docs/zh_hans/reference/compat/predicate/conformsTo.md b/docs/zh_hans/compat/reference/predicate/conformsTo.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/conformsTo.md rename to docs/zh_hans/compat/reference/predicate/conformsTo.md diff --git a/docs/zh_hans/reference/compat/predicate/isArguments.md b/docs/zh_hans/compat/reference/predicate/isArguments.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isArguments.md rename to docs/zh_hans/compat/reference/predicate/isArguments.md diff --git a/docs/zh_hans/reference/compat/predicate/isArray.md b/docs/zh_hans/compat/reference/predicate/isArray.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isArray.md rename to docs/zh_hans/compat/reference/predicate/isArray.md diff --git a/docs/zh_hans/compat/reference/predicate/isArrayBuffer.md b/docs/zh_hans/compat/reference/predicate/isArrayBuffer.md new file mode 100644 index 000000000..09f816c28 --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isArrayBuffer.md @@ -0,0 +1,44 @@ +# isArrayBuffer (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [isArrayBuffer](../../../reference/predicate/isArrayBuffer.md) +此 `isArrayBuffer` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 + +请改用更快的现代化 `es-toolkit` 的 [isArrayBuffer](../../../reference/predicate/isArrayBuffer.md)。 +::: + +检查值是否为 ArrayBuffer。 + +```typescript +const result = isArrayBuffer(value); +``` + +## 用法 + +### `isArrayBuffer(value)` + +当您想要类型安全地检查值是否为 ArrayBuffer 时,请使用 `isArrayBuffer`。在 TypeScript 中也作为类型守卫工作。 + +```typescript +import { isArrayBuffer } from 'es-toolkit/compat'; + +// 检查 ArrayBuffer +const buffer = new ArrayBuffer(16); +isArrayBuffer(buffer); // true + +// 其他类型返回 false +isArrayBuffer(new Array()); // false +isArrayBuffer(new Map()); // false +isArrayBuffer({}); // false +isArrayBuffer('hello'); // false +isArrayBuffer(123); // false +isArrayBuffer(null); // false +isArrayBuffer(undefined); // false +``` + +#### 参数 + +- `value` (`unknown`): 要检查是否为 ArrayBuffer 的值。 + +#### 返回值 + +(`value is ArrayBuffer`): 如果值是 ArrayBuffer 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isArrayLike.md b/docs/zh_hans/compat/reference/predicate/isArrayLike.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isArrayLike.md rename to docs/zh_hans/compat/reference/predicate/isArrayLike.md diff --git a/docs/zh_hans/reference/compat/predicate/isArrayLikeObject.md b/docs/zh_hans/compat/reference/predicate/isArrayLikeObject.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isArrayLikeObject.md rename to docs/zh_hans/compat/reference/predicate/isArrayLikeObject.md diff --git a/docs/zh_hans/reference/compat/predicate/isBoolean.md b/docs/zh_hans/compat/reference/predicate/isBoolean.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isBoolean.md rename to docs/zh_hans/compat/reference/predicate/isBoolean.md diff --git a/docs/zh_hans/compat/reference/predicate/isBuffer.md b/docs/zh_hans/compat/reference/predicate/isBuffer.md new file mode 100644 index 000000000..86fe5d958 --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isBuffer.md @@ -0,0 +1,43 @@ +# isBuffer (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [isBuffer](../../../reference/predicate/isBuffer.md) +此 `isBuffer` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 + +请改用更快的现代化 `es-toolkit` 的 [isBuffer](../../../reference/predicate/isBuffer.md)。 +::: + +检查值是否为 Buffer 实例。 + +```typescript +const result = isBuffer(value); +``` + +## 用法 + +### `isBuffer(value)` + +当您想要类型安全地检查值是否为 Buffer 实例时,请使用 `isBuffer`。在 Node.js 环境中处理 Buffer 对象时很有用。在 TypeScript 中也作为类型守卫工作。 + +```typescript +import { isBuffer } from 'es-toolkit/compat'; + +// 检查 Buffer 实例 +const buffer = Buffer.from('hello'); +isBuffer(buffer); // true + +// 其他类型返回 false +isBuffer('hello'); // false +isBuffer([1, 2, 3]); // false +isBuffer(new Uint8Array([1, 2, 3])); // false +isBuffer({}); // false +isBuffer(null); // false +isBuffer(undefined); // false +``` + +#### 参数 + +- `value` (`unknown`): 要检查是否为 Buffer 实例的值。 + +#### 返回值 + +(`boolean`): 如果值是 Buffer 实例则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/compat/reference/predicate/isDate.md b/docs/zh_hans/compat/reference/predicate/isDate.md new file mode 100644 index 000000000..c57cfff6a --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isDate.md @@ -0,0 +1,46 @@ +# isDate (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [isDate](../../../reference/predicate/isDate.md) +这个 `isDate` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 + +建议使用更快、更现代的 `es-toolkit` 的 [isDate](../../../reference/predicate/isDate.md)。 +::: + +检查值是否为 Date 对象。 + +```typescript +const result = isDate(value); +``` + +## 用法 + +### `isDate(value)` + +当你想要类型安全地检查值是否为 Date 对象时使用 `isDate`。在 TypeScript 中它也可以作为类型守卫使用。 + +```typescript +import { isDate } from 'es-toolkit/compat'; + +// 检查 Date 对象 +const date = new Date(); +isDate(date); // true + +// 无效的 Date 也被识别为 Date 对象 +const invalidDate = new Date('invalid'); +isDate(invalidDate); // true + +// 其他类型返回 false +isDate('2024-01-01'); // false +isDate(1640995200000); // false +isDate({}); // false +isDate(null); // false +isDate(undefined); // false +``` + +#### 参数 + +- `value` (`unknown`): 要检查是否为 Date 对象的值。 + +#### 返回值 + +(`value is Date`): 如果值是 Date 对象则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isElement.md b/docs/zh_hans/compat/reference/predicate/isElement.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isElement.md rename to docs/zh_hans/compat/reference/predicate/isElement.md diff --git a/docs/zh_hans/reference/compat/predicate/isEmpty.md b/docs/zh_hans/compat/reference/predicate/isEmpty.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isEmpty.md rename to docs/zh_hans/compat/reference/predicate/isEmpty.md diff --git a/docs/zh_hans/compat/reference/predicate/isEqual.md b/docs/zh_hans/compat/reference/predicate/isEqual.md new file mode 100644 index 000000000..61038686f --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isEqual.md @@ -0,0 +1,82 @@ +# isEqual (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 [isEqual](../../../reference/predicate/isEqual.md) +这个 `isEqual` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 + +建议使用更快、更现代的 `es-toolkit` 的 [isEqual](../../../reference/predicate/isEqual.md)。 +::: + +深度比较两个值是否相等。 + +```typescript +const result = isEqual(value1, value2); +``` + +## 用法 + +### `isEqual(a, b)` + +当需要深度比较两个值是否相等时使用 `isEqual`。它会比较复杂类型如 Date、RegExp、对象、数组等的内容。 + +```typescript +import { isEqual } from 'es-toolkit/compat'; + +// 基本类型比较 +isEqual(1, 1); // true +isEqual('hello', 'hello'); // true +isEqual(true, true); // true + +// 对象深度比较 +isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true +isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true +isEqual({ a: 1 }, { a: 1, b: undefined }); // false + +// 数组深度比较 +isEqual([1, 2, 3], [1, 2, 3]); // true +isEqual([1, [2, 3]], [1, [2, 3]]); // true + +// Date 对象比较 +isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true +isEqual(new Date('2020-01-01'), new Date('2020-01-02')); // false + +// RegExp 对象比较 +isEqual(/abc/g, /abc/g); // true +isEqual(/abc/g, /abc/i); // false +``` + +它也会递归比较嵌套的对象和数组。 + +```typescript +import { isEqual } from 'es-toolkit/compat'; + +const obj1 = { + user: { + name: 'John', + details: { + age: 30, + hobbies: ['reading', 'gaming'], + }, + }, +}; + +const obj2 = { + user: { + name: 'John', + details: { + age: 30, + hobbies: ['reading', 'gaming'], + }, + }, +}; + +isEqual(obj1, obj2); // true +``` + +#### 参数 + +- `a` (`unknown`): 要比较的第一个值。 +- `b` (`unknown`): 要比较的第二个值。 + +#### 返回值 + +(`boolean`): 如果两个值相等则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/compat/reference/predicate/isEqualWith.md b/docs/zh_hans/compat/reference/predicate/isEqualWith.md new file mode 100644 index 000000000..488e720a8 --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isEqualWith.md @@ -0,0 +1,92 @@ +# isEqualWith (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [isEqualWith](../../../reference/predicate/isEqualWith.md) +这个 `isEqualWith` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 + +建议使用更快、更现代的 `es-toolkit` 的 [isEqualWith](../../../reference/predicate/isEqualWith.md)。 +::: + +使用自定义比较函数检查两个值是否相等。 + +```typescript +const result = isEqualWith(a, b, customizer); +``` + +## 用法 + +### `isEqualWith(a, b, areValuesEqual?)` + +使用自定义比较函数深度比较两个值。如果自定义函数返回布尔值,则使用该结果;如果返回 `undefined`,则使用默认相等性比较。 + +自定义比较函数也会用于比较对象、数组、Map、Set 等复杂结构内部的值,确保深度比较。 + +```typescript +import { isEqualWith } from 'es-toolkit/compat'; + +// 忽略大小写的字符串比较 +const customizer = (a: any, b: any) => { + if (typeof a === 'string' && typeof b === 'string') { + return a.toLowerCase() === b.toLowerCase(); + } +}; + +isEqualWith('Hello', 'hello', customizer); // true +isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true + +// 按绝对值比较数字 +const absCustomizer = (a: any, b: any) => { + if (typeof a === 'number' && typeof b === 'number') { + return Math.abs(a) === Math.abs(b); + } +}; + +isEqualWith([-1, 2], [1, -2], absCustomizer); // true + +// 复杂对象比较 +const obj1 = { + name: 'JOHN', + details: { age: 30, city: 'NYC' }, +}; +const obj2 = { + name: 'john', + details: { age: 30, city: 'nyc' }, +}; + +isEqualWith(obj1, obj2, customizer); // true +``` + +对 Map 和 Set 进行特殊处理。 + +```typescript +import { isEqualWith } from 'es-toolkit/compat'; + +const customizer = (a: any, b: any) => { + if (typeof a === 'string' && typeof b === 'string') { + return a.toLowerCase() === b.toLowerCase(); + } +}; + +const map1 = new Map([['KEY', 'value']]); +const map2 = new Map([['key', 'value']]); +isEqualWith(map1, map2, customizer); // true + +const set1 = new Set(['HELLO']); +const set2 = new Set(['hello']); +isEqualWith(set1, set2, customizer); // true +``` + +#### 参数 + +- `a` (`any`): 要比较的第一个值。 +- `b` (`any`): 要比较的第二个值。 +- `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): 自定义比较函数。 + - `x`: 来自第一个对象 `a` 的值 + - `y`: 来自第二个对象 `b` 的值 + - `property`: 获取 `x` 和 `y` 时使用的属性键 + - `xParent`: 第一个值 `x` 的父对象 + - `yParent`: 第二个值 `y` 的父对象 + - `stack`: 处理循环引用的内部栈 (Map) + +#### 返回值 + +(`boolean`): 根据自定义函数,如果两个值相等则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/compat/reference/predicate/isError.md b/docs/zh_hans/compat/reference/predicate/isError.md new file mode 100644 index 000000000..3b423fc5c --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isError.md @@ -0,0 +1,47 @@ +# isError (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [isError](../../../reference/predicate/isError.md) +这个 `isError` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 + +建议使用更快、更现代的 `es-toolkit` 的 [isError](../../../reference/predicate/isError.md)。 +::: + +检查值是否为 Error 对象。 + +```typescript +const result = isError(value); +``` + +## 用法 + +### `isError(value)` + +当需要类型安全地检查值是否为 Error 对象时使用 `isError`。在 TypeScript 中它也可以作为类型守卫使用。 + +```typescript +import { isError } from 'es-toolkit/compat'; + +// 检查 Error 对象 +isError(new Error()); // true +isError(new TypeError('Type error')); // true +isError(new ReferenceError('Reference error')); // true + +// 继承 Error 的自定义错误 +class CustomError extends Error {} +isError(new CustomError()); // true + +// 其他类型返回 false +isError('Error'); // false +isError({ name: 'Error', message: 'Something went wrong' }); // false +isError({}); // false +isError(null); // false +isError(undefined); // false +``` + +#### 参数 + +- `value` (`unknown`): 要检查是否为 Error 对象的值。 + +#### 返回值 + +(`value is Error`): 如果值是 Error 对象则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isFinite.md b/docs/zh_hans/compat/reference/predicate/isFinite.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isFinite.md rename to docs/zh_hans/compat/reference/predicate/isFinite.md diff --git a/docs/zh_hans/compat/reference/predicate/isFunction.md b/docs/zh_hans/compat/reference/predicate/isFunction.md new file mode 100644 index 000000000..eb8b4e966 --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isFunction.md @@ -0,0 +1,52 @@ +# isFunction (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [isFunction](../../../reference/predicate/isFunction.md) +这个 `isFunction` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 + +建议使用更快、更现代的 `es-toolkit` 的 [isFunction](../../../reference/predicate/isFunction.md)。 +::: + +检查值是否为函数。 + +```typescript +const result = isFunction(value); +``` + +## 用法 + +### `isFunction(value)` + +当需要类型安全地检查值是否为函数时使用 `isFunction`。在 TypeScript 中它也可以作为类型守卫使用。 + +```typescript +import { isFunction } from 'es-toolkit/compat'; + +// 普通函数 +isFunction(function () {}); // true +isFunction(() => {}); // true + +// 内置函数和构造函数 +isFunction(Array.prototype.slice); // true +isFunction(Proxy); // true +isFunction(Int8Array); // true + +// 异步函数和生成器函数 +isFunction(async function () {}); // true +isFunction(function* () {}); // true + +// 其他类型返回 false +isFunction('function'); // false +isFunction({}); // false +isFunction([]); // false +isFunction(null); // false +isFunction(undefined); // false +isFunction(123); // false +``` + +#### 参数 + +- `value` (`unknown`): 要检查是否为函数的值。 + +#### 返回值 + +(`value is (...args: any[]) => any`): 如果值是函数则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isInteger.md b/docs/zh_hans/compat/reference/predicate/isInteger.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isInteger.md rename to docs/zh_hans/compat/reference/predicate/isInteger.md diff --git a/docs/zh_hans/compat/reference/predicate/isLength.md b/docs/zh_hans/compat/reference/predicate/isLength.md new file mode 100644 index 000000000..21b33c672 --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isLength.md @@ -0,0 +1,63 @@ +# isLength (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [isLength](../../../reference/predicate/isLength.md) +这个 `isLength` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 + +建议使用更快、更现代的 `es-toolkit` 的 [isLength](../../../reference/predicate/isLength.md)。 +::: + +检查值是否为有效长度。 + +```typescript +const result = isLength(value); +``` + +## 用法 + +### `isLength(value)` + +当需要检查值是否为有效长度时使用 `isLength`。有效长度必须是数字类型、非负整数,且不超过 JavaScript 的最大安全整数(`Number.MAX_SAFE_INTEGER`)。在 TypeScript 中它也可以作为类型守卫使用。 + +```typescript +import { isLength } from 'es-toolkit/compat'; + +// 有效长度 +isLength(0); // true +isLength(42); // true +isLength(100); // true +isLength(Number.MAX_SAFE_INTEGER); // true + +// 无效长度 +isLength(-1); // false (负数) +isLength(1.5); // false (非整数) +isLength(Number.MAX_SAFE_INTEGER + 1); // false (超出安全范围) +isLength('3'); // false (字符串) +isLength(null); // false +isLength(undefined); // false +isLength({}); // false +isLength([]); // false +``` + +在验证数组或字符串的 length 属性是否有效时很有用。 + +```typescript +import { isLength } from 'es-toolkit/compat'; + +function validateArrayLength(arr: any[]) { + if (isLength(arr.length)) { + console.log(`数组长度 ${arr.length} 是有效的`); + return true; + } + return false; +} + +validateArrayLength([1, 2, 3]); // "数组长度 3 是有效的" +``` + +#### 参数 + +- `value` (`any`): 要检查是否为有效长度的值。 + +#### 返回值 + +(`boolean`): 如果值是有效长度则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/compat/reference/predicate/isMap.md b/docs/zh_hans/compat/reference/predicate/isMap.md new file mode 100644 index 000000000..efed49f92 --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isMap.md @@ -0,0 +1,63 @@ +# isMap (Lodash 兼容性) + +::: warning 请使用 es-toolkit 的 [isMap](../../../reference/predicate/isMap.md) + +这个 `isMap` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 + +建议使用更快、更现代的 `es-toolkit` 的 [isMap](../../../reference/predicate/isMap.md)。 + +::: + +检查值是否为 Map。 + +```typescript +const result = isMap(value); +``` + +## 用法 + +### `isMap(value)` + +当需要类型安全地检查值是否为 Map 时使用 `isMap`。在 TypeScript 中它也可以作为类型守卫使用。 + +```typescript +import { isMap } from 'es-toolkit/compat'; + +// 检查 Map +const map = new Map(); +isMap(map); // true + +// 其他类型返回 false +isMap(new Set()); // false +isMap(new WeakMap()); // false +isMap({}); // false +isMap([]); // false +isMap('map'); // false +isMap(123); // false +isMap(null); // false +isMap(undefined); // false +``` + +它也可以区分 Map 和其他类似的集合。 + +```typescript +import { isMap } from 'es-toolkit/compat'; + +// Map vs Set vs WeakMap +isMap(new Map([['key', 'value']])); // true +isMap(new Set(['value'])); // false +isMap(new WeakMap()); // false + +// Map vs 普通对象 +isMap({}); // false +isMap({ key: 'value' }); // false +isMap(Object.create(null)); // false +``` + +#### 参数 + +- `value` (`unknown`): 要检查是否为 Map 的值。 + +#### 返回值 + +(`value is Map`): 如果值是 Map 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isMatch.md b/docs/zh_hans/compat/reference/predicate/isMatch.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isMatch.md rename to docs/zh_hans/compat/reference/predicate/isMatch.md diff --git a/docs/zh_hans/reference/compat/predicate/isMatchWith.md b/docs/zh_hans/compat/reference/predicate/isMatchWith.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isMatchWith.md rename to docs/zh_hans/compat/reference/predicate/isMatchWith.md diff --git a/docs/zh_hans/reference/compat/predicate/isNaN.md b/docs/zh_hans/compat/reference/predicate/isNaN.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isNaN.md rename to docs/zh_hans/compat/reference/predicate/isNaN.md diff --git a/docs/zh_hans/reference/compat/predicate/isNative.md b/docs/zh_hans/compat/reference/predicate/isNative.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isNative.md rename to docs/zh_hans/compat/reference/predicate/isNative.md diff --git a/docs/zh_hans/compat/reference/predicate/isNil.md b/docs/zh_hans/compat/reference/predicate/isNil.md new file mode 100644 index 000000000..9d3209897 --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isNil.md @@ -0,0 +1,60 @@ +# isNil (Lodash 兼容性) + +::: warning 使用 es-toolkit 的 [isNil](../../../reference/predicate/isNil.md) +这个 `isNil` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 + +请使用更快且现代的 es-toolkit 的 [isNil](../../../reference/predicate/isNil.md)。 +::: + +检查值是否为 `null` 或 `undefined`。 + +```typescript +const result = isNil(value); +``` + +## 用法 + +### `isNil(x)` + +当您想类型安全地检查值是否为 `null` 或 `undefined` 时使用 `isNil`。在 TypeScript 中也可以作为类型守卫使用。 + +```typescript +import { isNil } from 'es-toolkit/compat'; + +// null 和 undefined 返回 true +isNil(null); // true +isNil(undefined); // true + +// 所有其他值返回 false +isNil(0); // false +isNil(''); // false +isNil(false); // false +isNil([]); // false +isNil({}); // false +isNil('hello'); // false +isNil(42); // false +``` + +与被认为是假值但不是 `null` 或 `undefined` 的值进行区分。 + +```typescript +import { isNil } from 'es-toolkit/compat'; + +// 被认为是假值但不是 null/undefined 的值 +isNil(0); // false +isNil(''); // false +isNil(false); // false +isNil(NaN); // false + +// 只有 null 和 undefined 返回 true +isNil(null); // true +isNil(undefined); // true +``` + +#### 参数 + +- `x` (`any`): 要检查是否为 `null` 或 `undefined` 的值。 + +#### 返回值 + +(`x is null | undefined`): 如果值为 `null` 或 `undefined` 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/compat/reference/predicate/isNull.md b/docs/zh_hans/compat/reference/predicate/isNull.md new file mode 100644 index 000000000..d44a3bd67 --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isNull.md @@ -0,0 +1,66 @@ +# isNull (Lodash 兼容性) + +::: warning 使用 es-toolkit 的 [isNull](../../../reference/predicate/isNull.md) +这个 `isNull` 函数是 Lodash 兼容性的函数,但与主库具有相同的实现。 + +请使用更快且现代的 es-toolkit 的 [isNull](../../../reference/predicate/isNull.md)。 +::: + +检查值是否为 `null`。 + +```typescript +const result = isNull(value); +``` + +## 用法 + +### `isNull(value)` + +当您想类型安全地检查值是否恰好为 `null` 时使用 `isNull`。在 TypeScript 中也可以作为类型守卫使用。 + +```typescript +import { isNull } from 'es-toolkit/compat'; + +// 只有 null 返回 true +isNull(null); // true + +// undefined 也返回 false +isNull(undefined); // false + +// 所有其他值也返回 false +isNull(0); // false +isNull(''); // false +isNull(false); // false +isNull([]); // false +isNull({}); // false +isNull('null'); // false +isNull(NaN); // false +``` + +可以区分检查 `null` 和 `undefined`。 + +```typescript +import { isNull } from 'es-toolkit/compat'; + +function handleValue(value: string | null | undefined) { + if (isNull(value)) { + console.log('值明确为 null'); + } else if (value === undefined) { + console.log('值为 undefined'); + } else { + console.log(`有值: ${value}`); + } +} + +handleValue(null); // "值明确为 null" +handleValue(undefined); // "值为 undefined" +handleValue('hello'); // "有值: hello" +``` + +#### 参数 + +- `value` (`any`): 要检查是否为 `null` 的值。 + +#### 返回值 + +(`value is null`): 如果值为 `null` 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isNumber.md b/docs/zh_hans/compat/reference/predicate/isNumber.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isNumber.md rename to docs/zh_hans/compat/reference/predicate/isNumber.md diff --git a/docs/zh_hans/reference/compat/predicate/isObject.md b/docs/zh_hans/compat/reference/predicate/isObject.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isObject.md rename to docs/zh_hans/compat/reference/predicate/isObject.md diff --git a/docs/zh_hans/reference/compat/predicate/isObjectLike.md b/docs/zh_hans/compat/reference/predicate/isObjectLike.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isObjectLike.md rename to docs/zh_hans/compat/reference/predicate/isObjectLike.md diff --git a/docs/zh_hans/compat/reference/predicate/isPlainObject.md b/docs/zh_hans/compat/reference/predicate/isPlainObject.md new file mode 100644 index 000000000..e50cf7aba --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isPlainObject.md @@ -0,0 +1,83 @@ +# isPlainObject (Lodash 兼容性) + +::: warning 使用 es-toolkit 的 [isPlainObject](../../../reference/predicate/isPlainObject.md) +这个 `isPlainObject` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 + +请使用更快且现代的 es-toolkit 的 [isPlainObject](../../../reference/predicate/isPlainObject.md)。 +::: + +检查值是否为纯对象。 + +```typescript +const result = isPlainObject(object); +``` + +## 用法 + +### `isPlainObject(object)` + +当您想检查值是否为纯对象时使用 `isPlainObject`。纯对象是通过 `{}` 字面量、`new Object()` 或 `Object.create(null)` 创建的对象。在 TypeScript 中也可以作为类型守卫使用。 + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +// 纯对象 +isPlainObject({}); // true +isPlainObject(new Object()); // true +isPlainObject(Object.create(null)); // true +isPlainObject({ name: 'John', age: 30 }); // true + +// 不是纯对象的值 +isPlainObject([]); // false (数组) +isPlainObject(new Date()); // false (Date 实例) +isPlainObject(new Map()); // false (Map 实例) +isPlainObject(new Set()); // false (Set 实例) +isPlainObject(/regex/); // false (正则表达式) +isPlainObject(function () {}); // false (函数) +isPlainObject(null); // false +isPlainObject(undefined); // false +isPlainObject('object'); // false (字符串) +isPlainObject(42); // false (数字) +``` + +区分类实例和纯对象。 + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +class Person { + name: string; + constructor(name: string) { + this.name = name; + } +} + +const person = new Person('John'); +const plainObj = { name: 'John' }; + +isPlainObject(person); // false (类实例) +isPlainObject(plainObj); // true (纯对象) +``` + +正确处理自定义 `Symbol.toStringTag` 属性。 + +```typescript +import { isPlainObject } from 'es-toolkit/compat'; + +// 可写的 Symbol.toStringTag +const obj1 = {}; +obj1[Symbol.toStringTag] = 'CustomObject'; +isPlainObject(obj1); // true + +// 只读的 Symbol.toStringTag (内置对象) +const date = new Date(); +isPlainObject(date); // false +``` + +#### 参数 + +- `object` (`any`): 要检查是否为纯对象的值。 + +#### 返回值 + +(`boolean`): 如果值为纯对象则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/compat/reference/predicate/isRegExp.md b/docs/zh_hans/compat/reference/predicate/isRegExp.md new file mode 100644 index 000000000..4ad34b27f --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isRegExp.md @@ -0,0 +1,80 @@ +# isRegExp (Lodash 兼容性) + +::: warning 使用 es-toolkit 的 [isRegExp](../../../reference/predicate/isRegExp.md) +这个 `isRegExp` 函数是 Lodash 兼容性的函数,但是简单的类型检查。 + +请使用更快且现代的 es-toolkit 的 [isRegExp](../../../reference/predicate/isRegExp.md)。 +::: + +检查值是否为正则表达式。 + +```typescript +const result = isRegExp(value); +``` + +## 用法 + +### `isRegExp(value)` + +当您想类型安全地检查值是否为正则表达式时使用 `isRegExp`。在 TypeScript 中也可以作为类型守卫使用。 + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// 正则表达式 +isRegExp(/abc/); // true +isRegExp(new RegExp('abc')); // true +isRegExp(/[a-z]+/g); // true +isRegExp(/pattern/gi); // true + +// 其他类型返回 false +isRegExp('/abc/'); // false (字符串) +isRegExp('pattern'); // false (字符串) +isRegExp({}); // false (对象) +isRegExp([]); // false (数组) +isRegExp(null); // false +isRegExp(undefined); // false +isRegExp(123); // false (数字) +``` + +区分正则表达式字符串和实际正则表达式对象。 + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// 正则表达式 vs 正则表达式字符串 +isRegExp(/test/); // true +isRegExp('/test/'); // false +isRegExp('\\d+'); // false +isRegExp('/\\d+/g'); // false + +// 各种正则表达式标志 +isRegExp(/test/i); // true (忽略大小写) +isRegExp(/test/g); // true (全局搜索) +isRegExp(/test/m); // true (多行) +isRegExp(/test/gim); // true (所有标志组合) +``` + +也识别动态创建的正则表达式。 + +```typescript +import { isRegExp } from 'es-toolkit/compat'; + +// 通过 RegExp 构造函数创建的正则表达式 +const dynamicRegex = new RegExp('\\d{3}-\\d{4}', 'g'); +isRegExp(dynamicRegex); // true + +// 通过字符串创建的正则表达式 +const pattern = 'hello'; +const flags = 'gi'; +const regex = new RegExp(pattern, flags); +isRegExp(regex); // true +``` + +#### 参数 + +- `value` (`any`): 要检查是否为正则表达式的值。 + +#### 返回值 + +(`value is RegExp`): 如果值为正则表达式则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isSafeInteger.md b/docs/zh_hans/compat/reference/predicate/isSafeInteger.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isSafeInteger.md rename to docs/zh_hans/compat/reference/predicate/isSafeInteger.md diff --git a/docs/zh_hans/compat/reference/predicate/isSet.md b/docs/zh_hans/compat/reference/predicate/isSet.md new file mode 100644 index 000000000..8b7c2cf5f --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isSet.md @@ -0,0 +1,65 @@ +# isSet (Lodash 兼容性) + +::: warning 使用 `es-toolkit` 的 [isSet](../../../reference/predicate/isSet.md) +这个 `isSet` 函数是 Lodash 兼容性的函数,但与主库具有相同的实现。 + +请使用更快且现代的 `es-toolkit` 的 [isSet](../../../reference/predicate/isSet.md)。 +::: + +检查值是否为 Set。 + +```typescript +const result = isSet(value); +``` + +## 用法 + +### `isSet(value)` + +当您想类型安全地检查值是否为 Set 时使用 `isSet`。在 TypeScript 中也可以作为类型守卫使用。 + +```typescript +import { isSet } from 'es-toolkit/compat'; + +// Set 检查 +const set = new Set(); +isSet(set); // true + +// 其他类型返回 false +isSet(new Map()); // false +isSet(new WeakSet()); // false +isSet([]); // false +isSet({}); // false +isSet('set'); // false +isSet(123); // false +isSet(null); // false +isSet(undefined); // false +``` + +也与其他类似 Set 的集合进行区分。 + +```typescript +import { isSet } from 'es-toolkit/compat'; + +// Set vs Map vs WeakSet +isSet(new Set([1, 2, 3])); // true +isSet(new Map([['key', 'value']])); // false +isSet(new WeakSet()); // false + +// Set vs 数组 +isSet(new Set([1, 2, 3])); // true +isSet([1, 2, 3]); // false + +// Set vs 普通对象 +isSet(new Set()); // true +isSet({}); // false +isSet(Object.create(null)); // false +``` + +#### 参数 + +- `value` (`unknown`): 要检查是否为 Set 的值。 + +#### 返回值 + +(`value is Set`): 如果值为 Set 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isString.md b/docs/zh_hans/compat/reference/predicate/isString.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isString.md rename to docs/zh_hans/compat/reference/predicate/isString.md diff --git a/docs/zh_hans/reference/compat/predicate/isSymbol.md b/docs/zh_hans/compat/reference/predicate/isSymbol.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isSymbol.md rename to docs/zh_hans/compat/reference/predicate/isSymbol.md diff --git a/docs/zh_hans/reference/compat/predicate/isTypedArray.md b/docs/zh_hans/compat/reference/predicate/isTypedArray.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isTypedArray.md rename to docs/zh_hans/compat/reference/predicate/isTypedArray.md diff --git a/docs/zh_hans/compat/reference/predicate/isUndefined.md b/docs/zh_hans/compat/reference/predicate/isUndefined.md new file mode 100644 index 000000000..61e0317e6 --- /dev/null +++ b/docs/zh_hans/compat/reference/predicate/isUndefined.md @@ -0,0 +1,90 @@ +# isUndefined (Lodash 兼容性) + +::: warning 使用 es-toolkit 的 [isUndefined](../../../reference/predicate/isUndefined.md) +这个 `isUndefined` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 + +请使用更快且现代的 es-toolkit 的 [isUndefined](../../../reference/predicate/isUndefined.md)。 +::: + +检查值是否为 `undefined`。 + +```typescript +const result = isUndefined(value); +``` + +## 用法 + +### `isUndefined(x)` + +当您想类型安全地检查值是否恰好为 `undefined` 时使用 `isUndefined`。在 TypeScript 中也可以作为类型守卫使用。 + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +// 只有 undefined 返回 true +isUndefined(undefined); // true + +// null 也返回 false +isUndefined(null); // false + +// 所有其他值也返回 false +isUndefined(0); // false +isUndefined(''); // false +isUndefined(false); // false +isUndefined([]); // false +isUndefined({}); // false +isUndefined('undefined'); // false +isUndefined(NaN); // false +``` + +可以区分检查 `undefined` 和 `null`。 + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +function handleValue(value: string | null | undefined) { + if (isUndefined(value)) { + console.log('值为 undefined'); + } else if (value === null) { + console.log('值明确为 null'); + } else { + console.log(`有值: ${value}`); + } +} + +handleValue(undefined); // "值为 undefined" +handleValue(null); // "值明确为 null" +handleValue('hello'); // "有值: hello" +``` + +在检查未声明的变量或未初始化的属性时很有用。 + +```typescript +import { isUndefined } from 'es-toolkit/compat'; + +const obj: { name?: string; age?: number } = { name: 'John' }; + +if (isUndefined(obj.age)) { + console.log('年龄未设置'); + obj.age = 25; // 设置默认值 +} + +// 函数参数的默认值处理 +function greet(name: string, title?: string) { + if (isUndefined(title)) { + title = '先生/女士'; + } + console.log(`您好,${name}${title}!`); +} + +greet('张三'); // "您好,张三先生/女士!" +greet('张三', '老师'); // "您好,张三老师!" +``` + +#### 参数 + +- `x` (`any`): 要检查是否为 `undefined` 的值。 + +#### 返回值 + +(`x is undefined`): 如果值为 `undefined` 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isWeakMap.md b/docs/zh_hans/compat/reference/predicate/isWeakMap.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isWeakMap.md rename to docs/zh_hans/compat/reference/predicate/isWeakMap.md diff --git a/docs/zh_hans/reference/compat/predicate/isWeakSet.md b/docs/zh_hans/compat/reference/predicate/isWeakSet.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/isWeakSet.md rename to docs/zh_hans/compat/reference/predicate/isWeakSet.md diff --git a/docs/zh_hans/reference/compat/predicate/matches.md b/docs/zh_hans/compat/reference/predicate/matches.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/matches.md rename to docs/zh_hans/compat/reference/predicate/matches.md diff --git a/docs/zh_hans/reference/compat/predicate/matchesProperty.md b/docs/zh_hans/compat/reference/predicate/matchesProperty.md similarity index 100% rename from docs/zh_hans/reference/compat/predicate/matchesProperty.md rename to docs/zh_hans/compat/reference/predicate/matchesProperty.md diff --git a/docs/zh_hans/compat/reference/string/camelCase.md b/docs/zh_hans/compat/reference/string/camelCase.md new file mode 100644 index 000000000..c47f1fda5 --- /dev/null +++ b/docs/zh_hans/compat/reference/string/camelCase.md @@ -0,0 +1,48 @@ +# camelCase (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `camelCase` + +由于处理非字符串输入值和删除缩写撇号等原因,此 `camelCase` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [camelCase](../../../reference/string/camelCase.md)。 + +::: + +将字符串转换为驼峰命名法。 + +```typescript +const result = camelCase(str); +``` + +## 用法 + +### `camelCase(str)` + +将字符串转换为驼峰命名法。驼峰命名法是一种命名约定,第一个单词以小写字母开头,后续单词的首字母大写,所有单词连接时不带空格。 + +```typescript +import { camelCase } from 'es-toolkit/compat'; + +camelCase('camelCase'); // 'camelCase' +camelCase('some whitespace'); // 'someWhitespace' +camelCase('hyphen-text'); // 'hyphenText' +camelCase('HTTPRequest'); // 'httpRequest' +``` + +非字符串值也会在处理前转换为字符串。 + +```typescript +import { camelCase } from 'es-toolkit/compat'; + +camelCase(123); // '123' +camelCase(null); // '' +camelCase(undefined); // '' +``` + +#### 参数 + +- `str` (`string | object`,可选): 要转换为驼峰命名法的值。 + +#### 返回值 + +(`string`): 返回转换为驼峰命名法的字符串。 diff --git a/docs/zh_hans/compat/reference/string/capitalize.md b/docs/zh_hans/compat/reference/string/capitalize.md new file mode 100644 index 000000000..cef8a37b0 --- /dev/null +++ b/docs/zh_hans/compat/reference/string/capitalize.md @@ -0,0 +1,48 @@ +# capitalize (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `capitalize` + +由于处理非字符串输入值,此 `capitalize` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [capitalize](../../../reference/string/capitalize.md)。 + +::: + +将字符串的第一个字符转换为大写,其余字符转换为小写。 + +```typescript +const result = capitalize(str); +``` + +## 用法 + +### `capitalize(str)` + +将字符串的第一个字符转换为大写,其余字符转换为小写。这对于改善单词的第一印象或将其格式化为标题形式很有用。 + +```typescript +import { capitalize } from 'es-toolkit/compat'; + +capitalize('fred'); // 'Fred' +capitalize('FRED'); // 'Fred' +capitalize('fRED'); // 'Fred' +``` + +空字符串和非字符串值也可以处理。 + +```typescript +import { capitalize } from 'es-toolkit/compat'; + +capitalize(''); // '' +capitalize(123); // '123' +capitalize(null); // '' +capitalize(undefined); // '' +``` + +#### 参数 + +- `str` (`string`,可选): 要首字母大写的字符串。 + +#### 返回值 + +(`string`): 返回首字母大写、其余字母小写的字符串。 diff --git a/docs/zh_hans/compat/reference/string/deburr.md b/docs/zh_hans/compat/reference/string/deburr.md new file mode 100644 index 000000000..0b53ade9b --- /dev/null +++ b/docs/zh_hans/compat/reference/string/deburr.md @@ -0,0 +1,47 @@ +# deburr (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `deburr` + +由于处理非字符串输入值,此 `deburr` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [deburr](../../../reference/string/deburr.md)。 + +::: + +将字符串中的特殊字符和变音符号转换为ASCII字符。 + +```typescript +const result = deburr(str); +``` + +## 用法 + +### `deburr(str)` + +将字符串中的特殊字符和变音符号转换为ASCII字符。这对于使多语言文本更易于搜索或排序很有用。 + +```typescript +import { deburr } from 'es-toolkit/compat'; + +deburr('Æthelred'); // 'Aethelred' +deburr('München'); // 'Munchen' +deburr('Crème brûlée'); // 'Creme brulee' +``` + +非字符串值也会在处理前转换为字符串。 + +```typescript +import { deburr } from 'es-toolkit/compat'; + +deburr(123); // '123' +deburr(null); // '' +deburr(undefined); // '' +``` + +#### 参数 + +- `str` (`string`,可选): 要删除特殊字符的字符串。 + +#### 返回值 + +(`string`): 返回特殊字符和变音符号转换为ASCII字符的字符串。 diff --git a/docs/zh_hans/reference/compat/string/endsWith.md b/docs/zh_hans/compat/reference/string/endsWith.md similarity index 100% rename from docs/zh_hans/reference/compat/string/endsWith.md rename to docs/zh_hans/compat/reference/string/endsWith.md diff --git a/docs/zh_hans/compat/reference/string/escape.md b/docs/zh_hans/compat/reference/string/escape.md new file mode 100644 index 000000000..b9b46ac72 --- /dev/null +++ b/docs/zh_hans/compat/reference/string/escape.md @@ -0,0 +1,48 @@ +# escape (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `escape` + +由于处理非字符串输入值,此 `escape` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [escape](../../../reference/string/escape.md)。 + +::: + +将字符串中的HTML特殊字符转换为HTML实体。 + +```typescript +const result = escape(str); +``` + +## 用法 + +### `escape(str)` + +将字符串中的 `&`、`<`、`>`、`"`、`'` 字符转换为相应的HTML实体。这对于在HTML文档中安全插入文本以防止XSS攻击很有用。 + +```typescript +import { escape } from 'es-toolkit/compat'; + +escape('This is a
element.'); // 'This is a <div> element.' +escape('This is a "quote"'); // 'This is a "quote"' +escape("This is a 'quote'"); // 'This is a 'quote'' +escape('This is a & symbol'); // 'This is a & symbol' +``` + +非字符串值也会在处理前转换为字符串。 + +```typescript +import { escape } from 'es-toolkit/compat'; + +escape(123); // '123' +escape(null); // '' +escape(undefined); // '' +``` + +#### 参数 + +- `str` (`string`,可选): 要转义HTML特殊字符的字符串。 + +#### 返回值 + +(`string`): 返回HTML特殊字符转换为实体的字符串。 diff --git a/docs/zh_hans/compat/reference/string/escapeRegExp.md b/docs/zh_hans/compat/reference/string/escapeRegExp.md new file mode 100644 index 000000000..93dd78990 --- /dev/null +++ b/docs/zh_hans/compat/reference/string/escapeRegExp.md @@ -0,0 +1,49 @@ +# escapeRegExp (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `escapeRegExp` + +由于处理非字符串输入值,此 `escapeRegExp` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [escapeRegExp](../../../reference/string/escapeRegExp.md)。 + +::: + +转义字符串中的正则表达式特殊字符。 + +```typescript +const result = escapeRegExp(str); +``` + +## 用法 + +### `escapeRegExp(str)` + +转义字符串中的正则表达式特殊字符 `^`、`$`、`\`、`.`、`*`、`+`、`?`、`(`、`)`、`[`、`]`、`{`、`}`、`|`。当您想在动态创建正则表达式时将字符串按字面处理时很有用。 + +```typescript +import { escapeRegExp } from 'es-toolkit/compat'; + +escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); +// '\\[es-toolkit\\]\\(https://es-toolkit\\.dev/\\)' + +escapeRegExp('$^{}.+*?()[]|\\'); +// '\\$\\^\\{\\}\\.\\+\\*\\?\\(\\)\\[\\]\\|\\\\' +``` + +非字符串值也会在处理前转换为字符串。 + +```typescript +import { escapeRegExp } from 'es-toolkit/compat'; + +escapeRegExp(123); // '123' +escapeRegExp(null); // '' +escapeRegExp(undefined); // '' +``` + +#### 参数 + +- `str` (`string`,可选): 要转义正则表达式特殊字符的字符串。 + +#### 返回值 + +(`string`): 返回正则表达式特殊字符被转义的字符串。 diff --git a/docs/zh_hans/compat/reference/string/kebabCase.md b/docs/zh_hans/compat/reference/string/kebabCase.md new file mode 100644 index 000000000..6e6c2e3df --- /dev/null +++ b/docs/zh_hans/compat/reference/string/kebabCase.md @@ -0,0 +1,48 @@ +# kebabCase (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `kebabCase` + +由于处理非字符串输入值和删除缩写撇号等原因,此 `kebabCase` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [kebabCase](../../../reference/string/kebabCase.md)。 + +::: + +将字符串转换为短横线命名法。 + +```typescript +const result = kebabCase(str); +``` + +## 用法 + +### `kebabCase(str)` + +将字符串转换为短横线命名法。短横线命名法是一种命名约定,每个单词以小写字母书写,并用短横线(-)字符连接。它通常用于URL和CSS类名。 + +```typescript +import { kebabCase } from 'es-toolkit/compat'; + +kebabCase('camelCase'); // 'camel-case' +kebabCase('some whitespace'); // 'some-whitespace' +kebabCase('hyphen-text'); // 'hyphen-text' +kebabCase('HTTPRequest'); // 'http-request' +``` + +非字符串值也会在处理前转换为字符串。 + +```typescript +import { kebabCase } from 'es-toolkit/compat'; + +kebabCase(123); // '123' +kebabCase(null); // '' +kebabCase(undefined); // '' +``` + +#### 参数 + +- `str` (`string | object`,可选): 要转换为短横线命名法的值。 + +#### 返回值 + +(`string`): 返回转换为短横线命名法的字符串。 diff --git a/docs/zh_hans/compat/reference/string/lowerCase.md b/docs/zh_hans/compat/reference/string/lowerCase.md new file mode 100644 index 000000000..622a24ddb --- /dev/null +++ b/docs/zh_hans/compat/reference/string/lowerCase.md @@ -0,0 +1,48 @@ +# lowerCase (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `lowerCase` + +由于处理非字符串输入值和删除缩写撇号等原因,此 `lowerCase` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [lowerCase](../../../reference/string/lowerCase.md)。 + +::: + +将字符串转换为小写单词并用空格分隔。 + +```typescript +const result = lowerCase(str); +``` + +## 用法 + +### `lowerCase(str)` + +将字符串转换为小写单词并用空格分隔。每个单词都转换为小写并用空格字符连接。这对于创建人类可读的文本形式很有用。 + +```typescript +import { lowerCase } from 'es-toolkit/compat'; + +lowerCase('camelCase'); // 'camel case' +lowerCase('some whitespace'); // 'some whitespace' +lowerCase('hyphen-text'); // 'hyphen text' +lowerCase('HTTPRequest'); // 'http request' +``` + +非字符串值也会在处理前转换为字符串。 + +```typescript +import { lowerCase } from 'es-toolkit/compat'; + +lowerCase(123); // '123' +lowerCase(null); // '' +lowerCase(undefined); // '' +``` + +#### 参数 + +- `str` (`string | object`,可选): 要转换为小写格式的值。 + +#### 返回值 + +(`string`): 返回小写单词用空格分隔的字符串。 diff --git a/docs/zh_hans/compat/reference/string/lowerFirst.md b/docs/zh_hans/compat/reference/string/lowerFirst.md new file mode 100644 index 000000000..f4863c62b --- /dev/null +++ b/docs/zh_hans/compat/reference/string/lowerFirst.md @@ -0,0 +1,48 @@ +# lowerFirst (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `lowerFirst` + +由于处理非字符串输入值,此 `lowerFirst` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [lowerFirst](../../../reference/string/lowerFirst.md)。 + +::: + +将字符串的第一个字符转换为小写。 + +```typescript +const result = lowerFirst(str); +``` + +## 用法 + +### `lowerFirst(str)` + +将字符串的第一个字符转换为小写。其余字符保持不变。这对于创建驼峰命名变量名或只想将第一个字符小写时很有用。 + +```typescript +import { lowerFirst } from 'es-toolkit/compat'; + +lowerFirst('fred'); // 'fred' +lowerFirst('Fred'); // 'fred' +lowerFirst('FRED'); // 'fRED' +lowerFirst(''); // '' +``` + +非字符串值也会在处理前转换为字符串。 + +```typescript +import { lowerFirst } from 'es-toolkit/compat'; + +lowerFirst(123); // '123' +lowerFirst(null); // '' +lowerFirst(undefined); // '' +``` + +#### 参数 + +- `str` (`string`,可选): 要将首字母转换为小写的字符串。 + +#### 返回值 + +(`string`): 返回首字母转换为小写的字符串。 diff --git a/docs/zh_hans/compat/reference/string/pad.md b/docs/zh_hans/compat/reference/string/pad.md new file mode 100644 index 000000000..ae62a2488 --- /dev/null +++ b/docs/zh_hans/compat/reference/string/pad.md @@ -0,0 +1,60 @@ +# pad (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `pad` + +由于处理 `null` 或 `undefined` 等原因,此 `pad` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [pad](../../../reference/string/pad.md)。 + +::: + +在字符串的两侧添加填充字符以达到指定的长度。 + +```typescript +const padded = pad(str, length, chars); +``` + +## 用法 + +### `pad(str, length, chars)` + +当您想在字符串两侧添加填充以匹配所需长度时,请使用 `pad`。如果填充字符不能均匀分配,额外的字符将放在右侧。 + +```typescript +import { pad } from 'es-toolkit/compat'; + +// 用默认空格填充 +pad('abc', 8); +// Returns: ' abc ' + +// 用指定字符填充 +pad('abc', 8, '_-'); +// Returns: '_-abc_-_' + +// 如果已经足够长则原样返回 +pad('abc', 3); +// Returns: 'abc' + +// 如果长度更短则原样返回 +pad('abc', 2); +// Returns: 'abc' +``` + +`null` 或 `undefined` 被视为空字符串。 + +```typescript +import { pad } from 'es-toolkit/compat'; + +pad(null, 5); // ' ' +pad(undefined, 3, '*'); // '***' +``` + +#### 参数 + +- `str` (`string`,可选): 要填充的字符串。 +- `length` (`number`,可选): 目标长度。默认为 `0`。 +- `chars` (`string`,可选): 用于填充的字符。默认为空格 `' '`。 + +#### 返回值 + +(`string`): 返回填充到指定长度的字符串。 diff --git a/docs/zh_hans/reference/compat/string/padEnd.md b/docs/zh_hans/compat/reference/string/padEnd.md similarity index 100% rename from docs/zh_hans/reference/compat/string/padEnd.md rename to docs/zh_hans/compat/reference/string/padEnd.md diff --git a/docs/zh_hans/reference/compat/string/padStart.md b/docs/zh_hans/compat/reference/string/padStart.md similarity index 100% rename from docs/zh_hans/reference/compat/string/padStart.md rename to docs/zh_hans/compat/reference/string/padStart.md diff --git a/docs/zh_hans/reference/compat/string/repeat.md b/docs/zh_hans/compat/reference/string/repeat.md similarity index 100% rename from docs/zh_hans/reference/compat/string/repeat.md rename to docs/zh_hans/compat/reference/string/repeat.md diff --git a/docs/zh_hans/reference/compat/string/replace.md b/docs/zh_hans/compat/reference/string/replace.md similarity index 100% rename from docs/zh_hans/reference/compat/string/replace.md rename to docs/zh_hans/compat/reference/string/replace.md diff --git a/docs/zh_hans/compat/reference/string/snakeCase.md b/docs/zh_hans/compat/reference/string/snakeCase.md new file mode 100644 index 000000000..d2ef66655 --- /dev/null +++ b/docs/zh_hans/compat/reference/string/snakeCase.md @@ -0,0 +1,58 @@ +# snakeCase (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `snakeCase` + +此 `snakeCase` 函数由于处理 `null` 或 `undefined` 的规范化逻辑而运行缓慢。 + +请改用更快、更现代的 `es-toolkit` 的 [snakeCase](../../../reference/string/snakeCase.md)。 + +::: + +将字符串转换为蛇形命名法。 + +```typescript +const snakeCased = snakeCase(str); +``` + +## 用法 + +### `snakeCase(str)` + +当您想将字符串转换为蛇形命名法 (snake*case) 时,请使用 `snakeCase`。蛇形命名法是一种命名约定,其中每个单词都以小写字母书写,并用下划线 (*) 连接。 + +```typescript +import { snakeCase } from 'es-toolkit/compat'; + +// 转换驼峰命名法 +snakeCase('camelCase'); +// Returns: 'camel_case' + +// 转换空格分隔的字符串 +snakeCase('some whitespace'); +// Returns: 'some_whitespace' + +// 转换连字符分隔的字符串 +snakeCase('hyphen-text'); +// Returns: 'hyphen_text' + +// 处理连续大写字母 +snakeCase('HTTPRequest'); +// Returns: 'http_request' +``` + +`null` 或 `undefined` 被视为空字符串。 + +```typescript +import { snakeCase } from 'es-toolkit/compat'; + +snakeCase(null); // '' +snakeCase(undefined); // '' +``` + +#### 参数 + +- `str` (`string`, 可选): 要转换为蛇形命名法的字符串。 + +#### 返回值 + +(`string`): 返回转换为蛇形命名法的字符串。 diff --git a/docs/zh_hans/reference/compat/string/split.md b/docs/zh_hans/compat/reference/string/split.md similarity index 100% rename from docs/zh_hans/reference/compat/string/split.md rename to docs/zh_hans/compat/reference/string/split.md diff --git a/docs/zh_hans/compat/reference/string/startCase.md b/docs/zh_hans/compat/reference/string/startCase.md new file mode 100644 index 000000000..5964a2ffc --- /dev/null +++ b/docs/zh_hans/compat/reference/string/startCase.md @@ -0,0 +1,58 @@ +# startCase (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `startCase` + +由于处理 `null` 或 `undefined` 的规范化逻辑,此 `startCase` 函数运行速度较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [startCase](../../../reference/string/startCase.md)。 + +::: + +将字符串转换为 start case。 + +```typescript +const startCased = startCase(str); +``` + +## 用法 + +### `startCase(str)` + +当您想将字符串转换为 Start Case 时,请使用 `startCase`。Start Case 是一种命名约定,每个单词的首字母大写并用空格分隔。 + +```typescript +import { startCase } from 'es-toolkit/compat'; + +// 转换普通字符串 +startCase('hello world'); +// 返回值: 'Hello World' + +// 已经大写的单词保持不变 +startCase('HELLO WORLD'); +// 返回值: 'HELLO WORLD' + +// 转换连字符分隔的字符串 +startCase('hello-world'); +// 返回值: 'Hello World' + +// 转换下划线分隔的字符串 +startCase('hello_world'); +// 返回值: 'Hello World' +``` + +`null` 或 `undefined` 被视为空字符串。 + +```typescript +import { startCase } from 'es-toolkit/compat'; + +startCase(null); // '' +startCase(undefined); // '' +``` + +#### 参数 + +- `str` (`string`, 可选): 要转换为 start case 的字符串。 + +#### 返回值 + +(`string`): 返回转换为 start case 的字符串。 diff --git a/docs/zh_hans/reference/compat/string/startsWith.md b/docs/zh_hans/compat/reference/string/startsWith.md similarity index 100% rename from docs/zh_hans/reference/compat/string/startsWith.md rename to docs/zh_hans/compat/reference/string/startsWith.md diff --git a/docs/zh_hans/reference/compat/string/template.md b/docs/zh_hans/compat/reference/string/template.md similarity index 100% rename from docs/zh_hans/reference/compat/string/template.md rename to docs/zh_hans/compat/reference/string/template.md diff --git a/docs/zh_hans/reference/compat/string/toLower.md b/docs/zh_hans/compat/reference/string/toLower.md similarity index 100% rename from docs/zh_hans/reference/compat/string/toLower.md rename to docs/zh_hans/compat/reference/string/toLower.md diff --git a/docs/zh_hans/reference/compat/string/toUpper.md b/docs/zh_hans/compat/reference/string/toUpper.md similarity index 100% rename from docs/zh_hans/reference/compat/string/toUpper.md rename to docs/zh_hans/compat/reference/string/toUpper.md diff --git a/docs/zh_hans/compat/reference/string/trim.md b/docs/zh_hans/compat/reference/string/trim.md new file mode 100644 index 000000000..7ca5dc200 --- /dev/null +++ b/docs/zh_hans/compat/reference/string/trim.md @@ -0,0 +1,55 @@ +# trim (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `trim` + +由于需要处理 `null` 或 `undefined` 以及数组类型的 `chars`,此 `trim` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [trim](../../../reference/string/trim.md)。 + +::: + +移除字符串开头和结尾的空格或指定字符。 + +```typescript +const trimmed = trim(str, chars); +``` + +## 用法 + +### `trim(str, chars)` + +当您想要移除字符串开头和结尾的空格或特定字符时,请使用 `trim`。如果未指定 `chars`,则只移除开头和结尾的空格。 + +```typescript +import { trim } from 'es-toolkit/compat'; + +// 移除开头和结尾的空格 +trim(' hello '); +// 返回: 'hello' + +// 移除指定字符 +trim('--hello--', '-'); +// 返回: 'hello' + +// 使用数组移除多个字符 +trim('##hello##', ['#', 'o']); +// 返回: 'hell' +``` + +`null` 或 `undefined` 被视为空字符串。 + +```typescript +import { trim } from 'es-toolkit/compat'; + +trim(null); // '' +trim(undefined); // '' +``` + +#### 参数 + +- `str` (`string`, 可选): 要修剪的字符串。 +- `chars` (`string`, 可选): 要移除的字符。如果未指定,将移除空格。 + +#### 返回值 + +(`string`): 返回从开头和结尾移除指定字符后的字符串。 diff --git a/docs/zh_hans/compat/reference/string/trimEnd.md b/docs/zh_hans/compat/reference/string/trimEnd.md new file mode 100644 index 000000000..17d687f3e --- /dev/null +++ b/docs/zh_hans/compat/reference/string/trimEnd.md @@ -0,0 +1,55 @@ +# trimEnd (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `trimEnd` + +由于需要处理 `null` 或 `undefined` 以及参数顺序变更,此 `trimEnd` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [trimEnd](../../../reference/string/trimEnd.md)。 + +::: + +移除字符串结尾的空格或指定字符。 + +```typescript +const trimmed = trimEnd(str, chars); +``` + +## 用法 + +### `trimEnd(str, chars)` + +当您想要移除字符串结尾的空格或特定字符时,请使用 `trimEnd`。如果未指定 `chars`,则只移除结尾的空格。 + +```typescript +import { trimEnd } from 'es-toolkit/compat'; + +// 移除结尾的空格 +trimEnd(' abc '); +// 返回: ' abc' + +// 移除指定字符 +trimEnd('-_-abc-_-', '_-'); +// 返回: '-_-abc' + +// 仅应用于字符串结尾 +trimEnd('abc', 'a'); +// 返回: 'abc' +``` + +`null` 或 `undefined` 被视为空字符串。 + +```typescript +import { trimEnd } from 'es-toolkit/compat'; + +trimEnd(null); // '' +trimEnd(undefined); // '' +``` + +#### 参数 + +- `str` (`string`, 可选): 要从结尾修剪的字符串。 +- `chars` (`string`, 可选): 要移除的字符。如果未指定,将移除空格。 + +#### 返回值 + +(`string`): 返回从结尾移除指定字符后的字符串。 diff --git a/docs/zh_hans/compat/reference/string/trimStart.md b/docs/zh_hans/compat/reference/string/trimStart.md new file mode 100644 index 000000000..1c6fe052d --- /dev/null +++ b/docs/zh_hans/compat/reference/string/trimStart.md @@ -0,0 +1,55 @@ +# trimStart (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `trimStart` + +由于需要处理 `null` 或 `undefined` 以及参数顺序变更,此 `trimStart` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [trimStart](../../../reference/string/trimStart.md)。 + +::: + +移除字符串开头的空格或指定字符。 + +```typescript +const trimmed = trimStart(str, chars); +``` + +## 用法 + +### `trimStart(str, chars)` + +当您想要移除字符串开头的空格或特定字符时,请使用 `trimStart`。如果未指定 `chars`,则只移除开头的空格。 + +```typescript +import { trimStart } from 'es-toolkit/compat'; + +// 移除开头的空格 +trimStart(' abc '); +// 返回: 'abc ' + +// 移除指定字符 +trimStart('-_-abc-_-', '_-'); +// 返回: 'abc-_-' + +// 仅应用于字符串开头 +trimStart('abc', 'c'); +// 返回: 'abc' +``` + +`null` 或 `undefined` 被视为空字符串。 + +```typescript +import { trimStart } from 'es-toolkit/compat'; + +trimStart(null); // '' +trimStart(undefined); // '' +``` + +#### 参数 + +- `str` (`string`, 可选): 要从开头修剪的字符串。 +- `chars` (`string`, 可选): 要移除的字符。如果未指定,将移除空格。 + +#### 返回值 + +(`string`): 返回从开头移除指定字符后的字符串。 diff --git a/docs/zh_hans/reference/compat/string/truncate.md b/docs/zh_hans/compat/reference/string/truncate.md similarity index 100% rename from docs/zh_hans/reference/compat/string/truncate.md rename to docs/zh_hans/compat/reference/string/truncate.md diff --git a/docs/zh_hans/compat/reference/string/unescape.md b/docs/zh_hans/compat/reference/string/unescape.md new file mode 100644 index 000000000..8201e19e9 --- /dev/null +++ b/docs/zh_hans/compat/reference/string/unescape.md @@ -0,0 +1,58 @@ +# unescape (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `unescape` + +由于需要处理 `null` 或 `undefined` 的转换逻辑,此 `unescape` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [unescape](../../../reference/string/unescape.md)。 + +::: + +将 HTML 实体转换为原始字符。 + +```typescript +const unescaped = unescape(str); +``` + +## 用法 + +### `unescape(str)` + +当您想要将 HTML 实体 `&`、`<`、`>`、`"`、`'` 转换回原始字符时,请使用 `unescape`。这是 `escape` 函数的反向操作。 + +```typescript +import { unescape } from 'es-toolkit/compat'; + +// 反转义 HTML 标签 +unescape('This is a <div> element.'); +// 返回: 'This is a
element.' + +// 反转义引号 +unescape('This is a "quote"'); +// 返回: 'This is a "quote"' + +// 反转义撇号 +unescape('This is a 'quote''); +// 返回: 'This is a 'quote'' + +// 反转义 & 符号 +unescape('This is a & symbol'); +// 返回: 'This is a & symbol' +``` + +`null` 或 `undefined` 被视为空字符串。 + +```typescript +import { unescape } from 'es-toolkit/compat'; + +unescape(null); // '' +unescape(undefined); // '' +``` + +#### 参数 + +- `str` (`string`, 可选): 要反转义的字符串。 + +#### 返回值 + +(`string`): 返回将 HTML 实体转换为原始字符后的字符串。 diff --git a/docs/zh_hans/compat/reference/string/upperCase.md b/docs/zh_hans/compat/reference/string/upperCase.md new file mode 100644 index 000000000..8e3fbf3ad --- /dev/null +++ b/docs/zh_hans/compat/reference/string/upperCase.md @@ -0,0 +1,58 @@ +# upperCase (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `upperCase` + +由于需要处理 `null` 或 `undefined` 的规范化逻辑,此 `upperCase` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [upperCase](../../../reference/string/upperCase.md)。 + +::: + +将字符串转换为大写形式。 + +```typescript +const upperCased = upperCase(str); +``` + +## 用法 + +### `upperCase(str)` + +当您想要将字符串转换为大写形式 (UPPER CASE) 时,请使用 `upperCase`。大写是一种命名约定,每个单词都用大写字母书写并用空格连接。 + +```typescript +import { upperCase } from 'es-toolkit/compat'; + +// 转换驼峰命名 +upperCase('camelCase'); +// 返回: 'CAMEL CASE' + +// 转换空格分隔的字符串 +upperCase('some whitespace'); +// 返回: 'SOME WHITESPACE' + +// 转换连字符分隔的字符串 +upperCase('hyphen-text'); +// 返回: 'HYPHEN TEXT' + +// 当大写字母连续出现时 +upperCase('HTTPRequest'); +// 返回: 'HTTP REQUEST' +``` + +`null` 或 `undefined` 被视为空字符串。 + +```typescript +import { upperCase } from 'es-toolkit/compat'; + +upperCase(null); // '' +upperCase(undefined); // '' +``` + +#### 参数 + +- `str` (`string`, 可选): 要转换为大写形式的字符串。 + +#### 返回值 + +(`string`): 返回转换为大写形式的字符串。 diff --git a/docs/zh_hans/compat/reference/string/upperFirst.md b/docs/zh_hans/compat/reference/string/upperFirst.md new file mode 100644 index 000000000..8b12d3fcf --- /dev/null +++ b/docs/zh_hans/compat/reference/string/upperFirst.md @@ -0,0 +1,54 @@ +# upperFirst (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `upperFirst` + +由于需要处理 `null` 或 `undefined` 的转换逻辑,此 `upperFirst` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [upperFirst](../../../reference/string/upperFirst.md)。 + +::: + +将字符串的第一个字符转换为大写。 + +```typescript +const upperCased = upperFirst(str); +``` + +## 用法 + +### `upperFirst(str)` + +当您想要仅将字符串的第一个字符大写时,请使用 `upperFirst`。其余字符保持不变。 + +```typescript +import { upperFirst } from 'es-toolkit/compat'; + +// 以小写字母开头的字符串 +upperFirst('fred'); +// 返回: 'Fred' + +// 已经以大写字母开头的字符串 +upperFirst('Fred'); +// 返回: 'Fred' + +// 全大写字符串 +upperFirst('FRED'); +// 返回: 'FRED' +``` + +`null` 或 `undefined` 被视为空字符串。 + +```typescript +import { upperFirst } from 'es-toolkit/compat'; + +upperFirst(null); // '' +upperFirst(undefined); // '' +``` + +#### 参数 + +- `str` (`string`, 可选): 要将第一个字符转换为大写的字符串。 + +#### 返回值 + +(`string`): 返回第一个字符转换为大写后的字符串。 diff --git a/docs/zh_hans/compat/reference/string/words.md b/docs/zh_hans/compat/reference/string/words.md new file mode 100644 index 000000000..3b3f9201f --- /dev/null +++ b/docs/zh_hans/compat/reference/string/words.md @@ -0,0 +1,69 @@ +# words (Lodash 兼容性) + +::: warning 请使用 `es-toolkit` 的 `words` + +由于需要处理 `null` 或 `undefined` 以及复杂的 Unicode 支持,此 `words` 函数运行较慢。 + +请改用更快、更现代的 `es-toolkit` 的 [words](../../../reference/string/words.md)。 + +::: + +将字符串拆分为单词数组。 + +```typescript +const wordArray = words(str, pattern); +``` + +## 用法 + +### `words(str, pattern)` + +当您想要将字符串拆分为单词时,请使用 `words`。默认情况下,它会识别英文字母、数字、表情符号等来提取单词。 + +```typescript +import { words } from 'es-toolkit/compat'; + +// 基本单词提取 +words('fred, barney, & pebbles'); +// 返回: ['fred', 'barney', 'pebbles'] + +// 从驼峰命名中提取单词 +words('camelCaseWord'); +// 返回: ['camel', 'Case', 'Word'] + +// 包含数字的字符串 +words('hello123world'); +// 返回: ['hello', '123', 'world'] +``` + +您还可以使用自定义模式提取单词。 + +```typescript +import { words } from 'es-toolkit/compat'; + +// 使用正则表达式提取单词 +words('hello world', /\w+/g); +// 返回: ['hello', 'world'] + +// 使用字符串模式 +words('one-two-three', '-'); +// 返回: ['-'] +``` + +`null` 或 `undefined` 被视为空数组。 + +```typescript +import { words } from 'es-toolkit/compat'; + +words(null); // [] +words(undefined); // [] +``` + +#### 参数 + +- `str` (`string`, 可选): 要拆分为单词的字符串。 +- `pattern` (`RegExp | string`, 可选): 用于匹配单词的模式。默认为内置的 Unicode 单词模式。 + +#### 返回值 + +(`string[]`): 返回提取的单词数组。 diff --git a/docs/zh_hans/reference/compat/util/bindAll.md b/docs/zh_hans/compat/reference/util/bindAll.md similarity index 100% rename from docs/zh_hans/reference/compat/util/bindAll.md rename to docs/zh_hans/compat/reference/util/bindAll.md diff --git a/docs/zh_hans/reference/compat/util/cond.md b/docs/zh_hans/compat/reference/util/cond.md similarity index 100% rename from docs/zh_hans/reference/compat/util/cond.md rename to docs/zh_hans/compat/reference/util/cond.md diff --git a/docs/zh_hans/reference/compat/util/constant.md b/docs/zh_hans/compat/reference/util/constant.md similarity index 100% rename from docs/zh_hans/reference/compat/util/constant.md rename to docs/zh_hans/compat/reference/util/constant.md diff --git a/docs/zh_hans/reference/compat/util/defaultTo.md b/docs/zh_hans/compat/reference/util/defaultTo.md similarity index 100% rename from docs/zh_hans/reference/compat/util/defaultTo.md rename to docs/zh_hans/compat/reference/util/defaultTo.md diff --git a/docs/zh_hans/reference/compat/util/eq.md b/docs/zh_hans/compat/reference/util/eq.md similarity index 100% rename from docs/zh_hans/reference/compat/util/eq.md rename to docs/zh_hans/compat/reference/util/eq.md diff --git a/docs/zh_hans/reference/compat/util/gt.md b/docs/zh_hans/compat/reference/util/gt.md similarity index 100% rename from docs/zh_hans/reference/compat/util/gt.md rename to docs/zh_hans/compat/reference/util/gt.md diff --git a/docs/zh_hans/reference/compat/util/gte.md b/docs/zh_hans/compat/reference/util/gte.md similarity index 100% rename from docs/zh_hans/reference/compat/util/gte.md rename to docs/zh_hans/compat/reference/util/gte.md diff --git a/docs/zh_hans/reference/compat/util/invoke.md b/docs/zh_hans/compat/reference/util/invoke.md similarity index 100% rename from docs/zh_hans/reference/compat/util/invoke.md rename to docs/zh_hans/compat/reference/util/invoke.md diff --git a/docs/zh_hans/reference/compat/util/iteratee.md b/docs/zh_hans/compat/reference/util/iteratee.md similarity index 100% rename from docs/zh_hans/reference/compat/util/iteratee.md rename to docs/zh_hans/compat/reference/util/iteratee.md diff --git a/docs/zh_hans/reference/compat/util/lt.md b/docs/zh_hans/compat/reference/util/lt.md similarity index 100% rename from docs/zh_hans/reference/compat/util/lt.md rename to docs/zh_hans/compat/reference/util/lt.md diff --git a/docs/zh_hans/reference/compat/util/lte.md b/docs/zh_hans/compat/reference/util/lte.md similarity index 100% rename from docs/zh_hans/reference/compat/util/lte.md rename to docs/zh_hans/compat/reference/util/lte.md diff --git a/docs/zh_hans/reference/compat/util/method.md b/docs/zh_hans/compat/reference/util/method.md similarity index 100% rename from docs/zh_hans/reference/compat/util/method.md rename to docs/zh_hans/compat/reference/util/method.md diff --git a/docs/zh_hans/reference/compat/util/methodOf.md b/docs/zh_hans/compat/reference/util/methodOf.md similarity index 100% rename from docs/zh_hans/reference/compat/util/methodOf.md rename to docs/zh_hans/compat/reference/util/methodOf.md diff --git a/docs/zh_hans/reference/compat/util/now.md b/docs/zh_hans/compat/reference/util/now.md similarity index 100% rename from docs/zh_hans/reference/compat/util/now.md rename to docs/zh_hans/compat/reference/util/now.md diff --git a/docs/zh_hans/reference/compat/util/over.md b/docs/zh_hans/compat/reference/util/over.md similarity index 100% rename from docs/zh_hans/reference/compat/util/over.md rename to docs/zh_hans/compat/reference/util/over.md diff --git a/docs/zh_hans/reference/compat/util/overEvery.md b/docs/zh_hans/compat/reference/util/overEvery.md similarity index 100% rename from docs/zh_hans/reference/compat/util/overEvery.md rename to docs/zh_hans/compat/reference/util/overEvery.md diff --git a/docs/zh_hans/reference/compat/util/overSome.md b/docs/zh_hans/compat/reference/util/overSome.md similarity index 100% rename from docs/zh_hans/reference/compat/util/overSome.md rename to docs/zh_hans/compat/reference/util/overSome.md diff --git a/docs/zh_hans/reference/compat/util/stubArray.md b/docs/zh_hans/compat/reference/util/stubArray.md similarity index 100% rename from docs/zh_hans/reference/compat/util/stubArray.md rename to docs/zh_hans/compat/reference/util/stubArray.md diff --git a/docs/zh_hans/reference/compat/util/stubFalse.md b/docs/zh_hans/compat/reference/util/stubFalse.md similarity index 100% rename from docs/zh_hans/reference/compat/util/stubFalse.md rename to docs/zh_hans/compat/reference/util/stubFalse.md diff --git a/docs/zh_hans/reference/compat/util/stubObject.md b/docs/zh_hans/compat/reference/util/stubObject.md similarity index 100% rename from docs/zh_hans/reference/compat/util/stubObject.md rename to docs/zh_hans/compat/reference/util/stubObject.md diff --git a/docs/zh_hans/reference/compat/util/stubString.md b/docs/zh_hans/compat/reference/util/stubString.md similarity index 100% rename from docs/zh_hans/reference/compat/util/stubString.md rename to docs/zh_hans/compat/reference/util/stubString.md diff --git a/docs/zh_hans/reference/compat/util/stubTrue.md b/docs/zh_hans/compat/reference/util/stubTrue.md similarity index 100% rename from docs/zh_hans/reference/compat/util/stubTrue.md rename to docs/zh_hans/compat/reference/util/stubTrue.md diff --git a/docs/zh_hans/reference/compat/util/times.md b/docs/zh_hans/compat/reference/util/times.md similarity index 100% rename from docs/zh_hans/reference/compat/util/times.md rename to docs/zh_hans/compat/reference/util/times.md diff --git a/docs/zh_hans/reference/compat/util/toArray.md b/docs/zh_hans/compat/reference/util/toArray.md similarity index 100% rename from docs/zh_hans/reference/compat/util/toArray.md rename to docs/zh_hans/compat/reference/util/toArray.md diff --git a/docs/zh_hans/reference/compat/util/toFinite.md b/docs/zh_hans/compat/reference/util/toFinite.md similarity index 100% rename from docs/zh_hans/reference/compat/util/toFinite.md rename to docs/zh_hans/compat/reference/util/toFinite.md diff --git a/docs/zh_hans/reference/compat/util/toInteger.md b/docs/zh_hans/compat/reference/util/toInteger.md similarity index 100% rename from docs/zh_hans/reference/compat/util/toInteger.md rename to docs/zh_hans/compat/reference/util/toInteger.md diff --git a/docs/zh_hans/reference/compat/util/toLength.md b/docs/zh_hans/compat/reference/util/toLength.md similarity index 100% rename from docs/zh_hans/reference/compat/util/toLength.md rename to docs/zh_hans/compat/reference/util/toLength.md diff --git a/docs/zh_hans/reference/compat/util/toNumber.md b/docs/zh_hans/compat/reference/util/toNumber.md similarity index 100% rename from docs/zh_hans/reference/compat/util/toNumber.md rename to docs/zh_hans/compat/reference/util/toNumber.md diff --git a/docs/zh_hans/reference/compat/util/toPath.md b/docs/zh_hans/compat/reference/util/toPath.md similarity index 100% rename from docs/zh_hans/reference/compat/util/toPath.md rename to docs/zh_hans/compat/reference/util/toPath.md diff --git a/docs/zh_hans/reference/compat/util/toPlainObject.md b/docs/zh_hans/compat/reference/util/toPlainObject.md similarity index 100% rename from docs/zh_hans/reference/compat/util/toPlainObject.md rename to docs/zh_hans/compat/reference/util/toPlainObject.md diff --git a/docs/zh_hans/reference/compat/util/toSafeInteger.md b/docs/zh_hans/compat/reference/util/toSafeInteger.md similarity index 100% rename from docs/zh_hans/reference/compat/util/toSafeInteger.md rename to docs/zh_hans/compat/reference/util/toSafeInteger.md diff --git a/docs/zh_hans/reference/compat/util/toString.md b/docs/zh_hans/compat/reference/util/toString.md similarity index 100% rename from docs/zh_hans/reference/compat/util/toString.md rename to docs/zh_hans/compat/reference/util/toString.md diff --git a/docs/zh_hans/reference/compat/util/uniqueId.md b/docs/zh_hans/compat/reference/util/uniqueId.md similarity index 100% rename from docs/zh_hans/reference/compat/util/uniqueId.md rename to docs/zh_hans/compat/reference/util/uniqueId.md diff --git a/docs/zh_hans/compatibility.md b/docs/zh_hans/compatibility.md deleted file mode 100644 index d352504c3..000000000 --- a/docs/zh_hans/compatibility.md +++ /dev/null @@ -1,62 +0,0 @@ -# 与 Lodash 兼容性 - -::: tip ✅ 从1.39.3版本开始,我们确保与Lodash 100%兼容 - -`es-toolkit/compat`在所有Lodash函数上表现相同,同时更轻更快。 - -- 确保与Lodash的实际测试代码行为一致。 -- 被Storybook、Recharts、CKEditor等知名开源库使用,并受到Nuxt的推荐。 - -所有兼容性函数的详细文档可以在[兼容性参考](/zh_hans/reference/compat/array/castArray)中查看。 - -::: - -```tsx -// es-toolkit/compat 的目标是提供与 lodash 百分之百的功能兼容性 -import { chunk } from 'es-toolkit/compat'; - -chunk([1, 2, 3, 4], 0); -// 返回 [], 与 lodash 完全相同 -``` - -为了最大限度地兼容 `lodash`,请使用 `es-toolkit/compat`,这是一个弥合这两个库之间差距的兼容性层。 - -该模块旨在提供与 `lodash` 相同的 API,使得在这两个库之间能够更加容易地进行切换。 - -`es-toolkit/compat` 已经对 `lodash` 的实际测试用例进行了全面测试。 - -需要注意的是,与原始 `es-toolkit` 相比,`es-toolkit/compat` 可能会对性能产生轻微影响,并且包大小可能会更大。该模块旨在促进平滑过渡,一旦迁移完成,应替换回原始的 `es-toolkit` 以获得最佳性能。 - -## 设计原则 - -::: info -设计原则可能会发生变化。 -::: - -我们的兼容层旨在实现以下功能百分之百的特性一致性: - -- 作为 lodash 测试用例编写的功能。 -- 可以从 `@types/lodash` 或 `@types/lodash-es` 的类型推断出的功能。 -- 在从 `lodash` 迁移到 `es-toolkit` 的过程中发现的功能差异(请在[问题页面](https://github.com/toss/es-toolkit/issues)报告。) - -然而,以下内容不在 `es-toolkit/compat` 的范围之内: - -- 隐式类型转换,例如将空字符串转换为零或假。 -- 对特定类型数组有专门实现的函数,比如 [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq)。 -- 处理内部对象原型(例如 `Array.prototype`)被修改的情况。 -- 处理涉及 JavaScript 领域(Realms)的情况。 -- 通过 "Seq" 方法支持方法链。 - -## 实现状态 - -::: info -以下表情符号表示每个功能的状态: - -- ✅: 已完成(该功能已完全实现,并通过了所有lodash测试代码。) -- 📝: 审查中(该功能已实现,但尚未使用lodash测试代码进行测试。) -- ❌: 未实现(该功能尚未实现。) - -即使某个功能标记为“审查中”,它也可能已经在审查中,以确保其与lodash完全一致,并且可能已经提供了相同的功能。 -::: - - diff --git a/docs/zh_hans/index.md b/docs/zh_hans/index.md index a626105ac..11e3ab20f 100644 --- a/docs/zh_hans/index.md +++ b/docs/zh_hans/index.md @@ -29,7 +29,7 @@ features: details: 与其他替代库相比,es-toolkit的JavaScript代码体积最多减少了97%。 - title: 简单替代Lodash details: es-toolkit提供了一个完整的兼容层,可以轻松替代Lodash。 - link: /zh_hans/compatibility + link: /zh_hans/compat/intro - title: 现代化实现 details: es-toolkit充分利用现代JavaScript API进行简单且无错误的实现。 - title: 强大的类型支持 diff --git a/docs/zh_hans/reference/compat/array/chunk.md b/docs/zh_hans/reference/compat/array/chunk.md deleted file mode 100644 index 507916981..000000000 --- a/docs/zh_hans/reference/compat/array/chunk.md +++ /dev/null @@ -1,70 +0,0 @@ -# chunk(Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [`chunk`](../../array/chunk.md) - -此 `chunk` 函数由于处理 `null`、`undefined` 和默认 `size` 值等原因运行较慢。 - -请使用 `es-toolkit` 中更快、更现代的 [chunk](../../array/chunk.md) 实现。 - -::: - -将数组划分为指定大小的较小数组。 - -```typescript -const chunked = chunk(arr, size); -``` - -## 用法 - -### `chunk(arr, size?)` - -当你想要将一个长数组分割成多个相同大小的较小数组时,使用 `chunk`。如果数组不能被均匀分割,最后一个数组将包含剩余的元素。 - -```typescript -import { chunk } from 'es-toolkit/compat'; - -// 将数字数组分成大小为 2 的块。 -chunk([1, 2, 3, 4], 2); -// 返回值:[[1, 2], [3, 4]] - -// 将字符串数组分成大小为 3 的块。 -chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); -// 返回值:[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] - -// 当不能均匀分割时 -chunk([1, 2, 3, 4, 5], 2); -// 返回值:[[1, 2], [3, 4], [5]] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { chunk } from 'es-toolkit/compat'; - -chunk(null, 2); -// 返回值:[] - -chunk(undefined, 2); -// 返回值:[] -``` - -如果大小为 0 或负数,返回空数组。 - -```typescript -import { chunk } from 'es-toolkit/compat'; - -chunk([1, 2, 3], 0); -// 返回值:[] - -chunk([1, 2, 3], -1); -// 返回值:[] -``` - -#### 参数 - -- `arr` (`ArrayLike | null | undefined`): 要划分的数组。 -- `size` (`number`, 可选): 每个较小数组的大小。默认值为 `1`。 - -#### 返回值 - -(`T[][]`): 返回按大小 `size` 划分的二维数组。 diff --git a/docs/zh_hans/reference/compat/array/compact.md b/docs/zh_hans/reference/compat/array/compact.md deleted file mode 100644 index b518c4481..000000000 --- a/docs/zh_hans/reference/compat/array/compact.md +++ /dev/null @@ -1,77 +0,0 @@ -# compact(Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [`compact`](../../array/compact.md) - -此 `compact` 函数由于处理 `null` 和 `undefined` 值、`size` 默认值处理等原因运行较慢。 - -请使用 `es-toolkit` 中更快、更现代的 [compact](../../array/compact.md) 实现。 - -::: - -从数组中移除假值。 - -```typescript -const compacted = compact(arr); -``` - -## 用法 - -### `compact(arr)` - -当你想要从数组中移除像 `false`、`null`、`0`、`""`、`undefined` 和 `NaN` 这样的假值时,使用 `compact`。 - -```typescript -import { compact } from 'es-toolkit/compat'; - -// 移除假值 -compact([0, 1, false, 2, '', 3]); -// Returns: [1, 2, 3] - -compact(['a', null, 'b', undefined, 'c', NaN]); -// Returns: ['a', 'b', 'c'] - -// 也会移除 bigint 0 -compact([0n, 1n, false, 2n]); -// Returns: [1n, 2n] - -// 处理空数组 -compact([]); -// Returns: [] - -// 当所有值都是假值时 -compact([false, null, 0, '', undefined, NaN]); -// Returns: [] -``` - -真值会保持原样。 - -```typescript -import { compact } from 'es-toolkit/compat'; - -compact([1, 'hello', true, {}, []]); -// Returns: [1, 'hello', true, {}, []] - -// 非零数字 -compact([0, -1, 2, -3]); -// Returns: [-1, 2, -3] -``` - -`null` 或 `undefined` 数组被视为空数组。 - -```typescript -import { compact } from 'es-toolkit/compat'; - -compact(null); -// Returns: [] - -compact(undefined); -// Returns: [] -``` - -#### 参数 - -- `arr` (`ArrayLike | null | undefined`): 要压缩的数组。 - -#### 返回值 - -(`T[]`): 返回移除假值后的新数组。 diff --git a/docs/zh_hans/reference/compat/array/countBy.md b/docs/zh_hans/reference/compat/array/countBy.md deleted file mode 100644 index 2483371df..000000000 --- a/docs/zh_hans/reference/compat/array/countBy.md +++ /dev/null @@ -1,88 +0,0 @@ -# countBy(Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `countBy` - -此 `countBy` 函数由于复杂的转换函数处理和类型转换而运行较慢。 - -请使用 `es-toolkit` 中更快、更现代的 [countBy](../../array/countBy.md)。 - -::: - -根据条件对数组或对象的元素进行分类并计算每个分类的数量。 - -```typescript -const counts = countBy(collection, iteratee); -``` - -## 用法 - -### `countBy(collection, iteratee?)` - -当你想要按某个标准对数组或对象的每个元素进行分组,并计算每个组中有多少个元素时,使用 `countBy`。迭代函数返回的值将成为键,该键对应的元素数量将成为值。 - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// 按向下取整对数字分组 -countBy([6.1, 4.2, 6.3], Math.floor); -// Returns: { '4': 1, '6': 2 } - -// 按长度对字符串分组 -countBy(['one', 'two', 'three'], 'length'); -// Returns: { '3': 2, '5': 1 } - -// 按年龄段对用户分组 -const users = [ - { name: 'Alice', age: 25 }, - { name: 'Bob', age: 35 }, - { name: 'Charlie', age: 25 }, -]; -countBy(users, user => Math.floor(user.age / 10) * 10); -// Returns: { '20': 2, '30': 1 } -``` - -也可以处理对象。 - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// 按类型对对象的值进行分类 -const obj = { a: 1, b: 'string', c: 2, d: 'text' }; -countBy(obj, value => typeof value); -// Returns: { 'number': 2, 'string': 2 } -``` - -不使用迭代函数时,会按值本身分组。 - -```typescript -import { countBy } from 'es-toolkit/compat'; - -// 按值本身分组 -countBy([1, 2, 1, 3, 2, 1]); -// Returns: { '1': 3, '2': 2, '3': 1 } - -// 按布尔值分组 -countBy([true, false, true, true]); -// Returns: { 'true': 3, 'false': 1 } -``` - -`null` 或 `undefined` 集合返回空对象。 - -```typescript -import { countBy } from 'es-toolkit/compat'; - -countBy(null); -// Returns: {} - -countBy(undefined); -// Returns: {} -``` - -#### 参数 - -- `collection` (`ArrayLike | object | null | undefined`): 要处理的数组或对象。 -- `iteratee` (`ValueIteratee`, 可选): 决定每个元素分组标准的函数。可以使用函数、属性名或部分对象。 - -#### 返回值 - -(`Record`): 返回包含每个组的键和该组元素数量的对象。 diff --git a/docs/zh_hans/reference/compat/array/difference.md b/docs/zh_hans/reference/compat/array/difference.md deleted file mode 100644 index 3640685b0..000000000 --- a/docs/zh_hans/reference/compat/array/difference.md +++ /dev/null @@ -1,94 +0,0 @@ -# difference(Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `difference` - -此 `difference` 函数由于处理 `null` 和 `undefined`、多个数组参数处理而变得复杂。 - -请使用 `es-toolkit` 中更快、更现代的 [difference](../../array/difference.md)。 - -::: - -从第一个数组中排除其他数组的值,求差集。 - -```typescript -const result = difference(arr, ...values); -``` - -## 用法 - -### `difference(arr, ...values)` - -当你想要从第一个数组中删除所有包含在其余数组中的值时,使用 `difference`。顺序保持第一个数组的顺序。 - -```typescript -import { difference } from 'es-toolkit/compat'; - -// 基本用法 -const array1 = [1, 2, 3, 4, 5]; -const array2 = [2, 4]; -const array3 = [5, 6]; -difference(array1, array2, array3); -// Returns: [1, 3] - -// 字符串数组 -difference(['a', 'b', 'c'], ['b'], ['c', 'd']); -// Returns: ['a'] - -// 处理重复值 -difference([1, 2, 2, 3], [2]); -// Returns: [1, 3] -``` - -也可以处理空数组或空差集。 - -```typescript -import { difference } from 'es-toolkit/compat'; - -// 与空数组的差集 -difference([1, 2, 3], []); -// Returns: [1, 2, 3] - -// 所有值都被排除的情况 -difference([1, 2, 3], [1, 2, 3]); -// Returns: [] - -// 没有重叠值的情况 -difference([1, 2], [3, 4]); -// Returns: [1, 2] -``` - -`null` 或 `undefined` 数组被视为空数组。 - -```typescript -import { difference } from 'es-toolkit/compat'; - -difference(null, [1, 2]); -// Returns: [] - -difference(undefined, [1, 2]); -// Returns: [] - -difference([1, 2, 3], null, undefined); -// Returns: [1, 2, 3] (null和undefined被忽略) -``` - -也支持类数组对象。 - -```typescript -import { difference } from 'es-toolkit/compat'; - -// 类数组对象 -const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; -const arrayLike2 = { 0: 2, 1: 4, length: 2 }; -difference(arrayLike1, arrayLike2); -// Returns: [1, 3] -``` - -#### 参数 - -- `arr` (`ArrayLike | null | undefined`): 求差集的基准数组。 -- `values` (`...ArrayLike[]`): 包含要排除的值的数组。 - -#### 返回值 - -(`T[]`): 返回从第一个数组中排除其他数组值的新数组。 diff --git a/docs/zh_hans/reference/compat/array/differenceBy.md b/docs/zh_hans/reference/compat/array/differenceBy.md deleted file mode 100644 index d57a56413..000000000 --- a/docs/zh_hans/reference/compat/array/differenceBy.md +++ /dev/null @@ -1,88 +0,0 @@ -# differenceBy(Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `differenceBy` - -此 `differenceBy` 函数由于复杂的参数处理和迭代器转换而运行较慢。 - -请使用 `es-toolkit` 中更快、更现代的 [differenceBy](../../array/differenceBy.md)。 - -::: - -根据迭代函数转换的值,从第一个数组中排除其他数组的元素,求差集。 - -```typescript -const result = differenceBy(array, ...values, iteratee); -``` - -## 用法 - -### `differenceBy(array, ...values, iteratee)` - -当你想要将第一个数组的每个元素和要排除的数组的元素通过迭代函数转换后,删除产生相同值的元素时,使用 `differenceBy`。在对象数组中按特定属性值或转换值进行比较时很有用。 - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// 按向下取整比较 -differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); -// Returns: [1.2] (因为Math.floor(2.1) === Math.floor(2.3),所以排除2.1) - -// 按字符串长度比较 -differenceBy(['one', 'two', 'three'], ['four', 'eight'], 'length'); -// Returns: ['one', 'two'] (因为three和eight长度相同,所以排除three) - -// 按对象属性比较 -const users1 = [ - { id: 1, name: 'Alice' }, - { id: 2, name: 'Bob' }, -]; -const users2 = [{ id: 1, name: 'Different Alice' }]; -differenceBy(users1, users2, 'id'); -// Returns: [{ id: 2, name: 'Bob' }] (排除id为1的对象) -``` - -可以一次排除多个数组。 - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// 从多个数组中排除 -differenceBy([2.1, 1.2, 3.5], [2.3], [1.4], [3.2], Math.floor); -// Returns: [] (所有元素都被排除) - -// 按长度比较字符串数组 -differenceBy(['a', 'bb', 'ccc'], ['x'], ['yy'], ['zzz'], 'length'); -// Returns: [] (长度1、2、3都被排除) -``` - -没有迭代函数时,像普通 `difference` 一样工作。 - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -// 不使用迭代函数 -differenceBy([1, 2, 3], [2, 4]); -// Returns: [1, 3] -``` - -`null` 或 `undefined` 数组被视为空数组。 - -```typescript -import { differenceBy } from 'es-toolkit/compat'; - -differenceBy(null, [1, 2], Math.floor); -// Returns: [] - -differenceBy(undefined, [1, 2], x => x); -// Returns: [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 求差集的基准数组。 -- `values` (`...ArrayLike[]`): 包含要排除的值的数组。 -- `iteratee` (`ValueIteratee`): 将每个元素转换为比较值的函数。可以使用函数、属性名或部分对象。 - -#### 返回值 - -(`T[]`): 返回根据迭代函数转换的值排除元素后的新数组。 diff --git a/docs/zh_hans/reference/compat/array/differenceWith.md b/docs/zh_hans/reference/compat/array/differenceWith.md deleted file mode 100644 index 14d292c28..000000000 --- a/docs/zh_hans/reference/compat/array/differenceWith.md +++ /dev/null @@ -1,79 +0,0 @@ -# differenceWith(Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `differenceWith` - -此 `differenceWith` 函数由于处理 `null` 和 `undefined`、多个数组处理、`ArrayLike` 类型处理等而运行较慢。 - -请使用 `es-toolkit` 中更快、更现代的 [differenceWith](../../array/differenceWith.md)。 - -::: - -使用比较函数从第一个数组中删除其他数组中包含的元素。 - -```typescript -const result = differenceWith(array, ...values, comparator); -``` - -## 用法 - -### `differenceWith(array, ...values, comparator)` - -当你想要用比较函数比较每个元素来求差时,使用 `differenceWith`。最后一个参数成为比较函数。 - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -// 按id比较对象 -const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]; -const others = [{ id: 2 }]; -const comparator = (a, b) => a.id === b.id; - -differenceWith(objects, others, comparator); -// Returns: [{ id: 1 }, { id: 3 }] - -// 一次排除多个数组 -const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]; -const values1 = [{ id: 2 }]; -const values2 = [{ id: 3 }]; - -differenceWith(array, values1, values2, comparator); -// Returns: [{ id: 1 }, { id: 4 }] -``` - -不提供比较函数时,像普通 `difference` 一样工作。 - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -// 不使用比较函数时进行普通比较 -differenceWith([1, 2, 3], [2], [3]); -// Returns: [1] -``` - -也可以使用复杂的比较逻辑。 - -```typescript -import { differenceWith } from 'es-toolkit/compat'; - -const users = [ - { name: 'alice', age: 25 }, - { name: 'bob', age: 30 }, - { name: 'charlie', age: 35 }, -]; -const excludeUsers = [{ name: 'bob', age: 25 }]; // 不同的年龄 - -// 只按名称比较 -const compareByName = (a, b) => a.name === b.name; -differenceWith(users, excludeUsers, compareByName); -// Returns: [{ name: 'alice', age: 25 }, { name: 'charlie', age: 35 }] -// bob被排除(即使年龄不同,名称相同) -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 求差的基准数组。 -- `...values` (`Array>` + `(a: T, b: T) => boolean`): 包含要排除的元素的数组,最后是比较函数。 - -#### 返回值 - -(`T[]`): 返回使用比较函数从第一个数组中删除其余数组元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/drop.md b/docs/zh_hans/reference/compat/array/drop.md deleted file mode 100644 index eb55ef3d6..000000000 --- a/docs/zh_hans/reference/compat/array/drop.md +++ /dev/null @@ -1,97 +0,0 @@ -# drop (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `drop` - -此 `drop` 函数由于处理 `null` 或 `undefined`、`toInteger` 转换等原因而表现复杂。 - -请改用更快、更现代的 `es-toolkit` 的 [`drop`](../../array/drop.md)。 - -::: - -从数组的开头删除指定数量的元素。 - -```typescript -const result = drop(array, n); -``` - -## 用法 - -### `drop(array, n?)` - -当您想从数组的开头删除几个元素并获取其余元素时,使用 `drop`。默认情况下,它会删除第一个元素。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 基本用法(删除第一个元素) -drop([1, 2, 3, 4, 5]); -// 返回: [2, 3, 4, 5] - -// 删除前 2 个元素 -drop([1, 2, 3, 4, 5], 2); -// 返回: [3, 4, 5] - -// 删除前 3 个元素 -drop(['a', 'b', 'c', 'd'], 3); -// 返回: ['d'] -``` - -指定 0 或负数时,返回原始数组。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 删除 0 个元素 -drop([1, 2, 3], 0); -// 返回: [1, 2, 3] - -// 指定负数 -drop([1, 2, 3], -1); -// 返回: [1, 2, 3] -``` - -指定大于数组的数字时,返回空数组。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 指定大于数组大小的数字 -drop([1, 2, 3], 5); -// 返回: [] - -// 从空数组中删除 -drop([], 1); -// 返回: [] -``` - -`null` 或 `undefined` 数组被视为空数组。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -drop(null, 1); -// 返回: [] - -drop(undefined, 2); -// 返回: [] -``` - -也支持类数组对象。 - -```typescript -import { drop } from 'es-toolkit/compat'; - -// 类数组对象 -const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; -drop(arrayLike, 1); -// 返回: ['b', 'c'] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要删除元素的数组。 -- `n` (`number`, 可选): 要删除的元素数量。默认为 `1`。 - -#### 返回值 - -(`T[]`): 返回从开头删除指定数量元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/dropRight.md b/docs/zh_hans/reference/compat/array/dropRight.md deleted file mode 100644 index d3352a97e..000000000 --- a/docs/zh_hans/reference/compat/array/dropRight.md +++ /dev/null @@ -1,55 +0,0 @@ -# dropRight (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `dropRight` - -此 `dropRight` 函数由于处理 `null` 或 `undefined`、`guard` 参数处理、`toInteger` 转换等原因而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`dropRight`](../../array/dropRight.md)。 - -::: - -从数组的末尾删除指定数量的元素,返回一个新数组。 - -```typescript -const result = dropRight(array, itemsCount); -``` - -## 用法 - -### `dropRight(array, itemsCount)` - -当您想从数组的末尾删除特定数量的元素并创建一个包含剩余元素的新数组时,使用 `dropRight`。 - -```typescript -import { dropRight } from 'es-toolkit/compat'; - -// 从数字数组中删除末尾的 2 个元素。 -dropRight([1, 2, 3, 4, 5], 2); -// 返回: [1, 2, 3] - -// 从字符串数组中删除末尾的 1 个元素。 -dropRight(['a', 'b', 'c'], 1); -// 返回: ['a', 'b'] - -// 如果未指定要删除的数量,则使用默认值 1。 -dropRight([1, 2, 3]); -// 返回: [1, 2] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { dropRight } from 'es-toolkit/compat'; - -dropRight(null, 2); // [] -dropRight(undefined, 2); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要删除元素的数组。 -- `itemsCount` (`number`, 可选): 要从数组末尾删除的元素数量。默认为 `1`。 - -#### 返回值 - -(`T[]`): 返回从末尾删除 `itemsCount` 个元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/dropRightWhile.md b/docs/zh_hans/reference/compat/array/dropRightWhile.md deleted file mode 100644 index 08a6dfaf7..000000000 --- a/docs/zh_hans/reference/compat/array/dropRightWhile.md +++ /dev/null @@ -1,65 +0,0 @@ -# dropRightWhile (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `dropRightWhile` - -此 `dropRightWhile` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等原因而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`dropRightWhile`](../../array/dropRightWhile.md)。 - -::: - -根据条件函数从数组的末尾删除元素。 - -```typescript -const result = dropRightWhile(array, predicate); -``` - -## 用法 - -### `dropRightWhile(array, predicate)` - -当您想从数组的末尾连续删除满足特定条件的元素时,使用 `dropRightWhile`。当条件函数返回 `false` 时停止删除。 - -```typescript -import { dropRightWhile } from 'es-toolkit/compat'; - -// 使用函数作为条件。 -const users = [ - { user: 'barney', active: true }, - { user: 'fred', active: false }, - { user: 'pebbles', active: false }, -]; - -dropRightWhile(users, user => !user.active); -// 返回: [{ user: 'barney', active: true }] - -// 使用对象模式进行匹配。 -dropRightWhile(users, { user: 'pebbles', active: false }); -// 返回: [{ user: 'barney', active: true }, { user: 'fred', active: false }] - -// 以数组形式指定属性和值。 -dropRightWhile(users, ['active', false]); -// 返回: [{ user: 'barney', active: true }] - -// 通过属性名检查条件。 -dropRightWhile(users, 'active'); -// 返回: [{ user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false }] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { dropRightWhile } from 'es-toolkit/compat'; - -dropRightWhile(null, x => x > 0); // [] -dropRightWhile(undefined, x => x > 0); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要删除元素的数组。 -- `predicate` (`ListIteratee`, 可选): 应用于每个元素的条件函数。可以接受函数、对象模式、数组模式或属性名。 - -#### 返回值 - -(`T[]`): 返回从第一个不满足条件的元素开始的新数组。 diff --git a/docs/zh_hans/reference/compat/array/dropWhile.md b/docs/zh_hans/reference/compat/array/dropWhile.md deleted file mode 100644 index 96fe915a6..000000000 --- a/docs/zh_hans/reference/compat/array/dropWhile.md +++ /dev/null @@ -1,67 +0,0 @@ -# dropWhile (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `dropWhile` - -此 `dropWhile` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等原因而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`dropWhile`](../../array/dropWhile.md)。 - -::: - -根据条件函数从数组的开头删除元素。 - -```typescript -const result = dropWhile(array, predicate); -``` - -## 用法 - -### `dropWhile(array, predicate)` - -当您想从数组的开头连续删除满足特定条件的元素时,使用 `dropWhile`。当条件函数返回 `false` 时停止删除。 - -```typescript -import { dropWhile } from 'es-toolkit/compat'; - -// 使用函数作为条件。 -dropWhile([1, 2, 3, 4, 5], n => n < 3); -// 返回: [3, 4, 5] - -// 使用对象模式进行匹配。 -const users = [ - { name: 'alice', active: false }, - { name: 'bob', active: false }, - { name: 'charlie', active: true }, -]; - -dropWhile(users, { active: false }); -// 返回: [{ name: 'charlie', active: true }] - -// 以数组形式指定属性和值。 -dropWhile(users, ['active', false]); -// 返回: [{ name: 'charlie', active: true }] - -// 通过属性名检查条件。 -const items = [{ visible: false }, { visible: false }, { visible: true }]; - -dropWhile(items, 'visible'); -// 返回: [{ visible: false }, { visible: false }, { visible: true }] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { dropWhile } from 'es-toolkit/compat'; - -dropWhile(null, x => x > 0); // [] -dropWhile(undefined, x => x > 0); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要删除元素的数组。 -- `predicate` (`ListIteratee`, 可选): 应用于每个元素的条件函数。可以接受函数、对象模式、数组模式或属性名。默认为 `identity`。 - -#### 返回值 - -(`T[]`): 返回从第一个不满足条件的元素开始的新数组。 diff --git a/docs/zh_hans/reference/compat/array/eachRight.md b/docs/zh_hans/reference/compat/array/eachRight.md deleted file mode 100644 index 388fcd9a5..000000000 --- a/docs/zh_hans/reference/compat/array/eachRight.md +++ /dev/null @@ -1,58 +0,0 @@ -# eachRight (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `forEachRight` - -此 `eachRight` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等原因而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`forEachRight`](../../array/forEachRight.md)。 - -::: - -对数组或对象的每个元素从右到左执行迭代操作。 - -```typescript -const result = eachRight(collection, iteratee); -``` - -## 用法 - -### `eachRight(collection, iteratee)` - -从右到左遍历数组、对象或字符串的每个元素并执行给定的函数。对于数组,从最后一个索引开始逆序迭代;对于对象,以逆序遍历可枚举属性。 - -```typescript -import { eachRight } from 'es-toolkit/compat'; - -// 逆序遍历数组 -eachRight([1, 2, 3], (value, index) => console.log(value, index)); -// 日志: 3 2, 2 1, 1 0 - -// 逆序遍历对象 -eachRight({ a: 1, b: 2 }, (value, key) => console.log(key, value)); -// 日志: 'b' 2, 'a' 1 - -// 逆序遍历字符串 -eachRight('hello', (char, index) => console.log(char, index)); -// 日志: 'o' 4, 'l' 3, 'l' 2, 'e' 1, 'h' 0 -``` - -如果函数返回 `false`,则停止迭代。 - -```typescript -import { eachRight } from 'es-toolkit/compat'; - -eachRight([1, 2, 3, 4], value => { - console.log(value); - return value !== 2; // 在 2 处停止 -}); -// 日志: 4, 3, 2 -``` - -#### 参数 - -- `collection` (`ArrayLike | Record | string | null | undefined`): 要遍历的集合。 -- `iteratee` (`(item: any, index: any, collection: any) => unknown`, 可选): 对每个元素执行的函数。默认为 `identity` 函数。 - -#### 返回值 - -(`ArrayLike | Record | string | null | undefined`): 返回原始集合。 diff --git a/docs/zh_hans/reference/compat/array/fill.md b/docs/zh_hans/reference/compat/array/fill.md deleted file mode 100644 index 90e7b84bb..000000000 --- a/docs/zh_hans/reference/compat/array/fill.md +++ /dev/null @@ -1,82 +0,0 @@ -# fill (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `fill` - -此 `fill` 函数由于处理 `null` 或 `undefined`、支持类数组对象等原因而表现复杂。 - -请改用更快、更现代的 `es-toolkit` 的 [`fill`](../../array/fill.md)。 - -::: - -用指定的值填充数组的元素。 - -```typescript -const result = fill(array, value, start, end); -``` - -## 用法 - -### `fill(array, value, start?, end?)` - -当您想用相同的值填充数组的特定范围或整个数组时,使用 `fill`。它会直接修改原始数组。 - -```typescript -import { fill } from 'es-toolkit/compat'; - -// 填充整个数组 -const arr1 = [1, 2, 3]; -fill(arr1, 'a'); -// 返回: ['a', 'a', 'a'] - -// 填充特定范围 -const arr2 = [1, 2, 3, 4, 5]; -fill(arr2, '*', 1, 4); -// 返回: [1, '*', '*', '*', 5] - -// 使用负数索引 -const arr3 = [1, 2, 3, 4, 5]; -fill(arr3, 'x', -3, -1); -// 返回: [1, 2, 'x', 'x', 5] -``` - -也支持类数组对象。 - -```typescript -import { fill } from 'es-toolkit/compat'; - -const arrayLike = { 0: 1, 1: 2, 2: 3, length: 3 }; -fill(arrayLike, 'a', 1, 2); -// 返回: { 0: 1, 1: 'a', 2: 3, length: 3 } -``` - -`null` 或 `undefined` 数组被视为空数组。 - -```typescript -import { fill } from 'es-toolkit/compat'; - -fill(null, 'a'); -// 返回: [] - -fill(undefined, 'a'); -// 返回: [] -``` - -字符串是只读的,因此按原样返回。 - -```typescript -import { fill } from 'es-toolkit/compat'; - -fill('abc', 'x'); -// 返回: 'abc' (未修改) -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要填充的数组。 -- `value` (`U`): 用于填充数组的值。 -- `start` (`number`, 可选): 起始位置。默认为 `0`。 -- `end` (`number`, 可选): 结束位置(不包括)。默认为 `array.length`。 - -#### 返回值 - -(`ArrayLike`): 返回用值填充的数组。 diff --git a/docs/zh_hans/reference/compat/array/first.md b/docs/zh_hans/reference/compat/array/first.md deleted file mode 100644 index 4d78b3668..000000000 --- a/docs/zh_hans/reference/compat/array/first.md +++ /dev/null @@ -1,78 +0,0 @@ -# first (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `head` - -此 `first` 函数由于处理 `null` 或 `undefined` 和类数组对象转换而运行较慢。`es-toolkit` 的 `head` 函数没有这些额外处理,运行更快、更简单。 - -请改用更快、更现代的 `es-toolkit` 的 [head](../../array/head.md)。 - -::: - -返回数组的第一个元素。 - -```typescript -const firstElement = first(array); -``` - -## 用法 - -### `first(array)` - -当您想要获取数组的第一个元素时使用 `first`。如果数组为空或为 `null` 或 `undefined`,则返回 `undefined`。 - -```typescript -import { first } from 'es-toolkit/compat'; - -// 从常规数组获取第一个元素 -first([1, 2, 3]); -// Returns: 1 - -// 从字符串数组获取第一个元素 -first(['a', 'b', 'c']); -// Returns: 'a' - -// 空数组 -first([]); -// Returns: undefined -``` - -`null` 或 `undefined` 返回 `undefined`。 - -```typescript -import { first } from 'es-toolkit/compat'; - -first(null); // undefined -first(undefined); // undefined -``` - -可用于类数组对象。 - -```typescript -import { first } from 'es-toolkit/compat'; - -const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }; -first(arrayLike); -// Returns: 'a' - -// 字符串也被视为数组 -first('hello'); -// Returns: 'h' -``` - -对于类型保证的元组,返回确切的类型。 - -```typescript -import { first } from 'es-toolkit/compat'; - -const tuple = [1, 'two', true] as const; -first(tuple); -// Returns: 1 (类型推断为 1) -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要获取第一个元素的数组。 - -#### 返回值 - -(`T | undefined`): 返回数组的第一个元素。如果数组为空或无效,则返回 `undefined`。 diff --git a/docs/zh_hans/reference/compat/array/flatMap.md b/docs/zh_hans/reference/compat/array/flatMap.md deleted file mode 100644 index f7d34da6c..000000000 --- a/docs/zh_hans/reference/compat/array/flatMap.md +++ /dev/null @@ -1,77 +0,0 @@ -# flatMap (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `flatMap` - -此 `flatMap` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等而运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [flatMap](../../array/flatMap.md)。 - -::: - -对每个元素应用函数并展平结果。 - -```typescript -const result = flatMap(collection, iteratee); -``` - -## 用法 - -### `flatMap(collection, iteratee)` - -对集合的每个元素应用迭代函数并返回展平一层的数组。支持数组、对象和字符串,可以使用各种形式的迭代器。 - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -// 对数组应用函数 -function duplicate(n) { - return [n, n]; -} -flatMap([1, 2], duplicate); -// 结果: [1, 1, 2, 2] - -// 对对象应用函数 -const obj = { a: 1, b: 2 }; -flatMap(obj, (value, key) => [key, value]); -// 结果: ['a', 1, 'b', 2] - -// 使用字符串属性映射 -const users = [ - { user: 'barney', hobbies: ['hiking', 'coding'] }, - { user: 'fred', hobbies: ['reading'] }, -]; -flatMap(users, 'hobbies'); -// 结果: ['hiking', 'coding', 'reading'] -``` - -不使用迭代器时将值展平一层。 - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -const obj = { a: [1, 2], b: [3, 4] }; -flatMap(obj); -// 结果: [1, 2, 3, 4] -``` - -也可以使用部分对象进行条件映射。 - -```typescript -import { flatMap } from 'es-toolkit/compat'; - -const users = [ - { user: 'barney', age: 36, active: true }, - { user: 'fred', age: 40, active: false }, -]; -flatMap(users, { active: false }); -// 结果: [false, true] (active 为 false 的元素的匹配结果) -``` - -#### 参数 - -- `collection` (`object | null | undefined`): 要迭代的集合。可以是数组、对象或字符串。 -- `iteratee` (`ListIterator | ObjectIterator | string | object`, 可选): 应用于每个元素的迭代器。可以是函数、属性名或部分对象。 - -#### 返回值 - -(`any[]`): 返回映射后展平一层的新数组。 diff --git a/docs/zh_hans/reference/compat/array/flatMapDeep.md b/docs/zh_hans/reference/compat/array/flatMapDeep.md deleted file mode 100644 index cae355053..000000000 --- a/docs/zh_hans/reference/compat/array/flatMapDeep.md +++ /dev/null @@ -1,77 +0,0 @@ -# flatMapDeep (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [`flatMapDeep`](../../array/flatMapDeep.md) - -此 `flatMapDeep` 函数由于复杂的集合类型处理和深度展平逻辑而运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [flatMapDeep](../../array/flatMapDeep.md)。 - -::: - -对每个元素应用函数并递归展平结果。 - -```typescript -const result = flatMapDeep(collection, iteratee); -``` - -## 用法 - -### `flatMapDeep(collection, iteratee)` - -对集合的每个元素应用迭代函数并返回展平到无限深度的数组。所有嵌套的数组结构都将被展平为一维数组。 - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -// 对数组应用函数并深度展平 -function duplicate(n) { - return [[[n, n]]]; -} -flatMapDeep([1, 2], duplicate); -// 结果: [1, 1, 2, 2] - -// 对对象应用函数并深度展平 -const obj = { a: 1, b: 2 }; -flatMapDeep(obj, (value, key) => [[[key, value]]]); -// 结果: ['a', 1, 'b', 2] - -// 使用字符串属性映射并深度展平 -const users = [ - { user: 'barney', hobbies: [['hiking', 'coding']] }, - { user: 'fred', hobbies: [['reading']] }, -]; -flatMapDeep(users, 'hobbies'); -// 结果: ['hiking', 'coding', 'reading'] -``` - -不使用迭代器时递归展平值。 - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -const obj = { a: [[1, 2]], b: [[[3]]] }; -flatMapDeep(obj); -// 结果: [1, 2, 3] -``` - -也可以使用部分对象进行条件映射。 - -```typescript -import { flatMapDeep } from 'es-toolkit/compat'; - -const users = [ - { user: 'barney', active: [true, false] }, - { user: 'fred', active: [false] }, -]; -flatMapDeep(users, { active: [false] }); -// 结果: [true, true] (active 数组包含 [false] 的元素的匹配结果) -``` - -#### 参数 - -- `collection` (`object | null | undefined`): 要迭代的集合。可以是数组、对象或字符串。 -- `iteratee` (`ListIterator | ObjectIterator | string | object`, 可选): 应用于每个元素的迭代器。可以是函数、属性名或部分对象。 - -#### 返回值 - -(`any[]`): 返回映射后递归展平的新数组。 diff --git a/docs/zh_hans/reference/compat/array/flatMapDepth.md b/docs/zh_hans/reference/compat/array/flatMapDepth.md deleted file mode 100644 index fb7969068..000000000 --- a/docs/zh_hans/reference/compat/array/flatMapDepth.md +++ /dev/null @@ -1,79 +0,0 @@ -# flatMapDepth (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [flatMap](../../array/flatMap.md) - -此 `flatMapDepth` 函数为了 Lodash 兼容性支持各种形式的迭代器和处理 `null` 或 `undefined`,实现较为复杂。主库中的 `flatMap` 函数仅支持简单的函数迭代器,因此运行更快。 - -请改用更快、更现代的 `es-toolkit` 的 [flatMap](../../array/flatMap.md)。 - -::: - -使用迭代函数转换数组的每个元素并展平到指定深度。 - -```typescript -const result = flatMapDepth(collection, iteratee, depth); -``` - -## 用法 - -### `flatMapDepth(collection, iteratee, depth)` - -使用给定函数转换数组或对象的每个元素,然后将结果展平到指定深度并返回新数组。当您想将嵌套的数组结构仅展平到所需深度时很有用。 - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -// 转换数组并展平到深度2 -flatMapDepth([1, 2], n => [[n, n]], 2); -// => [1, 1, 2, 2] - -// 限制为深度1时不会完全展平 -flatMapDepth([1, 2], n => [[n, n]], 1); -// => [[1, 1], [2, 2]] - -// 从对象提取值并展平 -const users = [ - { user: 'barney', hobbies: [['hiking'], ['coding']] }, - { user: 'fred', hobbies: [['reading']] }, -]; -flatMapDepth(users, 'hobbies', 2); -// => ['hiking', 'coding', 'reading'] -``` - -此函数支持各种形式的迭代器。 - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -// 使用函数转换 -flatMapDepth([1, 2, 3], n => [[n, n]], 2); - -// 按属性名提取值 -const objects = [{ items: [['a'], ['b']] }, { items: [['c']] }]; -flatMapDepth(objects, 'items', 2); -// => ['a', 'b', 'c'] - -// 使用对象部分匹配 -const users = [{ active: [[true], [false]] }, { active: [[false]] }]; -flatMapDepth(users, { active: [[false]] }, 2); -// => [true, true] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { flatMapDepth } from 'es-toolkit/compat'; - -flatMapDepth(null, n => [n], 1); // => [] -flatMapDepth(undefined, n => [n], 1); // => [] -``` - -#### 参数 - -- `collection` (`ArrayLike | Record | Record | object | null | undefined`): 要迭代的数组或对象。 -- `iteratee` (`((value: T, index: number, collection: any) => any) | string | object`, 可选): 对每个元素执行的转换函数或属性名。默认为 `identity`。 -- `depth` (`number`, 可选): 要展平的最大深度。默认为 `1`。 - -#### 返回值 - -(`T[]`): 返回使用迭代器转换后展平到指定深度的新数组。 diff --git a/docs/zh_hans/reference/compat/array/flatten.md b/docs/zh_hans/reference/compat/array/flatten.md deleted file mode 100644 index 09df6cbdc..000000000 --- a/docs/zh_hans/reference/compat/array/flatten.md +++ /dev/null @@ -1,69 +0,0 @@ -# flatten (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `flatten` - -此 `flatten` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等而运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [flatten](../../array/flatten.md)。 - -::: - -将数组展平一层。 - -```typescript -const result = flatten(array, depth); -``` - -## 用法 - -### `flatten(value, depth)` - -按指定深度展平嵌套数组。默认情况下只展平一层,并且还支持 Arguments 对象和具有 Symbol.isConcatSpreadable 的对象。 - -```typescript -import { flatten } from 'es-toolkit/compat'; - -// 基本展平(一层) -flatten([1, [2, [3, [4]], 5]]); -// 结果: [1, 2, [3, [4]], 5] - -// 指定深度 -flatten([1, [2, [3, [4]], 5]], 2); -// 结果: [1, 2, 3, [4], 5] - -// 支持 Arguments 对象 -function example() { - return flatten(arguments); -} -example(1, [2, 3], [[4]]); -// 结果: [1, 2, 3, [4]] -``` - -空数组、null 或 undefined 返回空数组。 - -```typescript -import { flatten } from 'es-toolkit/compat'; - -flatten(null); // [] -flatten(undefined); // [] -flatten([]); // [] -``` - -具有 Symbol.isConcatSpreadable 的对象也像数组一样被展平。 - -```typescript -import { flatten } from 'es-toolkit/compat'; - -const spreadable = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true }; -flatten([1, spreadable, 3]); -// 结果: [1, 'a', 'b', 3] -``` - -#### 参数 - -- `value` (`ArrayLike | null | undefined`): 要展平的数组。 -- `depth` (`number`, 可选): 要展平的最大深度。默认为 `1`。 - -#### 返回值 - -(`T[]`): 返回新的展平数组。 diff --git a/docs/zh_hans/reference/compat/array/flattenDeep.md b/docs/zh_hans/reference/compat/array/flattenDeep.md deleted file mode 100644 index c35d641c0..000000000 --- a/docs/zh_hans/reference/compat/array/flattenDeep.md +++ /dev/null @@ -1,64 +0,0 @@ -# flattenDeep (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `flattenDeep` - -此 `flattenDeep` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数格式等而运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [flattenDeep](../../array/flattenDeep.md)。 - -::: - -完全展平数组。 - -```typescript -const result = flattenDeep(array); -``` - -## 用法 - -### `flattenDeep(value)` - -在所有深度递归展平嵌套数组。移除所有嵌套级别,返回完全展平的一维数组。 - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -// 完全展平深层嵌套数组 -flattenDeep([1, [2, [3, [4]], 5]]); -// 结果: [1, 2, 3, 4, 5] - -// 完全展平复杂嵌套结构 -flattenDeep([1, [2, [3, [[[[4]]]]], 5]]); -// 结果: [1, 2, 3, 4, 5] - -// 支持混合类型 -flattenDeep(['a', ['b', ['c', [['d']]]]]); -// 结果: ['a', 'b', 'c', 'd'] -``` - -空数组、null 或 undefined 返回空数组。 - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -flattenDeep(null); // [] -flattenDeep(undefined); // [] -flattenDeep([]); // [] -``` - -已经展平的数组按原样复制。 - -```typescript -import { flattenDeep } from 'es-toolkit/compat'; - -flattenDeep([1, 2, 3, 4, 5]); -// 结果: [1, 2, 3, 4, 5] -``` - -#### 参数 - -- `value` (`ListOfRecursiveArraysOrValues | null | undefined`): 要完全展平的数组。 - -#### 返回值 - -(`Array`): 返回移除所有嵌套的完全展平的新数组。 diff --git a/docs/zh_hans/reference/compat/array/flattenDepth.md b/docs/zh_hans/reference/compat/array/flattenDepth.md deleted file mode 100644 index f01f00fc0..000000000 --- a/docs/zh_hans/reference/compat/array/flattenDepth.md +++ /dev/null @@ -1,55 +0,0 @@ -# flattenDepth (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `flatten` - -此 `flattenDepth` 函数由于处理 `null` 或 `undefined` 而运行较慢。`es-toolkit` 的 `flatten` 函数没有这些额外处理,运行更快、更简单。 - -请改用更快、更现代的 `es-toolkit` 的 [flatten](../../array/flatten.md)。 - -::: - -将数组展平到指定深度。 - -```typescript -const flattened = flattenDepth(array, depth); -``` - -## 用法 - -### `flattenDepth(array, depth)` - -当您想将嵌套数组展平到所需深度时使用 `flattenDepth`。指定深度后,它只会将嵌套数组展平到该深度。 - -```typescript -import { flattenDepth } from 'es-toolkit/compat'; - -// 展平到深度1 -flattenDepth([1, [2, [3, [4]], 5]], 1); -// Returns: [1, 2, [3, [4]], 5] - -// 展平到深度2 -flattenDepth([1, [2, [3, [4]], 5]], 2); -// Returns: [1, 2, 3, [4], 5] - -// 如果未指定深度,默认为1 -flattenDepth([1, [2, [3, [4]], 5]]); -// Returns: [1, 2, [3, [4]], 5] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { flattenDepth } from 'es-toolkit/compat'; - -flattenDepth(null, 2); // [] -flattenDepth(undefined, 2); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要展平的数组。 -- `depth` (`number`, 可选): 要展平的最大深度。默认为 `1`。 - -#### 返回值 - -(`T[]`): 返回展平到指定深度的新数组。 diff --git a/docs/zh_hans/reference/compat/array/forEachRight.md b/docs/zh_hans/reference/compat/array/forEachRight.md deleted file mode 100644 index 21069dae3..000000000 --- a/docs/zh_hans/reference/compat/array/forEachRight.md +++ /dev/null @@ -1,75 +0,0 @@ -# forEachRight (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `forEachRight` - -此 `forEachRight` 函数由于处理 `null` 或 `undefined`、处理 `ArrayLike` 类型、支持各种条件函数形式等原因运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [forEachRight](../../array/forEachRight.md)。 - -::: - -从右到左遍历数组或对象的元素,并对每个元素执行函数。 - -```typescript -forEachRight(collection, callback); -``` - -## 用法 - -### `forEachRight(collection, callback)` - -从右到左顺序遍历数组、对象或字符串,并对每个元素执行回调函数。如果回调返回 `false`,则停止遍历。 - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -// 逆序遍历数组 -forEachRight([1, 2, 3], (value, index) => { - console.log(value, index); -}); -// 输出: 3 2, 2 1, 1 0 - -// 逆序遍历字符串 -forEachRight('abc', (char, index) => { - console.log(char, index); -}); -// 输出: 'c' 2, 'b' 1, 'a' 0 - -// 逆序遍历对象 -forEachRight({ a: 1, b: 2, c: 3 }, (value, key) => { - console.log(value, key); -}); -// 输出: 3 'c', 2 'b', 1 'a' -``` - -`null` 或 `undefined` 按原样返回。 - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -forEachRight(null, value => console.log(value)); // null -forEachRight(undefined, value => console.log(value)); // undefined -``` - -如果回调返回 `false`,则停止遍历。 - -```typescript -import { forEachRight } from 'es-toolkit/compat'; - -forEachRight([1, 2, 3, 4], value => { - console.log(value); - if (value === 2) { - return false; // 停止遍历 - } -}); -// 输出: 4, 3, 2 -``` - -#### 参数 - -- `collection` (`ArrayLike | Record | string | null | undefined`): 要遍历的集合。可以是数组、对象、字符串或 null/undefined。 -- `callback` (`(item: any, index: any, arr: any) => unknown`, 选择): 对每个元素执行的函数。返回 `false` 以停止遍历。默认值是 `identity` 函数。 - -#### 返回值 - -(`ArrayLike | Record | string | null | undefined`): 按原样返回原始集合。 diff --git a/docs/zh_hans/reference/compat/array/groupBy.md b/docs/zh_hans/reference/compat/array/groupBy.md deleted file mode 100644 index c0a6d106d..000000000 --- a/docs/zh_hans/reference/compat/array/groupBy.md +++ /dev/null @@ -1,79 +0,0 @@ -# groupBy (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [groupBy](../../array/groupBy.md) - -此 `groupBy` 函数由于处理 `null` 或 `undefined`、对象支持、复杂类型处理等原因运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [groupBy](../../array/groupBy.md)。 - -::: - -根据给定条件将数组或对象的元素分组。 - -```typescript -const grouped = groupBy(collection, iteratee); -``` - -## 用法 - -### `groupBy(collection, iteratee)` - -根据给定的条件函数对数组或对象的每个元素进行分组,并返回按组分类的对象。条件可以以各种形式提供,如函数、属性名、部分对象等。 - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -// 按函数分组 -const array = [6.1, 4.2, 6.3]; -const result = groupBy(array, Math.floor); -// result 为 { '4': [4.2], '6': [6.1, 6.3] } - -// 按属性名分组 -const users = [ - { name: 'john', age: 30 }, - { name: 'jane', age: 25 }, - { name: 'bob', age: 30 }, -]; -const byAge = groupBy(users, 'age'); -// byAge 为 { '25': [{ name: 'jane', age: 25 }], '30': [{ name: 'john', age: 30 }, { name: 'bob', age: 30 }] } - -// 从对象分组 -const obj = { a: 6.1, b: 4.2, c: 6.3 }; -const groupedObj = groupBy(obj, Math.floor); -// groupedObj 为 { '4': [4.2], '6': [6.1, 6.3] } -``` - -`null` 或 `undefined` 被视为空对象。 - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -groupBy(null, x => x); // {} -groupBy(undefined, x => x); // {} -``` - -也可以按部分对象或属性-值对进行分组。 - -```typescript -import { groupBy } from 'es-toolkit/compat'; - -const products = [ - { category: 'fruit', name: 'apple' }, - { category: 'fruit', name: 'banana' }, - { category: 'vegetable', name: 'carrot' }, -]; - -// 按部分对象分组 -const byCategory = groupBy(products, { category: 'fruit' }); -// 按属性-值对分组 -const byName = groupBy(products, ['name', 'apple']); -``` - -#### 参数 - -- `collection` (`ArrayLike | Record | null | undefined`): 要分组的数组或对象。 -- `iteratee` (`Function | PropertyKey | Array | Object`, 选择): 分组条件。可以是函数、属性名、属性-值对或部分对象。默认值是 `identity` 函数。 - -#### 返回值 - -(`Record`): 返回一个对象,其中每个键是组的条件值,值是属于该组的元素数组。 diff --git a/docs/zh_hans/reference/compat/array/head.md b/docs/zh_hans/reference/compat/array/head.md deleted file mode 100644 index 566815c03..000000000 --- a/docs/zh_hans/reference/compat/array/head.md +++ /dev/null @@ -1,61 +0,0 @@ -# head (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [head](../../array/head.md) - -此 `head` 函数由于 `ArrayLike` 对象处理和数组转换过程而运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [head](../../array/head.md)。 - -::: - -返回数组的第一个元素。 - -```typescript -const firstElement = head(array); -``` - -## 用法 - -### `head(array)` - -返回数组或类数组对象的第一个元素。如果数组为空或无效,则返回 `undefined`。 - -```typescript -import { head } from 'es-toolkit/compat'; - -// 数字数组的第一个元素 -const numbers = [1, 2, 3, 4]; -const first = head(numbers); -// first 为 1 - -// 字符串数组的第一个元素 -const strings = ['a', 'b', 'c']; -const firstChar = head(strings); -// firstChar 为 'a' - -// 类数组对象 -const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; -const firstItem = head(arrayLike); -// firstItem 为 'x' -``` - -空数组或无效输入返回 `undefined`。 - -```typescript -import { head } from 'es-toolkit/compat'; - -const emptyArray: number[] = []; -const noElement = head(emptyArray); -// noElement 为 undefined - -head(null); // undefined -head(undefined); // undefined -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要获取第一个元素的数组或类数组对象。 - -#### 返回值 - -(`T | undefined`): 返回数组的第一个元素,如果数组为空或无效,则返回 `undefined`。 diff --git a/docs/zh_hans/reference/compat/array/initial.md b/docs/zh_hans/reference/compat/array/initial.md deleted file mode 100644 index dc787fcc6..000000000 --- a/docs/zh_hans/reference/compat/array/initial.md +++ /dev/null @@ -1,65 +0,0 @@ -# initial (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [initial](../../array/initial.md) - -此 `initial` 函数由于 `ArrayLike` 对象处理和数组转换过程而运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [initial](../../array/initial.md)。 - -::: - -返回一个新数组,其中包含数组中除最后一个元素外的所有元素。 - -```typescript -const result = initial(array); -``` - -## 用法 - -### `initial(array)` - -返回一个新数组,其中包含数组或类数组对象中除最后一个元素外的所有元素。如果数组为空或只有一个元素,则返回空数组。 - -```typescript -import { initial } from 'es-toolkit/compat'; - -// 从数字数组中排除最后一个元素 -const numbers = [1, 2, 3, 4]; -const result = initial(numbers); -// result 为 [1, 2, 3] - -// 从字符串数组中排除最后一个元素 -const strings = ['a', 'b', 'c', 'd']; -const withoutLast = initial(strings); -// withoutLast 为 ['a', 'b', 'c'] - -// 类数组对象 -const arrayLike = { 0: 'x', 1: 'y', 2: 'z', length: 3 }; -const items = initial(arrayLike); -// items 为 ['x', 'y'] -``` - -空数组或无效输入返回空数组。 - -```typescript -import { initial } from 'es-toolkit/compat'; - -const emptyArray: number[] = []; -const result = initial(emptyArray); -// result 为 [] - -const singleItem = [42]; -const onlyOne = initial(singleItem); -// onlyOne 为 [] - -initial(null); // [] -initial(undefined); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要排除最后一个元素的数组或类数组对象。 - -#### 返回值 - -(`T[]`): 返回排除最后一个元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/intersection.md b/docs/zh_hans/reference/compat/array/intersection.md deleted file mode 100644 index 77f119d8f..000000000 --- a/docs/zh_hans/reference/compat/array/intersection.md +++ /dev/null @@ -1,80 +0,0 @@ -# intersection (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [intersection](../../array/intersection.md) - -此 `intersection` 函数由于处理 `null` 或 `undefined`、多数组支持、去重过程等原因运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [intersection](../../array/intersection.md)。 - -::: - -查找多个数组的交集。 - -```typescript -const result = intersection(...arrays); -``` - -## 用法 - -### `intersection(...arrays)` - -查找在所有数组中都存在的元素,并将它们作为新数组返回。结果已去重并保持第一个数组的顺序。 - -```typescript -import { intersection } from 'es-toolkit/compat'; - -// 两个数组的交集 -const array1 = [1, 2, 3, 4]; -const array2 = [2, 3, 5, 6]; -const result = intersection(array1, array2); -// result 为 [2, 3] - -// 三个数组的交集 -const array3 = [3, 4, 7, 8]; -const multiResult = intersection(array1, array2, array3); -// multiResult 为 [3] - -// 字符串数组 -const strings1 = ['a', 'b', 'c']; -const strings2 = ['b', 'c', 'd']; -const stringResult = intersection(strings1, strings2); -// stringResult 为 ['b', 'c'] - -// 类数组对象 -const arrayLike1 = { 0: 1, 1: 2, 2: 3, length: 3 }; -const arrayLike2 = { 0: 2, 1: 3, 2: 4, length: 3 }; -const likeResult = intersection(arrayLike1, arrayLike2); -// likeResult 为 [2, 3] -``` - -`null` 或 `undefined` 数组被视为空数组。 - -```typescript -import { intersection } from 'es-toolkit/compat'; - -const array1 = [1, 2, 3]; -const result1 = intersection(array1, null); -// result1 为 [] - -const result2 = intersection(null, undefined); -// result2 为 [] -``` - -重复元素会从结果中删除。 - -```typescript -import { intersection } from 'es-toolkit/compat'; - -const array1 = [1, 1, 2, 3]; -const array2 = [1, 2, 2, 4]; -const result = intersection(array1, array2); -// result 为 [1, 2](已去重) -``` - -#### 参数 - -- `...arrays` (`Array | null | undefined>`): 要查找交集的数组。也允许类数组对象、null 或 undefined。 - -#### 返回值 - -(`T[]`): 返回在所有数组中都存在的元素的新数组。已去重并遵循第一个数组的顺序。 diff --git a/docs/zh_hans/reference/compat/array/intersectionBy.md b/docs/zh_hans/reference/compat/array/intersectionBy.md deleted file mode 100644 index 0f45cd3ca..000000000 --- a/docs/zh_hans/reference/compat/array/intersectionBy.md +++ /dev/null @@ -1,93 +0,0 @@ -# intersectionBy (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [intersectionBy](../../array/intersectionBy.md) - -此 `intersectionBy` 函数由于复杂的条件处理、多数组支持、属性路径解析等原因运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [intersectionBy](../../array/intersectionBy.md)。 - -::: - -使用给定的条件函数查找多个数组的交集。 - -```typescript -const result = intersectionBy(...arrays, iteratee); -``` - -## 用法 - -### `intersectionBy(...arrays, iteratee)` - -根据给定条件函数转换后的值,查找多个数组的交集。条件可以以各种形式提供,如函数、属性名、部分对象等。 - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -// 按函数查找交集 -const array1 = [2.1, 1.2]; -const array2 = [2.3, 3.4]; -const result = intersectionBy(array1, array2, Math.floor); -// result 为 [2.1](基于 Math.floor,2 是共同的) - -// 按属性查找交集 -const users1 = [ - { id: 1, name: 'john' }, - { id: 2, name: 'jane' }, -]; -const users2 = [ - { id: 2, name: 'jane' }, - { id: 3, name: 'bob' }, -]; -const byId = intersectionBy(users1, users2, 'id'); -// byId 为 [{ id: 2, name: 'jane' }] - -// 三个数组的交集 -const array3 = [2.5, 4.1]; -const multiResult = intersectionBy(array1, array2, array3, Math.floor); -// multiResult 为 [2.1] - -// 类数组对象 -const arrayLike1 = { 0: { x: 1 }, 1: { x: 2 }, length: 2 }; -const arrayLike2 = { 0: { x: 2 }, 1: { x: 3 }, length: 2 }; -const byProperty = intersectionBy(arrayLike1, arrayLike2, 'x'); -// byProperty 为 [{ x: 2 }] -``` - -`null` 或 `undefined` 数组被视为空数组。 - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -const array1 = [{ x: 1 }, { x: 2 }]; -const result = intersectionBy(array1, null, 'x'); -// result 为 [] -``` - -也可以使用部分对象或属性-值对指定条件。 - -```typescript -import { intersectionBy } from 'es-toolkit/compat'; - -const products1 = [ - { category: 'fruit', name: 'apple' }, - { category: 'vegetable', name: 'carrot' }, -]; -const products2 = [ - { category: 'fruit', name: 'banana' }, - { category: 'meat', name: 'beef' }, -]; - -// 使用部分对象指定条件 -const byCategory = intersectionBy(products1, products2, { category: 'fruit' }); -// 使用属性-值对指定条件 -const byCategoryPair = intersectionBy(products1, products2, ['category', 'fruit']); -``` - -#### 参数 - -- `...arrays` (`Array | null | undefined>`): 要查找交集的数组。 -- `iteratee` (`Function | PropertyKey | Array | Object`): 转换每个元素的条件。可以是函数、属性名、属性-值对或部分对象。 - -#### 返回值 - -(`T[]`): 返回基于转换值在所有数组中都存在的元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/intersectionWith.md b/docs/zh_hans/reference/compat/array/intersectionWith.md deleted file mode 100644 index 263a9e428..000000000 --- a/docs/zh_hans/reference/compat/array/intersectionWith.md +++ /dev/null @@ -1,64 +0,0 @@ -# intersectionWith (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [intersectionWith](../../array/intersectionWith.md) - -此 `intersectionWith` 函数由于处理 `null` 或 `undefined`、支持各种重载等原因运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [intersectionWith](../../array/intersectionWith.md)。 - -::: - -使用自定义比较函数创建在所有数组中找到的共同元素的数组。 - -```typescript -const result = intersectionWith(array, ...otherArrays, comparator); -``` - -## 用法 - -### `intersectionWith(array, ...otherArrays, comparator)` - -使用自定义比较函数查找第一个数组与其余数组的交集。比较函数确定元素是否相等,只返回在所有数组中找到的元素。 - -```typescript -import { intersectionWith } from 'es-toolkit/compat'; - -const objects = [ - { id: 1, name: 'john' }, - { id: 2, name: 'jane' }, -]; -const others = [ - { id: 1, name: 'john' }, - { id: 3, name: 'joe' }, -]; - -intersectionWith(objects, others, (a, b) => a.id === b.id); -// => [{ id: 1, name: 'john' }] - -// 您可以与多个数组进行比较 -const array1 = [{ x: 1 }, { x: 2 }]; -const array2 = [{ x: 1 }, { x: 3 }]; -const array3 = [{ x: 1 }, { x: 4 }]; - -intersectionWith(array1, array2, array3, (a, b) => a.x === b.x); -// => [{ x: 1 }] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { intersectionWith } from 'es-toolkit/compat'; - -intersectionWith(null, [1, 2], (a, b) => a === b); // [] -intersectionWith([1, 2], undefined, (a, b) => a === b); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要比较的第一个数组。 -- `...otherArrays` (`Array | ((a: T, b: T | U) => boolean)>`): 要比较的其他数组和作为最后一个元素的比较函数。 -- `comparator` (`(a: T, b: T | U) => boolean`): 确定两个元素是否相等的函数。 - -#### 返回值 - -(`T[]`): 返回在所有数组中共同找到的元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/keyBy.md b/docs/zh_hans/reference/compat/array/keyBy.md deleted file mode 100644 index 22fd083c8..000000000 --- a/docs/zh_hans/reference/compat/array/keyBy.md +++ /dev/null @@ -1,64 +0,0 @@ -# keyBy (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [keyBy](../../array/keyBy.md) - -由于需要处理 `null` 或 `undefined`、各种参数类型等,这个 `keyBy` 函数运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [keyBy](../../array/keyBy.md)。 - -::: - -将集合的元素按指定键组织成对象。 - -```typescript -const result = keyBy(collection, iteratee); -``` - -## 用法 - -### `keyBy(collection, iteratee)` - -使用指定的键生成函数或属性名将数组或对象的每个元素组织成对象。如果有多个元素具有相同的键,则使用最后一个元素。 - -```typescript -import { keyBy } from 'es-toolkit/compat'; - -// 通过属性名生成键 -const array = [ - { dir: 'left', code: 97 }, - { dir: 'right', code: 100 }, -]; - -keyBy(array, 'dir'); -// => { left: { dir: 'left', code: 97 }, right: { dir: 'right', code: 100 } } - -// 使用函数生成键 -keyBy(array, o => String.fromCharCode(o.code)); -// => { a: { dir: 'left', code: 97 }, d: { dir: 'right', code: 100 } } - -// 也可以用于对象 -const obj = { - a: { id: 1, name: 'john' }, - b: { id: 2, name: 'jane' }, -}; -keyBy(obj, 'name'); -// => { john: { id: 1, name: 'john' }, jane: { id: 2, name: 'jane' } } -``` - -`null` 或 `undefined` 被视为空对象。 - -```typescript -import { keyBy } from 'es-toolkit/compat'; - -keyBy(null, 'id'); // {} -keyBy(undefined, 'id'); // {} -``` - -#### 参数 - -- `collection` (`ArrayLike | null | undefined`): 要按键组织的数组或对象。 -- `iteratee` (`ValueIterateeCustom`, 可选): 用于生成键的函数或属性名。如果省略,则使用元素本身作为键。 - -#### 返回值 - -(`Record`): 返回一个新对象,其中每个元素映射到生成的键。 diff --git a/docs/zh_hans/reference/compat/array/last.md b/docs/zh_hans/reference/compat/array/last.md deleted file mode 100644 index f68f74ed3..000000000 --- a/docs/zh_hans/reference/compat/array/last.md +++ /dev/null @@ -1,79 +0,0 @@ -# last (Lodash兼容性) - -::: warning 使用`es-toolkit`的[last](../../array/last.md) - -此`last`函数由于处理`null`或`undefined`而变得复杂。 - -请使用更快、更现代的`es-toolkit`的[last](../../array/last.md)。 - -::: - -返回数组的最后一个元素。 - -```typescript -const lastElement = last(array); -``` - -## 用法 - -### `last(array)` - -当您想获取数组的最后一个元素时使用`last`。如果数组为空,则返回`undefined`。 - -```typescript -import { last } from 'es-toolkit/compat'; - -// 数字数组的最后一个元素 -last([1, 2, 3, 4, 5]); -// Returns: 5 - -// 字符串数组的最后一个元素 -last(['a', 'b', 'c']); -// Returns: 'c' - -// 对象数组的最后一个元素 -const users = [{ name: 'Alice' }, { name: 'Bob' }]; -last(users); -// Returns: { name: 'Bob' } -``` - -空数组或`null`、`undefined`返回`undefined`。 - -```typescript -import { last } from 'es-toolkit/compat'; - -// 空数组 -last([]); -// Returns: undefined - -// null数组 -last(null); -// Returns: undefined - -// undefined数组 -last(undefined); -// Returns: undefined -``` - -也支持类数组对象。 - -```typescript -import { last } from 'es-toolkit/compat'; - -// 类数组对象 -const arrayLike = { 0: 'first', 1: 'second', length: 2 }; -last(arrayLike); -// Returns: 'second' - -// 字符串也是类数组对象 -last('hello'); -// Returns: 'o' -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要获取最后一个元素的数组。 - -#### 返回值 - -(`T | undefined`): 返回数组的最后一个元素,如果数组为空、`null`或`undefined`,则返回`undefined`。 diff --git a/docs/zh_hans/reference/compat/array/orderBy.md b/docs/zh_hans/reference/compat/array/orderBy.md deleted file mode 100644 index 6b2726164..000000000 --- a/docs/zh_hans/reference/compat/array/orderBy.md +++ /dev/null @@ -1,82 +0,0 @@ -# orderBy (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [orderBy](../../array/orderBy.md) - -由于需要处理 `null` 或 `undefined`、复杂路径导航和各种排序条件,这个 `orderBy` 函数运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [orderBy](../../array/orderBy.md)。 - -::: - -按多个条件对集合的元素进行排序。 - -```typescript -const result = orderBy(collection, criteria, orders); -``` - -## 用法 - -### `orderBy(collection, criteria, orders)` - -根据指定的条件和排序顺序对数组或对象的元素进行排序。您可以使用多个条件,并为每个条件指定升序 (`'asc'`) 或降序 (`'desc'`) 排序。 - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -const users = [ - { name: 'fred', age: 48 }, - { name: 'barney', age: 34 }, - { name: 'fred', age: 40 }, - { name: 'barney', age: 36 }, -]; - -// 按名称升序、年龄降序排序 -orderBy(users, ['name', 'age'], ['asc', 'desc']); -// => [ -// { name: 'barney', age: 36 }, -// { name: 'barney', age: 34 }, -// { name: 'fred', age: 48 }, -// { name: 'fred', age: 40 } -// ] - -// 使用函数指定排序条件 -orderBy(users, [user => user.name, user => user.age], ['asc', 'desc']); -// => 与上面相同的结果 - -// 按单个条件排序 -orderBy(users, 'age', 'desc'); -// => [{ name: 'fred', age: 48 }, { name: 'fred', age: 40 }, ...] -``` - -对于对象,对值进行排序。 - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -const obj = { - a: { name: 'fred', age: 48 }, - b: { name: 'barney', age: 34 }, -}; - -orderBy(obj, 'age', 'desc'); -// => [{ name: 'fred', age: 48 }, { name: 'barney', age: 34 }] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { orderBy } from 'es-toolkit/compat'; - -orderBy(null, 'name'); // [] -orderBy(undefined, 'age'); // [] -``` - -#### 参数 - -- `collection` (`ArrayLike | object | null | undefined`): 要排序的数组或对象。 -- `criteria` (`Criterion | Array>`, 可选): 排序条件。可以使用属性名称、属性路径、函数等。默认为 `[null]`。 -- `orders` (`unknown | unknown[]`, 可选): 每个条件的排序顺序。可以使用 `'asc'`(升序)、`'desc'`(降序)、`true`(升序)、`false`(降序)。默认为 `[]`。 - -#### 返回值 - -(`T[]`): 返回一个新的已排序数组。 diff --git a/docs/zh_hans/reference/compat/array/partition.md b/docs/zh_hans/reference/compat/array/partition.md deleted file mode 100644 index 3e05313f1..000000000 --- a/docs/zh_hans/reference/compat/array/partition.md +++ /dev/null @@ -1,89 +0,0 @@ -# partition (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [partition](../../array/partition.md) - -由于需要处理 `null` 或 `undefined` 和各种条件类型,这个 `partition` 函数运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [partition](../../array/partition.md)。 - -::: - -根据条件将集合的元素分成两组。 - -```typescript -const [truthy, falsy] = partition(collection, predicate); -``` - -## 用法 - -### `partition(collection, predicate)` - -根据给定的条件函数将数组或对象的元素分成两组。第一组包含条件为真的元素,第二组包含条件为假的元素。 - -```typescript -import { partition } from 'es-toolkit/compat'; - -// 将数字数组分成偶数和奇数 -partition([1, 2, 3, 4, 5, 6], n => n % 2 === 0); -// => [[2, 4, 6], [1, 3, 5]] - -// 使用属性名称指定条件 -const users = [ - { name: 'john', active: true }, - { name: 'jane', active: false }, - { name: 'bob', active: true }, -]; - -partition(users, 'active'); -// => [ -// [{ name: 'john', active: true }, { name: 'bob', active: true }], -// [{ name: 'jane', active: false }] -// ] - -// 使用对象条件过滤 -partition(users, { active: true }); -// => [ -// [{ name: 'john', active: true }, { name: 'bob', active: true }], -// [{ name: 'jane', active: false }] -// ] - -// 使用数组条件过滤 -partition(users, ['name', 'john']); -// => [ -// [{ name: 'john', active: true }], -// [{ name: 'jane', active: false }, { name: 'bob', active: true }] -// ] -``` - -对于对象,分割值。 - -```typescript -import { partition } from 'es-toolkit/compat'; - -const obj = { - a: { score: 90 }, - b: { score: 40 }, - c: { score: 80 }, -}; - -partition(obj, item => item.score >= 80); -// => [[{ score: 90 }, { score: 80 }], [{ score: 40 }]] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { partition } from 'es-toolkit/compat'; - -partition(null, x => x > 0); // [[], []] -partition(undefined, 'active'); // [[], []] -``` - -#### 参数 - -- `collection` (`ArrayLike | T | null | undefined`): 要分割的数组或对象。 -- `predicate` (`((value: T) => unknown) | Partial | [PropertyKey, any] | PropertyKey`, 可选): 测试每个元素的条件。可以是函数、部分对象、属性-值数组或属性名称。默认为 `identity`。 - -#### 返回值 - -(`[T[], T[]]`): 返回一个数组,包含满足条件的元素数组和不满足条件的元素数组。 diff --git a/docs/zh_hans/reference/compat/array/pull.md b/docs/zh_hans/reference/compat/array/pull.md deleted file mode 100644 index 2563fbcb3..000000000 --- a/docs/zh_hans/reference/compat/array/pull.md +++ /dev/null @@ -1,44 +0,0 @@ -# pull (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [pull](../../array/pull.md) - -此 `pull` 函数用于 Lodash 兼容性,由于更复杂的类型处理和重载而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [pull](../../array/pull.md)。 - -::: - -从数组中删除所有指定的值。 - -```typescript -const result = pull(array, ...valuesToRemove); -``` - -## 用法 - -### `pull(array, ...valuesToRemove)` - -从数组中删除所有指定的值并修改原始数组。通过直接修改原始数组而不是复制它可以节省内存。 - -```typescript -import { pull } from 'es-toolkit/compat'; - -// 从数字数组中删除特定值 -const numbers = [1, 2, 3, 2, 4, 2, 5]; -pull(numbers, 2, 3); -console.log(numbers); // [1, 4, 5] - -// 从字符串数组中删除特定值 -const fruits = ['apple', 'banana', 'apple', 'cherry']; -pull(fruits, 'apple'); -console.log(fruits); // ['banana', 'cherry'] -``` - -#### 参数 - -- `array` (`T[]`): 要修改的数组。 -- `...valuesToRemove` (`T[]`): 要从数组中删除的值。 - -#### 返回值 - -(`T[]`): 返回修改后的原始数组。 diff --git a/docs/zh_hans/reference/compat/array/pullAt.md b/docs/zh_hans/reference/compat/array/pullAt.md deleted file mode 100644 index d2935928b..000000000 --- a/docs/zh_hans/reference/compat/array/pullAt.md +++ /dev/null @@ -1,57 +0,0 @@ -# pullAt (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [pullAt](../../array/pullAt.md) - -由于复杂的类型处理和重载,这个 `pullAt` 函数运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [pullAt](../../array/pullAt.md)。 - -::: - -从数组中删除指定索引处的元素并返回已删除的元素。 - -```typescript -const removed = pullAt(array, ...indexes); -``` - -## 用法 - -### `pullAt(array, ...indexes)` - -从数组中删除指定索引处的元素并返回已删除元素的数组。原始数组会被修改。 - -```typescript -import { pullAt } from 'es-toolkit/compat'; - -// 通过单个索引删除 -const array = [1, 2, 3, 4, 5]; -const removed = pullAt(array, 1, 3); -console.log(array); // [1, 3, 5] -console.log(removed); // [2, 4] - -// 通过索引数组删除 -const colors = ['red', 'green', 'blue', 'yellow']; -const removedColors = pullAt(colors, [0, 2]); -console.log(colors); // ['green', 'yellow'] -console.log(removedColors); // ['red', 'blue'] -``` - -不存在的索引被视为 `undefined`。 - -```typescript -import { pullAt } from 'es-toolkit/compat'; - -const numbers = [10, 20, 30]; -const removed = pullAt(numbers, 1, 5); -console.log(numbers); // [10, 30] -console.log(removed); // [20, undefined] -``` - -#### 参数 - -- `array` (`ArrayLike`): 要修改的数组。 -- `...indexes` (`Array`): 要删除的元素的索引。可以传递单个数字或数字数组。 - -#### 返回值 - -(`ArrayLike`): 返回已删除元素的数组。 diff --git a/docs/zh_hans/reference/compat/array/remove.md b/docs/zh_hans/reference/compat/array/remove.md deleted file mode 100644 index b4b8dbe5a..000000000 --- a/docs/zh_hans/reference/compat/array/remove.md +++ /dev/null @@ -1,70 +0,0 @@ -# remove (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `remove` - -此 `remove` 函数为了 Lodash 兼容性支持各种形式的谓词,因此实现较为复杂。主库中的 `remove` 函数仅支持简单的函数谓词,因此运行更快。 - -请改用更快、更现代的 `es-toolkit` 的 [remove](../../array/remove.md)。 - -::: - -从数组中删除匹配条件的元素并返回被删除的元素。 - -```typescript -const removedElements = remove(array, predicate); -``` - -## 用法 - -### `remove(array, predicate)` - -遍历数组并从原始数组中删除满足给定条件的元素,将删除的元素作为新数组返回。请注意,原始数组会被直接修改。 - -```typescript -import { remove } from 'es-toolkit/compat'; - -// 使用函数条件删除 -const numbers = [1, 2, 3, 4, 5]; -const evens = remove(numbers, n => n % 2 === 0); -console.log(numbers); // => [1, 3, 5] -console.log(evens); // => [2, 4] - -// 使用部分对象匹配删除 -const objects = [{ a: 1 }, { a: 2 }, { a: 3 }]; -const removed = remove(objects, { a: 1 }); -console.log(objects); // => [{ a: 2 }, { a: 3 }] -console.log(removed); // => [{ a: 1 }] - -// 使用属性-值对删除 -const items = [{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }]; -const cherries = remove(items, ['name', 'cherry']); -console.log(items); // => [{ name: 'apple' }, { name: 'banana' }] -console.log(cherries); // => [{ name: 'cherry' }] -``` - -此函数支持各种形式的谓词。 - -```typescript -import { remove } from 'es-toolkit/compat'; - -// 使用函数条件 -remove(users, user => user.active === false); - -// 部分对象匹配 -remove(users, { status: 'inactive' }); - -// 属性-值数组 -remove(users, ['type', 'guest']); - -// 按属性名检查真值 -remove(users, 'isDeleted'); -``` - -#### 参数 - -- `array` (`ArrayLike`): 要修改的数组。 -- `predicate` (`((value: T, index: number, array: ArrayLike) => boolean) | Partial | [keyof T, unknown] | keyof T`, 可选): 对每个元素执行的条件。默认为 `identity`。 - -#### 返回值 - -(`T[]`): 返回由因匹配条件而被删除的元素组成的新数组。 diff --git a/docs/zh_hans/reference/compat/array/sample.md b/docs/zh_hans/reference/compat/array/sample.md deleted file mode 100644 index 555b8ba06..000000000 --- a/docs/zh_hans/reference/compat/array/sample.md +++ /dev/null @@ -1,54 +0,0 @@ -# sample(Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [sample](../../array/sample.md) - -此 `sample` 函数由于 `null` 或 `undefined` 处理、对象值处理等原因运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [sample](../../array/sample.md)。 - -::: - -从数组或对象中获取一个随机元素。 - -```typescript -const randomItem = sample(collection); -``` - -## 用法 - -### `sample(collection)` - -当需要从数组或对象中选择一个随机元素时,使用 `sample`。对于数组,返回一个随机元素,对于对象,返回一个随机值。 - -```typescript -import { sample } from 'es-toolkit/compat'; - -// 从数组中获取随机元素 -sample([1, 2, 3, 4, 5]); -// 返回1到5之间的随机数字 - -// 从对象中获取随机值 -sample({ a: 1, b: 2, c: 3 }); -// 返回1、2、3中的随机值 - -// 也可以处理字符串 -sample('hello'); -// 返回 'h'、'e'、'l'、'l'、'o' 中的随机字符 -``` - -`null` 或 `undefined` 返回 `undefined`。 - -```typescript -import { sample } from 'es-toolkit/compat'; - -sample(null); // undefined -sample(undefined); // undefined -``` - -#### 参数 - -- `collection` (`ArrayLike | Record | null | undefined`):要采样的数组或对象。 - -#### 返回值 - -(`T | string | undefined`):返回从数组或对象中随机选择的元素。如果集合为空或为 `null`、`undefined`,则返回 `undefined`。 diff --git a/docs/zh_hans/reference/compat/array/sampleSize.md b/docs/zh_hans/reference/compat/array/sampleSize.md deleted file mode 100644 index 28d885905..000000000 --- a/docs/zh_hans/reference/compat/array/sampleSize.md +++ /dev/null @@ -1,54 +0,0 @@ -# sampleSize(Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [sampleSize](../../array/sampleSize.md) - -此 `sampleSize` 函数由于 `null` 或 `undefined` 处理、对象支持、默认值处理等原因运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [sampleSize](../../array/sampleSize.md)。 - -::: - -从数组或对象中随机选择指定数量的元素。 - -```typescript -const sampled = sampleSize(collection, size); -``` - -## 用法 - -### `sampleSize(collection, size?)` - -当需要从数组或对象中随机选择元素时,使用 `sampleSize`。它使用 Floyd 算法进行高效的无重复采样。 - -```typescript -import { sampleSize } from 'es-toolkit/compat'; - -// 从数组中随机选择3个元素。 -sampleSize([1, 2, 3, 4, 5], 3); -// 返回值:[2, 4, 5](实际结果可能不同) - -// 从对象中随机选择2个值。 -sampleSize({ a: 1, b: 2, c: 3, d: 4 }, 2); -// 返回值:[2, 4](实际结果可能不同) -``` - -`null` 或 `undefined` 作为空数组处理。 - -```typescript -import { sampleSize } from 'es-toolkit/compat'; - -sampleSize(null, 2); -// 返回值:[] - -sampleSize(undefined, 2); -// 返回值:[] -``` - -#### 参数 - -- `collection` (`Record | Record | T | null | undefined`):要采样的数组或对象。 -- `size` (`number`,可选):要选择的元素数量。默认值为 `1`。 - -#### 返回值 - -(`T[]`):返回由随机选择的元素组成的新数组。 diff --git a/docs/zh_hans/reference/compat/array/shuffle.md b/docs/zh_hans/reference/compat/array/shuffle.md deleted file mode 100644 index 4f98e6774..000000000 --- a/docs/zh_hans/reference/compat/array/shuffle.md +++ /dev/null @@ -1,60 +0,0 @@ -# shuffle(Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `shuffle` - -此 `shuffle` 函数为了与 Lodash 兼容而包含额外的处理,运行缓慢。 - -请使用更快、更现代的 `es-toolkit` 的 [shuffle](../../array/shuffle.md)。 - -::: - -随机打乱数组或对象的元素并返回新数组。 - -```typescript -const result = shuffle(collection); -``` - -## 用法 - -### `shuffle(collection)` - -使用 Fisher-Yates 算法随机打乱数组或对象的元素并返回新数组。不会修改原数组。 - -```typescript -import { shuffle } from 'es-toolkit/compat'; - -// 打乱数字数组 -const numbers = [1, 2, 3, 4, 5]; -const shuffled1 = shuffle(numbers); -// 返回值:例如 [3, 1, 5, 2, 4](每次顺序不同) - -// 打乱字符串数组 -const fruits = ['apple', 'banana', 'cherry', 'date']; -const shuffled2 = shuffle(fruits); -// 返回值:例如 ['cherry', 'apple', 'date', 'banana'] - -// 打乱对象的值 -const obj = { a: 1, b: 2, c: 3, d: 4 }; -const shuffled3 = shuffle(obj); -// 返回值:例如 [3, 1, 4, 2](对象值被随机打乱) -``` - -`null` 或 `undefined` 作为空数组处理。 - -```typescript -import { shuffle } from 'es-toolkit/compat'; - -shuffle(null); -// 返回值:[] - -shuffle(undefined); -// 返回值:[] -``` - -#### 参数 - -- `collection` (`ArrayLike | T | null | undefined`):要打乱的数组或对象。 - -#### 返回值 - -(`T[]`):返回元素被随机打乱的新数组。 diff --git a/docs/zh_hans/reference/compat/array/tail.md b/docs/zh_hans/reference/compat/array/tail.md deleted file mode 100644 index 9823126d3..000000000 --- a/docs/zh_hans/reference/compat/array/tail.md +++ /dev/null @@ -1,58 +0,0 @@ -# tail (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [tail](../../array/tail.md) - -这个 `tail` 函数由于处理 `null` 或 `undefined` 等原因运行较慢。 - -请使用更快且现代的 `es-toolkit` 的 [tail](../../array/tail.md) 代替。 - -::: - -返回数组中除第一个元素外的所有元素。 - -```typescript -const result = tail(array); -``` - -## 用法 - -### `tail(array)` - -当您想要创建一个包含输入数组中除第一个元素外所有元素的新数组时,使用 `tail`。如果输入数组为空或只有一个元素,则返回空数组。 - -```typescript -import { tail } from 'es-toolkit/compat'; - -// 从数字数组中删除第一个元素。 -tail([1, 2, 3]); -// Returns: [2, 3] - -// 从字符串数组中删除第一个元素。 -tail(['a', 'b', 'c']); -// Returns: ['b', 'c'] - -// 只有一个元素的数组。 -tail([1]); -// Returns: [] - -// 空数组。 -tail([]); -// Returns: [] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { tail } from 'es-toolkit/compat'; - -tail(null); // [] -tail(undefined); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要删除第一个元素的数组。 - -#### 返回值 - -(`T[]`): 返回包含除第一个元素外的所有元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/take.md b/docs/zh_hans/reference/compat/array/take.md deleted file mode 100644 index d6c103a4e..000000000 --- a/docs/zh_hans/reference/compat/array/take.md +++ /dev/null @@ -1,56 +0,0 @@ -# take (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [take](../../array/take.md) - -这个 `take` 函数由于包含与 Lodash 兼容的额外处理而运行较慢。 - -请使用更快且现代的 `es-toolkit` 的 [take](../../array/take.md) 代替。 - -::: - -从数组开头获取指定数量的元素并创建一个新数组。 - -```typescript -const result = take([1, 2, 3, 4, 5], 3); -// result 变为 [1, 2, 3]。 -``` - -## 用法 - -### `take(array, count)` - -从数组开头获取指定数量的元素并返回一个新数组。如果 `count` 大于数组长度,则返回整个数组。 - -```typescript -import { take } from 'es-toolkit/compat'; - -// 基本用法 -const numbers = [1, 2, 3, 4, 5]; -const result1 = take(numbers, 3); -// Returns: [1, 2, 3] - -// 请求的数量大于数组长度 -const result2 = take(numbers, 10); -// Returns: [1, 2, 3, 4, 5] (整个数组) - -// 请求 0 个元素 -const result3 = take(numbers, 0); -// Returns: [] - -// 处理空数组 -const result4 = take([], 3); -// Returns: [] - -// 处理负数 -const result5 = take(numbers, -1); -// Returns: [] -``` - -#### 参数 - -- `array` (`T[]`): 要获取元素的数组。 -- `count` (`number`): 要获取的元素数量。默认值为 1。 - -#### 返回值 - -(`T[]`): 包含从开头获取的指定数量元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/takeRight.md b/docs/zh_hans/reference/compat/array/takeRight.md deleted file mode 100644 index 0eaebf027..000000000 --- a/docs/zh_hans/reference/compat/array/takeRight.md +++ /dev/null @@ -1,63 +0,0 @@ -# takeRight (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [takeRight](../../array/takeRight.md) - -这个 `takeRight` 函数由于处理 `null` 或 `undefined` 等原因运行较慢。 - -请使用更快且现代的 `es-toolkit` 的 [takeRight](../../array/takeRight.md) 代替。 - -::: - -从数组末尾获取指定数量的元素。 - -```typescript -const result = takeRight(array, count); -``` - -## 用法 - -### `takeRight(array, count)` - -当您想要从数组末尾获取指定数量的元素来创建新数组时,使用 `takeRight`。如果请求的数量大于数组长度,则返回整个数组。 - -```typescript -import { takeRight } from 'es-toolkit/compat'; - -// 从数字数组中获取末尾的 2 个元素。 -takeRight([1, 2, 3, 4, 5], 2); -// Returns: [4, 5] - -// 从字符串数组中获取末尾的 3 个元素。 -takeRight(['a', 'b', 'c'], 2); -// Returns: ['b', 'c'] - -// 当请求的数量大于数组长度时 -takeRight([1, 2, 3], 5); -// Returns: [1, 2, 3] - -// 请求 0 个元素 -takeRight([1, 2, 3], 0); -// Returns: [] - -// 请求负数 -takeRight([1, 2, 3], -1); -// Returns: [] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { takeRight } from 'es-toolkit/compat'; - -takeRight(null, 2); // [] -takeRight(undefined, 2); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要获取元素的数组。 -- `count` (`number`, 可选): 要获取的元素数量。默认值为 `1`。 - -#### 返回值 - -(`T[]`): 返回包含从末尾获取的指定数量元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/takeRightWhile.md b/docs/zh_hans/reference/compat/array/takeRightWhile.md deleted file mode 100644 index 899993de0..000000000 --- a/docs/zh_hans/reference/compat/array/takeRightWhile.md +++ /dev/null @@ -1,71 +0,0 @@ -# takeRightWhile (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [takeRightWhile](../../array/takeRightWhile.md) - -这个 `takeRightWhile` 函数由于处理 `null` 或 `undefined` 等原因运行较慢。 - -请使用更快且现代的 `es-toolkit` 的 [takeRightWhile](../../array/takeRightWhile.md) 代替。 - -::: - -在条件满足时从数组末尾获取元素。 - -```typescript -const result = takeRightWhile(array, predicate); -``` - -## 用法 - -### `takeRightWhile(array, predicate)` - -当您想要从数组末尾开始在条件满足时获取元素来创建新数组时,使用 `takeRightWhile`。当条件评估为 false 时停止。 - -```typescript -import { takeRightWhile } from 'es-toolkit/compat'; - -// 使用函数条件 -const numbers = [1, 2, 3, 4, 5]; -takeRightWhile(numbers, x => x > 3); -// Returns: [4, 5] - -// 使用对象属性条件 -const users = [ - { user: 'barney', active: true }, - { user: 'fred', active: false }, - { user: 'pebbles', active: false }, -]; - -takeRightWhile(users, o => !o.active); -// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] - -// 使用部分对象进行条件匹配 -takeRightWhile(users, { active: false }); -// Returns: [{ user: 'pebbles', active: false }] - -// 使用属性-值数组进行条件匹配 -takeRightWhile(users, ['active', false]); -// Returns: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }] - -// 使用属性名检查真值 -const items = [{ active: false }, { active: true }, { active: true }]; -takeRightWhile(items, 'active'); -// Returns: [{ active: true }, { active: true }] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { takeRightWhile } from 'es-toolkit/compat'; - -takeRightWhile(null, x => x > 0); // [] -takeRightWhile(undefined, x => x > 0); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要处理的数组。 -- `predicate` (`ListIteratee`, 可选): 对每个元素执行的条件。可以是函数、部分对象、属性-值数组或属性名。默认值为恒等函数。 - -#### 返回值 - -(`T[]`): 返回在条件满足时从数组末尾获取的元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/takeWhile.md b/docs/zh_hans/reference/compat/array/takeWhile.md deleted file mode 100644 index 739a5896d..000000000 --- a/docs/zh_hans/reference/compat/array/takeWhile.md +++ /dev/null @@ -1,71 +0,0 @@ -# takeWhile (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [takeWhile](../../array/takeWhile.md) - -这个 `takeWhile` 函数由于处理 `null` 或 `undefined` 等原因运行较慢。 - -请使用更快且现代的 `es-toolkit` 的 [takeWhile](../../array/takeWhile.md) 代替。 - -::: - -在条件满足时从数组开头获取元素。 - -```typescript -const result = takeWhile(array, predicate); -``` - -## 用法 - -### `takeWhile(array, predicate)` - -当您想要从数组开头开始在条件满足时获取元素来创建新数组时,使用 `takeWhile`。当条件评估为 false 时停止。 - -```typescript -import { takeWhile } from 'es-toolkit/compat'; - -// 使用函数条件 -const numbers = [1, 2, 3, 4, 5]; -takeWhile(numbers, x => x < 3); -// Returns: [1, 2] - -// 使用对象属性条件 -const users = [ - { user: 'barney', active: false }, - { user: 'fred', active: false }, - { user: 'pebbles', active: true }, -]; - -takeWhile(users, o => !o.active); -// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] - -// 使用部分对象进行条件匹配 -takeWhile(users, { active: false }); -// Returns: [{ user: 'barney', active: false }] - -// 使用属性-值数组进行条件匹配 -takeWhile(users, ['active', false]); -// Returns: [{ user: 'barney', active: false }, { user: 'fred', active: false }] - -// 使用属性名检查真值 -const items = [{ active: true }, { active: true }, { active: false }]; -takeWhile(items, 'active'); -// Returns: [{ active: true }, { active: true }] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { takeWhile } from 'es-toolkit/compat'; - -takeWhile(null, x => x > 0); // [] -takeWhile(undefined, x => x > 0); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要处理的数组。 -- `predicate` (`ListIteratee`, 可选): 对每个元素执行的条件。可以是函数、部分对象、属性-值数组或属性名。默认值为恒等函数。 - -#### 返回值 - -(`T[]`): 返回在条件满足时从数组开头获取的元素的新数组。 diff --git a/docs/zh_hans/reference/compat/array/union.md b/docs/zh_hans/reference/compat/array/union.md deleted file mode 100644 index 2d06590b1..000000000 --- a/docs/zh_hans/reference/compat/array/union.md +++ /dev/null @@ -1,62 +0,0 @@ -# union (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [union](../../array/union.md) - -此 `union` 函数由于复杂的数组处理而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [union](../../array/union.md)。 - -::: - -从多个数组中创建一个仅包含唯一值的新数组。 - -```typescript -const result = union(...arrays); -``` - -## 用法 - -### `union(...arrays)` - -当您想要合并多个数组并去除重复项以创建仅包含唯一值的新数组时,请使用 `union`。保留每个值首次出现的顺序。 - -```typescript -import { union } from 'es-toolkit/compat'; - -// 合并数字数组 -union([2], [1, 2]); -// 返回: [2, 1] - -// 合并多个数组 -union([2], [1, 2], [2, 3]); -// 返回: [2, 1, 3] - -// 嵌套数组不会被展平 -union([1, 3, 2], [1, [5]], [2, [4]]); -// 返回: [1, 3, 2, [5], [4]] - -// 非数组值会被忽略 -union([0], 3, { '0': 1 }, null, [2, 1]); -// 返回: [0, 2, 1] - -// 类数组对象也会被处理 -union([0], { 0: 'a', length: 1 }, [2, 1]); -// 返回: [0, 'a', 2, 1] -``` - -`null` 或 `undefined` 会被忽略。 - -```typescript -import { union } from 'es-toolkit/compat'; - -union([1, 2], null, undefined, [3, 4]); -// 返回: [1, 2, 3, 4] -``` - -#### 参数 - -- `...arrays` (`Array | null | undefined>`): 要合并的数组。非数组值会被忽略。 - -#### 返回值 - -(`T[]`): 返回一个包含所有数组唯一值的新数组。 diff --git a/docs/zh_hans/reference/compat/array/unionBy.md b/docs/zh_hans/reference/compat/array/unionBy.md deleted file mode 100644 index 19c85a56c..000000000 --- a/docs/zh_hans/reference/compat/array/unionBy.md +++ /dev/null @@ -1,66 +0,0 @@ -# unionBy (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [unionBy](../../array/unionBy.md) - -此 `unionBy` 函数由于复杂的处理而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [unionBy](../../array/unionBy.md)。 - -::: - -合并多个数组并根据指定的标准仅保留唯一值。 - -```typescript -const result = unionBy(...arrays, iteratee); -``` - -## 用法 - -### `unionBy(...arrays, iteratee)` - -当您想要合并多个数组并根据给定的标准函数去除重复项以创建仅包含唯一值的新数组时,请使用 `unionBy`。保留每个值首次出现的顺序。 - -```typescript -import { unionBy } from 'es-toolkit/compat'; - -// 通过向下取整比较小数 -unionBy([2.1], [1.2, 2.3], Math.floor); -// 返回: [2.1, 1.2] - -// 通过对象属性比较 -unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); -// 返回: [{ x: 1 }, { x: 2 }] - -// 使用函数比较 -unionBy( - [{ id: 1, name: 'a' }], - [ - { id: 2, name: 'b' }, - { id: 1, name: 'c' }, - ], - item => item.id -); -// 返回: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }] - -// 使用部分对象比较 -unionBy([{ x: 1, y: 1 }], [{ x: 1, y: 2 }], { x: 1 }); -// 返回: [{ x: 1, y: 1 }] -``` - -`null` 或 `undefined` 数组会被忽略。 - -```typescript -import { unionBy } from 'es-toolkit/compat'; - -unionBy([1, 2], null, undefined, [3, 4], x => x); -// 返回: [1, 2, 3, 4] -``` - -#### 参数 - -- `...arrays` (`Array | null | undefined>`): 要合并的数组。 -- `iteratee` (`ValueIteratee`): 确定唯一性的标准。可以是函数、属性名称、部分对象或属性-值数组。 - -#### 返回值 - -(`T[]`): 返回一个根据指定标准去除重复项的唯一值新数组。 diff --git a/docs/zh_hans/reference/compat/array/unionWith.md b/docs/zh_hans/reference/compat/array/unionWith.md deleted file mode 100644 index c70482a40..000000000 --- a/docs/zh_hans/reference/compat/array/unionWith.md +++ /dev/null @@ -1,64 +0,0 @@ -# unionWith (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [unionWith](../../array/unionWith.md) - -此 `unionWith` 函数由于复杂的处理而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [unionWith](../../array/unionWith.md)。 - -::: - -合并多个数组并使用比较函数仅保留唯一值。 - -```typescript -const result = unionWith(...arrays, comparator); -``` - -## 用法 - -### `unionWith(...arrays, comparator)` - -当您想要合并多个数组并使用自定义比较函数去除重复项以创建仅包含唯一值的新数组时,请使用 `unionWith`。保留每个值首次出现的顺序。 - -```typescript -import { unionWith } from 'es-toolkit/compat'; - -// 使用自定义比较函数 -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, -]; -const others = [ - { x: 1, y: 1 }, - { x: 1, y: 2 }, -]; - -unionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); -// 返回: [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 1, y: 1 }] - -// 简单的相等性比较 -unionWith([1, 2], [2, 3], (a, b) => a === b); -// 返回: [1, 2, 3] - -// 按字符串长度比较 -unionWith(['ab', 'cd'], ['ef', 'gh', 'ab'], (a, b) => a.length === b.length); -// 返回: ['ab'] -``` - -`null` 或 `undefined` 数组会被忽略。 - -```typescript -import { unionWith } from 'es-toolkit/compat'; - -unionWith([1, 2], null, undefined, [3, 4], (a, b) => a === b); -// 返回: [1, 2, 3, 4] -``` - -#### 参数 - -- `...arrays` (`Array | null | undefined>`): 要合并的数组。 -- `comparator` (`(a: T, b: T) => boolean`): 确定两个值是否相等的比较函数。 - -#### 返回值 - -(`T[]`): 返回一个使用比较函数去除重复项的唯一值新数组。 diff --git a/docs/zh_hans/reference/compat/array/uniq.md b/docs/zh_hans/reference/compat/array/uniq.md deleted file mode 100644 index e7cdf3e94..000000000 --- a/docs/zh_hans/reference/compat/array/uniq.md +++ /dev/null @@ -1,51 +0,0 @@ -# uniq (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [uniq](../../array/uniq.md) - -此 `uniq` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [uniq](../../array/uniq.md)。 - -::: - -通过从数组中去除重复项来创建一个仅包含唯一元素的新数组。 - -```typescript -const result = uniq([1, 2, 2, 3, 3, 4]); -// result 是 [1, 2, 3, 4]。 -``` - -## 用法 - -### `uniq(array)` - -通过从数组中去除重复项返回一个仅包含唯一元素的新数组。仅保留每个元素的第一次出现,并保留顺序。 - -```typescript -import { uniq } from 'es-toolkit/compat'; - -// 从数字数组中去除重复项 -const numbers = [1, 2, 2, 3, 3, 4, 1]; -const result1 = uniq(numbers); -// 返回: [1, 2, 3, 4] - -// 从字符串数组中去除重复项 -const strings = ['a', 'b', 'b', 'c', 'a']; -const result2 = uniq(strings); -// 返回: ['a', 'b', 'c'] - -// 从对象数组中去除重复项(引用值比较) -const obj1 = { id: 1 }; -const obj2 = { id: 2 }; -const objects = [obj1, obj2, obj1]; -const result3 = uniq(objects); -// 返回: [{ id: 1 }, { id: 2 }] -``` - -#### 参数 - -- `array` (`T[]`): 要处理的数组。 - -#### 返回值 - -(`T[]`): 去除重复项的新数组。 diff --git a/docs/zh_hans/reference/compat/array/uniqBy.md b/docs/zh_hans/reference/compat/array/uniqBy.md deleted file mode 100644 index 074553961..000000000 --- a/docs/zh_hans/reference/compat/array/uniqBy.md +++ /dev/null @@ -1,55 +0,0 @@ -# uniqBy (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [uniqBy](../../array/uniqBy.md) - -此 `uniqBy` 函数由于处理 `null` 或 `undefined`、复杂参数类型处理等而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [uniqBy](../../array/uniqBy.md)。 - -::: - -根据转换函数返回的值去除重复项来创建一个唯一元素的新数组。 - -```typescript -const result = uniqBy(array, iteratee); -``` - -## 用法 - -### `uniqBy(array, iteratee)` - -对数组的每个元素应用转换函数,并仅保留转换结果相同的元素中的第一个元素。这在根据对象数组中的特定属性或数字数组中的特定计算结果去除重复项时很有用。 - -```typescript -import { uniqBy } from 'es-toolkit/compat'; - -// 在数字数组中通过 Math.floor 结果去除重复项 -uniqBy([2.1, 1.2, 2.3], Math.floor); -// 返回: [2.1, 1.2] - -// 在对象数组中通过属性去除重复项 -uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); -// 返回: [{ x: 1 }, { x: 2 }] - -// 使用函数去除重复项 -uniqBy([{ name: 'John' }, { name: 'Jane' }, { name: 'John' }], obj => obj.name); -// 返回: [{ name: 'John' }, { name: 'Jane' }] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { uniqBy } from 'es-toolkit/compat'; - -uniqBy(null, Math.floor); // [] -uniqBy(undefined, 'x'); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要去除重复项的数组。 -- `iteratee` (`ValueIteratee`): 要应用于每个元素的转换函数。可以是函数、属性名称、部分对象等。 - -#### 返回值 - -(`T[]`): 返回一个根据转换函数结果去除重复项的新数组。 diff --git a/docs/zh_hans/reference/compat/array/uniqWith.md b/docs/zh_hans/reference/compat/array/uniqWith.md deleted file mode 100644 index 835e39bf9..000000000 --- a/docs/zh_hans/reference/compat/array/uniqWith.md +++ /dev/null @@ -1,60 +0,0 @@ -# uniqWith (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [uniqWith](../../array/uniqWith.md) - -此 `uniqWith` 函数由于处理 `null` 或 `undefined`、复杂参数类型处理等而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [uniqWith](../../array/uniqWith.md)。 - -::: - -使用比较函数去除重复项来创建一个唯一元素的新数组。 - -```typescript -const result = uniqWith(array, comparator); -``` - -## 用法 - -### `uniqWith(array, comparator)` - -使用比较函数比较数组的每个元素来去除重复项。当比较函数返回 `true` 时,两个元素被视为相等,仅保留第一次出现的元素。如果未提供比较函数,默认使用浅相等性比较。 - -```typescript -import { uniqWith } from 'es-toolkit/compat'; - -// 不使用比较函数(浅相等性比较) -uniqWith([1, 2, 2, 3]); -// 返回: [1, 2, 3] - -// 使用自定义比较函数根据奇偶性标准去除重复项 -uniqWith([1, 2, 3, 4], (a, b) => a % 2 === b % 2); -// 返回: [1, 2] - -// 在对象数组中根据属性去除重复项 -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 1, y: 2 }, -]; -uniqWith(objects, (a, b) => a.x === b.x && a.y === b.y); -// 返回: [{ x: 1, y: 2 }, { x: 2, y: 1 }] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { uniqWith } from 'es-toolkit/compat'; - -uniqWith(null); // [] -uniqWith(undefined); // [] -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要去除重复项的数组。 -- `comparator` (`(a: T, b: T) => boolean`, 可选): 比较两个元素是否相等的函数。如果相等则返回 `true`。默认为浅相等性比较。 - -#### 返回值 - -(`T[]`): 返回一个根据比较函数结果去除重复项的新数组。 diff --git a/docs/zh_hans/reference/compat/array/unzip.md b/docs/zh_hans/reference/compat/array/unzip.md deleted file mode 100644 index 1a692fd83..000000000 --- a/docs/zh_hans/reference/compat/array/unzip.md +++ /dev/null @@ -1,68 +0,0 @@ -# unzip (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [unzip](../../array/unzip.md) - -此 `unzip` 函数由于处理 `null` 或 `undefined`、过滤非数组值等而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [unzip](../../array/unzip.md)。 - -::: - -将分组数组中相同位置的元素收集到新数组中。 - -```typescript -const result = unzip(array); -``` - -## 用法 - -### `unzip(array)` - -收集嵌套数组中相同索引处的元素并将它们作为新数组返回。执行与 `zip` 函数相反的操作。这在转置矩阵或重组结构化数据时很有用。 - -```typescript -import { unzip } from 'es-toolkit/compat'; - -// 解压混合字符串、布尔值和数字的数组 -const zipped = [ - ['a', true, 1], - ['b', false, 2], -]; -const result = unzip(zipped); -// 返回: [['a', 'b'], [true, false], [1, 2]] - -// 解压数字数组 -const numbers = [ - [1, 4], - [2, 5], - [3, 6], -]; -unzip(numbers); -// 返回: [[1, 2, 3], [4, 5, 6]] - -// 处理不同长度的数组 -const uneven = [ - ['a', 1], - ['b', 2, true], -]; -unzip(uneven); -// 返回: [['a', 'b'], [1, 2], [undefined, true]] -``` - -`null`、`undefined` 或空数组被视为空数组。 - -```typescript -import { unzip } from 'es-toolkit/compat'; - -unzip(null); // [] -unzip(undefined); // [] -unzip([]); // [] -``` - -#### 参数 - -- `array` (`T[][] | ArrayLike> | null | undefined`): 要解压的嵌套数组。每个内部数组中相同位置的元素被收集在一起。 - -#### 返回值 - -(`T[][]`): 返回一个将相同位置的元素收集在一起的新数组。 diff --git a/docs/zh_hans/reference/compat/array/unzipWith.md b/docs/zh_hans/reference/compat/array/unzipWith.md deleted file mode 100644 index 263a73daf..000000000 --- a/docs/zh_hans/reference/compat/array/unzipWith.md +++ /dev/null @@ -1,84 +0,0 @@ -# unzipWith (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `unzipWith` - -此 `unzipWith` 函数由于处理 `null` 或 `undefined`、`ArrayLike` 类型处理、支持各种条件函数形式等而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [unzipWith](../../array/unzipWith.md)。 - -::: - -收集分组数组中相同位置的元素并应用转换函数来创建一个新数组。 - -```typescript -const result = unzipWith(array, iteratee); -``` - -## 用法 - -### `unzipWith(array, iteratee)` - -收集嵌套数组中相同索引处的元素并应用转换函数。类似于 `unzip` 函数,但可以对每个组应用转换函数。如果未提供转换函数,则执行默认的 `unzip` 操作。 - -```typescript -import { unzipWith } from 'es-toolkit/compat'; - -// 将相同位置的元素相加 -unzipWith( - [ - [1, 10, 100], - [2, 20, 200], - ], - (a, b) => a + b -); -// 返回: [3, 30, 300] - -// 不使用转换函数(默认 unzip 操作) -unzipWith([ - [1, 4], - [2, 5], - [3, 6], -]); -// 返回: [[1, 2, 3], [4, 5, 6]] - -// 字符串连接 -unzipWith( - [ - ['a', 'x'], - ['b', 'y'], - ['c', 'z'], - ], - (a, b) => a + b -); -// 返回: ['abc', 'xyz'] - -// 查找最大值 -unzipWith( - [ - [1, 10], - [2, 20], - [3, 5], - ], - Math.max -); -// 返回: [3, 20] -``` - -`null`、`undefined` 或空数组被视为空数组。 - -```typescript -import { unzipWith } from 'es-toolkit/compat'; - -unzipWith(null, (a, b) => a + b); // [] -unzipWith(undefined, (a, b) => a + b); // [] -unzipWith([], (a, b) => a + b); // [] -``` - -#### 参数 - -- `array` (`ArrayLike> | null | undefined`): 要解压的嵌套数组。 -- `iteratee` (`(...values: T[]) => R`, 可选): 要应用于每组元素的转换函数。如果未提供,执行默认的 `unzip` 操作。 - -#### 返回值 - -(`R[]` 或 `T[][]`): 如果提供了转换函数则返回转换结果数组,否则返回解压数组。 diff --git a/docs/zh_hans/reference/compat/array/without.md b/docs/zh_hans/reference/compat/array/without.md deleted file mode 100644 index 0d9a6791f..000000000 --- a/docs/zh_hans/reference/compat/array/without.md +++ /dev/null @@ -1,49 +0,0 @@ -# without (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [without](../../array/without.md) - -此 `without` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [without](../../array/without.md)。 - -::: - -创建一个从数组中排除指定值的新数组。 - -```typescript -const result = without([1, 2, 3, 4, 5], 2, 4); -// result 是 [1, 3, 5]。 -``` - -## 用法 - -### `without(array, ...values)` - -返回一个从数组中删除指定值的新数组。原始数组不会被修改。 - -```typescript -import { without } from 'es-toolkit/compat'; - -// 从数字数组中删除多个值 -const numbers = [1, 2, 3, 4, 5, 2, 4]; -const result1 = without(numbers, 2, 4); -// 返回: [1, 3, 5] - -// 从字符串数组中删除值 -const fruits = ['apple', 'banana', 'cherry', 'banana']; -const result2 = without(fruits, 'banana'); -// 返回: ['apple', 'cherry'] - -// 处理空数组 -const result3 = without([], 1, 2, 3); -// 返回: [] -``` - -#### 参数 - -- `array` (`T[]`): 要处理的原始数组。 -- `...values` (`T[]`): 要删除的值。 - -#### 返回值 - -(`T[]`): 删除指定值的新数组。 diff --git a/docs/zh_hans/reference/compat/array/xor.md b/docs/zh_hans/reference/compat/array/xor.md deleted file mode 100644 index 64f7dd0ff..000000000 --- a/docs/zh_hans/reference/compat/array/xor.md +++ /dev/null @@ -1,61 +0,0 @@ -# xor (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [xor](../../array/xor.md) - -此 `xor` 函数由于处理 `null` 或 `undefined`、复杂的重复计算逻辑等而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [xor](../../array/xor.md)。 - -::: - -创建一个由恰好存在于多个数组中的一个数组中的元素组成的新数组。 - -```typescript -const result = xor(...arrays); -``` - -## 用法 - -### `xor(...arrays)` - -计算多个数组的对称差集。换句话说,返回恰好存在于给定数组中的一个数组中的元素。这在比较两个或多个数组时查找不重叠的唯一元素时很有用。 - -```typescript -import { xor } from 'es-toolkit/compat'; - -// 两个数组的对称差集 -xor([1, 2, 3, 4], [3, 4, 5, 6]); -// 返回: [1, 2, 5, 6] - -// 三个数组的对称差集 -xor([1, 2], [2, 3], [4, 5]); -// 返回: [1, 3, 4, 5] - -// 字符串数组 -xor(['a', 'b'], ['b', 'c']); -// 返回: ['a', 'c'] - -// 仅提供一个数组 -xor([1, 2, 3]); -// 返回: [1, 2, 3] -``` - -`null`、`undefined` 或空数组被忽略,只处理有效数组。 - -```typescript -import { xor } from 'es-toolkit/compat'; - -xor([1, 2], null, [2, 3]); -// 返回: [1, 3] - -xor([], [1, 2], [2, 3]); -// 返回: [1, 3] -``` - -#### 参数 - -- `...arrays` (`Array | null | undefined>`): 要计算对称差集的数组。`null` 或 `undefined` 被忽略。 - -#### 返回值 - -(`T[]`): 返回一个由恰好存在于数组中的一个数组中的元素组成的新数组。 diff --git a/docs/zh_hans/reference/compat/array/xorBy.md b/docs/zh_hans/reference/compat/array/xorBy.md deleted file mode 100644 index 8ce41cf3a..000000000 --- a/docs/zh_hans/reference/compat/array/xorBy.md +++ /dev/null @@ -1,63 +0,0 @@ -# xorBy (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [xorBy](../../array/xorBy.md) - -此 `xorBy` 函数由于处理 `null` 或 `undefined`、复杂的重复计算逻辑等而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [xorBy](../../array/xorBy.md)。 - -::: - -根据转换函数创建一个由恰好存在于多个数组中的一个数组中的元素组成的新数组。 - -```typescript -const result = xorBy(...arrays, iteratee); -``` - -## 用法 - -### `xorBy(...arrays, iteratee)` - -根据转换函数计算多个数组的对称差集。返回其转换结果恰好存在于数组中的一个数组中的元素。这在根据对象数组中的特定属性或数字数组中的特定计算结果进行比较时很有用。 - -```typescript -import { xorBy } from 'es-toolkit/compat'; - -// 通过 Math.floor 结果计算对称差集 -xorBy([2.1, 1.2], [4.3, 2.4], Math.floor); -// 返回: [1.2, 4.3] - -// 通过对象属性计算对称差集 -xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x'); -// 返回: [{ x: 2 }] - -// 使用函数计算对称差集 -const users1 = [{ name: 'John', age: 30 }]; -const users2 = [ - { name: 'Jane', age: 25 }, - { name: 'John', age: 30 }, -]; -xorBy(users1, users2, user => user.name); -// 返回: [{ name: 'Jane', age: 25 }] - -// 三个数组的对称差集 -xorBy([1.2, 2.3], [3.4, 4.5], [5.6, 6.7], Math.floor); -// 返回: [1.2, 2.3, 3.4, 4.5, 5.6, 6.7] -``` - -`null` 或 `undefined` 被忽略。 - -```typescript -import { xorBy } from 'es-toolkit/compat'; - -xorBy([2.1, 1.2], null, [4.3, 2.4], Math.floor); -// 返回: [1.2, 4.3] -``` - -#### 参数 - -- `...arrays` (`Array | null | undefined | ValueIteratee>`): 要计算对称差集的数组和末尾的转换函数。可以是函数、属性名称、部分对象等。 - -#### 返回值 - -(`T[]`): 返回一个根据转换函数结果由恰好存在于数组中的一个数组中的元素组成的新数组。 diff --git a/docs/zh_hans/reference/compat/array/xorWith.md b/docs/zh_hans/reference/compat/array/xorWith.md deleted file mode 100644 index f9a9f2a63..000000000 --- a/docs/zh_hans/reference/compat/array/xorWith.md +++ /dev/null @@ -1,66 +0,0 @@ -# xorWith (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [xorWith](../../array/xorWith.md) - -此 `xorWith` 函数由于处理 `null` 或 `undefined`、复杂的重复计算逻辑等而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [xorWith](../../array/xorWith.md)。 - -::: - -使用比较函数创建一个由恰好存在于多个数组中的一个数组中的元素组成的新数组。 - -```typescript -const result = xorWith(...arrays, comparator); -``` - -## 用法 - -### `xorWith(...arrays, comparator)` - -使用比较函数计算多个数组的对称差集。当比较函数返回 `true` 时,两个元素被视为相等,并返回恰好存在于数组中的一个数组中的元素。这在处理复杂对象或需要自定义比较逻辑时很有用。 - -```typescript -import { xorWith } from 'es-toolkit/compat'; - -// 简单数字比较 -xorWith([1, 2], [2, 3], (a, b) => a === b); -// 返回: [1, 3] - -// 比较对象属性 -const objects = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, -]; -const others = [ - { x: 1, y: 1 }, - { x: 1, y: 2 }, -]; -xorWith(objects, others, (a, b) => a.x === b.x && a.y === b.y); -// 返回: [{ x: 2, y: 1 }, { x: 1, y: 1 }] - -// 三个数组的对称差集 -xorWith([1], [2], [3], (a, b) => a === b); -// 返回: [1, 2, 3] - -// 按字符串长度比较 -xorWith(['hello'], ['world', 'hi'], (a, b) => a.length === b.length); -// 返回: ['hi'] -``` - -如果未提供比较函数,默认使用浅相等性比较。 - -```typescript -import { xorWith } from 'es-toolkit/compat'; - -xorWith([1, 2], [2, 3]); -// 返回: [1, 3] -``` - -#### 参数 - -- `...arrays` (`Array | null | undefined | ((a: T, b: T) => boolean)>`): 要计算对称差集的数组和末尾的比较函数。比较函数应在两个元素相等时返回 `true`。 - -#### 返回值 - -(`T[]`): 返回一个根据比较函数结果由恰好存在于数组中的一个数组中的元素组成的新数组。 diff --git a/docs/zh_hans/reference/compat/array/zip.md b/docs/zh_hans/reference/compat/array/zip.md deleted file mode 100644 index 0f47cfeb8..000000000 --- a/docs/zh_hans/reference/compat/array/zip.md +++ /dev/null @@ -1,48 +0,0 @@ -# zip (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [zip](../../array/zip.md) - -此 `zip` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [zip](../../array/zip.md)。 - -::: - -将多个数组组合成一个元组数组。 - -```typescript -const result = zip([1, 2], ['a', 'b']); -// result 是 [[1, 'a'], [2, 'b']]。 -``` - -## 用法 - -### `zip(...arrs)` - -接受多个数组并将每个索引处的元素分组为一个元组来创建一个新数组。如果输入数组的长度不同,结果数组的长度将与最长输入数组的长度相匹配,缺失的元素用 `undefined` 填充。 - -```typescript -import { zip } from 'es-toolkit/compat'; - -const arr1 = [1, 2, 3]; -const arr2 = ['a', 'b', 'c']; -const result = zip(arr1, arr2); -// 返回: [[1, 'a'], [2, 'b'], [3, 'c']] - -// 不同长度的数组 -const arr3 = [true, false]; -const result2 = zip(arr1, arr2, arr3); -// 返回: [[1, 'a', true], [2, 'b', false], [3, 'c', undefined]] - -// 包含空数组 -zip([1, 2], [], ['a', 'b']); -// 返回: [[1, undefined, 'a'], [2, undefined, 'b']] -``` - -#### 参数 - -- `...arrs` (`any[][]`): 要组合的数组。 - -#### 返回值 - -(`any[][]`): 包含输入数组每个索引元素的元组的新数组。 diff --git a/docs/zh_hans/reference/compat/array/zipObject.md b/docs/zh_hans/reference/compat/array/zipObject.md deleted file mode 100644 index 9cb6eb5cd..000000000 --- a/docs/zh_hans/reference/compat/array/zipObject.md +++ /dev/null @@ -1,50 +0,0 @@ -# zipObject (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [zipObject](../../array/zipObject.md) - -此 `zipObject` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [zipObject](../../array/zipObject.md)。 - -::: - -使用两个数组创建一个对象。第一个数组用作属性名称,第二个数组用作相应的值。 - -```typescript -const result = zipObject(keys, values); -``` - -## 用法 - -### `zipObject(keys, values)` - -当您想要从键数组和值数组创建单个对象时,请使用 `zipObject`。它使用第一个数组的元素作为属性名称,第二个数组的元素作为其相应的值。这在处理 API 响应或转换数据时特别有用。 - -```typescript -import { zipObject } from 'es-toolkit/compat'; - -// 基本用法 -const keys = ['a', 'b', 'c']; -const values = [1, 2, 3]; -const result = zipObject(keys, values); -// 返回: { a: 1, b: 2, c: 3 } - -// 不同长度的数组 -const keys2 = ['x', 'y', 'z']; -const values2 = [10, 20]; -const result2 = zipObject(keys2, values2); -// 返回: { x: 10, y: 20, z: undefined } - -// 提供空数组 -const result3 = zipObject([], []); -// 返回: {} -``` - -#### 参数 - -- `keys` (`PropertyKey[]`): 用作属性名称的数组。 -- `values` (`T[]`): 用作属性值的数组。 - -#### 返回值 - -(`Record`): 创建的对象。 diff --git a/docs/zh_hans/reference/compat/array/zipWith.md b/docs/zh_hans/reference/compat/array/zipWith.md deleted file mode 100644 index 492699e04..000000000 --- a/docs/zh_hans/reference/compat/array/zipWith.md +++ /dev/null @@ -1,47 +0,0 @@ -# zipWith (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [zipWith](../../array/zipWith.md) - -此 `zipWith` 函数由于为 Lodash 兼容性进行额外处理而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [zipWith](../../array/zipWith.md)。 - -::: - -使用组合函数将多个数组的元素组合成一个新数组。 - -```typescript -const result = zipWith([1, 2], [3, 4], (a, b) => a + b); -// result 是 [4, 6]。 -``` - -## 用法 - -### `zipWith(...arrs, iteratee)` - -接受多个数组并使用提供的函数组合每个索引处的元素来创建一个新数组。如果数组的长度不同,它将处理到最长数组的长度,对于缺失的值传递 `undefined`。 - -```typescript -import { zipWith } from 'es-toolkit/compat'; - -// 将两个数组的元素相加 -const result1 = zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b); -// 返回: [5, 7, 9] - -// 组合三个数组的元素 -const result2 = zipWith([1, 2], [3, 4], [5, 6], (a, b, c) => a + b + c); -// 返回: [9, 12] - -// 不同长度的数组 -const result3 = zipWith([1, 2, 3], [4, 5], (a, b) => (a || 0) + (b || 0)); -// 返回: [5, 7, 3] -``` - -#### 参数 - -- `...arrs` (`any[][]`): 要组合的数组。 -- `iteratee` (`Function`): 组合每个索引处元素的函数。 - -#### 返回值 - -(`any[]`): 应用组合函数的结果组成的新数组。 diff --git a/docs/zh_hans/reference/compat/function/after.md b/docs/zh_hans/reference/compat/function/after.md deleted file mode 100644 index 5849b113f..000000000 --- a/docs/zh_hans/reference/compat/function/after.md +++ /dev/null @@ -1,75 +0,0 @@ -# after (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [`after`](../../function/after.md) - -由于复杂的类型验证和整数转换处理,此 `after` 函数运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [after](../../function/after.md)。 - -::: - -创建一个只在被调用指定次数后才执行的函数。 - -```typescript -const restrictedFunction = after(n, func); -``` - -## 用法 - -### `after(n, func)` - -当您想限制函数仅在被调用特定次数后才执行时,请使用 `after`。它在多个异步操作完成后执行回调,或在初始化阶段后激活函数时非常有用。 - -```typescript -import { after } from 'es-toolkit/compat'; - -// 基本用法 -const logAfterThree = after(3, () => { - console.log('从第3次调用开始执行!'); -}); - -logAfterThree(); // 不执行 -logAfterThree(); // 不执行 -logAfterThree(); // 输出 "从第3次调用开始执行!" -logAfterThree(); // 输出 "从第3次调用开始执行!" (继续执行) -``` - -您还可以使用它在所有异步操作完成后执行特定回调。 - -```typescript -import { after } from 'es-toolkit/compat'; - -const tasks = ['task1', 'task2', 'task3']; -const allTasksComplete = after(tasks.length, () => { - console.log('所有任务已完成!'); -}); - -// 每个任务完成时调用 -tasks.forEach(task => { - performAsyncTask(task, () => { - console.log(`${task} 完成`); - allTasksComplete(); // 第3次调用时输出 "所有任务已完成!" - }); -}); -``` - -当传递0或负数时,从第一次调用开始立即执行。 - -```typescript -import { after } from 'es-toolkit/compat'; - -const immediate = after(0, () => console.log('立即执行')); -immediate(); // "立即执行" - -const negative = after(-1, () => console.log('立即执行')); -negative(); // "立即执行" -``` - -#### 参数 - -- `n` (`number`): 函数执行前所需的调用次数。 -- `func` (`TFunc`): 要限制的函数。 - -#### 返回值 - -(`TFunc`): 返回一个新的受限函数,从第 n 次调用开始执行原始函数。 diff --git a/docs/zh_hans/reference/compat/function/ary.md b/docs/zh_hans/reference/compat/function/ary.md deleted file mode 100644 index c3f16a48d..000000000 --- a/docs/zh_hans/reference/compat/function/ary.md +++ /dev/null @@ -1,90 +0,0 @@ -# ary (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [`ary`](../../function/ary.md) - -由于复杂的参数验证,此 `ary` 函数运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [ary](../../function/ary.md)。 - -::: - -创建一个限制可接收参数数量的函数。 - -```typescript -const cappedFunction = ary(func, n); -``` - -## 用法 - -### `ary(func, n)` - -当您想限制函数接收的参数数量时,请使用 `ary`。它在安全地使用接收太多参数的函数或在回调函数中忽略不必要的参数时非常有用。 - -```typescript -import { ary } from 'es-toolkit/compat'; - -// 基本用法 -function greet(name, age, city) { - return `你好, ${name}! ${age}岁, 来自${city}。`; -} - -const limitedGreet = ary(greet, 2); -console.log(limitedGreet('张三', 30, '北京', '额外参数')); -// "你好, 张三! 30岁, 来自undefined。" -// 第3个参数之后被忽略 -``` - -与数组方法一起使用时,可以防止不必要的参数传递给回调函数。 - -```typescript -import { ary } from 'es-toolkit/compat'; - -// parseInt接受第二个参数(基数),但map的回调传递3个参数 -const numbers = ['1', '2', '3', '4', '5']; - -// 错误用法 - parseInt将索引作为基数接收 -console.log(numbers.map(parseInt)); // [1, NaN, NaN, NaN, NaN] - -// 使用ary只传递第一个参数 -console.log(numbers.map(ary(parseInt, 1))); // [1, 2, 3, 4, 5] -``` - -可以限制函数只接收所需数量的参数。 - -```typescript -import { ary } from 'es-toolkit/compat'; - -function sum(...args) { - return args.reduce((total, num) => total + num, 0); -} - -const sum0 = ary(sum, 0); -const sum1 = ary(sum, 1); -const sum2 = ary(sum, 2); -const sum3 = ary(sum, 3); - -console.log(sum0(1, 2, 3, 4, 5)); // 0 (无参数) -console.log(sum1(1, 2, 3, 4, 5)); // 1 (仅第一个参数) -console.log(sum2(1, 2, 3, 4, 5)); // 3 (仅前两个参数) -console.log(sum3(1, 2, 3, 4, 5)); // 6 (仅前三个参数) -``` - -当传递负数或 `NaN` 时,会被视为0,所有参数都被忽略。 - -```typescript -import { ary } from 'es-toolkit/compat'; - -const func = (a, b, c) => [a, b, c]; - -console.log(ary(func, -1)(1, 2, 3)); // [] (负数视为0) -console.log(ary(func, NaN)(1, 2, 3)); // [] (NaN视为0) -``` - -#### 参数 - -- `func` (`Function`): 要限制参数数量的函数。 -- `n` (`number`, 可选): 允许的最大参数数量。如果省略,则使用函数的 `length` 属性。 - -#### 返回值 - -(`Function`): 返回一个最多接受 `n` 个参数的新函数。 diff --git a/docs/zh_hans/reference/compat/function/attempt.md b/docs/zh_hans/reference/compat/function/attempt.md deleted file mode 100644 index 3a1fe9f16..000000000 --- a/docs/zh_hans/reference/compat/function/attempt.md +++ /dev/null @@ -1,66 +0,0 @@ -# attempt (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [`attempt`](../../util/attempt.md) 函数或 try-catch 块 - -此 `attempt` 函数可能会让人困惑,因为它不区分地返回错误和返回值。 - -请改用更直接和清晰的 [`attempt`](../../util/attempt.md) 函数或 try-catch 块。 - -::: - -执行函数并在发生错误时返回错误对象的函数。 - -```typescript -const result = attempt(func, ...args); -``` - -## 用法 - -### `attempt(func, ...args)` - -当您想安全地执行函数时使用 `attempt`。在执行可能抛出错误的函数时,它很有用,可以防止程序崩溃并将错误作为返回值处理。 - -```typescript -import { attempt } from 'es-toolkit/compat'; - -// 基本用法 - 成功的情况 -const result = attempt((x, y) => x + y, 2, 3); -console.log(result); // 5 - -// 错误情况 -const errorResult = attempt(() => { - throw new Error('出错了'); -}); -console.log(errorResult); // Error: 出错了 -``` - -以下是与使用 try-catch 块的区别。 - -```typescript -// 使用 attempt -import { attempt } from 'es-toolkit/compat'; - -const result = attempt(riskyFunction, arg1, arg2); -if (result instanceof Error) { - console.log('发生错误:', result.message); -} else { - console.log('结果:', result); -} - -// 使用 try-catch (更直接) -try { - const result = riskyFunction(arg1, arg2); - console.log('结果:', result); -} catch (error) { - console.log('发生错误:', error.message); -} -``` - -#### 参数 - -- `func` (`Function`): 要执行的函数。 -- `args` (`...any[]`): 要传递给函数的参数。 - -#### 返回值 - -(`ReturnType | Error`): 如果函数成功则返回返回值,如果发生错误则返回 Error 对象。 diff --git a/docs/zh_hans/reference/compat/function/before.md b/docs/zh_hans/reference/compat/function/before.md deleted file mode 100644 index 0c7460bbd..000000000 --- a/docs/zh_hans/reference/compat/function/before.md +++ /dev/null @@ -1,186 +0,0 @@ -# before (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [`before`](../../function/before.md) - -由于复杂的类型验证和整数转换处理,这个 `before` 函数的运行速度较慢。 - -请使用更快、更现代的 `es-toolkit` 的 [before](../../function/before.md)。 - -::: - -创建一个函数,该函数在指定次数内执行原始函数,之后返回最后一次的结果。 - -```typescript -const limitedFunction = before(n, func); -``` - -## 用法 - -### `before(n, func)` - -当您想要限制函数只执行到特定次数时,请使用 `before`。这对于限制函数调用次数或只在初始设置阶段执行函数时非常有用。 - -```typescript -import { before } from 'es-toolkit/compat'; - -// 基本用法 -let count = 0; -const beforeThree = before(3, () => ++count); - -console.log(beforeThree()); // 1 (第一次调用) -console.log(beforeThree()); // 2 (第二次调用) -console.log(beforeThree()); // 2 (从第三次调用开始返回最后结果) -console.log(beforeThree()); // 2 (继续返回最后结果) -``` - -使用闭包的替代方案: - -```typescript -// 使用 before -const beforeThree = before(3, myFunction); - -// 使用闭包(更简单更快) -function createBefore(limit, callback) { - let callCount = 0; - let lastResult; - - return function (...args) { - if (callCount < limit - 1) { - lastResult = callback.apply(this, args); - callCount++; - } - return lastResult; - }; -} - -const beforeThreeAlternative = createBefore(3, myFunction); -``` - -用作初始化函数: - -```typescript -import { before } from 'es-toolkit/compat'; - -class Database { - constructor() { - this.isInitialized = false; - - // 初始化只执行一次 - this.initialize = before(2, () => { - console.log('正在初始化数据库...'); - this.setupConnection(); - this.isInitialized = true; - return '初始化完成'; - }); - } - - setupConnection() { - // 实际连接设置逻辑 - } - - query(sql) { - const initResult = this.initialize(); - console.log(initResult); // 第一次调用: "初始化完成",之后:相同结果 - - // 查询执行逻辑 - return `执行查询: ${sql}`; - } -} - -const db = new Database(); -db.query('SELECT * FROM users'); // 执行初始化 -db.query('SELECT * FROM products'); // 不执行初始化 -``` - -限制 API 调用: - -```typescript -import { before } from 'es-toolkit/compat'; - -// 最多允许 5 次 API 调用 -const limitedApiCall = before(6, endpoint => { - console.log(`API 调用: ${endpoint}`); - return fetch(endpoint).then(res => res.json()); -}); - -// 前 5 次执行实际的 API 调用 -limitedApiCall('/api/data1'); // 实际调用 -limitedApiCall('/api/data2'); // 实际调用 -limitedApiCall('/api/data3'); // 实际调用 -limitedApiCall('/api/data4'); // 实际调用 -limitedApiCall('/api/data5'); // 实际调用 -limitedApiCall('/api/data6'); // 返回最后结果(不进行 API 调用) -``` - -限制事件监听器: - -```typescript -import { before } from 'es-toolkit/compat'; - -// 最多处理 3 次点击事件 -const limitedClickHandler = before(4, event => { - console.log('处理点击:', event.target.id); - return `处理完成: ${Date.now()}`; -}); - -document.getElementById('button').addEventListener('click', limitedClickHandler); -// 只处理前 3 次点击,之后返回最后结果 -``` - -处理参数和返回值: - -```typescript -import { before } from 'es-toolkit/compat'; - -const limitedCalculator = before(3, (operation, a, b) => { - const result = operation === 'add' ? a + b : a - b; - console.log(`计算: ${a} ${operation} ${b} = ${result}`); - return result; -}); - -console.log(limitedCalculator('add', 5, 3)); // "计算: 5 add 3 = 8",返回: 8 -console.log(limitedCalculator('subtract', 10, 4)); // "计算: 10 subtract 4 = 6",返回: 6 -console.log(limitedCalculator('multiply', 7, 2)); // 不计算,返回: 6(最后结果) -``` - -传递 0 或 1 会使函数不执行: - -```typescript -import { before } from 'es-toolkit/compat'; - -const neverCalled = before(0, () => { - console.log('此函数不会执行'); - return '结果'; -}); - -const onceOnly = before(1, () => { - console.log('此函数也不会执行'); - return '结果'; -}); - -console.log(neverCalled()); // undefined -console.log(onceOnly()); // undefined -``` - -资源清理优化: - -```typescript -import { before } from 'es-toolkit/compat'; - -// 函数引用会自动清理以防止内存泄漏 -const limitedProcessor = before(2, data => { - // 复杂的数据处理 - return processComplexData(data); -}); - -// 第 2 次调用后,原始函数引用被移除(垃圾回收) -``` - -#### 参数 - -- `n` (`number`): 函数执行的最大次数。执行到 n-1 次,从第 n 次调用开始返回最后结果。 -- `func` (`Function`): 要限制的函数。 - -#### 返回值 - -(`Function`): 返回一个新函数,该函数在指定次数内执行原始函数,之后返回最后一次的结果。 diff --git a/docs/zh_hans/reference/compat/function/curry.md b/docs/zh_hans/reference/compat/function/curry.md deleted file mode 100644 index ecd149c71..000000000 --- a/docs/zh_hans/reference/compat/function/curry.md +++ /dev/null @@ -1,222 +0,0 @@ -# curry (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `curry` 或手动闭包 -此 `curry` 函数由于复杂的占位符处理、参数个数验证和参数组合逻辑而运行缓慢。 - -如果不需要占位符,请改用更快的 `es-toolkit` 的 [`curry`](../../function/curry.md) 或简单闭包。 -::: - -对函数进行柯里化,使其可以一次接受一个参数或一次接受多个参数。 - -```typescript -const curriedFunction = curry(func, arity); -``` - -## 用法 - -### `curry(func, arity)` - -当您想要对函数进行柯里化以便更容易地进行部分应用时,使用 `curry`。它对于逐步提供参数或使用占位符稍后在特定位置提供参数非常有用。 - -```typescript -import { curry } from 'es-toolkit/compat'; - -// 基本用法 -function add(a, b, c) { - return a + b + c; -} - -const curriedAdd = curry(add); - -// 可以用各种方式调用 -console.log(curriedAdd(1)(2)(3)); // 6 -console.log(curriedAdd(1, 2)(3)); // 6 -console.log(curriedAdd(1)(2, 3)); // 6 -console.log(curriedAdd(1, 2, 3)); // 6 -``` - -与主库 curry 的比较: - -```typescript -// compat 版本 (灵活,但较慢) -import { curry } from 'es-toolkit/compat'; -const curriedCompat = curry(add); -curriedCompat(1, 2)(3); // 支持 -curriedCompat(1)(curry.placeholder, 3)(2); // 支持占位符 - -// 主库版本 (更快,但只能一次一个) -import { curry } from 'es-toolkit'; -const curriedMain = curry(add); -curriedMain(1)(2)(3); // 支持 -curriedMain(1, 2)(3); // 不支持 -``` - -使用占位符功能: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function greet(greeting, name, punctuation) { - return `${greeting}, ${name}${punctuation}`; -} - -const curriedGreet = curry(greet); - -// 使用占位符跳过中间参数 -const greetWithExclamation = curriedGreet(curry.placeholder, curry.placeholder, '!'); -console.log(greetWithExclamation('Hello', 'John')); // "Hello, John!" - -const sayHello = curriedGreet('Hello'); -console.log(sayHello(curry.placeholder, '~')('Jane')); // "Hello, Jane~" -``` - -在函数式编程中使用: - -```typescript -import { curry } from 'es-toolkit/compat'; - -// 创建映射函数 -const map = curry((fn, array) => array.map(fn)); -const filter = curry((predicate, array) => array.filter(predicate)); - -const numbers = [1, 2, 3, 4, 5]; - -// 创建可重用的函数 -const double = x => x * 2; -const isEven = x => x % 2 === 0; - -const mapDouble = map(double); -const filterEven = filter(isEven); - -console.log(mapDouble(numbers)); // [2, 4, 6, 8, 10] -console.log(filterEven(numbers)); // [2, 4] - -// 函数组合 -const processNumbers = nums => mapDouble(filterEven(nums)); -console.log(processNumbers(numbers)); // [4, 8] -``` - -配置 API 客户端: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function apiRequest(method, baseUrl, endpoint, options) { - return fetch(`${baseUrl}${endpoint}`, { - method, - ...options, - }); -} - -const curriedApiRequest = curry(apiRequest); - -// 使用默认设置创建专用函数 -const apiGet = curriedApiRequest('GET', 'https://api.example.com'); -const apiPost = curriedApiRequest('POST', 'https://api.example.com'); - -// 包含认证标头 -const authenticatedPost = apiPost(curry.placeholder, { - headers: { Authorization: 'Bearer token123' }, -}); - -// 使用 -apiGet('/users'); // GET https://api.example.com/users -authenticatedPost('/users'); // POST with auth headers -``` - -数学运算函数: - -```typescript -import { curry } from 'es-toolkit/compat'; - -const calculate = curry((operation, a, b) => { - switch (operation) { - case '+': - return a + b; - case '-': - return a - b; - case '*': - return a * b; - case '/': - return a / b; - default: - throw new Error('不支持的操作'); - } -}); - -// 专用操作函数 -const add = calculate('+'); -const subtract = calculate('-'); -const multiply = calculate('*'); - -console.log(add(5, 3)); // 8 -console.log(subtract(10)(4)); // 6 -console.log(multiply(3, 4)); // 12 - -// 使用占位符固定第二个操作数 -const addFive = calculate('+', curry.placeholder, 5); -console.log(addFive(10)); // 15 -``` - -指定参数个数: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function variableArgsFunction(a, b, c, ...rest) { - return [a, b, c, rest]; -} - -// 将参数个数限制为 3 -const curriedFixed = curry(variableArgsFunction, 3); - -console.log(curriedFixed(1)(2)(3)); // [1, 2, 3, []] -console.log(curriedFixed(1, 2)(3)); // [1, 2, 3, []] - -// 不指定参数个数使用 (默认值: function.length) -const curriedDefault = curry(variableArgsFunction); // arity = 3 -``` - -简单的柯里化替代方案: - -```typescript -// 使用 curry -const curriedAdd = curry((a, b, c) => a + b + c); - -// 手动闭包 (更快) -const manualCurry = a => b => c => a + b + c; - -// 两者产生相同的结果 -console.log(curriedAdd(1)(2)(3)); // 6 -console.log(manualCurry(1)(2)(3)); // 6 -``` - -也支持构造函数: - -```typescript -import { curry } from 'es-toolkit/compat'; - -function Person(name, age, city) { - this.name = name; - this.age = age; - this.city = city; -} - -const CurriedPerson = curry(Person); -const SeoulPerson = CurriedPerson(curry.placeholder, curry.placeholder, 'Seoul'); - -const person1 = new SeoulPerson('John', 30); -const person2 = new SeoulPerson('Jane', 25); - -console.log(person1.city); // "Seoul" -console.log(person2.city); // "Seoul" -``` - -#### 参数 - -- `func` (`Function`): 要柯里化的函数。 -- `arity` (`number`, 可选): 函数的参数个数。如果省略,使用 `func.length`。 - -#### 返回值 - -(`Function & { placeholder: symbol }`): 返回柯里化的函数。`placeholder` 属性允许您控制参数位置。 diff --git a/docs/zh_hans/reference/compat/function/curryRight.md b/docs/zh_hans/reference/compat/function/curryRight.md deleted file mode 100644 index 2071854ef..000000000 --- a/docs/zh_hans/reference/compat/function/curryRight.md +++ /dev/null @@ -1,242 +0,0 @@ -# curryRight (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [`curryRight`](../../function/curryRight.md) 或手动闭包 - -由于复杂的占位符处理、参数数量验证和参数组合逻辑,这个 `curryRight` 函数运行较慢。 - -如果不需要占位符,请使用更快的 `es-toolkit` 的 [`curryRight`](../../function/curryRight.md) 或简单的闭包。 - -::: - -从右到左柯里化一个函数,创建一个可以一次接受一个或多个参数的函数,从最后一个参数开始。 - -```typescript -const curriedFunction = curryRight(func, arity); -``` - -## 用法 - -### `curryRight(func, arity)` - -当您想要从右到左柯里化一个函数并从最后一个参数开始部分应用参数时,请使用 `curryRight`。与常规的 `curry` 不同,它首先从最后一个参数开始处理。 - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 基本用法 -function subtract(a, b, c) { - return a - b - c; -} - -const curriedSubtract = curryRight(subtract); - -// 从右开始柯里化(从最后一个参数开始) -console.log(curriedSubtract(1)(2)(5)); // 5 - 2 - 1 = 2 -console.log(curriedSubtract(1, 2)(5)); // 5 - 2 - 1 = 2 -console.log(curriedSubtract(1)(2, 5)); // 2 - 5 - 1 = -4 -console.log(curriedSubtract(1, 2, 5)); // 1 - 2 - 5 = -6 -``` - -`curry` 和 `curryRight` 的区别: - -```typescript -import { curry, curryRight } from 'es-toolkit/compat'; - -function divide(a, b, c) { - return a / b / c; -} - -// 常规 curry(从左开始) -const leftCurried = curry(divide); -console.log(leftCurried(12)(3)(2)); // ((12 / 3) / 2) = 2 - -// curryRight(从右开始) -const rightCurried = curryRight(divide); -console.log(rightCurried(2)(3)(12)); // ((12 / 3) / 2) = 2 -// 最后提供的 12 成为第一个参数(a) -``` - -与主库的比较: - -```typescript -// compat 版本(灵活,但较慢) -import { curryRight } from 'es-toolkit/compat'; -const curriedCompat = curryRight(subtract); -curriedCompat(1, 2)(3); // 支持 -curriedCompat(1)(curryRight.placeholder, 3)(2); // 支持占位符 - -// 主库版本(更快,但一次只能一个) -import { curryRight } from 'es-toolkit'; -const curriedMain = curryRight(subtract); -curriedMain(1)(2)(3); // 支持 -curriedMain(1, 2)(3); // 不支持 -``` - -使用占位符功能: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function formatMessage(name, action, time) { - return `${name} 在 ${time} ${action}了`; -} - -const curriedFormat = curryRight(formatMessage); - -// 使用占位符跳过特定位置 -const todayAction = curriedFormat('今天'); -const todayLoginAction = todayAction(curryRight.placeholder, '登录'); - -console.log(todayLoginAction('张三')); -// "张三 在 今天 登录了" - -// 首先固定时间 -const morningFormat = curriedFormat('早上9点'); -console.log(morningFormat('评论', '李四')); -// "李四 在 早上9点 评论了" -``` - -在数组处理中使用: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 从数组末尾获取特定数量的项 -function takeFromEnd(array, count, separator = ', ') { - return array.slice(-count).join(separator); -} - -const curriedTake = curryRight(takeFromEnd); - -// 创建用逗号分隔的函数 -const takeWithComma = curriedTake(', '); - -// 获取最后3项 -const takeLast3 = takeWithComma(3); - -const fruits = ['苹果', '香蕉', '橙子', '葡萄', '猕猴桃']; -console.log(takeLast3(fruits)); // "橙子, 葡萄, 猕猴桃" - -// 使用不同的分隔符 -const takeWithDash = curriedTake(' - '); -console.log(takeWithDash(2, fruits)); // "葡萄 - 猕猴桃" -``` - -在函数组合中使用: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 日志输出函数 -function logWithPrefix(message, level, timestamp) { - return `[${timestamp}] ${level}: ${message}`; -} - -const curriedLog = curryRight(logWithPrefix); - -// 用当前时间固定 -const currentTimeLog = curriedLog(new Date().toISOString()); - -// 按级别创建记录器 -const errorLog = currentTimeLog('ERROR'); -const infoLog = currentTimeLog('INFO'); -const debugLog = currentTimeLog('DEBUG'); - -// 使用 -console.log(errorLog('数据库连接失败')); -console.log(infoLog('服务器已启动')); -console.log(debugLog('正在处理用户请求')); -``` - -函数式编程管道: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -// 数据转换函数 -const mapWith = curryRight((array, fn) => array.map(fn)); -const filterWith = curryRight((array, predicate) => array.filter(predicate)); -const reduceWith = curryRight((array, reducer, initial) => array.reduce(reducer, initial)); - -const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - -// 定义转换函数 -const double = x => x * 2; -const isEven = x => x % 2 === 0; -const sum = (acc, val) => acc + val; - -// 组合管道(右侧优先) -const processNumbers = nums => { - return reduceWith(filterWith(mapWith(nums, double), isEven), sum, 0); -}; - -console.log(processNumbers(numbers)); // 所有数字翻倍,过滤偶数,然后求和 -``` - -API 请求构建器: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function makeRequest(url, method, headers, body) { - return fetch(url, { method, headers, body }); -} - -const curriedRequest = curryRight(makeRequest); - -// 首先设置 body -const withJsonBody = curriedRequest(JSON.stringify({ data: 'test' })); - -// 添加 headers -const withHeaders = withJsonBody({ - 'Content-Type': 'application/json', - Authorization: 'Bearer token123', -}); - -// 设置 POST 方法 -const postRequest = withHeaders('POST'); - -// 最终使用 -postRequest('/api/data') - .then(response => response.json()) - .then(data => console.log(data)); -``` - -手动柯里化替代方案: - -```typescript -// 使用 curryRight -const curriedSubtract = curryRight((a, b, c) => a - b - c); - -// 手动闭包(更快,从右开始) -const manualCurryRight = c => b => a => a - b - c; - -// 两者结果相同 -console.log(curriedSubtract(1)(2)(5)); // 2 -console.log(manualCurryRight(1)(2)(5)); // 2 -``` - -指定参数数量: - -```typescript -import { curryRight } from 'es-toolkit/compat'; - -function variableArgsFunction(a, b, c, ...rest) { - return { a, b, c, rest }; -} - -// 将参数数量限制为3(忽略 rest) -const curriedFixed = curryRight(variableArgsFunction, 3); - -// 从右侧按 c, b, a 的顺序接收 -console.log(curriedFixed(3)(2)(1)); // { a: 1, b: 2, c: 3, rest: [] } -``` - -#### 参数 - -- `func` (`Function`): 要从右到左柯里化的函数。 -- `arity` (`number`, 可选): 函数的参数数量。如果省略,则使用 `func.length`。 - -#### 返回值 - -(`Function & { placeholder: symbol }`): 返回从右到左柯里化的函数。可以使用 `placeholder` 属性控制参数位置。 diff --git a/docs/zh_hans/reference/compat/function/debounce.md b/docs/zh_hans/reference/compat/function/debounce.md deleted file mode 100644 index 876c99278..000000000 --- a/docs/zh_hans/reference/compat/function/debounce.md +++ /dev/null @@ -1,264 +0,0 @@ -# debounce (Lodash 兼容) - -::: warning 请使用 `es-toolkit` 的 [`debounce`](../../function/debounce.md) - -这个 `debounce` 函数由于复杂的 `maxWait` 处理和 Lodash 兼容的选项结构而存在开销。 - -请使用更快、更现代的 `es-toolkit` 的 [`debounce`](../../function/debounce.md)。 - -::: - -创建一个防抖函数,延迟调用提供的函数,直到自上次调用后经过 `wait` 毫秒。 - -```typescript -const debouncedFunction = debounce(func, wait, options); -``` - -## 用法 - -### `debounce(func, wait, options)` - -当您想要延迟函数调用时,使用 `debounce`。它对于防止搜索输入、滚动事件、按钮点击等中的过度调用很有用。 - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// 基本用法 -const searchFunction = debounce(query => { - console.log('搜索:', query); -}, 300); - -// 仅当在 300ms 内未再次调用时执行 -searchFunction('React'); // 不执行 -searchFunction('Vue'); // 不执行 -searchFunction('Angular'); // 300ms 后输出 "搜索: Angular" -``` - -与主库 debounce 的比较: - -```typescript -// compat 版本(Lodash 兼容,包含 maxWait 等额外选项) -import { debounce } from 'es-toolkit/compat'; -const debouncedCompat = debounce(func, 300, { - leading: true, - trailing: false, - maxWait: 1000 -}); - -// 主库版本(更快、更简单) -import { debounce } from 'es-toolkit'; -const debouncedMain = debounce(func, 300, { - edges: ['leading'] // 使用 edges 而不是 leading/trailing -}); -``` - -leading 和 trailing 选项: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const func = () => console.log('执行了'); - -// leading: true - 首次调用时立即执行 -const leadingDebounce = debounce(func, 1000, { leading: true }); -leadingDebounce(); // 立即输出 "执行了" -leadingDebounce(); // 等待 1 秒 -// 1 秒后没有额外执行 - -// trailing: true(默认) - 最后一次调用后延迟执行 -const trailingDebounce = debounce(func, 1000, { trailing: true }); -trailingDebounce(); // 等待 1 秒 -trailingDebounce(); // 等待 1 秒(取消之前的计时器) -// 1 秒后输出 "执行了" - -// 两者都为 true - 在开始和结束时执行 -const bothDebounce = debounce(func, 1000, { - leading: true, - trailing: true, -}); -bothDebounce(); // 立即输出 "执行了" -bothDebounce(); // 等待 1 秒 -// 1 秒后输出 "执行了"(trailing) -``` - -maxWait 选项: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// 保证至少每 2 秒执行一次 -const debouncedWithMaxWait = debounce(() => console.log('已保存'), 500, { maxWait: 2000 }); - -// 即使快速连续调用,也会每 2 秒执行一次 -setInterval(() => { - debouncedWithMaxWait(); -}, 100); // 每 100ms 调用一次,但每 2 秒输出 "已保存" -``` - -实际搜索示例: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -class SearchComponent { - constructor() { - this.searchInput = document.getElementById('search'); - - // 将用户输入防抖 300ms - this.debouncedSearch = debounce(this.performSearch.bind(this), 300, { - leading: false, // 输入开始时不立即搜索 - trailing: true, // 输入停止后搜索 - }); - - this.searchInput.addEventListener('input', e => { - this.debouncedSearch(e.target.value); - }); - } - - performSearch(query) { - if (query.length < 2) return; - - console.log('API 调用:', query); - // fetch(`/api/search?q=${query}`)... - } -} -``` - -滚动事件优化: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -// 将滚动事件防抖 100ms,但至少每 500ms 执行一次 -const optimizedScrollHandler = debounce( - () => { - const scrollTop = window.pageYOffset; - console.log('滚动位置:', scrollTop); - - // 头部隐藏/显示逻辑 - if (scrollTop > 100) { - document.header.classList.add('hidden'); - } else { - document.header.classList.remove('hidden'); - } - }, - 100, - { maxWait: 500 } -); - -window.addEventListener('scroll', optimizedScrollHandler); -``` - -API 调用限制: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -class AutoSave { - constructor() { - // 防抖 500ms,至少每 5 秒保存一次 - this.debouncedSave = debounce(this.saveToServer.bind(this), 500, { maxWait: 5000 }); - } - - onTextChange(content) { - this.pendingContent = content; - this.debouncedSave(); - } - - saveToServer() { - if (!this.pendingContent) return; - - console.log('保存到服务器:', this.pendingContent); - // fetch('/api/save', { ... }) - - this.pendingContent = null; - } -} -``` - -cancel 和 flush 方法: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const debouncedFunc = debounce(() => { - console.log('执行了'); -}, 1000); - -debouncedFunc(); // 等待 1 秒 - -// 取消待执行的调用 -debouncedFunc.cancel(); - -// 或立即执行 -debouncedFunc(); // 开始等待 1 秒 -debouncedFunc.flush(); // 立即输出 "执行了" 并取消计时器 -``` - -防止重复按钮点击: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const handleSubmit = debounce( - async formData => { - console.log('正在提交表单...'); - try { - const response = await fetch('/api/submit', { - method: 'POST', - body: formData, - }); - console.log('提交完成'); - } catch (error) { - console.error('提交失败:', error); - } - }, - 1000, - { leading: true, trailing: false } // 仅处理第一次点击 -); - -document.getElementById('submit-btn').addEventListener('click', e => { - const formData = new FormData(e.target.form); - handleSubmit(formData); -}); -``` - -调整大小事件处理: - -```typescript -import { debounce } from 'es-toolkit/compat'; - -const handleResize = debounce( - () => { - const width = window.innerWidth; - const height = window.innerHeight; - - console.log('窗口已调整大小:', { width, height }); - - // 重新计算布局 - recalculateLayout(); - }, - 250, - { leading: false, trailing: true } -); - -window.addEventListener('resize', handleResize); - -// 页面卸载时清理 -window.addEventListener('beforeunload', () => { - handleResize.cancel(); -}); -``` - -#### 参数 - -- `func` (`Function`): 要防抖的函数。 -- `wait` (`number`, 可选): 要延迟的毫秒数。默认为 `0`。 -- `options` (`DebounceSettings`, 可选): 选项对象。 - - `leading` (`boolean`): 如果为 `true`,则在延迟开始时执行函数。默认为 `false`。 - - `trailing` (`boolean`): 如果为 `true`,则在延迟结束时执行函数。默认为 `true`。 - - `maxWait` (`number`): 函数执行可以延迟的最大时间。默认为 `Infinity`。 - -#### 返回值 - -(`DebouncedFunc`): 返回防抖函数。它包含 `cancel()` 和 `flush()` 方法。 diff --git a/docs/zh_hans/reference/compat/function/flow.md b/docs/zh_hans/reference/compat/function/flow.md deleted file mode 100644 index 8007a2c53..000000000 --- a/docs/zh_hans/reference/compat/function/flow.md +++ /dev/null @@ -1,87 +0,0 @@ -# flow (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `flow` -这个 `flow` 函数为了 Lodash 兼容性添加了数组扁平化处理,变得复杂了。 - -建议使用更快、更现代的 `es-toolkit` 的 [flow](../../function/flow.md)。 -::: - -创建一个新函数,从左到右依次执行给定的函数。 - -```typescript -const combinedFunc = flow(...functions); -``` - -## 用法 - -### `flow(...functions)` - -当您想要创建一个从左到右依次执行多个函数的组合函数时,请使用 `flow`。它对于创建数据转换管道很有用。 - -```typescript -import { flow } from 'es-toolkit/compat'; - -// 基本用法 -function add(x, y) { - return x + y; -} - -function square(n) { - return n * n; -} - -function double(n) { - return n * 2; -} - -// 从左到右执行: double(square(add(x, y))) -const calculate = flow(add, square, double); -console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 - -// 以数组形式传递函数 -const calculate2 = flow([add, square], double); -console.log(calculate2(2, 3)); // 50 - -// 现代替代方案(推荐) -const modernCalculate = (x, y) => double(square(add(x, y))); -console.log(modernCalculate(1, 2)); // 18 - -// 使用管道操作符(未来的 JavaScript) -const pipeCalculate = (x, y) => add(x, y) |> square |> double; - -// 或使用链式模式 -class Calculator { - constructor(value) { - this.value = value; - } - - add(n) { - this.value += n; - return this; - } - - square() { - this.value *= this.value; - return this; - } - - double() { - this.value *= 2; - return this; - } - - valueOf() { - return this.value; - } -} - -const chainedResult = new Calculator(3).square().double().valueOf(); // 18 -``` - -#### 参数 - -- `...functions` (`Array`): 要从左到右执行的函数。也可以以数组形式传递。 - -#### 返回值 - -(`Function`): 返回一个新的组合函数,从左到右依次执行所有函数。 diff --git a/docs/zh_hans/reference/compat/function/flowRight.md b/docs/zh_hans/reference/compat/function/flowRight.md deleted file mode 100644 index d4c9fe024..000000000 --- a/docs/zh_hans/reference/compat/function/flowRight.md +++ /dev/null @@ -1,65 +0,0 @@ -# flowRight (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `flowRight` -这个 `flowRight` 函数为了 Lodash 兼容性添加了数组扁平化处理,变得复杂了。 - -建议使用更快、更现代的 `es-toolkit` 的 [flowRight](../../function/flowRight.md)。 -::: - -创建一个新函数,从右到左依次执行给定的函数。 - -```typescript -const combinedFunc = flowRight(...functions); -``` - -## 用法 - -### `flowRight(...functions)` - -当您想要创建一个从右到左依次执行多个函数的组合函数时,请使用 `flowRight`。它对于创建数据转换管道很有用。 - -```typescript -import { flowRight } from 'es-toolkit/compat'; - -// 基本用法 -function add(x, y) { - return x + y; -} - -function square(n) { - return n * n; -} - -function double(n) { - return n * 2; -} - -// 从右到左执行: double(square(add(x, y))) -const calculate = flowRight(double, square, add); -console.log(calculate(1, 2)); // double(square(add(1, 2))) = double(square(3)) = double(9) = 18 - -// 以数组形式传递函数 -const calculate2 = flowRight([double, square], add); -console.log(calculate2(2, 3)); // 50 - -// 现代替代方案(推荐) -const modernCalculate = (x, y) => double(square(add(x, y))); -console.log(modernCalculate(1, 2)); // 18 - -// 或使用函数链 -const chainedCalculate = (x, y) => [x, y] - .reduce((acc, val, idx) => idx === 0 ? val : acc + val) - .valueOf() - |> (n => n * n) - |> (n => n * 2); -``` - -通常以与 `flow` 相反的顺序工作。它的工作方式类似于函数组合,因此很直观。 - -#### 参数 - -- `...functions` (`Array`): 要从右到左执行的函数。也可以以数组形式传递。 - -#### 返回值 - -(`Function`): 返回一个新的组合函数,从右到左依次执行所有函数。 diff --git a/docs/zh_hans/reference/compat/function/identity.md b/docs/zh_hans/reference/compat/function/identity.md deleted file mode 100644 index e138cb1b0..000000000 --- a/docs/zh_hans/reference/compat/function/identity.md +++ /dev/null @@ -1,62 +0,0 @@ -# identity (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `identity` -这个 `identity` 函数在 `es-toolkit` 的主库中也有相同功能的函数。它只是简单地返回输入值。 - -建议使用更快、更现代的 `es-toolkit` 的 [identity](../../function/identity.md)。 -::: - -返回接收到的值。 - -```typescript -const result = identity(value); -``` - -## 用法 - -### `identity(value)` - -当您想要原样返回接收到的值时,请使用 `identity`。它主要用作默认值或占位符函数,在函数式编程中经常使用。 - -```typescript -import { identity } from 'es-toolkit/compat'; - -// 基本用法 -console.log(identity(5)); // 5 -console.log(identity('hello')); // 'hello' -console.log(identity({ key: 'value' })); // { key: 'value' } - -// 与数组的 map 一起使用(值复制) -const numbers = [1, 2, 3, 4, 5]; -const copied = numbers.map(identity); -console.log(copied); // [1, 2, 3, 4, 5] - -// 在过滤中用作默认值 -const values = [1, 0, '', 'hello', null, undefined, false, true]; -const filtered = values.filter(identity); // 只保留真值 -console.log(filtered); // [1, 'hello', true] - -// 用作默认转换函数 -function processData(data, transform = identity) { - return transform(data); -} - -console.log(processData('hello')); // 'hello' -console.log(processData('hello', x => x.toUpperCase())); // 'HELLO' -``` - -在大多数情况下,可以用更简单的箭头函数 `x => x` 替代: - -```typescript -// 使用箭头函数而不是 identity(推荐) -const copied = numbers.map(x => x); -const filtered = values.filter(x => x); -``` - -#### 参数 - -- `value` (`T`): 要返回的值。 - -#### 返回值 - -(`T`): 原样返回接收到的值。 diff --git a/docs/zh_hans/reference/compat/function/memoize.md b/docs/zh_hans/reference/compat/function/memoize.md deleted file mode 100644 index 9b4e6cdbf..000000000 --- a/docs/zh_hans/reference/compat/function/memoize.md +++ /dev/null @@ -1,66 +0,0 @@ -# memoize (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `memoize` -这个 `memoize` 函数由于 `resolver` 函数的 `null` 检查、`MapCache` 接口的复杂类型处理以及为了 Lodash 兼容性而产生的额外开销,导致运行缓慢。 - -建议使用更快、更现代的 `es-toolkit` 的 [memoize](../../function/memoize.md)。 -::: - -缓存函数结果,以在使用相同参数调用时提高性能。 - -```typescript -const memoizedFunc = memoize(func, resolver); -``` - -## 用法 - -### `memoize(func, resolver)` - -当您想要缓存函数结果以在使用相同参数调用时重用之前的结果时,请使用 `memoize`。它对于昂贵的计算或 API 调用很有用。 - -```typescript -import { memoize } from 'es-toolkit/compat'; - -// 基本用法 -function expensiveCalculation(n) { - console.log('计算中...', n); - return n * n; -} - -const memoizedCalc = memoize(expensiveCalculation); - -console.log(memoizedCalc(5)); // '计算中... 5', 25 -console.log(memoizedCalc(5)); // 25 (缓存的结果,不计算) -console.log(memoizedCalc(10)); // '计算中... 10', 100 - -// 使用自定义解析器 -function fetchUserData(userId, includeProfile) { - console.log('获取用户数据...', userId, includeProfile); - return { id: userId, profile: includeProfile ? '个人资料数据' : null }; -} - -// 生成考虑所有参数的缓存键 -const memoizedFetch = memoize(fetchUserData, (userId, includeProfile) => { - return `${userId}_${includeProfile}`; -}); - -memoizedFetch(1, true); // '获取用户数据... 1 true' -memoizedFetch(1, true); // 使用缓存的结果 -memoizedFetch(1, false); // '获取用户数据... 1 false' (不同的缓存键) - -// 访问和修改缓存 -console.log(memoizedCalc.cache.get(5)); // 25 -memoizedCalc.cache.set(7, 49); // 手动设置缓存 -console.log(memoizedCalc(7)); // 49 (使用缓存值,不计算) -``` - -在大多数情况下使用基本哈希映射,但根据需要也可以使用自定义缓存实现。 - -#### 参数 - -- `func` (`Function`): 要记忆化的函数。 -- `resolver` (`Function`, 可选): 确定缓存键的函数。如果未提供,使用第一个参数作为键。 - -#### 返回值 - -(`Function & { cache: MapCache }`): 返回记忆化的函数。返回的函数具有 `cache` 属性,可直接访问缓存。 diff --git a/docs/zh_hans/reference/compat/function/noop.md b/docs/zh_hans/reference/compat/function/noop.md deleted file mode 100644 index 4e0ec6f4d..000000000 --- a/docs/zh_hans/reference/compat/function/noop.md +++ /dev/null @@ -1,60 +0,0 @@ -# noop (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `noop` - -`es-toolkit` 也有相同行为的 [noop](../../function/noop.md) 函数。 - -::: - -什么都不做的空函数。 - -```typescript -noop(); -``` - -## 用法 - -### `noop(...args)` - -当您需要一个什么都不做的占位符函数时,使用 `noop`。它通常用作默认值或回调函数。 - -```typescript -import { noop } from 'es-toolkit/compat'; - -// 基本用法 -noop(); // 什么都不做 -noop(1, 2, 3); // 接受参数但什么都不做 - -// 用作默认回调 -function processData(data, callback = noop) { - // 处理数据 - console.log('处理数据中...', data); - - // 调用回调(如果未提供则为 noop) - callback(data); -} - -processData('测试'); // 即使未提供回调也能正常工作 - -// 现代替代方案(推荐) -function modernProcessData(data, callback = () => {}) { - console.log('处理数据中...', data); - callback(data); -} - -// 或使用可选回调 -function processDataOptional(data, callback) { - console.log('处理数据中...', data); - callback?.(data); // 仅在提供回调时调用 -} -``` - -在需要默认值或占位符的情况下很有用,但在现代 JavaScript 中,使用可选链(`?.`)或默认参数更常见。 - -#### 参数 - -- `...args` (`any[]`): 可以接受任何参数,但都会被忽略。 - -#### 返回值 - -(`void`): 不返回任何内容。 diff --git a/docs/zh_hans/reference/compat/function/once.md b/docs/zh_hans/reference/compat/function/once.md deleted file mode 100644 index 61248159f..000000000 --- a/docs/zh_hans/reference/compat/function/once.md +++ /dev/null @@ -1,56 +0,0 @@ -# once (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `once` - -这个 `once` 函数与 `es-toolkit` 主库的 [once](../../function/once.md) 函数具有相同的功能。 - -::: - -限制函数只能被调用一次。 - -```typescript -const limitedFunc = once(func); -``` - -## 用法 - -### `once(func)` - -当您想限制函数只能被调用一次时,使用 `once`。第一次调用后,结果会被缓存并返回相同的值。 - -```typescript -import { once } from 'es-toolkit/compat'; - -// 基本用法 -let count = 0; -const increment = once(() => { - count++; - console.log('计数器递增:', count); - return count; -}); - -increment(); // 输出 '计数器递增: 1',返回 1 -increment(); // 不输出任何内容,返回 1 -increment(); // 不输出任何内容,返回 1 - -// 实用示例 - 初始化函数 -const initialize = once(() => { - console.log('正在初始化应用程序...'); - // 昂贵的初始化操作 - return '初始化完成'; -}); - -// 即使多次调用,初始化也只执行一次 -initialize(); // 输出 '正在初始化应用程序...' -initialize(); // 不输出任何内容 -``` - -在创建昂贵的初始化操作或设置函数时很有用。例如,可以用于数据库连接、API 令牌初始化等。 - -#### 参数 - -- `func` (`Function`): 要限制为只调用一次的函数。 - -#### 返回值 - -(`Function`): 返回一个新函数,该函数只被调用一次。从第二次调用开始,返回第一次调用的结果。 diff --git a/docs/zh_hans/reference/compat/function/partial.md b/docs/zh_hans/reference/compat/function/partial.md deleted file mode 100644 index 178c5ef73..000000000 --- a/docs/zh_hans/reference/compat/function/partial.md +++ /dev/null @@ -1,59 +0,0 @@ -# partial (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `partial` - -这个 `partial` 函数由于许多重载和联合类型处理而效率低下。此外,在大多数情况下可以用更简单的箭头函数替代。 - -建议使用更快且更现代的 `es-toolkit` 的 [`partial`](../../function/partial.md)。 - -::: - -通过预填充参数来创建部分应用的函数。 - -```typescript -const partialFunc = partial(func, ...args); -``` - -## 用法 - -### `partial(func, ...args)` - -当您想通过预填充参数来创建部分应用的函数时,使用 `partial`。主要在参数顺序重要的函数中固定前面的参数时很有用。 - -```typescript -import { partial } from 'es-toolkit/compat'; - -// 基本用法 -function greet(greeting, name, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// 预设第一个参数 -const sayHello = partial(greet, 'Hello'); -sayHello('Alice', '!'); // 'Hello Alice!' - -// 预设多个参数 -const greetAlice = partial(greet, 'Hello', 'Alice'); -greetAlice('!'); // 'Hello Alice!' - -// 使用 placeholder 控制参数顺序 -const greetWithExclamation = partial(greet, partial.placeholder, 'Alice', '!'); -greetWithExclamation('Hi'); // 'Hi Alice!' -``` - -在大多数情况下可以用箭头函数替代: - -```typescript -// 使用箭头函数代替 partial(推荐) -const sayHello = (name, punctuation) => greet('Hello', name, punctuation); -const greetAlice = punctuation => greet('Hello', 'Alice', punctuation); -``` - -#### 参数 - -- `func` (`Function`): 要部分应用的函数。 -- `...args` (`any[]`): 要预填充的参数。使用 `partial.placeholder` 可以控制参数顺序。 - -#### 返回值 - -(`Function`): 返回一个预填充了参数的新函数。 diff --git a/docs/zh_hans/reference/compat/function/partialRight.md b/docs/zh_hans/reference/compat/function/partialRight.md deleted file mode 100644 index bbc7035f8..000000000 --- a/docs/zh_hans/reference/compat/function/partialRight.md +++ /dev/null @@ -1,59 +0,0 @@ -# partialRight (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 `partialRight` - -这个 `partialRight` 函数由于许多重载和联合类型处理而效率低下。此外,在大多数情况下可以用更简单的箭头函数替代。 - -建议使用更快且更现代的 `es-toolkit` 的 [`partialRight`](../../function/partialRight.md)。 - -::: - -通过从右侧预填充参数来创建部分应用的函数。 - -```typescript -const partialFunc = partialRight(func, ...args); -``` - -## 用法 - -### `partialRight(func, ...args)` - -当您想通过从右侧预填充参数来创建部分应用的函数时,使用 `partialRight`。主要在参数顺序重要的函数中固定最后的参数时很有用。 - -```typescript -import { partialRight } from 'es-toolkit/compat'; - -// 基本用法 -function greet(greeting, name, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// 预设最后一个参数 -const greetWithExclamation = partialRight(greet, '!'); -greetWithExclamation('Hello', 'Alice'); // 'Hello Alice!' - -// 预设多个参数 -const sayHiToAlice = partialRight(greet, 'Alice', '!'); -sayHiToAlice('Hi'); // 'Hi Alice!' - -// 使用 placeholder 控制参数顺序 -const greetAliceWithCustom = partialRight(greet, 'Alice', partialRight.placeholder); -greetAliceWithCustom('Hello', '?'); // 'Hello Alice?' -``` - -在大多数情况下可以用箭头函数替代: - -```typescript -// 使用箭头函数代替 partialRight(推荐) -const greetWithExclamation = (greeting, name) => greet(greeting, name, '!'); -const sayHiToAlice = greeting => greet(greeting, 'Alice', '!'); -``` - -#### 参数 - -- `func` (`Function`): 要部分应用的函数。 -- `...args` (`any[]`): 要预填充的参数。使用 `partialRight.placeholder` 可以控制参数顺序。 - -#### 返回值 - -(`Function`): 返回一个从右侧预填充了参数的新函数。 diff --git a/docs/zh_hans/reference/compat/function/rest.md b/docs/zh_hans/reference/compat/function/rest.md deleted file mode 100644 index 98e6978f2..000000000 --- a/docs/zh_hans/reference/compat/function/rest.md +++ /dev/null @@ -1,54 +0,0 @@ -# rest (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `rest` - -此 `rest` 函数由于额外的逻辑(如默认值处理和索引验证)可能会导致性能下降。 - -请改用更快、更现代的 `es-toolkit` 的 [rest](../../function/rest.md)。 - -::: - -创建一个函数,从指定索引开始将剩余参数分组到数组中。 - -```typescript -const restFunc = rest(func, start); -``` - -## 用法 - -### `rest(func, start)` - -当您想通过将指定索引开始的剩余参数分组到数组中来转换函数参数时,请使用 `rest`。它对于创建可变参数函数很有用。 - -```typescript -import { rest } from 'es-toolkit/compat'; - -// 基本用法 - 将最后的参数分组到数组中 -function logMessage(level, message, ...details) { - console.log(`[${level}] ${message}`, details); -} - -const restLogger = rest(logMessage, 2); -restLogger('ERROR', '发生错误', '详细信息 1', '详细信息 2'); -// 内部调用 logMessage('ERROR', '发生错误', [['详细信息 1', '详细信息 2']]) - -// 不同索引的示例 -function process(action, target, ...args) { - return { action, target, args }; -} - -const restProcess = rest(process, 1); -restProcess('update', 'user', 'name', 'John', 'age', 25); -// { action: 'update', target: ['user', 'name', 'John', 'age', 25], args: [] } -``` - -当您想将函数的最后参数作为数组接收时使用它。在现代 JavaScript 中,使用剩余参数语法(`...args`)更为常见。 - -#### 参数 - -- `func` (`Function`): 要转换的函数。 -- `start` (`number`, 可选): 开始将参数分组到数组中的索引。默认值为 `func.length - 1`。 - -#### 返回值 - -(`Function`): 返回一个新函数,从指定索引开始将剩余参数分组到数组中。 diff --git a/docs/zh_hans/reference/compat/function/throttle.md b/docs/zh_hans/reference/compat/function/throttle.md deleted file mode 100644 index a266c6a4c..000000000 --- a/docs/zh_hans/reference/compat/function/throttle.md +++ /dev/null @@ -1,52 +0,0 @@ -# throttle (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `throttle` - -此 `throttle` 函数为了 Lodash 兼容性在内部使用 debounce 函数,使其变得有些复杂。它还具有更复杂的默认值和选项处理。 - -请改用更快、更现代的 `es-toolkit` 的 [throttle](../../function/throttle.md)。 - -::: - -限制函数调用,使其在指定时间间隔内最多执行一次。 - -```typescript -const throttledFunc = throttle(func, wait, options); -``` - -## 用法 - -### `throttle(func, wait, options)` - -当您想限制函数调用在指定时间间隔内最多执行一次时,请使用 `throttle`。它对于限制事件处理程序或 API 调用的频率很有用。 - -```typescript -import { throttle } from 'es-toolkit/compat'; - -// 基本用法 - 每秒最多执行一次 -const throttledLog = throttle(() => { - console.log('事件发生!'); -}, 1000); - -// 使用选项的示例 -const throttledScroll = throttle(handleScroll, 100, { - leading: true, // 首次调用时立即执行 - trailing: false, // 最后一次调用后不执行 -}); - -window.addEventListener('scroll', throttledScroll); -``` - -在处理快速发生的事件(如滚动或调整大小事件)时,这对于性能至关重要。 - -#### 参数 - -- `func` (`Function`): 要节流的函数。 -- `wait` (`number`, 可选): 等待时间(毫秒)。默认值为 `0`。 -- `options` (`ThrottleSettings`, 可选): 节流选项。 - - `leading` (`boolean`): 是否在首次调用时执行。默认值为 `true`。 - - `trailing` (`boolean`): 是否在最后一次调用后执行。默认值为 `true`。 - -#### 返回值 - -(`DebouncedFunc`): 返回节流函数。您可以使用 `cancel()` 方法取消待处理的执行。 diff --git a/docs/zh_hans/reference/compat/function/unary.md b/docs/zh_hans/reference/compat/function/unary.md deleted file mode 100644 index b4c6614ae..000000000 --- a/docs/zh_hans/reference/compat/function/unary.md +++ /dev/null @@ -1,46 +0,0 @@ -# unary (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `ary` - -此 `unary` 函数是作为 `ary` 函数的特殊情况实现的。如果您需要更多控制,直接使用 `es-toolkit` 的 [ary](../../function/ary.md) 会更高效。 - -请改用更快、更现代的 `es-toolkit` 的 [ary](../../function/ary.md)。 - -::: - -限制函数最多接受一个参数。 - -```typescript -const limitedFunc = unary(func); -``` - -## 用法 - -### `unary(func)` - -当您想限制函数最多接受一个参数时,请使用 `unary`。传递的任何额外参数都将被忽略。 - -```typescript -import { unary } from 'es-toolkit/compat'; - -function greet(name, greeting, punctuation) { - return `${greeting} ${name}${punctuation}`; -} - -// 转换为只接受第一个参数的函数 -const greetOne = unary(greet); -greetOne('Alice', 'Hello', '!'); // 与 greet('Alice') 相同 - -// 与数组的 map 函数一起使用时很有用 -const numbers = ['1', '2', '3']; -numbers.map(parseInt); // [1, NaN, NaN] - 意外结果 -numbers.map(unary(parseInt)); // [1, 2, 3] - 正确结果 -``` - -#### 参数 - -- `func` (`(...args: any[]) => any`): 要限制参数的函数。 - -#### 返回值 - -(`(...args: any[]) => any`): 返回最多接受一个参数的新函数。 diff --git a/docs/zh_hans/reference/compat/math/clamp.md b/docs/zh_hans/reference/compat/math/clamp.md deleted file mode 100644 index 15b22b656..000000000 --- a/docs/zh_hans/reference/compat/math/clamp.md +++ /dev/null @@ -1,82 +0,0 @@ -# clamp (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [clamp](../../math/clamp.md) - -这个 `clamp` 函数由于 NaN 验证和处理会运行较慢。 - -请使用更快、更现代的 `es-toolkit` 的 [clamp](../../math/clamp.md)。 - -::: - -将数字限制在指定范围内。 - -```typescript -const clamped = clamp(number, lower, upper); -``` - -## 用法 - -### `clamp(number, lower, upper)` - -当您想要将数字限制在指定的最小值和最大值之间时,请使用 `clamp`。 - -```typescript -import { clamp } from 'es-toolkit/compat'; - -// 基本用法 -clamp(3, 2, 4); -// Returns: 3 (在范围内) - -clamp(0, 5, 10); -// Returns: 5 (限制为最小值) - -clamp(15, 5, 10); -// Returns: 10 (限制为最大值) - -// 处理负数 -clamp(-5, -10, -1); -// Returns: -5 - -clamp(-15, -10, -1); -// Returns: -10 (限制为最小值) -``` - -### `clamp(number, upper)` - -如果只提供一个参数,该值将用作最大值。 - -```typescript -import { clamp } from 'es-toolkit/compat'; - -// 只指定最大值 -clamp(5, 3); -// Returns: 3 (限制为最大值) - -clamp(2, 3); -// Returns: 2 (在范围内) - -clamp(1, 5); -// Returns: 1 -``` - -NaN 值被处理为 0。 - -```typescript -import { clamp } from 'es-toolkit/compat'; - -clamp(5, NaN, 10); -// Returns: 5 (NaN 被处理为 0,范围是 0~10) - -clamp(5, 2, NaN); -// Returns: 2 (NaN 被处理为 0,范围是 0~2) -``` - -#### 参数 - -- `number` (`number`): 要限制的数字。 -- `lower` (`number`): 最小值。如果只有第二个参数,则为最大值。 -- `upper` (`number`, 可选): 最大值。 - -#### 返回值 - -(`number`): 返回限制在指定范围内的数字。 diff --git a/docs/zh_hans/reference/compat/math/inRange.md b/docs/zh_hans/reference/compat/math/inRange.md deleted file mode 100644 index 0959e96dc..000000000 --- a/docs/zh_hans/reference/compat/math/inRange.md +++ /dev/null @@ -1,101 +0,0 @@ -# inRange (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [inRange](../../math/inRange.md) - -这个 `inRange` 函数由于复杂的类型转换和 null/undefined 处理会运行较慢。 - -请使用更快、更现代的 `es-toolkit` 的 [inRange](../../math/inRange.md)。 - -::: - -检查数字是否在指定范围内。 - -```typescript -const result = inRange(value, minimum, maximum); -``` - -## 用法 - -### `inRange(value, minimum, maximum?)` - -当您想要检查数字是否在特定范围内时,请使用 `inRange`。最小值包含在内,最大值不包含在内。 - -```typescript -import { inRange } from 'es-toolkit/compat'; - -// 基本用法 -inRange(3, 2, 4); -// Returns: true (2 ≤ 3 < 4) - -inRange(1, 2, 5); -// Returns: false (1 < 2) - -inRange(5, 2, 5); -// Returns: false (5 不包含在内) - -// 范围边界值 -inRange(2, 2, 4); -// Returns: true (最小值包含在内) - -inRange(4, 2, 4); -// Returns: false (最大值不包含在内) -``` - -### `inRange(value, maximum)` - -如果只提供两个参数,则处理为从 0 到 maximum 的范围。 - -```typescript -import { inRange } from 'es-toolkit/compat'; - -inRange(3, 5); -// Returns: true (0 ≤ 3 < 5) - -inRange(-1, 5); -// Returns: false (-1 < 0) - -inRange(0, 5); -// Returns: true (0 ≤ 0 < 5) - -inRange(5, 5); -// Returns: false (5 不包含在内) -``` - -如果最小值大于最大值,会自动交换。 - -```typescript -import { inRange } from 'es-toolkit/compat'; - -inRange(3, 5, 2); -// Returns: true (范围变为 2~5,2 ≤ 3 < 5) - -inRange(1, 5, 2); -// Returns: false (1 < 2) -``` - -无效值会被适当转换。 - -```typescript -import { inRange } from 'es-toolkit/compat'; - -// 字符串数字转换 -inRange(3, '2', '4'); -// Returns: true - -// falsy 值被处理为 0 -inRange(1, null, 5); -// Returns: true (null 被处理为 0,范围为 0~5) - -inRange(3, false, 5); -// Returns: true (false 被处理为 0) -``` - -#### 参数 - -- `value` (`number`): 要检查是否在范围内的数字。 -- `minimum` (`number`): 范围的最小值(包含)。如果没有 `maximum`,此值变为最大值。 -- `maximum` (`number`, 可选): 范围的最大值(不包含)。 - -#### 返回值 - -(`boolean`): 如果值在指定范围内返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/math/maxBy.md b/docs/zh_hans/reference/compat/math/maxBy.md deleted file mode 100644 index 45cb575a3..000000000 --- a/docs/zh_hans/reference/compat/math/maxBy.md +++ /dev/null @@ -1,114 +0,0 @@ -# maxBy (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [maxBy](../../array/maxBy.md) - -这个 `maxBy` 函数由于 iteratee 函数处理和类型转换会运行较慢。 - -请使用更快、更现代的 `es-toolkit` 的 [maxBy](../../array/maxBy.md)。 - -::: - -在符合条件的值中查找最大值元素。 - -```typescript -const maxItem = maxBy(array, iteratee); -``` - -## 用法 - -### `maxBy(array, iteratee)` - -在数组中查找函数计算值最大的元素。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -// 对象数组中特定属性最大的元素 -const people = [ - { name: '张三', age: 25 }, - { name: '李四', age: 30 }, - { name: '王五', age: 35 }, -]; - -maxBy(people, person => person.age); -// Returns: { name: '王五', age: 35 } - -// 也可以使用属性名 -maxBy(people, 'age'); -// Returns: { name: '王五', age: 35 } -``` - -用函数转换值来查找最大值。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -maxBy(items, x => x.a); -// Returns: { a: 3 } - -const numbers = [-1, -2, -3]; -maxBy(numbers, x => Math.abs(x)); -// Returns: -3 (绝对值最大的元素) -``` - -通过数组元素访问。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const arrays = [ - [1, 2], - [3, 4], - [0, 5], -]; -maxBy(arrays, 0); // 第一个元素最大的数组 -// Returns: [3, 4] - -maxBy(arrays, 1); // 第二个元素最大的数组 -// Returns: [0, 5] -``` - -查找对象特定属性和值匹配的情况。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -const users = [ - { name: '张三', age: 25, active: true }, - { name: '李四', age: 30, active: false }, - { name: '王五', age: 35, active: true }, -]; - -// active 为 true 的元素中的第一个 -maxBy(users, ['active', true]); -// Returns: { name: '张三', age: 25, active: true } - -// 用对象指定条件 -maxBy(users, { active: true }); -// Returns: { name: '张三', age: 25, active: true } -``` - -空数组返回 undefined。 - -```typescript -import { maxBy } from 'es-toolkit/compat'; - -maxBy([], x => x.a); -// Returns: undefined - -maxBy(null); -// Returns: undefined - -maxBy(undefined); -// Returns: undefined -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要搜索的数组。 -- `iteratee` (`ValueIteratee`, 可选): 应用于每个元素的函数、属性名或条件。 - -#### 返回值 - -(`T | undefined`): 返回符合条件的值最大的元素。如果是空数组则返回 `undefined`。 diff --git a/docs/zh_hans/reference/compat/math/mean.md b/docs/zh_hans/reference/compat/math/mean.md deleted file mode 100644 index 998ff88ae..000000000 --- a/docs/zh_hans/reference/compat/math/mean.md +++ /dev/null @@ -1,76 +0,0 @@ -# mean (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [mean](../../math/mean.md) - -这个 `mean` 函数由于类型转换和 null/undefined 处理会运行较慢。 - -请使用更快、更现代的 `es-toolkit` 的 [mean](../../math/mean.md)。 - -::: - -计算数组的平均值。 - -```typescript -const average = mean(array); -``` - -## 用法 - -### `mean(array)` - -计算数字数组的平均值。 - -```typescript -import { mean } from 'es-toolkit/compat'; - -// 数字数组 -mean([1, 2, 3, 4, 5]); -// Returns: 3 - -mean([10, 20, 30]); -// Returns: 20 - -mean([1.5, 2.5, 3.5]); -// Returns: 2.5 -``` - -空数组返回 NaN。 - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean([]); -// Returns: NaN - -mean(null); -// Returns: NaN - -mean(undefined); -// Returns: NaN -``` - -无效值会被视作 0 并计算。 - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean([1, undefined, 2, null, 3]); -// Returns: 1.2 (1 + 2 + 3) / 5 = 1.2 -``` - -字符串将会被拼接。 - -```typescript -import { mean } from 'es-toolkit/compat'; - -mean(['1', '2', '3']); -// Returns: 41 (123 / 3 = 41) -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 包含要计算平均值的数字数组。 - -#### 返回值 - -(`number`): 返回数组的平均值。如果是空数组则返回 `NaN`。 diff --git a/docs/zh_hans/reference/compat/math/meanBy.md b/docs/zh_hans/reference/compat/math/meanBy.md deleted file mode 100644 index 064938a67..000000000 --- a/docs/zh_hans/reference/compat/math/meanBy.md +++ /dev/null @@ -1,103 +0,0 @@ -# meanBy (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [meanBy](../../math/meanBy.md) - -这个 `meanBy` 函数由于 iteratee 函数处理和类型转换会运行较慢。 - -请使用更快、更现代的 `es-toolkit` 的 [meanBy](../../math/meanBy.md)。 - -::: - -计算符合条件的值的平均值。 - -```typescript -const average = meanBy(array, iteratee); -``` - -## 用法 - -### `meanBy(array, iteratee)` - -计算数组中每个元素应用函数后结果的平均值。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -// 对象数组中特定属性的平均值 -const people = [ - { name: '张三', age: 25 }, - { name: '李四', age: 30 }, - { name: '王五', age: 35 }, -]; - -meanBy(people, person => person.age); -// Returns: 30 - -// 也可以使用属性名 -meanBy(people, 'age'); -// Returns: 30 -``` - -用函数转换值来计算平均值。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const numbers = [1.5, 2.7, 3.2, 4.8]; -meanBy(numbers, x => Math.floor(x)); -// Returns: 2.5 (1 + 2 + 3 + 4) / 4 - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -meanBy(items, x => x.a); -// Returns: 2 -``` - -通过数组元素访问。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const arrays = [[2], [3], [1]]; -meanBy(arrays, 0); // 第一个元素的平均值 -// Returns: 2 -``` - -只计算对象特定属性和值匹配的情况。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -const users = [ - { name: '张三', age: 25, active: true }, - { name: '李四', age: 30, active: false }, - { name: '王五', age: 35, active: true }, -]; - -// 只有 active 为 true 的人 -meanBy(users, { active: true }); -// Returns: 0.6666666 (active 为 true 的人占总人数的比例) -``` - -空数组返回 NaN。 - -```typescript -import { meanBy } from 'es-toolkit/compat'; - -meanBy([], x => x.a); -// Returns: NaN - -meanBy(null); -// Returns: NaN - -meanBy(undefined); -// Returns: NaN -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要处理的数组。 -- `iteratee` (`ValueIteratee`, 可选): 应用于每个元素的函数、属性名或条件。 - -#### 返回值 - -(`number`): 返回符合条件的值的平均值。如果是空数组则返回 `NaN`。 diff --git a/docs/zh_hans/reference/compat/math/minBy.md b/docs/zh_hans/reference/compat/math/minBy.md deleted file mode 100644 index 8fa43f365..000000000 --- a/docs/zh_hans/reference/compat/math/minBy.md +++ /dev/null @@ -1,114 +0,0 @@ -# minBy(Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [minBy](../../array/minBy.md) - -这个 `minBy` 函数由于 iteratee 函数处理和类型转换会运行较慢。 - -请使用更快、更现代的 `es-toolkit` 的 [minBy](../../array/minBy.md)。 - -::: - -在满足条件的值中找到最小值元素。 - -```typescript -const minItem = minBy(array, iteratee); -``` - -## 用法 - -### `minBy(array, iteratee)` - -在数组中找到通过函数计算后值最小的元素。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -// 对象数组中特定属性最小的元素 -const people = [ - { name: '张三', age: 25 }, - { name: '李四', age: 30 }, - { name: '王五', age: 35 }, -]; - -minBy(people, person => person.age); -// Returns: { name: '张三', age: 25 } - -// 也可以使用属性名 -minBy(people, 'age'); -// Returns: { name: '张三', age: 25 } -``` - -通过函数转换值来找到最小值。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const items = [{ a: 1 }, { a: 2 }, { a: 3 }]; -minBy(items, x => x.a); -// Returns: { a: 1 } - -const numbers = [-1, -2, -3]; -minBy(numbers, x => Math.abs(x)); -// Returns: -1 (绝对值最小的元素) -``` - -通过数组元素访问。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const arrays = [ - [1, 2], - [3, 4], - [0, 5], -]; -minBy(arrays, 0); // 第一个元素最小的数组 -// Returns: [0, 5] - -minBy(arrays, 1); // 第二个元素最小的数组 -// Returns: [1, 2] -``` - -查找对象的特定属性和值匹配的情况。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -const users = [ - { name: '张三', age: 25, active: true }, - { name: '李四', age: 30, active: false }, - { name: '王五', age: 35, active: true }, -]; - -// 在 active 为 true 的元素中找到不是第一个的元素 -minBy(users, ['active', true]); -// Returns: { name: '李四', age: 30, active: false } - -// 使用对象指定条件 -minBy(users, { active: true }); -// Returns: { name: '李四', age: 30, active: false } -``` - -空数组返回 undefined。 - -```typescript -import { minBy } from 'es-toolkit/compat'; - -minBy([], x => x.a); -// Returns: undefined - -minBy(null); -// Returns: undefined - -minBy(undefined); -// Returns: undefined -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要搜索的数组。 -- `iteratee` (`ValueIteratee`, 可选): 应用于每个元素的函数、属性名或条件。 - -#### 返回值 - -(`T | undefined`): 返回满足条件的值最小的元素。如果是空数组则返回 `undefined`。 diff --git a/docs/zh_hans/reference/compat/math/range.md b/docs/zh_hans/reference/compat/math/range.md deleted file mode 100644 index 5669bb0ec..000000000 --- a/docs/zh_hans/reference/compat/math/range.md +++ /dev/null @@ -1,99 +0,0 @@ -# range(Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [range](../../math/range.md) - -这个 `range` 函数由于复杂的参数处理和类型转换而运行缓慢。 - -请使用更快更现代的 `es-toolkit` 的 [range](../../math/range.md)。 - -::: - -创建数字范围数组。 - -```typescript -const numbers = range(start, end, step); -``` - -## 用法 - -### `range(end)` - -创建从 0 到 end 以 1 递增的数组。 - -```typescript -import { range } from 'es-toolkit/compat'; - -range(4); -// Returns: [0, 1, 2, 3] - -range(0); -// Returns: [] - -range(-4); -// Returns: [0, -1, -2, -3] -``` - -### `range(start, end)` - -创建从 start 到 end 以 1 递增的数组。 - -```typescript -import { range } from 'es-toolkit/compat'; - -range(1, 5); -// Returns: [1, 2, 3, 4] - -range(5, 1); -// Returns: [5, 4, 3, 2] (自动以 -1 递减) - -range(-2, 3); -// Returns: [-2, -1, 0, 1, 2] -``` - -### `range(start, end, step)` - -创建从 start 到 end 以 step 递增的数组。 - -```typescript -import { range } from 'es-toolkit/compat'; - -range(0, 20, 5); -// Returns: [0, 5, 10, 15] - -range(0, -4, -1); -// Returns: [0, -1, -2, -3] - -range(1, 4, 0); -// Returns: [1, 1, 1] -``` - -小数 step 也可以使用。 - -```typescript -import { range } from 'es-toolkit/compat'; - -range(0, 1, 0.2); -// Returns: [0, 0.2, 0.4, 0.6, 0.8] - -range(1, 0, -0.25); -// Returns: [1, 0.75, 0.5, 0.25] -``` - -用作 iteratee 时通过 guard 对象处理。 - -```typescript -import { range } from 'es-toolkit/compat'; - -[1, 2, 3].map(range); -// Returns: [[0], [0, 1], [0, 1, 2]] -``` - -#### 参数 - -- `start` (`number`): 范围的起始值(包含)。如果没有 `end`,此值将成为 end。 -- `end` (`number`, 可选): 范围的结束值(不包含)。 -- `step` (`number`, 可选): 递增幅度。默认值为 1 或 -1。 - -#### 返回值 - -(`number[]`): 返回指定范围的数字数组。 diff --git a/docs/zh_hans/reference/compat/math/rangeRight.md b/docs/zh_hans/reference/compat/math/rangeRight.md deleted file mode 100644 index d8b5b1b45..000000000 --- a/docs/zh_hans/reference/compat/math/rangeRight.md +++ /dev/null @@ -1,99 +0,0 @@ -# rangeRight(Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [rangeRight](../../math/rangeRight.md) - -这个 `rangeRight` 函数由于复杂的参数处理和类型转换而运行缓慢。 - -请使用更快更现代的 `es-toolkit` 的 [rangeRight](../../math/rangeRight.md)。 - -::: - -创建数字范围数组(逆序)。 - -```typescript -const numbers = rangeRight(start, end, step); -``` - -## 用法 - -### `rangeRight(end)` - -创建从 0 到 end 以 1 递增后逆序的数组。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(4); -// Returns: [3, 2, 1, 0] - -rangeRight(0); -// Returns: [] - -rangeRight(-4); -// Returns: [-3, -2, -1, 0] -``` - -### `rangeRight(start, end)` - -创建从 start 到 end 以 1 递增后逆序的数组。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(1, 5); -// Returns: [4, 3, 2, 1] - -rangeRight(5, 1); -// Returns: [2, 3, 4, 5] (自动以 -1 递减后逆序) - -rangeRight(-2, 3); -// Returns: [2, 1, 0, -1, -2] -``` - -### `rangeRight(start, end, step)` - -创建从 start 到 end 以 step 递增后逆序的数组。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(0, 8, 2); -// Returns: [6, 4, 2, 0] - -rangeRight(0, -4, -1); -// Returns: [-3, -2, -1, 0] - -rangeRight(1, 4, 0); -// Returns: [1, 1, 1] -``` - -小数 step 也可以使用。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -rangeRight(0, 1, 0.2); -// Returns: [0.8, 0.6, 0.4, 0.2, 0] - -rangeRight(1, 0, -0.25); -// Returns: [0.25, 0.5, 0.75, 1] -``` - -用作 iteratee 时通过 guard 对象处理。 - -```typescript -import { rangeRight } from 'es-toolkit/compat'; - -[1, 2, 3].map(rangeRight); -// Returns: [[0], [1, 0], [2, 1, 0]] -``` - -#### 参数 - -- `start` (`number`): 范围的起始值(包含)。如果没有 `end`,此值将成为 end。 -- `end` (`number`, 可选): 范围的结束值(不包含)。 -- `step` (`number`, 可选): 递增幅度。默认值为 1 或 -1。 - -#### 返回值 - -(`number[]`): 返回指定范围的数字数组(逆序)。 diff --git a/docs/zh_hans/reference/compat/math/sum.md b/docs/zh_hans/reference/compat/math/sum.md deleted file mode 100644 index f3618d607..000000000 --- a/docs/zh_hans/reference/compat/math/sum.md +++ /dev/null @@ -1,73 +0,0 @@ -# sum (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [sum](../../math/sum.md) - -这个 `sum` 函数由于类型转换和 null/undefined 处理会运行较慢。 - -请使用更快、更现代的 `es-toolkit` 的 [sum](../../math/sum.md)。 - -::: - -将数组的所有值相加。 - -```typescript -const total = sum(array); -``` - -## 用法 - -### `sum(array)` - -将数组中的所有数字相加得到总和。 - -```typescript -import { sum } from 'es-toolkit/compat'; - -// 数字数组 -sum([1, 2, 3]); -// Returns: 6 - -sum([1.5, 2.5, 3]); -// Returns: 7 - -// 空数组 -sum([]); -// Returns: 0 -``` - -BigInt 和字符串也能处理。 - -```typescript -import { sum } from 'es-toolkit/compat'; - -// BigInt 数组 -sum([1n, 2n, 3n]); -// Returns: 6n - -// 字符串数组(连接) -sum(['1', '2']); -// Returns: '12' -``` - -无效值会被忽略。 - -```typescript -import { sum } from 'es-toolkit/compat'; - -sum([1, undefined, 2]); -// Returns: 3 (忽略 undefined) - -sum(null); -// Returns: 0 - -sum(undefined); -// Returns: 0 -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 包含要相加值的数组。 - -#### 返回值 - -(`number`): 返回所有值相加的总和。 diff --git a/docs/zh_hans/reference/compat/math/sumBy.md b/docs/zh_hans/reference/compat/math/sumBy.md deleted file mode 100644 index 1dafb1cc9..000000000 --- a/docs/zh_hans/reference/compat/math/sumBy.md +++ /dev/null @@ -1,103 +0,0 @@ -# sumBy(Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [sumBy](../../math/sumBy.md) - -这个 `sumBy` 函数由于 iteratee 函数处理和类型转换而运行缓慢。 - -请使用更快更现代的 `es-toolkit` 的 [sumBy](../../math/sumBy.md)。 - -::: - -将满足条件的值相加。 - -```typescript -const total = sumBy(array, iteratee); -``` - -## 用法 - -### `sumBy(array, iteratee)` - -对数组的每个元素应用函数后将结果相加。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -// 数字数组 -sumBy([1, 2, 3], value => value); -// Returns: 6 - -sumBy([1.5, 2.5, 3.5], value => Math.floor(value)); -// Returns: 6 (1 + 2 + 3) - -// 空数组 -sumBy([], value => value); -// Returns: 0 -``` - -### `sumBy(array)` - -不提供函数时直接将数组值相加。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -sumBy([1, 2, 3]); -// Returns: 6 - -sumBy([1n, 2n, 3n]); -// Returns: 6n -``` - -将对象数组中的特定属性相加。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -const people = [ - { name: '张三', age: 25 }, - { name: '李四', age: 30 }, - { name: '王五', age: 35 }, -]; - -sumBy(people, person => person.age); -// Returns: 90 - -// 也可以使用属性名 -sumBy(people, 'age'); -// Returns: 90 -``` - -字符串也会被连接。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -const items = [{ a: '1' }, { a: '2' }]; -sumBy(items, obj => obj.a); -// Returns: '12' -``` - -无效值会被忽略。 - -```typescript -import { sumBy } from 'es-toolkit/compat'; - -sumBy([1, undefined, 2], value => value); -// Returns: 3 (忽略 undefined) - -sumBy(null); -// Returns: 0 - -sumBy(undefined); -// Returns: 0 -``` - -#### 参数 - -- `array` (`ArrayLike | null | undefined`): 要处理的数组。 -- `iteratee` (`((value: T) => number) | string`, 可选): 应用于每个元素的函数或属性名。 - -#### 返回值 - -(`number`): 返回满足条件的值的总和。 diff --git a/docs/zh_hans/reference/compat/object/clone.md b/docs/zh_hans/reference/compat/object/clone.md deleted file mode 100644 index 0a4c2903d..000000000 --- a/docs/zh_hans/reference/compat/object/clone.md +++ /dev/null @@ -1,89 +0,0 @@ -# clone (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `clone` - -这个 `clone` 函数由于处理特殊对象类型的复杂逻辑而相对较慢。 - -请改用 `es-toolkit` 的更快、更现代的 [clone](../../object/clone.md)。 - -::: - -创建对象的浅拷贝。 - -```typescript -const cloned = clone(value); -``` - -## 用法 - -### `clone(value)` - -当您想要创建值的浅拷贝时,请使用 `clone`。它可以复制各种类型的对象和原始值。 - -```typescript -import { clone } from 'es-toolkit/compat'; - -// 复制原始值 -const num = 42; -const clonedNum = clone(num); -// Returns: 42 (相同的值) - -// 复制数组 -const arr = [1, 2, 3]; -const clonedArr = clone(arr); -// Returns: [1, 2, 3] (新的数组实例) - -// 复制对象 -const obj = { a: 1, b: 'hello' }; -const clonedObj = clone(obj); -// Returns: { a: 1, b: 'hello' } (新的对象实例) - -// 复制Date对象 -const date = new Date('2023-01-01'); -const clonedDate = clone(date); -// Returns: new Date('2023-01-01') (新的Date实例) - -// 复制正则表达式 -const regex = /hello/gi; -regex.lastIndex = 3; -const clonedRegex = clone(regex); -// Returns: /hello/gi with lastIndex = 3 - -// 复制Map -const map = new Map([ - ['a', 1], - ['b', 2], -]); -const clonedMap = clone(map); -// Returns: new Map([['a', 1], ['b', 2]]) - -// 复制Set -const set = new Set([1, 2, 3]); -const clonedSet = clone(set); -// Returns: new Set([1, 2, 3]) -``` - -嵌套对象仅进行浅拷贝。 - -```typescript -import { clone } from 'es-toolkit/compat'; - -const nested = { - a: 1, - b: { - c: 2, - }, -}; -const clonedNested = clone(nested); - -console.log(clonedNested !== nested); // true (不同的对象) -console.log(clonedNested.b === nested.b); // true (嵌套对象具有相同的引用) -``` - -#### 参数 - -- `value` (`T`): 要复制的值。 - -#### 返回值 - -(`T`): 返回复制的值。 diff --git a/docs/zh_hans/reference/compat/object/cloneDeep.md b/docs/zh_hans/reference/compat/object/cloneDeep.md deleted file mode 100644 index 100ba96c9..000000000 --- a/docs/zh_hans/reference/compat/object/cloneDeep.md +++ /dev/null @@ -1,88 +0,0 @@ -# cloneDeep (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `cloneDeep` - -这个 `cloneDeep` 函数由于处理特殊对象类型的复杂逻辑而相对较慢。 - -请改用 `es-toolkit` 的更快、更现代的 [cloneDeep](../../object/cloneDeep.md)。 - -::: - -创建对象的深拷贝。 - -```typescript -const cloned = cloneDeep(value); -``` - -## 用法 - -### `cloneDeep(value)` - -当您想要创建值的深拷贝时,请使用 `cloneDeep`。它将嵌套的对象和数组完全复制为新实例。 - -```typescript -import { cloneDeep } from 'es-toolkit/compat'; - -// 复制原始值 -const num = 42; -const clonedNum = cloneDeep(num); -// Returns: 42 (相同的值) - -// 深拷贝数组 -const arr = [1, [2, 3], { a: 4 }]; -const clonedArr = cloneDeep(arr); -clonedArr[1][0] = 99; -console.log(arr[1][0]); // 2 (原始值未更改) -console.log(clonedArr[1][0]); // 99 - -// 深拷贝对象 -const obj = { - a: 1, - b: { - c: 2, - d: { - e: 3, - }, - }, -}; -const clonedObj = cloneDeep(obj); -clonedObj.b.d.e = 99; -console.log(obj.b.d.e); // 3 (原始值未更改) -console.log(clonedObj.b.d.e); // 99 - -// 深拷贝Date对象 -const date = new Date('2023-01-01'); -const clonedDate = cloneDeep(date); -// Returns: new Date('2023-01-01') (新的Date实例) - -// 复杂的嵌套结构 -const complex = { - arr: [1, { nested: true }], - map: new Map([['key', { value: 1 }]]), - set: new Set([{ item: 1 }]), - date: new Date(), -}; -const clonedComplex = cloneDeep(complex); -// 所有嵌套对象都作为完全新的实例被复制 -``` - -循环引用也得到正确处理。 - -```typescript -import { cloneDeep } from 'es-toolkit/compat'; - -const obj = { a: 1 }; -obj.self = obj; // 循环引用 - -const cloned = cloneDeep(obj); -console.log(cloned !== obj); // true -console.log(cloned.self === cloned); // true (保留循环引用) -``` - -#### 参数 - -- `value` (`T`): 要深拷贝的值。 - -#### 返回值 - -(`T`): 返回深拷贝的值。 diff --git a/docs/zh_hans/reference/compat/object/findKey.md b/docs/zh_hans/reference/compat/object/findKey.md deleted file mode 100644 index a221e7b0e..000000000 --- a/docs/zh_hans/reference/compat/object/findKey.md +++ /dev/null @@ -1,61 +0,0 @@ -# findKey (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `findKey` - -由于需要处理各种条件类型和兼容性逻辑,此 `findKey` 函数的行为较为复杂。 - -建议使用更快、更现代的 `es-toolkit` 的 [findKey](../../object/findKey.md)。 - -::: - -查找满足条件的第一个元素的键。 - -```typescript -const key = findKey(obj, predicate); -``` - -## 用法 - -### `findKey(obj, predicate)` - -使用 `findKey` 在对象中查找满足条件的第一个元素的键。可以使用函数、对象、数组、字符串等各种形式的条件。 - -```typescript -import { findKey } from 'es-toolkit/compat'; - -// 使用函数条件查找键 -const users = { - alice: { age: 25, active: true }, - bob: { age: 30, active: false }, - charlie: { age: 35, active: true }, -}; - -findKey(users, user => user.age > 30); -// 返回值: 'charlie' - -// 使用对象条件查找键 -findKey(users, { active: false }); -// 返回值: 'bob' - -// 使用属性路径查找键 -findKey(users, 'active'); -// 返回值: 'alice' -``` - -如果没有匹配的元素,则返回 `undefined`。 - -```typescript -import { findKey } from 'es-toolkit/compat'; - -findKey({ a: 1, b: 2 }, value => value > 5); -// 返回值: undefined -``` - -#### 参数 - -- `obj` (`T | null | undefined`): 要搜索的对象。 -- `predicate` (`ObjectIteratee`, 可选): 应用于每个元素的条件。可以是函数、对象、数组或字符串。 - -#### 返回值 - -(`string | undefined`): 返回满足条件的第一个元素的键。如果没有找到匹配项,则返回 `undefined`。 diff --git a/docs/zh_hans/reference/compat/object/invert.md b/docs/zh_hans/reference/compat/object/invert.md deleted file mode 100644 index c49e0b696..000000000 --- a/docs/zh_hans/reference/compat/object/invert.md +++ /dev/null @@ -1,60 +0,0 @@ -# invert (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `invert` - -由于 Lodash 兼容性所需的复杂处理,此 `invert` 函数运行较慢。 - -请使用更快、更现代的 `es-toolkit` 的 [`invert`](../../object/invert.md)。 - -::: - -反转对象的键和值。 - -```typescript -const inverted = invert(object); -``` - -## 用法 - -### `invert(object)` - -当您想要交换对象的键和值时,请使用 `invert`。原始对象的键将成为新对象的值,原始对象的值将成为新对象的键。 - -```typescript -import { invert } from 'es-toolkit/compat'; - -// 基本键值反转 -const object = { a: 1, b: 2, c: 3 }; -invert(object); -// => { '1': 'a', '2': 'b', '3': 'c' } - -// 反转字符串值 -const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' }; -invert(colors); -// => { '#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue' } - -// 混合键和值类型 -const mixed = { a: 1, 2: 'b', c: 3, 4: 'd' }; -invert(mixed); -// => { '1': 'a', 'b': '2', '3': 'c', 'd': '4' } -``` - -当存在重复值时,将使用最后一个键。 - -```typescript -import { invert } from 'es-toolkit/compat'; - -// 存在重复值的情况 -const object = { a: 1, b: 1, c: 2 }; -invert(object); -// => { '1': 'b', '2': 'c' } -// 'a' 被覆盖并丢失 -``` - -#### 参数 - -- `object` (`object`): 要反转的对象。 - -#### 返回值 - -(`Record`): 返回键和值反转后的新对象。 diff --git a/docs/zh_hans/reference/compat/object/mapKeys.md b/docs/zh_hans/reference/compat/object/mapKeys.md deleted file mode 100644 index 0edd24583..000000000 --- a/docs/zh_hans/reference/compat/object/mapKeys.md +++ /dev/null @@ -1,63 +0,0 @@ -# mapKeys (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `mapKeys` - -这个 `mapKeys` 函数由于处理 `null` 或 `undefined` 以及 `iteratee` 转换过程而相对较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`mapKeys`](../../object/mapKeys.md)。 - -::: - -通过转换键来创建新对象,同时保持值不变。 - -```typescript -const result = mapKeys(obj, iteratee); -``` - -## 用法 - -### `mapKeys(object, iteratee)` - -使用 `iteratee` 函数转换对象中的每个键来创建新对象。值保持不变,只修改键。适用于转换或规范化对象键。 - -```typescript -import { mapKeys } from 'es-toolkit/compat'; - -// 为键添加前缀 -const obj = { a: 1, b: 2, c: 3 }; -const result = mapKeys(obj, (value, key) => 'prefix_' + key); -// 结果: { prefix_a: 1, prefix_b: 2, prefix_c: 3 } - -// 将键转换为大写 -const data = { name: 'John', age: 30 }; -const uppercased = mapKeys(data, (value, key) => key.toUpperCase()); -// 结果: { NAME: 'John', AGE: 30 } - -// 将数组索引转换为键 -const arr = ['apple', 'banana', 'orange']; -const indexed = mapKeys(arr, (value, index) => `item_${index}`); -// 结果: { item_0: 'apple', item_1: 'banana', item_2: 'orange' } - -// 通过组合键和值创建新键 -const scores = { math: 90, science: 85, english: 92 }; -const detailed = mapKeys(scores, (value, key) => `${key}_score_${value}`); -// 结果: { math_score_90: 90, science_score_85: 85, english_score_92: 92 } -``` - -`null` 或 `undefined` 被视为空对象。 - -```typescript -import { mapKeys } from 'es-toolkit/compat'; - -mapKeys(null, iteratee); // {} -mapKeys(undefined, iteratee); // {} -``` - -#### 参数 - -- `object` (`ArrayLike | T | null | undefined`): 要转换键的对象或数组。 -- `iteratee` (`ListIteratee | ObjectIteratee`, 可选): 用于转换每个键的函数。默认为 `identity` 函数。 - -#### 返回值 - -(`Record | Record`): 返回一个具有转换后键的新对象。 diff --git a/docs/zh_hans/reference/compat/object/mapValues.md b/docs/zh_hans/reference/compat/object/mapValues.md deleted file mode 100644 index 6a19a0885..000000000 --- a/docs/zh_hans/reference/compat/object/mapValues.md +++ /dev/null @@ -1,71 +0,0 @@ -# mapValues (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `mapValues` - -这个 `mapValues` 函数由于处理 `null` 或 `undefined` 以及 `iteratee` 转换过程而相对较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`mapValues`](../../object/mapValues.md)。 - -::: - -通过转换值来创建新对象,同时保持键不变。 - -```typescript -const result = mapValues(obj, iteratee); -``` - -## 用法 - -### `mapValues(object, iteratee)` - -使用 `iteratee` 函数转换对象中的每个值来创建新对象。键保持不变,只修改值。可以处理字符串、数组和对象。适用于转换或计算数据。 - -```typescript -import { mapValues } from 'es-toolkit/compat'; - -// 转换对象值 -const obj = { a: 1, b: 2, c: 3 }; -const doubled = mapValues(obj, value => value * 2); -// 结果: { a: 2, b: 4, c: 6 } - -// 将字符串转换为大写 -const names = { first: 'john', last: 'doe' }; -const uppercased = mapValues(names, value => value.toUpperCase()); -// 结果: { first: 'JOHN', last: 'DOE' } - -// 转换字符串中的每个字符 -const str = 'abc'; -const charMap = mapValues(str, char => char.toUpperCase()); -// 结果: { '0': 'A', '1': 'B', '2': 'C' } - -// 将数组转换为对象 -const arr = [10, 20, 30]; -const arrMap = mapValues(arr, (value, index) => value + index); -// 结果: { '0': 10, '1': 21, '2': 32 } - -// 使用属性路径提取值 -const users = { - user1: { profile: { name: 'Alice' } }, - user2: { profile: { name: 'Bob' } }, -}; -const userNames = mapValues(users, 'profile.name'); -// 结果: { user1: 'Alice', user2: 'Bob' } -``` - -`null` 或 `undefined` 被视为空对象。 - -```typescript -import { mapValues } from 'es-toolkit/compat'; - -mapValues(null, iteratee); // {} -mapValues(undefined, iteratee); // {} -``` - -#### 参数 - -- `object` (`string | T[] | T | null | undefined`): 要转换值的对象、数组或字符串。 -- `iteratee` (`ValueIteratee`, 可选): 用于转换每个值的函数、属性路径或匹配对象。默认为 `identity` 函数。 - -#### 返回值 - -(`Record | { [P in keyof T]: U } | Record | Record | Partial`): 返回一个具有转换后值的新对象。 diff --git a/docs/zh_hans/reference/compat/object/merge.md b/docs/zh_hans/reference/compat/object/merge.md deleted file mode 100644 index f5e34eadd..000000000 --- a/docs/zh_hans/reference/compat/object/merge.md +++ /dev/null @@ -1,82 +0,0 @@ -# merge (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `merge` - -这个 `merge` 函数由于内部调用复杂的 `mergeWith` 函数而相对较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`merge`](../../object/merge.md)。 - -::: - -深度合并多个对象为单个对象。 - -```typescript -const result = merge(target, ...sources); -``` - -## 用法 - -### `merge(object, ...sources)` - -将一个或多个源对象深度合并到目标对象中。嵌套的对象和数组会递归合并。如果源对象的属性是 `undefined`,则不会覆盖目标对象中的现有值。适用于合并对象配置或应用默认值。 - -```typescript -import { merge } from 'es-toolkit/compat'; - -// 基本对象合并 -const target = { a: 1, b: { x: 1, y: 2 } }; -const source = { b: { y: 3, z: 4 }, c: 5 }; -const result = merge(target, source); -// 结果: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } - -// 数组合并 -const obj1 = { arr: [1, 2] }; -const obj2 = { arr: [3, 4] }; -const merged = merge(obj1, obj2); -// 结果: { arr: [3, 4] } (数组被替换) - -// 多个对象合并 -const base = { a: 1 }; -const ext1 = { b: 2 }; -const ext2 = { c: 3 }; -const ext3 = { d: 4 }; -const combined = merge(base, ext1, ext2, ext3); -// 结果: { a: 1, b: 2, c: 3, d: 4 } - -// 嵌套对象合并 -const config = { - api: { url: 'https://api.example.com', timeout: 5000 }, - features: { auth: true }, -}; -const overrides = { - api: { timeout: 10000, retries: 3 }, - features: { analytics: true }, -}; -const finalConfig = merge(config, overrides); -// 结果: { -// api: { url: 'https://api.example.com', timeout: 10000, retries: 3 }, -// features: { auth: true, analytics: true } -// } -``` - -目标对象会被修改,因此如需保留原始对象请使用空对象。 - -```typescript -import { merge } from 'es-toolkit/compat'; - -const original = { a: 1, b: { x: 1 } }; -const source = { b: { y: 2 } }; - -// 保留原始对象 -const result = merge({}, original, source); -// original 未被修改 -``` - -#### 参数 - -- `object` (`any`): 要合并到的目标对象。此对象会被修改。 -- `...sources` (`any[]`): 要合并的源对象。 - -#### 返回值 - -(`any`): 返回合并后的目标对象。 diff --git a/docs/zh_hans/reference/compat/object/mergeWith.md b/docs/zh_hans/reference/compat/object/mergeWith.md deleted file mode 100644 index a79155e50..000000000 --- a/docs/zh_hans/reference/compat/object/mergeWith.md +++ /dev/null @@ -1,94 +0,0 @@ -# mergeWith (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `mergeWith` - -这个 `mergeWith` 函数由于复杂的类型检查、循环引用处理和特殊对象处理而相对较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`mergeWith`](../../object/mergeWith.md)。 - -::: - -使用自定义函数控制合并行为,深度合并多个对象。 - -```typescript -const result = mergeWith(target, ...sources, customizer); -``` - -## 用法 - -### `mergeWith(object, ...sources, customizer)` - -将一个或多个源对象深度合并到目标对象中,使用自定义函数控制合并行为。如果自定义函数返回 `undefined`,则使用默认合并逻辑。适用于连接数组或应用特殊合并规则。 - -```typescript -import { mergeWith } from 'es-toolkit/compat'; - -// 数字相加 -const obj1 = { a: 1, b: 2 }; -const obj2 = { b: 3, c: 4 }; -const result = mergeWith(obj1, obj2, (objValue, srcValue) => { - if (typeof objValue === 'number' && typeof srcValue === 'number') { - return objValue + srcValue; - } -}); -// 结果: { a: 1, b: 5, c: 4 } - -// 连接数组 -const arr1 = { items: [1, 2] }; -const arr2 = { items: [3, 4] }; -const merged = mergeWith(arr1, arr2, (objValue, srcValue) => { - if (Array.isArray(objValue)) { - return objValue.concat(srcValue); - } -}); -// 结果: { items: [1, 2, 3, 4] } - -// 连接字符串 -const str1 = { message: 'Hello' }; -const str2 = { message: 'World' }; -const combined = mergeWith(str1, str2, (objValue, srcValue, key) => { - if (key === 'message' && typeof objValue === 'string') { - return objValue + ' ' + srcValue; - } -}); -// 结果: { message: 'Hello World' } - -// 多个源对象与自定义函数 -const base = { scores: [80] }; -const quiz1 = { scores: [90] }; -const quiz2 = { scores: [85] }; -const final = mergeWith(base, quiz1, quiz2, (objValue, srcValue) => { - if (Array.isArray(objValue)) { - return objValue.concat(srcValue); - } -}); -// 结果: { scores: [80, 90, 85] } -``` - -自定义函数接收各种参数。 - -```typescript -import { mergeWith } from 'es-toolkit/compat'; - -const customizer = (objValue, srcValue, key, object, source, stack) => { - console.log('合并中:', key, objValue, '->', srcValue); - - // 仅对特定键进行自定义 - if (key === 'specialField') { - return `${objValue}_${srcValue}`; - } - - // 返回undefined使用默认合并逻辑 - return undefined; -}; -``` - -#### 参数 - -- `object` (`any`): 要合并到的目标对象。此对象会被修改。 -- `...sources` (`any[]`): 要合并的源对象。 -- `customizer` (`MergeWithCustomizer`): 自定义值分配的函数。格式: `(objValue, srcValue, key, object, source, stack) => any`。 - -#### 返回值 - -(`any`): 返回合并后的目标对象。 diff --git a/docs/zh_hans/reference/compat/object/omit.md b/docs/zh_hans/reference/compat/object/omit.md deleted file mode 100644 index 7bcac4d49..000000000 --- a/docs/zh_hans/reference/compat/object/omit.md +++ /dev/null @@ -1,82 +0,0 @@ -# omit (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `omit` - -这个 `omit` 函数由于深拷贝和调用 `unset` 函数而相对较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`omit`](../../object/omit.md)。 - -::: - -创建一个排除指定键的新对象。 - -```typescript -const result = omit(obj, ...keys); -``` - -## 用法 - -### `omit(object, ...paths)` - -创建一个排除指定键的新对象。支持深层键路径,可以使用数组一次指定多个键。适用于从对象中删除敏感信息或仅选择需要的属性。 - -```typescript -import { omit } from 'es-toolkit/compat'; - -// 删除基本键 -const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }; -const publicUser = omit(user, 'password', 'email'); -// 结果: { id: 1, name: 'John' } - -// 使用数组删除多个键 -const data = { a: 1, b: 2, c: 3, d: 4 }; -const filtered = omit(data, ['a', 'c']); -// 结果: { b: 2, d: 4 } - -// 删除深层键路径 -const nested = { - user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, - admin: true, -}; -const result = omit(nested, 'user.profile.age', 'admin'); -// 结果: { user: { profile: { name: 'John' }, settings: { theme: 'dark' } } } - -// 组合嵌套数组和键 -const complex = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; -const simplified = omit(complex, 'a', ['b', 'c'], 'd.f'); -// 结果: { d: { e: 4 } } -``` - -您可以自由组合数组、字符串和键路径。 - -```typescript -import { omit } from 'es-toolkit/compat'; - -const config = { - api: { url: 'https://api.example.com', key: 'secret', timeout: 5000 }, - ui: { theme: 'dark', language: 'en' }, - debug: true, -}; - -// 以多种方式指定键 -const cleaned = omit(config, 'api.key', ['debug'], 'ui.language'); -// 结果: { api: { url: 'https://api.example.com', timeout: 5000 }, ui: { theme: 'dark' } } -``` - -`null` 或 `undefined` 被视为空对象。 - -```typescript -import { omit } from 'es-toolkit/compat'; - -omit(null, 'key'); // {} -omit(undefined, 'key'); // {} -``` - -#### 参数 - -- `object` (`T | null | undefined`): 要删除键的源对象。 -- `...paths` (`Array>`): 要删除的键。可以指定单个键、键数组或深层键路径。 - -#### 返回值 - -(`Partial`): 返回删除指定键后的新对象。 diff --git a/docs/zh_hans/reference/compat/object/omitBy.md b/docs/zh_hans/reference/compat/object/omitBy.md deleted file mode 100644 index ae54494e6..000000000 --- a/docs/zh_hans/reference/compat/object/omitBy.md +++ /dev/null @@ -1,76 +0,0 @@ -# omitBy (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `omitBy` - -这个 `omitBy` 函数由于类数组对象检查、`iteratee` 转换和键转换过程而相对较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`omitBy`](../../object/omitBy.md)。 - -::: - -创建一个新对象,排除断言函数返回true的属性。 - -```typescript -const result = omitBy(obj, predicate); -``` - -## 用法 - -### `omitBy(object, predicate)` - -对对象的每个属性执行断言函数,并创建一个新对象,排除断言返回true的属性。适用于根据条件动态过滤属性。 - -```typescript -import { omitBy } from 'es-toolkit/compat'; - -// 删除特定类型的值 -const data = { a: 1, b: 'remove', c: 3, d: 'keep' }; -const numbers = omitBy(data, value => typeof value === 'string'); -// 结果: { a: 1, c: 3 } - -// 根据条件删除属性 -const user = { id: 1, name: 'John', age: 0, active: false, email: '' }; -const validData = omitBy(user, value => !value); -// 结果: { id: 1, name: 'John' } (删除假值) - -// 按键名过滤 -const settings = { userSetting: true, adminSetting: false, debugMode: true }; -const userOnly = omitBy(settings, (value, key) => key.startsWith('admin')); -// 结果: { userSetting: true, debugMode: true } - -// 仅删除数字属性 -const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; -const noNumbers = omitBy(mixed, value => typeof value === 'number'); -// 结果: { str: 'hello', bool: true, obj: {} } - -// 也可用于数组 -const arr = [1, 2, 3, 4, 5]; -const filtered = omitBy(arr, value => value % 2 === 0); -// 结果: { '0': 1, '2': 3, '4': 5 } (偶数索引处的奇数值) - -// 利用值、键和原始对象 -const scores = { math: 90, science: 75, english: 85, art: 60 }; -const passingGrades = omitBy(scores, (value, key, obj) => { - console.log(`${key}: ${value} (平均: ${Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length})`); - return value < 80; -}); -// 结果: { math: 90, english: 85 } -``` - -`null` 或 `undefined` 被视为空对象。 - -```typescript -import { omitBy } from 'es-toolkit/compat'; - -omitBy(null, () => true); // {} -omitBy(undefined, () => true); // {} -``` - -#### 参数 - -- `object` (`Record | Record | object | null | undefined`): 要过滤的源对象。 -- `predicate` (`ValueKeyIteratee | ValueKeyIteratee`, 可选): 对每个属性执行的断言函数。此函数返回true的属性将被删除。默认为 `identity` 函数。 - -#### 返回值 - -(`Record | Record | Partial`): 返回一个由不满足条件的属性组成的新对象。 diff --git a/docs/zh_hans/reference/compat/object/pick.md b/docs/zh_hans/reference/compat/object/pick.md deleted file mode 100644 index c168bd632..000000000 --- a/docs/zh_hans/reference/compat/object/pick.md +++ /dev/null @@ -1,73 +0,0 @@ -# pick (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `pick` - -这个 `pick` 函数由于复杂的路径处理、调用 `get`/`set` 函数以及处理 `null`/`undefined` 而相对较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`pick`](../../object/pick.md)。 - -::: - -通过仅选择指定属性来创建新对象。 - -```typescript -const result = pick(obj, ...keys); -``` - -## 用法 - -### `pick(object, ...props)` - -当您想创建一个仅包含对象中所需属性的新对象时,请使用 `pick`。可以使用数组一次传递多个键,或将它们作为单个参数逐个传递。支持深层键路径,因此您也可以选择嵌套属性。 - -```typescript -import { pick } from 'es-toolkit/compat'; - -// 基本用法 -const obj = { a: 1, b: 2, c: 3, d: 4 }; -const result = pick(obj, ['a', 'c']); -// 结果: { a: 1, c: 3 } - -// 作为单个参数传递 -const result2 = pick(obj, 'a', 'c'); -// 结果: { a: 1, c: 3 } - -// 选择深层路径 -const nested = { - user: { profile: { name: 'John', age: 30 }, settings: { theme: 'dark' } }, - admin: true, -}; -const userInfo = pick(nested, 'user.profile.name', 'admin'); -// 结果: { user: { profile: { name: 'John' } }, admin: true } - -// 混合数组和单个键 -const mixed = { a: 1, b: 2, c: 3, d: { e: 4, f: 5 } }; -const selected = pick(mixed, ['a', 'b'], 'c', 'd.e'); -// 结果: { a: 1, b: 2, c: 3, d: { e: 4 } } - -// 区分点表示法键和实际带点的键 -const ambiguous = { - 'a.b': 1, // 实际键 'a.b' - a: { b: 2, c: 3 }, // 嵌套对象 -}; -const dotKey = pick(ambiguous, 'a.b'); -// 结果: { 'a.b': 1 } (实际键优先) -``` - -`null` 或 `undefined` 被视为空对象。 - -```typescript -import { pick } from 'es-toolkit/compat'; - -pick(null, ['a', 'b']); // {} -pick(undefined, ['a', 'b']); // {} -``` - -#### 参数 - -- `object` (`T | null | undefined`): 要选择属性的对象。 -- `...props` (`Array>`): 要选择的属性键。可以指定单个键、键数组或深层键路径。 - -#### 返回值 - -(`Pick | Partial`): 返回仅包含指定属性的新对象。 diff --git a/docs/zh_hans/reference/compat/object/pickBy.md b/docs/zh_hans/reference/compat/object/pickBy.md deleted file mode 100644 index 766c586b9..000000000 --- a/docs/zh_hans/reference/compat/object/pickBy.md +++ /dev/null @@ -1,86 +0,0 @@ -# pickBy (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `pickBy` - -这个 `pickBy` 函数由于类数组对象检查、`iteratee` 转换和键转换过程而相对较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [`pickBy`](../../object/pickBy.md)。 - -::: - -创建一个新对象,仅选择断言函数返回true的属性。 - -```typescript -const result = pickBy(obj, predicate); -``` - -## 用法 - -### `pickBy(object, predicate)` - -对对象的每个属性执行断言函数,并创建一个新对象,仅包含断言返回true的属性。适用于根据条件动态选择属性。 - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -// 仅选择特定类型的值 -const data = { a: 1, b: 'keep', c: 3, d: 'select' }; -const strings = pickBy(data, value => typeof value === 'string'); -// 结果: { b: 'keep', d: 'select' } - -// 根据条件选择属性 -const user = { id: 1, name: 'John', age: 0, active: true, email: '' }; -const validData = pickBy(user, value => Boolean(value)); -// 结果: { id: 1, name: 'John', active: true } (仅真值) - -// 按键名过滤 -const settings = { userSetting: true, adminSetting: false, debugMode: true }; -const userOnly = pickBy(settings, (value, key) => key.startsWith('user')); -// 结果: { userSetting: true } - -// 仅选择数字属性 -const mixed = { str: 'hello', num1: 42, bool: true, num2: 0, obj: {} }; -const numbersOnly = pickBy(mixed, value => typeof value === 'number'); -// 结果: { num1: 42, num2: 0 } - -// 也可用于数组 -const arr = [1, 2, 3, 4, 5]; -const evens = pickBy(arr, value => value % 2 === 0); -// 结果: { '1': 2, '3': 4 } (偶数的索引和值) - -// 利用值、键和原始对象 -const scores = { math: 90, science: 75, english: 85, art: 60 }; -const highScores = pickBy(scores, (value, key, obj) => { - const average = Object.values(obj).reduce((a, b) => a + b) / Object.keys(obj).length; - return value > average; -}); -// 结果: { math: 90, english: 85 } -``` - -不带断言函数调用时,仅选择真值。 - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -const data = { a: 1, b: '', c: 0, d: 'hello', e: null, f: true }; -const truthyValues = pickBy(data); -// 结果: { a: 1, d: 'hello', f: true } -``` - -`null` 或 `undefined` 被视为空对象。 - -```typescript -import { pickBy } from 'es-toolkit/compat'; - -pickBy(null, () => true); // {} -pickBy(undefined, () => true); // {} -``` - -#### 参数 - -- `object` (`Record | Record | object | null | undefined`): 要过滤的源对象。 -- `predicate` (`ValueKeyIterateeTypeGuard | ValueKeyIteratee | ValueKeyIteratee`, 可选): 对每个属性执行的断言函数。此函数返回true的属性将被选择。默认为 `identity` 函数。 - -#### 返回值 - -(`Record | Record | Partial`): 返回一个由满足条件的属性组成的新对象。 diff --git a/docs/zh_hans/reference/compat/predicate/isArrayBuffer.md b/docs/zh_hans/reference/compat/predicate/isArrayBuffer.md deleted file mode 100644 index 55958f109..000000000 --- a/docs/zh_hans/reference/compat/predicate/isArrayBuffer.md +++ /dev/null @@ -1,44 +0,0 @@ -# isArrayBuffer (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [isArrayBuffer](../../predicate/isArrayBuffer.md) -此 `isArrayBuffer` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 - -请改用更快的现代化 `es-toolkit` 的 [isArrayBuffer](../../predicate/isArrayBuffer.md)。 -::: - -检查值是否为 ArrayBuffer。 - -```typescript -const result = isArrayBuffer(value); -``` - -## 用法 - -### `isArrayBuffer(value)` - -当您想要类型安全地检查值是否为 ArrayBuffer 时,请使用 `isArrayBuffer`。在 TypeScript 中也作为类型守卫工作。 - -```typescript -import { isArrayBuffer } from 'es-toolkit/compat'; - -// 检查 ArrayBuffer -const buffer = new ArrayBuffer(16); -isArrayBuffer(buffer); // true - -// 其他类型返回 false -isArrayBuffer(new Array()); // false -isArrayBuffer(new Map()); // false -isArrayBuffer({}); // false -isArrayBuffer('hello'); // false -isArrayBuffer(123); // false -isArrayBuffer(null); // false -isArrayBuffer(undefined); // false -``` - -#### 参数 - -- `value` (`unknown`): 要检查是否为 ArrayBuffer 的值。 - -#### 返回值 - -(`value is ArrayBuffer`): 如果值是 ArrayBuffer 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isBuffer.md b/docs/zh_hans/reference/compat/predicate/isBuffer.md deleted file mode 100644 index 0d6c70e95..000000000 --- a/docs/zh_hans/reference/compat/predicate/isBuffer.md +++ /dev/null @@ -1,43 +0,0 @@ -# isBuffer (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [isBuffer](../../predicate/isBuffer.md) -此 `isBuffer` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 - -请改用更快的现代化 `es-toolkit` 的 [isBuffer](../../predicate/isBuffer.md)。 -::: - -检查值是否为 Buffer 实例。 - -```typescript -const result = isBuffer(value); -``` - -## 用法 - -### `isBuffer(value)` - -当您想要类型安全地检查值是否为 Buffer 实例时,请使用 `isBuffer`。在 Node.js 环境中处理 Buffer 对象时很有用。在 TypeScript 中也作为类型守卫工作。 - -```typescript -import { isBuffer } from 'es-toolkit/compat'; - -// 检查 Buffer 实例 -const buffer = Buffer.from('hello'); -isBuffer(buffer); // true - -// 其他类型返回 false -isBuffer('hello'); // false -isBuffer([1, 2, 3]); // false -isBuffer(new Uint8Array([1, 2, 3])); // false -isBuffer({}); // false -isBuffer(null); // false -isBuffer(undefined); // false -``` - -#### 参数 - -- `value` (`unknown`): 要检查是否为 Buffer 实例的值。 - -#### 返回值 - -(`boolean`): 如果值是 Buffer 实例则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isDate.md b/docs/zh_hans/reference/compat/predicate/isDate.md deleted file mode 100644 index 39cfd1395..000000000 --- a/docs/zh_hans/reference/compat/predicate/isDate.md +++ /dev/null @@ -1,46 +0,0 @@ -# isDate (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [isDate](../../predicate/isDate.md) -这个 `isDate` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 - -建议使用更快、更现代的 `es-toolkit` 的 [isDate](../../predicate/isDate.md)。 -::: - -检查值是否为 Date 对象。 - -```typescript -const result = isDate(value); -``` - -## 用法 - -### `isDate(value)` - -当你想要类型安全地检查值是否为 Date 对象时使用 `isDate`。在 TypeScript 中它也可以作为类型守卫使用。 - -```typescript -import { isDate } from 'es-toolkit/compat'; - -// 检查 Date 对象 -const date = new Date(); -isDate(date); // true - -// 无效的 Date 也被识别为 Date 对象 -const invalidDate = new Date('invalid'); -isDate(invalidDate); // true - -// 其他类型返回 false -isDate('2024-01-01'); // false -isDate(1640995200000); // false -isDate({}); // false -isDate(null); // false -isDate(undefined); // false -``` - -#### 参数 - -- `value` (`unknown`): 要检查是否为 Date 对象的值。 - -#### 返回值 - -(`value is Date`): 如果值是 Date 对象则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isEqual.md b/docs/zh_hans/reference/compat/predicate/isEqual.md deleted file mode 100644 index cd963c8be..000000000 --- a/docs/zh_hans/reference/compat/predicate/isEqual.md +++ /dev/null @@ -1,82 +0,0 @@ -# isEqual (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 [isEqual](../../predicate/isEqual.md) -这个 `isEqual` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 - -建议使用更快、更现代的 `es-toolkit` 的 [isEqual](../../predicate/isEqual.md)。 -::: - -深度比较两个值是否相等。 - -```typescript -const result = isEqual(value1, value2); -``` - -## 用法 - -### `isEqual(a, b)` - -当需要深度比较两个值是否相等时使用 `isEqual`。它会比较复杂类型如 Date、RegExp、对象、数组等的内容。 - -```typescript -import { isEqual } from 'es-toolkit/compat'; - -// 基本类型比较 -isEqual(1, 1); // true -isEqual('hello', 'hello'); // true -isEqual(true, true); // true - -// 对象深度比较 -isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true -isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // true -isEqual({ a: 1 }, { a: 1, b: undefined }); // false - -// 数组深度比较 -isEqual([1, 2, 3], [1, 2, 3]); // true -isEqual([1, [2, 3]], [1, [2, 3]]); // true - -// Date 对象比较 -isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true -isEqual(new Date('2020-01-01'), new Date('2020-01-02')); // false - -// RegExp 对象比较 -isEqual(/abc/g, /abc/g); // true -isEqual(/abc/g, /abc/i); // false -``` - -它也会递归比较嵌套的对象和数组。 - -```typescript -import { isEqual } from 'es-toolkit/compat'; - -const obj1 = { - user: { - name: 'John', - details: { - age: 30, - hobbies: ['reading', 'gaming'], - }, - }, -}; - -const obj2 = { - user: { - name: 'John', - details: { - age: 30, - hobbies: ['reading', 'gaming'], - }, - }, -}; - -isEqual(obj1, obj2); // true -``` - -#### 参数 - -- `a` (`unknown`): 要比较的第一个值。 -- `b` (`unknown`): 要比较的第二个值。 - -#### 返回值 - -(`boolean`): 如果两个值相等则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isEqualWith.md b/docs/zh_hans/reference/compat/predicate/isEqualWith.md deleted file mode 100644 index 38e93c859..000000000 --- a/docs/zh_hans/reference/compat/predicate/isEqualWith.md +++ /dev/null @@ -1,92 +0,0 @@ -# isEqualWith (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [isEqualWith](../../predicate/isEqualWith.md) -这个 `isEqualWith` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 - -建议使用更快、更现代的 `es-toolkit` 的 [isEqualWith](../../predicate/isEqualWith.md)。 -::: - -使用自定义比较函数检查两个值是否相等。 - -```typescript -const result = isEqualWith(a, b, customizer); -``` - -## 用法 - -### `isEqualWith(a, b, areValuesEqual?)` - -使用自定义比较函数深度比较两个值。如果自定义函数返回布尔值,则使用该结果;如果返回 `undefined`,则使用默认相等性比较。 - -自定义比较函数也会用于比较对象、数组、Map、Set 等复杂结构内部的值,确保深度比较。 - -```typescript -import { isEqualWith } from 'es-toolkit/compat'; - -// 忽略大小写的字符串比较 -const customizer = (a: any, b: any) => { - if (typeof a === 'string' && typeof b === 'string') { - return a.toLowerCase() === b.toLowerCase(); - } -}; - -isEqualWith('Hello', 'hello', customizer); // true -isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true - -// 按绝对值比较数字 -const absCustomizer = (a: any, b: any) => { - if (typeof a === 'number' && typeof b === 'number') { - return Math.abs(a) === Math.abs(b); - } -}; - -isEqualWith([-1, 2], [1, -2], absCustomizer); // true - -// 复杂对象比较 -const obj1 = { - name: 'JOHN', - details: { age: 30, city: 'NYC' }, -}; -const obj2 = { - name: 'john', - details: { age: 30, city: 'nyc' }, -}; - -isEqualWith(obj1, obj2, customizer); // true -``` - -对 Map 和 Set 进行特殊处理。 - -```typescript -import { isEqualWith } from 'es-toolkit/compat'; - -const customizer = (a: any, b: any) => { - if (typeof a === 'string' && typeof b === 'string') { - return a.toLowerCase() === b.toLowerCase(); - } -}; - -const map1 = new Map([['KEY', 'value']]); -const map2 = new Map([['key', 'value']]); -isEqualWith(map1, map2, customizer); // true - -const set1 = new Set(['HELLO']); -const set2 = new Set(['hello']); -isEqualWith(set1, set2, customizer); // true -``` - -#### 参数 - -- `a` (`any`): 要比较的第一个值。 -- `b` (`any`): 要比较的第二个值。 -- `areValuesEqual` (`(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void`): 自定义比较函数。 - - `x`: 来自第一个对象 `a` 的值 - - `y`: 来自第二个对象 `b` 的值 - - `property`: 获取 `x` 和 `y` 时使用的属性键 - - `xParent`: 第一个值 `x` 的父对象 - - `yParent`: 第二个值 `y` 的父对象 - - `stack`: 处理循环引用的内部栈 (Map) - -#### 返回值 - -(`boolean`): 根据自定义函数,如果两个值相等则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isError.md b/docs/zh_hans/reference/compat/predicate/isError.md deleted file mode 100644 index e505600ac..000000000 --- a/docs/zh_hans/reference/compat/predicate/isError.md +++ /dev/null @@ -1,47 +0,0 @@ -# isError (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [isError](../../predicate/isError.md) -这个 `isError` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 - -建议使用更快、更现代的 `es-toolkit` 的 [isError](../../predicate/isError.md)。 -::: - -检查值是否为 Error 对象。 - -```typescript -const result = isError(value); -``` - -## 用法 - -### `isError(value)` - -当需要类型安全地检查值是否为 Error 对象时使用 `isError`。在 TypeScript 中它也可以作为类型守卫使用。 - -```typescript -import { isError } from 'es-toolkit/compat'; - -// 检查 Error 对象 -isError(new Error()); // true -isError(new TypeError('Type error')); // true -isError(new ReferenceError('Reference error')); // true - -// 继承 Error 的自定义错误 -class CustomError extends Error {} -isError(new CustomError()); // true - -// 其他类型返回 false -isError('Error'); // false -isError({ name: 'Error', message: 'Something went wrong' }); // false -isError({}); // false -isError(null); // false -isError(undefined); // false -``` - -#### 参数 - -- `value` (`unknown`): 要检查是否为 Error 对象的值。 - -#### 返回值 - -(`value is Error`): 如果值是 Error 对象则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isFunction.md b/docs/zh_hans/reference/compat/predicate/isFunction.md deleted file mode 100644 index 29737e876..000000000 --- a/docs/zh_hans/reference/compat/predicate/isFunction.md +++ /dev/null @@ -1,52 +0,0 @@ -# isFunction (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [isFunction](../../predicate/isFunction.md) -这个 `isFunction` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 - -建议使用更快、更现代的 `es-toolkit` 的 [isFunction](../../predicate/isFunction.md)。 -::: - -检查值是否为函数。 - -```typescript -const result = isFunction(value); -``` - -## 用法 - -### `isFunction(value)` - -当需要类型安全地检查值是否为函数时使用 `isFunction`。在 TypeScript 中它也可以作为类型守卫使用。 - -```typescript -import { isFunction } from 'es-toolkit/compat'; - -// 普通函数 -isFunction(function () {}); // true -isFunction(() => {}); // true - -// 内置函数和构造函数 -isFunction(Array.prototype.slice); // true -isFunction(Proxy); // true -isFunction(Int8Array); // true - -// 异步函数和生成器函数 -isFunction(async function () {}); // true -isFunction(function* () {}); // true - -// 其他类型返回 false -isFunction('function'); // false -isFunction({}); // false -isFunction([]); // false -isFunction(null); // false -isFunction(undefined); // false -isFunction(123); // false -``` - -#### 参数 - -- `value` (`unknown`): 要检查是否为函数的值。 - -#### 返回值 - -(`value is (...args: any[]) => any`): 如果值是函数则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isLength.md b/docs/zh_hans/reference/compat/predicate/isLength.md deleted file mode 100644 index 7d4a4e52a..000000000 --- a/docs/zh_hans/reference/compat/predicate/isLength.md +++ /dev/null @@ -1,63 +0,0 @@ -# isLength (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [isLength](../../predicate/isLength.md) -这个 `isLength` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 - -建议使用更快、更现代的 `es-toolkit` 的 [isLength](../../predicate/isLength.md)。 -::: - -检查值是否为有效长度。 - -```typescript -const result = isLength(value); -``` - -## 用法 - -### `isLength(value)` - -当需要检查值是否为有效长度时使用 `isLength`。有效长度必须是数字类型、非负整数,且不超过 JavaScript 的最大安全整数(`Number.MAX_SAFE_INTEGER`)。在 TypeScript 中它也可以作为类型守卫使用。 - -```typescript -import { isLength } from 'es-toolkit/compat'; - -// 有效长度 -isLength(0); // true -isLength(42); // true -isLength(100); // true -isLength(Number.MAX_SAFE_INTEGER); // true - -// 无效长度 -isLength(-1); // false (负数) -isLength(1.5); // false (非整数) -isLength(Number.MAX_SAFE_INTEGER + 1); // false (超出安全范围) -isLength('3'); // false (字符串) -isLength(null); // false -isLength(undefined); // false -isLength({}); // false -isLength([]); // false -``` - -在验证数组或字符串的 length 属性是否有效时很有用。 - -```typescript -import { isLength } from 'es-toolkit/compat'; - -function validateArrayLength(arr: any[]) { - if (isLength(arr.length)) { - console.log(`数组长度 ${arr.length} 是有效的`); - return true; - } - return false; -} - -validateArrayLength([1, 2, 3]); // "数组长度 3 是有效的" -``` - -#### 参数 - -- `value` (`any`): 要检查是否为有效长度的值。 - -#### 返回值 - -(`boolean`): 如果值是有效长度则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isMap.md b/docs/zh_hans/reference/compat/predicate/isMap.md deleted file mode 100644 index 5fd45f863..000000000 --- a/docs/zh_hans/reference/compat/predicate/isMap.md +++ /dev/null @@ -1,63 +0,0 @@ -# isMap (Lodash 兼容性) - -::: warning 请使用 es-toolkit 的 [isMap](../../predicate/isMap.md) - -这个 `isMap` 函数由于 Lodash 兼容性的复杂处理而性能较慢。 - -建议使用更快、更现代的 `es-toolkit` 的 [isMap](../../predicate/isMap.md)。 - -::: - -检查值是否为 Map。 - -```typescript -const result = isMap(value); -``` - -## 用法 - -### `isMap(value)` - -当需要类型安全地检查值是否为 Map 时使用 `isMap`。在 TypeScript 中它也可以作为类型守卫使用。 - -```typescript -import { isMap } from 'es-toolkit/compat'; - -// 检查 Map -const map = new Map(); -isMap(map); // true - -// 其他类型返回 false -isMap(new Set()); // false -isMap(new WeakMap()); // false -isMap({}); // false -isMap([]); // false -isMap('map'); // false -isMap(123); // false -isMap(null); // false -isMap(undefined); // false -``` - -它也可以区分 Map 和其他类似的集合。 - -```typescript -import { isMap } from 'es-toolkit/compat'; - -// Map vs Set vs WeakMap -isMap(new Map([['key', 'value']])); // true -isMap(new Set(['value'])); // false -isMap(new WeakMap()); // false - -// Map vs 普通对象 -isMap({}); // false -isMap({ key: 'value' }); // false -isMap(Object.create(null)); // false -``` - -#### 参数 - -- `value` (`unknown`): 要检查是否为 Map 的值。 - -#### 返回值 - -(`value is Map`): 如果值是 Map 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isNil.md b/docs/zh_hans/reference/compat/predicate/isNil.md deleted file mode 100644 index 3e1acf16c..000000000 --- a/docs/zh_hans/reference/compat/predicate/isNil.md +++ /dev/null @@ -1,60 +0,0 @@ -# isNil (Lodash 兼容性) - -::: warning 使用 es-toolkit 的 [isNil](../../predicate/isNil.md) -这个 `isNil` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 - -请使用更快且现代的 es-toolkit 的 [isNil](../../predicate/isNil.md)。 -::: - -检查值是否为 `null` 或 `undefined`。 - -```typescript -const result = isNil(value); -``` - -## 用法 - -### `isNil(x)` - -当您想类型安全地检查值是否为 `null` 或 `undefined` 时使用 `isNil`。在 TypeScript 中也可以作为类型守卫使用。 - -```typescript -import { isNil } from 'es-toolkit/compat'; - -// null 和 undefined 返回 true -isNil(null); // true -isNil(undefined); // true - -// 所有其他值返回 false -isNil(0); // false -isNil(''); // false -isNil(false); // false -isNil([]); // false -isNil({}); // false -isNil('hello'); // false -isNil(42); // false -``` - -与被认为是假值但不是 `null` 或 `undefined` 的值进行区分。 - -```typescript -import { isNil } from 'es-toolkit/compat'; - -// 被认为是假值但不是 null/undefined 的值 -isNil(0); // false -isNil(''); // false -isNil(false); // false -isNil(NaN); // false - -// 只有 null 和 undefined 返回 true -isNil(null); // true -isNil(undefined); // true -``` - -#### 参数 - -- `x` (`any`): 要检查是否为 `null` 或 `undefined` 的值。 - -#### 返回值 - -(`x is null | undefined`): 如果值为 `null` 或 `undefined` 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isNull.md b/docs/zh_hans/reference/compat/predicate/isNull.md deleted file mode 100644 index 6066f7fd3..000000000 --- a/docs/zh_hans/reference/compat/predicate/isNull.md +++ /dev/null @@ -1,66 +0,0 @@ -# isNull (Lodash 兼容性) - -::: warning 使用 es-toolkit 的 [isNull](../../predicate/isNull.md) -这个 `isNull` 函数是 Lodash 兼容性的函数,但与主库具有相同的实现。 - -请使用更快且现代的 es-toolkit 的 [isNull](../../predicate/isNull.md)。 -::: - -检查值是否为 `null`。 - -```typescript -const result = isNull(value); -``` - -## 用法 - -### `isNull(value)` - -当您想类型安全地检查值是否恰好为 `null` 时使用 `isNull`。在 TypeScript 中也可以作为类型守卫使用。 - -```typescript -import { isNull } from 'es-toolkit/compat'; - -// 只有 null 返回 true -isNull(null); // true - -// undefined 也返回 false -isNull(undefined); // false - -// 所有其他值也返回 false -isNull(0); // false -isNull(''); // false -isNull(false); // false -isNull([]); // false -isNull({}); // false -isNull('null'); // false -isNull(NaN); // false -``` - -可以区分检查 `null` 和 `undefined`。 - -```typescript -import { isNull } from 'es-toolkit/compat'; - -function handleValue(value: string | null | undefined) { - if (isNull(value)) { - console.log('值明确为 null'); - } else if (value === undefined) { - console.log('值为 undefined'); - } else { - console.log(`有值: ${value}`); - } -} - -handleValue(null); // "值明确为 null" -handleValue(undefined); // "值为 undefined" -handleValue('hello'); // "有值: hello" -``` - -#### 参数 - -- `value` (`any`): 要检查是否为 `null` 的值。 - -#### 返回值 - -(`value is null`): 如果值为 `null` 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isPlainObject.md b/docs/zh_hans/reference/compat/predicate/isPlainObject.md deleted file mode 100644 index 0e3a2cbdf..000000000 --- a/docs/zh_hans/reference/compat/predicate/isPlainObject.md +++ /dev/null @@ -1,83 +0,0 @@ -# isPlainObject (Lodash 兼容性) - -::: warning 使用 es-toolkit 的 [isPlainObject](../../predicate/isPlainObject.md) -这个 `isPlainObject` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 - -请使用更快且现代的 es-toolkit 的 [isPlainObject](../../predicate/isPlainObject.md)。 -::: - -检查值是否为纯对象。 - -```typescript -const result = isPlainObject(object); -``` - -## 用法 - -### `isPlainObject(object)` - -当您想检查值是否为纯对象时使用 `isPlainObject`。纯对象是通过 `{}` 字面量、`new Object()` 或 `Object.create(null)` 创建的对象。在 TypeScript 中也可以作为类型守卫使用。 - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -// 纯对象 -isPlainObject({}); // true -isPlainObject(new Object()); // true -isPlainObject(Object.create(null)); // true -isPlainObject({ name: 'John', age: 30 }); // true - -// 不是纯对象的值 -isPlainObject([]); // false (数组) -isPlainObject(new Date()); // false (Date 实例) -isPlainObject(new Map()); // false (Map 实例) -isPlainObject(new Set()); // false (Set 实例) -isPlainObject(/regex/); // false (正则表达式) -isPlainObject(function () {}); // false (函数) -isPlainObject(null); // false -isPlainObject(undefined); // false -isPlainObject('object'); // false (字符串) -isPlainObject(42); // false (数字) -``` - -区分类实例和纯对象。 - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -class Person { - name: string; - constructor(name: string) { - this.name = name; - } -} - -const person = new Person('John'); -const plainObj = { name: 'John' }; - -isPlainObject(person); // false (类实例) -isPlainObject(plainObj); // true (纯对象) -``` - -正确处理自定义 `Symbol.toStringTag` 属性。 - -```typescript -import { isPlainObject } from 'es-toolkit/compat'; - -// 可写的 Symbol.toStringTag -const obj1 = {}; -obj1[Symbol.toStringTag] = 'CustomObject'; -isPlainObject(obj1); // true - -// 只读的 Symbol.toStringTag (内置对象) -const date = new Date(); -isPlainObject(date); // false -``` - -#### 参数 - -- `object` (`any`): 要检查是否为纯对象的值。 - -#### 返回值 - -(`boolean`): 如果值为纯对象则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isRegExp.md b/docs/zh_hans/reference/compat/predicate/isRegExp.md deleted file mode 100644 index facaad45c..000000000 --- a/docs/zh_hans/reference/compat/predicate/isRegExp.md +++ /dev/null @@ -1,80 +0,0 @@ -# isRegExp (Lodash 兼容性) - -::: warning 使用 es-toolkit 的 [isRegExp](../../predicate/isRegExp.md) -这个 `isRegExp` 函数是 Lodash 兼容性的函数,但是简单的类型检查。 - -请使用更快且现代的 es-toolkit 的 [isRegExp](../../predicate/isRegExp.md)。 -::: - -检查值是否为正则表达式。 - -```typescript -const result = isRegExp(value); -``` - -## 用法 - -### `isRegExp(value)` - -当您想类型安全地检查值是否为正则表达式时使用 `isRegExp`。在 TypeScript 中也可以作为类型守卫使用。 - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// 正则表达式 -isRegExp(/abc/); // true -isRegExp(new RegExp('abc')); // true -isRegExp(/[a-z]+/g); // true -isRegExp(/pattern/gi); // true - -// 其他类型返回 false -isRegExp('/abc/'); // false (字符串) -isRegExp('pattern'); // false (字符串) -isRegExp({}); // false (对象) -isRegExp([]); // false (数组) -isRegExp(null); // false -isRegExp(undefined); // false -isRegExp(123); // false (数字) -``` - -区分正则表达式字符串和实际正则表达式对象。 - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// 正则表达式 vs 正则表达式字符串 -isRegExp(/test/); // true -isRegExp('/test/'); // false -isRegExp('\\d+'); // false -isRegExp('/\\d+/g'); // false - -// 各种正则表达式标志 -isRegExp(/test/i); // true (忽略大小写) -isRegExp(/test/g); // true (全局搜索) -isRegExp(/test/m); // true (多行) -isRegExp(/test/gim); // true (所有标志组合) -``` - -也识别动态创建的正则表达式。 - -```typescript -import { isRegExp } from 'es-toolkit/compat'; - -// 通过 RegExp 构造函数创建的正则表达式 -const dynamicRegex = new RegExp('\\d{3}-\\d{4}', 'g'); -isRegExp(dynamicRegex); // true - -// 通过字符串创建的正则表达式 -const pattern = 'hello'; -const flags = 'gi'; -const regex = new RegExp(pattern, flags); -isRegExp(regex); // true -``` - -#### 参数 - -- `value` (`any`): 要检查是否为正则表达式的值。 - -#### 返回值 - -(`value is RegExp`): 如果值为正则表达式则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isSet.md b/docs/zh_hans/reference/compat/predicate/isSet.md deleted file mode 100644 index bc2747cb0..000000000 --- a/docs/zh_hans/reference/compat/predicate/isSet.md +++ /dev/null @@ -1,65 +0,0 @@ -# isSet (Lodash 兼容性) - -::: warning 使用 `es-toolkit` 的 [isSet](../../predicate/isSet.md) -这个 `isSet` 函数是 Lodash 兼容性的函数,但与主库具有相同的实现。 - -请使用更快且现代的 `es-toolkit` 的 [isSet](../../predicate/isSet.md)。 -::: - -检查值是否为 Set。 - -```typescript -const result = isSet(value); -``` - -## 用法 - -### `isSet(value)` - -当您想类型安全地检查值是否为 Set 时使用 `isSet`。在 TypeScript 中也可以作为类型守卫使用。 - -```typescript -import { isSet } from 'es-toolkit/compat'; - -// Set 检查 -const set = new Set(); -isSet(set); // true - -// 其他类型返回 false -isSet(new Map()); // false -isSet(new WeakSet()); // false -isSet([]); // false -isSet({}); // false -isSet('set'); // false -isSet(123); // false -isSet(null); // false -isSet(undefined); // false -``` - -也与其他类似 Set 的集合进行区分。 - -```typescript -import { isSet } from 'es-toolkit/compat'; - -// Set vs Map vs WeakSet -isSet(new Set([1, 2, 3])); // true -isSet(new Map([['key', 'value']])); // false -isSet(new WeakSet()); // false - -// Set vs 数组 -isSet(new Set([1, 2, 3])); // true -isSet([1, 2, 3]); // false - -// Set vs 普通对象 -isSet(new Set()); // true -isSet({}); // false -isSet(Object.create(null)); // false -``` - -#### 参数 - -- `value` (`unknown`): 要检查是否为 Set 的值。 - -#### 返回值 - -(`value is Set`): 如果值为 Set 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/predicate/isUndefined.md b/docs/zh_hans/reference/compat/predicate/isUndefined.md deleted file mode 100644 index b7c634f72..000000000 --- a/docs/zh_hans/reference/compat/predicate/isUndefined.md +++ /dev/null @@ -1,90 +0,0 @@ -# isUndefined (Lodash 兼容性) - -::: warning 使用 es-toolkit 的 [isUndefined](../../predicate/isUndefined.md) -这个 `isUndefined` 函数由于 Lodash 兼容性的复杂处理而运行较慢。 - -请使用更快且现代的 es-toolkit 的 [isUndefined](../../predicate/isUndefined.md)。 -::: - -检查值是否为 `undefined`。 - -```typescript -const result = isUndefined(value); -``` - -## 用法 - -### `isUndefined(x)` - -当您想类型安全地检查值是否恰好为 `undefined` 时使用 `isUndefined`。在 TypeScript 中也可以作为类型守卫使用。 - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -// 只有 undefined 返回 true -isUndefined(undefined); // true - -// null 也返回 false -isUndefined(null); // false - -// 所有其他值也返回 false -isUndefined(0); // false -isUndefined(''); // false -isUndefined(false); // false -isUndefined([]); // false -isUndefined({}); // false -isUndefined('undefined'); // false -isUndefined(NaN); // false -``` - -可以区分检查 `undefined` 和 `null`。 - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -function handleValue(value: string | null | undefined) { - if (isUndefined(value)) { - console.log('值为 undefined'); - } else if (value === null) { - console.log('值明确为 null'); - } else { - console.log(`有值: ${value}`); - } -} - -handleValue(undefined); // "值为 undefined" -handleValue(null); // "值明确为 null" -handleValue('hello'); // "有值: hello" -``` - -在检查未声明的变量或未初始化的属性时很有用。 - -```typescript -import { isUndefined } from 'es-toolkit/compat'; - -const obj: { name?: string; age?: number } = { name: 'John' }; - -if (isUndefined(obj.age)) { - console.log('年龄未设置'); - obj.age = 25; // 设置默认值 -} - -// 函数参数的默认值处理 -function greet(name: string, title?: string) { - if (isUndefined(title)) { - title = '先生/女士'; - } - console.log(`您好,${name}${title}!`); -} - -greet('张三'); // "您好,张三先生/女士!" -greet('张三', '老师'); // "您好,张三老师!" -``` - -#### 参数 - -- `x` (`any`): 要检查是否为 `undefined` 的值。 - -#### 返回值 - -(`x is undefined`): 如果值为 `undefined` 则返回 `true`,否则返回 `false`。 diff --git a/docs/zh_hans/reference/compat/string/camelCase.md b/docs/zh_hans/reference/compat/string/camelCase.md deleted file mode 100644 index 9ace6c3ab..000000000 --- a/docs/zh_hans/reference/compat/string/camelCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# camelCase (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `camelCase` - -由于处理非字符串输入值和删除缩写撇号等原因,此 `camelCase` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [camelCase](../../string/camelCase.md)。 - -::: - -将字符串转换为驼峰命名法。 - -```typescript -const result = camelCase(str); -``` - -## 用法 - -### `camelCase(str)` - -将字符串转换为驼峰命名法。驼峰命名法是一种命名约定,第一个单词以小写字母开头,后续单词的首字母大写,所有单词连接时不带空格。 - -```typescript -import { camelCase } from 'es-toolkit/compat'; - -camelCase('camelCase'); // 'camelCase' -camelCase('some whitespace'); // 'someWhitespace' -camelCase('hyphen-text'); // 'hyphenText' -camelCase('HTTPRequest'); // 'httpRequest' -``` - -非字符串值也会在处理前转换为字符串。 - -```typescript -import { camelCase } from 'es-toolkit/compat'; - -camelCase(123); // '123' -camelCase(null); // '' -camelCase(undefined); // '' -``` - -#### 参数 - -- `str` (`string | object`,可选): 要转换为驼峰命名法的值。 - -#### 返回值 - -(`string`): 返回转换为驼峰命名法的字符串。 diff --git a/docs/zh_hans/reference/compat/string/capitalize.md b/docs/zh_hans/reference/compat/string/capitalize.md deleted file mode 100644 index 4634c54ca..000000000 --- a/docs/zh_hans/reference/compat/string/capitalize.md +++ /dev/null @@ -1,48 +0,0 @@ -# capitalize (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `capitalize` - -由于处理非字符串输入值,此 `capitalize` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [capitalize](../../string/capitalize.md)。 - -::: - -将字符串的第一个字符转换为大写,其余字符转换为小写。 - -```typescript -const result = capitalize(str); -``` - -## 用法 - -### `capitalize(str)` - -将字符串的第一个字符转换为大写,其余字符转换为小写。这对于改善单词的第一印象或将其格式化为标题形式很有用。 - -```typescript -import { capitalize } from 'es-toolkit/compat'; - -capitalize('fred'); // 'Fred' -capitalize('FRED'); // 'Fred' -capitalize('fRED'); // 'Fred' -``` - -空字符串和非字符串值也可以处理。 - -```typescript -import { capitalize } from 'es-toolkit/compat'; - -capitalize(''); // '' -capitalize(123); // '123' -capitalize(null); // '' -capitalize(undefined); // '' -``` - -#### 参数 - -- `str` (`string`,可选): 要首字母大写的字符串。 - -#### 返回值 - -(`string`): 返回首字母大写、其余字母小写的字符串。 diff --git a/docs/zh_hans/reference/compat/string/deburr.md b/docs/zh_hans/reference/compat/string/deburr.md deleted file mode 100644 index 3ae262736..000000000 --- a/docs/zh_hans/reference/compat/string/deburr.md +++ /dev/null @@ -1,47 +0,0 @@ -# deburr (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `deburr` - -由于处理非字符串输入值,此 `deburr` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [deburr](../../string/deburr.md)。 - -::: - -将字符串中的特殊字符和变音符号转换为ASCII字符。 - -```typescript -const result = deburr(str); -``` - -## 用法 - -### `deburr(str)` - -将字符串中的特殊字符和变音符号转换为ASCII字符。这对于使多语言文本更易于搜索或排序很有用。 - -```typescript -import { deburr } from 'es-toolkit/compat'; - -deburr('Æthelred'); // 'Aethelred' -deburr('München'); // 'Munchen' -deburr('Crème brûlée'); // 'Creme brulee' -``` - -非字符串值也会在处理前转换为字符串。 - -```typescript -import { deburr } from 'es-toolkit/compat'; - -deburr(123); // '123' -deburr(null); // '' -deburr(undefined); // '' -``` - -#### 参数 - -- `str` (`string`,可选): 要删除特殊字符的字符串。 - -#### 返回值 - -(`string`): 返回特殊字符和变音符号转换为ASCII字符的字符串。 diff --git a/docs/zh_hans/reference/compat/string/escape.md b/docs/zh_hans/reference/compat/string/escape.md deleted file mode 100644 index 1d1a205dc..000000000 --- a/docs/zh_hans/reference/compat/string/escape.md +++ /dev/null @@ -1,48 +0,0 @@ -# escape (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `escape` - -由于处理非字符串输入值,此 `escape` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [escape](../../string/escape.md)。 - -::: - -将字符串中的HTML特殊字符转换为HTML实体。 - -```typescript -const result = escape(str); -``` - -## 用法 - -### `escape(str)` - -将字符串中的 `&`、`<`、`>`、`"`、`'` 字符转换为相应的HTML实体。这对于在HTML文档中安全插入文本以防止XSS攻击很有用。 - -```typescript -import { escape } from 'es-toolkit/compat'; - -escape('This is a
element.'); // 'This is a <div> element.' -escape('This is a "quote"'); // 'This is a "quote"' -escape("This is a 'quote'"); // 'This is a 'quote'' -escape('This is a & symbol'); // 'This is a & symbol' -``` - -非字符串值也会在处理前转换为字符串。 - -```typescript -import { escape } from 'es-toolkit/compat'; - -escape(123); // '123' -escape(null); // '' -escape(undefined); // '' -``` - -#### 参数 - -- `str` (`string`,可选): 要转义HTML特殊字符的字符串。 - -#### 返回值 - -(`string`): 返回HTML特殊字符转换为实体的字符串。 diff --git a/docs/zh_hans/reference/compat/string/escapeRegExp.md b/docs/zh_hans/reference/compat/string/escapeRegExp.md deleted file mode 100644 index 2a9916492..000000000 --- a/docs/zh_hans/reference/compat/string/escapeRegExp.md +++ /dev/null @@ -1,49 +0,0 @@ -# escapeRegExp (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `escapeRegExp` - -由于处理非字符串输入值,此 `escapeRegExp` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [escapeRegExp](../../string/escapeRegExp.md)。 - -::: - -转义字符串中的正则表达式特殊字符。 - -```typescript -const result = escapeRegExp(str); -``` - -## 用法 - -### `escapeRegExp(str)` - -转义字符串中的正则表达式特殊字符 `^`、`$`、`\`、`.`、`*`、`+`、`?`、`(`、`)`、`[`、`]`、`{`、`}`、`|`。当您想在动态创建正则表达式时将字符串按字面处理时很有用。 - -```typescript -import { escapeRegExp } from 'es-toolkit/compat'; - -escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); -// '\\[es-toolkit\\]\\(https://es-toolkit\\.dev/\\)' - -escapeRegExp('$^{}.+*?()[]|\\'); -// '\\$\\^\\{\\}\\.\\+\\*\\?\\(\\)\\[\\]\\|\\\\' -``` - -非字符串值也会在处理前转换为字符串。 - -```typescript -import { escapeRegExp } from 'es-toolkit/compat'; - -escapeRegExp(123); // '123' -escapeRegExp(null); // '' -escapeRegExp(undefined); // '' -``` - -#### 参数 - -- `str` (`string`,可选): 要转义正则表达式特殊字符的字符串。 - -#### 返回值 - -(`string`): 返回正则表达式特殊字符被转义的字符串。 diff --git a/docs/zh_hans/reference/compat/string/kebabCase.md b/docs/zh_hans/reference/compat/string/kebabCase.md deleted file mode 100644 index f6958981a..000000000 --- a/docs/zh_hans/reference/compat/string/kebabCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# kebabCase (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `kebabCase` - -由于处理非字符串输入值和删除缩写撇号等原因,此 `kebabCase` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [kebabCase](../../string/kebabCase.md)。 - -::: - -将字符串转换为短横线命名法。 - -```typescript -const result = kebabCase(str); -``` - -## 用法 - -### `kebabCase(str)` - -将字符串转换为短横线命名法。短横线命名法是一种命名约定,每个单词以小写字母书写,并用短横线(-)字符连接。它通常用于URL和CSS类名。 - -```typescript -import { kebabCase } from 'es-toolkit/compat'; - -kebabCase('camelCase'); // 'camel-case' -kebabCase('some whitespace'); // 'some-whitespace' -kebabCase('hyphen-text'); // 'hyphen-text' -kebabCase('HTTPRequest'); // 'http-request' -``` - -非字符串值也会在处理前转换为字符串。 - -```typescript -import { kebabCase } from 'es-toolkit/compat'; - -kebabCase(123); // '123' -kebabCase(null); // '' -kebabCase(undefined); // '' -``` - -#### 参数 - -- `str` (`string | object`,可选): 要转换为短横线命名法的值。 - -#### 返回值 - -(`string`): 返回转换为短横线命名法的字符串。 diff --git a/docs/zh_hans/reference/compat/string/lowerCase.md b/docs/zh_hans/reference/compat/string/lowerCase.md deleted file mode 100644 index 80701530e..000000000 --- a/docs/zh_hans/reference/compat/string/lowerCase.md +++ /dev/null @@ -1,48 +0,0 @@ -# lowerCase (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `lowerCase` - -由于处理非字符串输入值和删除缩写撇号等原因,此 `lowerCase` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [lowerCase](../../string/lowerCase.md)。 - -::: - -将字符串转换为小写单词并用空格分隔。 - -```typescript -const result = lowerCase(str); -``` - -## 用法 - -### `lowerCase(str)` - -将字符串转换为小写单词并用空格分隔。每个单词都转换为小写并用空格字符连接。这对于创建人类可读的文本形式很有用。 - -```typescript -import { lowerCase } from 'es-toolkit/compat'; - -lowerCase('camelCase'); // 'camel case' -lowerCase('some whitespace'); // 'some whitespace' -lowerCase('hyphen-text'); // 'hyphen text' -lowerCase('HTTPRequest'); // 'http request' -``` - -非字符串值也会在处理前转换为字符串。 - -```typescript -import { lowerCase } from 'es-toolkit/compat'; - -lowerCase(123); // '123' -lowerCase(null); // '' -lowerCase(undefined); // '' -``` - -#### 参数 - -- `str` (`string | object`,可选): 要转换为小写格式的值。 - -#### 返回值 - -(`string`): 返回小写单词用空格分隔的字符串。 diff --git a/docs/zh_hans/reference/compat/string/lowerFirst.md b/docs/zh_hans/reference/compat/string/lowerFirst.md deleted file mode 100644 index b66cc170e..000000000 --- a/docs/zh_hans/reference/compat/string/lowerFirst.md +++ /dev/null @@ -1,48 +0,0 @@ -# lowerFirst (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `lowerFirst` - -由于处理非字符串输入值,此 `lowerFirst` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [lowerFirst](../../string/lowerFirst.md)。 - -::: - -将字符串的第一个字符转换为小写。 - -```typescript -const result = lowerFirst(str); -``` - -## 用法 - -### `lowerFirst(str)` - -将字符串的第一个字符转换为小写。其余字符保持不变。这对于创建驼峰命名变量名或只想将第一个字符小写时很有用。 - -```typescript -import { lowerFirst } from 'es-toolkit/compat'; - -lowerFirst('fred'); // 'fred' -lowerFirst('Fred'); // 'fred' -lowerFirst('FRED'); // 'fRED' -lowerFirst(''); // '' -``` - -非字符串值也会在处理前转换为字符串。 - -```typescript -import { lowerFirst } from 'es-toolkit/compat'; - -lowerFirst(123); // '123' -lowerFirst(null); // '' -lowerFirst(undefined); // '' -``` - -#### 参数 - -- `str` (`string`,可选): 要将首字母转换为小写的字符串。 - -#### 返回值 - -(`string`): 返回首字母转换为小写的字符串。 diff --git a/docs/zh_hans/reference/compat/string/pad.md b/docs/zh_hans/reference/compat/string/pad.md deleted file mode 100644 index 41091d086..000000000 --- a/docs/zh_hans/reference/compat/string/pad.md +++ /dev/null @@ -1,60 +0,0 @@ -# pad (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `pad` - -由于处理 `null` 或 `undefined` 等原因,此 `pad` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [pad](../../string/pad.md)。 - -::: - -在字符串的两侧添加填充字符以达到指定的长度。 - -```typescript -const padded = pad(str, length, chars); -``` - -## 用法 - -### `pad(str, length, chars)` - -当您想在字符串两侧添加填充以匹配所需长度时,请使用 `pad`。如果填充字符不能均匀分配,额外的字符将放在右侧。 - -```typescript -import { pad } from 'es-toolkit/compat'; - -// 用默认空格填充 -pad('abc', 8); -// Returns: ' abc ' - -// 用指定字符填充 -pad('abc', 8, '_-'); -// Returns: '_-abc_-_' - -// 如果已经足够长则原样返回 -pad('abc', 3); -// Returns: 'abc' - -// 如果长度更短则原样返回 -pad('abc', 2); -// Returns: 'abc' -``` - -`null` 或 `undefined` 被视为空字符串。 - -```typescript -import { pad } from 'es-toolkit/compat'; - -pad(null, 5); // ' ' -pad(undefined, 3, '*'); // '***' -``` - -#### 参数 - -- `str` (`string`,可选): 要填充的字符串。 -- `length` (`number`,可选): 目标长度。默认为 `0`。 -- `chars` (`string`,可选): 用于填充的字符。默认为空格 `' '`。 - -#### 返回值 - -(`string`): 返回填充到指定长度的字符串。 diff --git a/docs/zh_hans/reference/compat/string/snakeCase.md b/docs/zh_hans/reference/compat/string/snakeCase.md deleted file mode 100644 index 2a8a555de..000000000 --- a/docs/zh_hans/reference/compat/string/snakeCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# snakeCase (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `snakeCase` - -此 `snakeCase` 函数由于处理 `null` 或 `undefined` 的规范化逻辑而运行缓慢。 - -请改用更快、更现代的 `es-toolkit` 的 [snakeCase](../../string/snakeCase.md)。 - -::: - -将字符串转换为蛇形命名法。 - -```typescript -const snakeCased = snakeCase(str); -``` - -## 用法 - -### `snakeCase(str)` - -当您想将字符串转换为蛇形命名法 (snake*case) 时,请使用 `snakeCase`。蛇形命名法是一种命名约定,其中每个单词都以小写字母书写,并用下划线 (*) 连接。 - -```typescript -import { snakeCase } from 'es-toolkit/compat'; - -// 转换驼峰命名法 -snakeCase('camelCase'); -// Returns: 'camel_case' - -// 转换空格分隔的字符串 -snakeCase('some whitespace'); -// Returns: 'some_whitespace' - -// 转换连字符分隔的字符串 -snakeCase('hyphen-text'); -// Returns: 'hyphen_text' - -// 处理连续大写字母 -snakeCase('HTTPRequest'); -// Returns: 'http_request' -``` - -`null` 或 `undefined` 被视为空字符串。 - -```typescript -import { snakeCase } from 'es-toolkit/compat'; - -snakeCase(null); // '' -snakeCase(undefined); // '' -``` - -#### 参数 - -- `str` (`string`, 可选): 要转换为蛇形命名法的字符串。 - -#### 返回值 - -(`string`): 返回转换为蛇形命名法的字符串。 diff --git a/docs/zh_hans/reference/compat/string/startCase.md b/docs/zh_hans/reference/compat/string/startCase.md deleted file mode 100644 index abde5d593..000000000 --- a/docs/zh_hans/reference/compat/string/startCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# startCase (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `startCase` - -由于处理 `null` 或 `undefined` 的规范化逻辑,此 `startCase` 函数运行速度较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [startCase](../../string/startCase.md)。 - -::: - -将字符串转换为 start case。 - -```typescript -const startCased = startCase(str); -``` - -## 用法 - -### `startCase(str)` - -当您想将字符串转换为 Start Case 时,请使用 `startCase`。Start Case 是一种命名约定,每个单词的首字母大写并用空格分隔。 - -```typescript -import { startCase } from 'es-toolkit/compat'; - -// 转换普通字符串 -startCase('hello world'); -// 返回值: 'Hello World' - -// 已经大写的单词保持不变 -startCase('HELLO WORLD'); -// 返回值: 'HELLO WORLD' - -// 转换连字符分隔的字符串 -startCase('hello-world'); -// 返回值: 'Hello World' - -// 转换下划线分隔的字符串 -startCase('hello_world'); -// 返回值: 'Hello World' -``` - -`null` 或 `undefined` 被视为空字符串。 - -```typescript -import { startCase } from 'es-toolkit/compat'; - -startCase(null); // '' -startCase(undefined); // '' -``` - -#### 参数 - -- `str` (`string`, 可选): 要转换为 start case 的字符串。 - -#### 返回值 - -(`string`): 返回转换为 start case 的字符串。 diff --git a/docs/zh_hans/reference/compat/string/trim.md b/docs/zh_hans/reference/compat/string/trim.md deleted file mode 100644 index 84b2fb421..000000000 --- a/docs/zh_hans/reference/compat/string/trim.md +++ /dev/null @@ -1,55 +0,0 @@ -# trim (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `trim` - -由于需要处理 `null` 或 `undefined` 以及数组类型的 `chars`,此 `trim` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [trim](../../string/trim.md)。 - -::: - -移除字符串开头和结尾的空格或指定字符。 - -```typescript -const trimmed = trim(str, chars); -``` - -## 用法 - -### `trim(str, chars)` - -当您想要移除字符串开头和结尾的空格或特定字符时,请使用 `trim`。如果未指定 `chars`,则只移除开头和结尾的空格。 - -```typescript -import { trim } from 'es-toolkit/compat'; - -// 移除开头和结尾的空格 -trim(' hello '); -// 返回: 'hello' - -// 移除指定字符 -trim('--hello--', '-'); -// 返回: 'hello' - -// 使用数组移除多个字符 -trim('##hello##', ['#', 'o']); -// 返回: 'hell' -``` - -`null` 或 `undefined` 被视为空字符串。 - -```typescript -import { trim } from 'es-toolkit/compat'; - -trim(null); // '' -trim(undefined); // '' -``` - -#### 参数 - -- `str` (`string`, 可选): 要修剪的字符串。 -- `chars` (`string`, 可选): 要移除的字符。如果未指定,将移除空格。 - -#### 返回值 - -(`string`): 返回从开头和结尾移除指定字符后的字符串。 diff --git a/docs/zh_hans/reference/compat/string/trimEnd.md b/docs/zh_hans/reference/compat/string/trimEnd.md deleted file mode 100644 index adafcc0bd..000000000 --- a/docs/zh_hans/reference/compat/string/trimEnd.md +++ /dev/null @@ -1,55 +0,0 @@ -# trimEnd (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `trimEnd` - -由于需要处理 `null` 或 `undefined` 以及参数顺序变更,此 `trimEnd` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [trimEnd](../../string/trimEnd.md)。 - -::: - -移除字符串结尾的空格或指定字符。 - -```typescript -const trimmed = trimEnd(str, chars); -``` - -## 用法 - -### `trimEnd(str, chars)` - -当您想要移除字符串结尾的空格或特定字符时,请使用 `trimEnd`。如果未指定 `chars`,则只移除结尾的空格。 - -```typescript -import { trimEnd } from 'es-toolkit/compat'; - -// 移除结尾的空格 -trimEnd(' abc '); -// 返回: ' abc' - -// 移除指定字符 -trimEnd('-_-abc-_-', '_-'); -// 返回: '-_-abc' - -// 仅应用于字符串结尾 -trimEnd('abc', 'a'); -// 返回: 'abc' -``` - -`null` 或 `undefined` 被视为空字符串。 - -```typescript -import { trimEnd } from 'es-toolkit/compat'; - -trimEnd(null); // '' -trimEnd(undefined); // '' -``` - -#### 参数 - -- `str` (`string`, 可选): 要从结尾修剪的字符串。 -- `chars` (`string`, 可选): 要移除的字符。如果未指定,将移除空格。 - -#### 返回值 - -(`string`): 返回从结尾移除指定字符后的字符串。 diff --git a/docs/zh_hans/reference/compat/string/trimStart.md b/docs/zh_hans/reference/compat/string/trimStart.md deleted file mode 100644 index f1e54beee..000000000 --- a/docs/zh_hans/reference/compat/string/trimStart.md +++ /dev/null @@ -1,55 +0,0 @@ -# trimStart (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `trimStart` - -由于需要处理 `null` 或 `undefined` 以及参数顺序变更,此 `trimStart` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [trimStart](../../string/trimStart.md)。 - -::: - -移除字符串开头的空格或指定字符。 - -```typescript -const trimmed = trimStart(str, chars); -``` - -## 用法 - -### `trimStart(str, chars)` - -当您想要移除字符串开头的空格或特定字符时,请使用 `trimStart`。如果未指定 `chars`,则只移除开头的空格。 - -```typescript -import { trimStart } from 'es-toolkit/compat'; - -// 移除开头的空格 -trimStart(' abc '); -// 返回: 'abc ' - -// 移除指定字符 -trimStart('-_-abc-_-', '_-'); -// 返回: 'abc-_-' - -// 仅应用于字符串开头 -trimStart('abc', 'c'); -// 返回: 'abc' -``` - -`null` 或 `undefined` 被视为空字符串。 - -```typescript -import { trimStart } from 'es-toolkit/compat'; - -trimStart(null); // '' -trimStart(undefined); // '' -``` - -#### 参数 - -- `str` (`string`, 可选): 要从开头修剪的字符串。 -- `chars` (`string`, 可选): 要移除的字符。如果未指定,将移除空格。 - -#### 返回值 - -(`string`): 返回从开头移除指定字符后的字符串。 diff --git a/docs/zh_hans/reference/compat/string/unescape.md b/docs/zh_hans/reference/compat/string/unescape.md deleted file mode 100644 index 0579739d1..000000000 --- a/docs/zh_hans/reference/compat/string/unescape.md +++ /dev/null @@ -1,58 +0,0 @@ -# unescape (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `unescape` - -由于需要处理 `null` 或 `undefined` 的转换逻辑,此 `unescape` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [unescape](../../string/unescape.md)。 - -::: - -将 HTML 实体转换为原始字符。 - -```typescript -const unescaped = unescape(str); -``` - -## 用法 - -### `unescape(str)` - -当您想要将 HTML 实体 `&`、`<`、`>`、`"`、`'` 转换回原始字符时,请使用 `unescape`。这是 `escape` 函数的反向操作。 - -```typescript -import { unescape } from 'es-toolkit/compat'; - -// 反转义 HTML 标签 -unescape('This is a <div> element.'); -// 返回: 'This is a
element.' - -// 反转义引号 -unescape('This is a "quote"'); -// 返回: 'This is a "quote"' - -// 反转义撇号 -unescape('This is a 'quote''); -// 返回: 'This is a 'quote'' - -// 反转义 & 符号 -unescape('This is a & symbol'); -// 返回: 'This is a & symbol' -``` - -`null` 或 `undefined` 被视为空字符串。 - -```typescript -import { unescape } from 'es-toolkit/compat'; - -unescape(null); // '' -unescape(undefined); // '' -``` - -#### 参数 - -- `str` (`string`, 可选): 要反转义的字符串。 - -#### 返回值 - -(`string`): 返回将 HTML 实体转换为原始字符后的字符串。 diff --git a/docs/zh_hans/reference/compat/string/upperCase.md b/docs/zh_hans/reference/compat/string/upperCase.md deleted file mode 100644 index 74059290c..000000000 --- a/docs/zh_hans/reference/compat/string/upperCase.md +++ /dev/null @@ -1,58 +0,0 @@ -# upperCase (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `upperCase` - -由于需要处理 `null` 或 `undefined` 的规范化逻辑,此 `upperCase` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [upperCase](../../string/upperCase.md)。 - -::: - -将字符串转换为大写形式。 - -```typescript -const upperCased = upperCase(str); -``` - -## 用法 - -### `upperCase(str)` - -当您想要将字符串转换为大写形式 (UPPER CASE) 时,请使用 `upperCase`。大写是一种命名约定,每个单词都用大写字母书写并用空格连接。 - -```typescript -import { upperCase } from 'es-toolkit/compat'; - -// 转换驼峰命名 -upperCase('camelCase'); -// 返回: 'CAMEL CASE' - -// 转换空格分隔的字符串 -upperCase('some whitespace'); -// 返回: 'SOME WHITESPACE' - -// 转换连字符分隔的字符串 -upperCase('hyphen-text'); -// 返回: 'HYPHEN TEXT' - -// 当大写字母连续出现时 -upperCase('HTTPRequest'); -// 返回: 'HTTP REQUEST' -``` - -`null` 或 `undefined` 被视为空字符串。 - -```typescript -import { upperCase } from 'es-toolkit/compat'; - -upperCase(null); // '' -upperCase(undefined); // '' -``` - -#### 参数 - -- `str` (`string`, 可选): 要转换为大写形式的字符串。 - -#### 返回值 - -(`string`): 返回转换为大写形式的字符串。 diff --git a/docs/zh_hans/reference/compat/string/upperFirst.md b/docs/zh_hans/reference/compat/string/upperFirst.md deleted file mode 100644 index 8a303cedf..000000000 --- a/docs/zh_hans/reference/compat/string/upperFirst.md +++ /dev/null @@ -1,54 +0,0 @@ -# upperFirst (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `upperFirst` - -由于需要处理 `null` 或 `undefined` 的转换逻辑,此 `upperFirst` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [upperFirst](../../string/upperFirst.md)。 - -::: - -将字符串的第一个字符转换为大写。 - -```typescript -const upperCased = upperFirst(str); -``` - -## 用法 - -### `upperFirst(str)` - -当您想要仅将字符串的第一个字符大写时,请使用 `upperFirst`。其余字符保持不变。 - -```typescript -import { upperFirst } from 'es-toolkit/compat'; - -// 以小写字母开头的字符串 -upperFirst('fred'); -// 返回: 'Fred' - -// 已经以大写字母开头的字符串 -upperFirst('Fred'); -// 返回: 'Fred' - -// 全大写字符串 -upperFirst('FRED'); -// 返回: 'FRED' -``` - -`null` 或 `undefined` 被视为空字符串。 - -```typescript -import { upperFirst } from 'es-toolkit/compat'; - -upperFirst(null); // '' -upperFirst(undefined); // '' -``` - -#### 参数 - -- `str` (`string`, 可选): 要将第一个字符转换为大写的字符串。 - -#### 返回值 - -(`string`): 返回第一个字符转换为大写后的字符串。 diff --git a/docs/zh_hans/reference/compat/string/words.md b/docs/zh_hans/reference/compat/string/words.md deleted file mode 100644 index 96879be39..000000000 --- a/docs/zh_hans/reference/compat/string/words.md +++ /dev/null @@ -1,69 +0,0 @@ -# words (Lodash 兼容性) - -::: warning 请使用 `es-toolkit` 的 `words` - -由于需要处理 `null` 或 `undefined` 以及复杂的 Unicode 支持,此 `words` 函数运行较慢。 - -请改用更快、更现代的 `es-toolkit` 的 [words](../../string/words.md)。 - -::: - -将字符串拆分为单词数组。 - -```typescript -const wordArray = words(str, pattern); -``` - -## 用法 - -### `words(str, pattern)` - -当您想要将字符串拆分为单词时,请使用 `words`。默认情况下,它会识别英文字母、数字、表情符号等来提取单词。 - -```typescript -import { words } from 'es-toolkit/compat'; - -// 基本单词提取 -words('fred, barney, & pebbles'); -// 返回: ['fred', 'barney', 'pebbles'] - -// 从驼峰命名中提取单词 -words('camelCaseWord'); -// 返回: ['camel', 'Case', 'Word'] - -// 包含数字的字符串 -words('hello123world'); -// 返回: ['hello', '123', 'world'] -``` - -您还可以使用自定义模式提取单词。 - -```typescript -import { words } from 'es-toolkit/compat'; - -// 使用正则表达式提取单词 -words('hello world', /\w+/g); -// 返回: ['hello', 'world'] - -// 使用字符串模式 -words('one-two-three', '-'); -// 返回: ['-'] -``` - -`null` 或 `undefined` 被视为空数组。 - -```typescript -import { words } from 'es-toolkit/compat'; - -words(null); // [] -words(undefined); // [] -``` - -#### 参数 - -- `str` (`string`, 可选): 要拆分为单词的字符串。 -- `pattern` (`RegExp | string`, 可选): 用于匹配单词的模式。默认为内置的 Unicode 单词模式。 - -#### 返回值 - -(`string[]`): 返回提取的单词数组。 diff --git a/yarn.lock b/yarn.lock index 855924a4e..848b6b975 100644 --- a/yarn.lock +++ b/yarn.lock @@ -590,6 +590,17 @@ __metadata: languageName: node linkType: hard +"@babel/parser@npm:^7.29.2": + version: 7.29.2 + resolution: "@babel/parser@npm:7.29.2" + dependencies: + "@babel/types": "npm:^7.29.0" + bin: + parser: ./bin/babel-parser.js + checksum: 10c0/e5a4e69e3ac7acdde995f37cf299a68458cfe7009dff66bd0962fd04920bef287201169006af365af479c08ff216bfefbb595e331f87f6ae7283858aebbc3317 + languageName: node + linkType: hard + "@babel/plugin-syntax-flow@npm:^7.24.7": version: 7.24.7 resolution: "@babel/plugin-syntax-flow@npm:7.24.7" @@ -861,6 +872,16 @@ __metadata: languageName: node linkType: hard +"@babel/types@npm:^7.29.0": + version: 7.29.0 + resolution: "@babel/types@npm:7.29.0" + dependencies: + "@babel/helper-string-parser": "npm:^7.27.1" + "@babel/helper-validator-identifier": "npm:^7.28.5" + checksum: 10c0/23cc3466e83bcbfab8b9bd0edaafdb5d4efdb88b82b3be6728bbade5ba2f0996f84f63b1c5f7a8c0d67efded28300898a5f930b171bb40b311bca2029c4e9b4f + languageName: node + linkType: hard + "@babel/types@npm:^8.0.0-rc.4": version: 8.0.0-rc.4 resolution: "@babel/types@npm:8.0.0-rc.4" @@ -3928,6 +3949,19 @@ __metadata: languageName: node linkType: hard +"@vue/compiler-core@npm:3.5.33": + version: 3.5.33 + resolution: "@vue/compiler-core@npm:3.5.33" + dependencies: + "@babel/parser": "npm:^7.29.2" + "@vue/shared": "npm:3.5.33" + entities: "npm:^7.0.1" + estree-walker: "npm:^2.0.2" + source-map-js: "npm:^1.2.1" + checksum: 10c0/4a7a7c17b8849901a539c7ca1b5a57d8dfe1a3e3886460ec0e7da7f2a9aa894d917bf4d303b8b9b31287a99359f3e26ce8c2734b5799f647b39f1bf0c5683a13 + languageName: node + linkType: hard + "@vue/compiler-dom@npm:3.5.13": version: 3.5.13 resolution: "@vue/compiler-dom@npm:3.5.13" @@ -3948,6 +3982,16 @@ __metadata: languageName: node linkType: hard +"@vue/compiler-dom@npm:3.5.33": + version: 3.5.33 + resolution: "@vue/compiler-dom@npm:3.5.33" + dependencies: + "@vue/compiler-core": "npm:3.5.33" + "@vue/shared": "npm:3.5.33" + checksum: 10c0/ea0114f75e7d1db9e650952cb1227b67b4a11f78b41bb197767fc09cbcc54c9375bd0737f6ba659ab74281a2b233f01fb307ce5138a62373a46c424fa1bc22d5 + languageName: node + linkType: hard + "@vue/compiler-sfc@npm:3.5.26": version: 3.5.26 resolution: "@vue/compiler-sfc@npm:3.5.26" @@ -4002,6 +4046,16 @@ __metadata: languageName: node linkType: hard +"@vue/compiler-ssr@npm:3.5.33": + version: 3.5.33 + resolution: "@vue/compiler-ssr@npm:3.5.33" + dependencies: + "@vue/compiler-dom": "npm:3.5.33" + "@vue/shared": "npm:3.5.33" + checksum: 10c0/9a812813d51765777229a43b8e40166cdfd0f0e4e3af6d2dc8fdd7481ce4e1635cb450d407d4f709d707c8efb962053a454abc532222933116651eb3f5c2878e + languageName: node + linkType: hard + "@vue/devtools-api@npm:^7.7.0": version: 7.7.9 resolution: "@vue/devtools-api@npm:7.7.9" @@ -4066,6 +4120,18 @@ __metadata: languageName: node linkType: hard +"@vue/server-renderer@npm:*": + version: 3.5.33 + resolution: "@vue/server-renderer@npm:3.5.33" + dependencies: + "@vue/compiler-ssr": "npm:3.5.33" + "@vue/shared": "npm:3.5.33" + peerDependencies: + vue: 3.5.33 + checksum: 10c0/c666f09f429878a67e4b7617979cb9430ba002027806b3a2ed2143d7032d5d073eb1ba7d885060f4b13c2902074b2d3bfc9f31f641e8d8adf60350fec36cb2a3 + languageName: node + linkType: hard + "@vue/server-renderer@npm:3.5.26": version: 3.5.26 resolution: "@vue/server-renderer@npm:3.5.26" @@ -4092,6 +4158,13 @@ __metadata: languageName: node linkType: hard +"@vue/shared@npm:3.5.33": + version: 3.5.33 + resolution: "@vue/shared@npm:3.5.33" + checksum: 10c0/c96ec56cf1ff246907ed734f7e61f81e96fccec9944d77ae79421d9d1548ea5be63694e951968b527bdd1dd2c6ab98a05229ee9ae252893051f4802c95c1d3f2 + languageName: node + linkType: hard + "@vueuse/core@npm:12.8.2, @vueuse/core@npm:^12.4.0": version: 12.8.2 resolution: "@vueuse/core@npm:12.8.2" @@ -5884,6 +5957,13 @@ __metadata: languageName: node linkType: hard +"entities@npm:^7.0.1": + version: 7.0.1 + resolution: "entities@npm:7.0.1" + checksum: 10c0/b4fb9937bb47ecb00aaaceb9db9cdd1cc0b0fb649c0e843d05cf5dbbd2e9d2df8f98721d8b1b286445689c72af7b54a7242fc2d63ef7c9739037a8c73363e7ca + languageName: node + linkType: hard + "env-paths@npm:^2.2.0": version: 2.2.1 resolution: "env-paths@npm:2.2.1"