Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🚀 find #153

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/forty-books-mate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@naverpay/hidash": patch
---

🚀 find

PR: [🚀 find](https://github.com/NaverPayDev/hidash/pull/153)
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const moduleMap = {
debounce: './src/debounce.ts',
eq: './src/eq.ts',
every: './src/every.ts',
find: './src/find.ts',
findIndex: './src/findIndex.ts',
findLastIndex: './src/findLastIndex.ts',
first: './src/first.ts',
Expand Down
10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,16 @@
"default": "./every.js"
}
},
"./find": {
"import": {
"types": "./find.d.mts",
"default": "./find.mjs"
},
"require": {
"types": "./find.d.ts",
"default": "./find.js"
}
},
"./findIndex": {
"import": {
"types": "./findIndex.d.mts",
Expand Down
61 changes: 61 additions & 0 deletions src/find.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import _find from 'lodash/find'
import {describe, bench} from 'vitest'

import {find} from './find'

const testCases = [
[[0, 1, 0, 1, 0], (v: number) => v === 1],
[new Array(10000).fill(0).map((_, i) => (i % 1000 === 0 ? 1 : 0)), (v: number) => v === 1],
[
[
{name: {first: 'a', last: 'b'}},
{name: {first: 'c', last: 'd'}},
{name: {first: 'e', last: 'f'}},
{name: {first: 'a', last: 'b'}},
],
{name: {first: 'a'}},
],
[
[
{id: 1, value: 'a'},
{id: 2, value: 'b'},
{id: 3, value: 'c'},
{id: 4, value: 'd'},
],
'value',
],
[
[
{id: 1, value: 'a'},
{id: 2, value: 'b'},
{id: 3, value: 'c'},
{id: 4, value: 'd'},
],
['value', 'b'],
],
// eslint-disable-next-line no-sparse-arrays
[[0, , 1, , , 3], (v: number) => v === 1],
['hello world'.split(''), (v: string) => v === 'o'],
] as const

const ITERATIONS = 1000

describe('find performance', () => {
bench('hidash', () => {
for (let i = 0; i < ITERATIONS; i++) {
testCases.forEach(([array, predicate]) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
find(array, predicate)
})
}
})

bench('lodash', () => {
for (let i = 0; i < ITERATIONS; i++) {
testCases.forEach(([array, predicate]) => {
_find(array, predicate)
})
}
})
})
70 changes: 70 additions & 0 deletions src/find.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import _find from 'lodash/find'
import {describe, it, expect} from 'vitest'

import {find} from './find'

describe('find', () => {
it('should find the first matching element based on the predicate', () => {
const array = [1, 2, 3, 4, 5]

expect(find(array, (x) => x === 10)).toBe(undefined)
expect(find(array, (x) => x === 3)).toBe(_find(array, (x) => x === 3))
expect(find(array, (x) => x > 3)).toBe(_find(array, (x) => x > 3))
expect(find(array, (x) => x === 10)).toBe(_find(array, (x) => x === 10))
})

it('should handle shorthand predicates', () => {
const nestedArray = [{a: 1}, {a: 2}, {a: 3}]

expect(find(nestedArray, {a: 2})).toEqual({a: 2})
expect(find(nestedArray, {a: 10})).toBe(undefined)
expect(find(nestedArray, {a: 2})).toEqual(_find(nestedArray, {a: 2}))
expect(find(nestedArray, {a: 10})).toEqual(_find(nestedArray, {a: 10}))
})

it('should handle array shorthand predicates', () => {
const nestedArray = [{a: 1}, {a: 2}, {a: 3}]

expect(find(nestedArray, ['a', 2])).toEqual({a: 2})
expect(find(nestedArray, ['a', 10])).toBe(undefined)
expect(find(nestedArray, ['a', 2])).toEqual(_find(nestedArray, ['a', 2]))
expect(find(nestedArray, ['a', 10])).toEqual(_find(nestedArray, ['a', 10]))
})

it('should handle string shorthand predicates', () => {
const nestedArray = [{a: 1}, {b: 2}, {a: 3}]

expect(find(nestedArray, 'a')).toEqual(_find(nestedArray, 'a'))
expect(find(nestedArray, 'b')).toEqual(_find(nestedArray, 'b'))
})

it('should return undefined for an empty array', () => {
expect(find([], (x) => x === 1)).toBe(undefined)
expect(find([], (x) => x === 1)).toBe(_find([], (x) => x === 1))
})

it('should handle complex objects with nested properties', () => {
const nestedArray = [
{name: {first: 'Alice', last: 'Smith'}},
{name: {first: 'Bob', last: 'Jones'}},
{name: {first: 'Alice', last: 'Brown'}},
]

expect(find(nestedArray, {name: {first: 'Alice'}})).toEqual(_find(nestedArray, {name: {first: 'Alice'}}))
expect(find(nestedArray, {name: {first: 'Alice', last: 'Brown'}})).toEqual(
_find(nestedArray, {name: {first: 'Alice', last: 'Brown'}}),
)
})

it('should handle truthy values if no predicate is provided', () => {
const array = [0, 1, false, 2, '', 3]

expect(find(array)).toBe(_find(array))
})

it('should handle sparse arrays', () => {
// eslint-disable-next-line no-sparse-arrays
const sparseArray = [0, , 1, , , 3]
expect(find(sparseArray)).toBe(_find(sparseArray))
})
})
65 changes: 65 additions & 0 deletions src/find.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import isArray from './isArray'
import isEqual from './isEqual'
import isObject from './isObject'

type Predicate<T> = (item: T, index: number, array: T[]) => boolean
type Shorthand<T> = DeepPartial<T> | [keyof T, unknown] | keyof T

type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]
}

function isPartialMatch<T>(item: T, partial: DeepPartial<T>): boolean {
if (!item || !partial) {
return false
}

return Object.keys(partial).every((key) => {
const partialValue = partial[key as keyof T]
const itemValue = item[key as keyof T]

if (isObject(partialValue) && isObject(itemValue)) {
return isPartialMatch(itemValue, partialValue as DeepPartial<typeof itemValue>)
}

return isEqual(itemValue, partialValue)
})
}

function isMatchPredicate<T>(item: T | undefined, predicate: Predicate<T> | Shorthand<T>): boolean {
if (!item) {
return false
}

if (typeof predicate === 'function') {
return predicate(item, 0, [])
}

if (isArray(predicate)) {
const [key, value] = predicate
return isEqual(item[key], value)
}

if (typeof predicate === 'string') {
return Boolean(item[predicate as keyof T])
}

return isPartialMatch(item, predicate as DeepPartial<T>)
}

export function find<T>(collection: T[] | Record<string, T>, predicate?: Predicate<T> | Shorthand<T>): T | undefined {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://deno.land/x/lodash@4.17.13-amd/_createFind.js?source

구현상 baseIteratee타입이 적용되어야 하는것 같아서 predicate: predicate?: ListIterateeCustom<T, unknown> 아닐까요 혹시~?

const iteratee = baseIteratee(predicate)

혹시 추가 성능 개선 필요하다면 baseIteratee 쪽에 통일되는 편이 앞으로 collection 처리할 때 유용할거 같습니다 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네네 최초에 그렇게 했는데... 초큼 많이 느려가지고 잠깐 손좀 보고 말씀드리겠습니다!

const array = isArray(collection) ? collection : Object.values(collection)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요거 보니까 collection이 꼭 T[]일 필요 없을거 같습니다~


const isMatch = predicate ? (item: T) => isMatchPredicate(item, predicate) : (item: T) => Boolean(item)

for (let i = 0; i < array.length; i++) {
const item = array[i]
if (item !== undefined && isMatch(item)) {
return item
}
}

return undefined
}

export default find
Loading