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

🚀 get #173

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/free-turkeys-sing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@naverpay/hidash": patch
---

🚀 get

PR: [ 🚀 get](https://github.com/NaverPayDev/hidash/pull/173)
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const moduleMap = {
first: './src/first.ts',
flatten: './src/flatten.ts',
flow: './src/flow.ts',
get: './src/get.ts',
groupBy: './src/groupBy.ts',
gt: './src/gt.ts',
has: './src/has.ts',
Expand Down
10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,16 @@
"default": "./flow.js"
}
},
"./get": {
"import": {
"types": "./get.d.mts",
"default": "./get.mjs"
},
"require": {
"types": "./get.d.ts",
"default": "./get.js"
}
},
"./groupBy": {
"import": {
"types": "./groupBy.d.mts",
Expand Down
27 changes: 27 additions & 0 deletions src/get.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import _get from 'lodash/get'
import {describe, bench} from 'vitest'

import get from './get'

const obj = {a: [{b: {c: 3}}], x: {y: {z: 'hello'}}}
const PATHS = ['a[0].b.c', ['x', 'y', 'z'], 'a.0.b.c', 'not.exist', ['a', '0', 'b', 'notThere']]

const ITERATIONS = 10000

describe('get performance', () => {
bench('hidash', () => {
for (let i = 0; i < ITERATIONS; i++) {
PATHS.forEach((path) => {
get(obj, path, 'default')
})
}
})

bench('lodash', () => {
for (let i = 0; i < ITERATIONS; i++) {
PATHS.forEach((path) => {
_get(obj, path, 'default')
})
}
})
})
103 changes: 103 additions & 0 deletions src/get.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import _get from 'lodash/get'
import {describe, it, expect} from 'vitest'

import get from './get'

describe('get', () => {
it('should get property by string path', () => {
const obj = {a: {b: {c: 3}}}
expect(get(obj, 'a.b.c')).toBe(_get(obj, 'a.b.c'))
})

it('should get property by array path', () => {
const obj = {a: [{b: {c: 3}}]}
expect(get(obj, ['a', 0, 'b', 'c'])).toBe(_get(obj, ['a', '0', 'b', 'c']))
})

it('should return default if not found', () => {
const obj = {a: {b: 2}}
expect(get(obj, 'a.b.c', 'default')).toBe(_get(obj, 'a.b.c', 'default'))
})

it('should handle null/undefined object', () => {
expect(get(null, 'a.b.c', 'default')).toBe(_get(null, 'a.b.c', 'default'))
expect(get(undefined, 'x.y', 10)).toBe(_get(undefined, 'x.y', 10))
})

it('should handle non-object', () => {
expect(get(42, 'a', 'not found')).toBe(_get(42, 'a', 'not found'))
})

it('should handle symbol keys', () => {
const sym = Symbol('test')
const obj = {[sym]: 'symbolValue'}
expect(get(obj, sym)).toBe(_get(obj, sym))
})

// 복잡한 경로 테스트
it('should handle complex paths with brackets and quotes', () => {
const obj = {
a: [
{
b: {
'complex.key': {
c: 'complexValue',
'escaped\\"quotes"': 'withEscapedQuotes',
},
},
},
],
'weird key with spaces': {x: 123},
}

// 경로: a[0].b["complex.key"].c
expect(get(obj, 'a[0].b["complex.key"].c')).toBe(_get(obj, 'a[0].b["complex.key"].c'))
// 경로: a[0].b["complex.key"]["escaped\\\"quotes"]
expect(get(obj, 'a[0].b["complex.key"]["escaped\\"quotes"]')).toBe(
_get(obj, 'a[0].b["complex.key"]["escaped\\"quotes"]'),
)

// 공백 포함 키: ["weird key with spaces"].x
expect(get(obj, '["weird key with spaces"].x')).toBe(_get(obj, '["weird key with spaces"].x'))
})

it('should handle array indices as strings and negative indices as keys', () => {
const obj = {
a: {
'0': {d: 4},
'-1': {d: 'negativeIndexKey'},
},
}
expect(get(obj, 'a["0"].d')).toBe(_get(obj, 'a["0"].d'))
expect(get(obj, 'a[-1].d')).toBe(_get(obj, 'a[-1].d'))
})

it('should handle empty string key', () => {
const obj = {
'': {value: 'emptyKey'},
a: {'': {nested: 'emptyNested'}},
}

expect(get(obj, '[""].value')).toBe(_get(obj, '[""].value'))
expect(get(obj, 'a[""].nested')).toBe(_get(obj, 'a[""].nested'))
})

it('should return undefined if intermediate property is missing', () => {
const obj = {a: {b: {c: 3}}}
expect(get(obj, 'a.x.y', 'not found')).toBe(_get(obj, 'a.x.y', 'not found'))
expect(get(obj, 'a.b.x.y', 'defaultVal')).toBe(_get(obj, 'a.b.x.y', 'defaultVal'))
})

it('should work with numeric paths as part of a complex path', () => {
const obj = {
arr: [
{
nested: [{val: 'first'}, {val: 'second'}],
},
],
}

expect(get(obj, 'arr[0].nested[1].val')).toBe(_get(obj, 'arr[0].nested[1].val'))
expect(get(obj, 'arr[0]["nested"][0].val')).toBe(_get(obj, 'arr[0]["nested"][0].val'))
})
})
91 changes: 91 additions & 0 deletions src/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import isArray from './isArray'

const rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g
const reEscapeChar = /\\(\\)?/g
const pathCache = new Map<string, (string | number)[]>()

function isObjectLike(value: unknown): value is object {
return value !== null && typeof value === 'object'
}

function isNumericKey(str: string): boolean {
return /^-?\d+$/.test(str)
}

function complexStringToPath(path: string): (string | number)[] {
const cached = pathCache.get(path)
if (cached) {
return cached
}

const result: (string | number)[] = []

// 선행 '.' 처리
if (path[0] === '.') {
result.push('')
}

path.replace(rePropName, (match, number, quote, subStr) => {
let key: string | number = match
let subString = subStr
if (quote) {
subString = subString ?? ''
key = subString.replace(reEscapeChar, '$1')
} else if (number !== undefined) {
key = Number(number)
} else if (isNumericKey(key)) {
key = Number(key)
}
result.push(key)
return ''
})

pathCache.set(path, result)
return result
}

function castPath(path: string | symbol | (string | number)[]): (string | number | symbol)[] {
if (isArray(path)) {
return path
}
if (typeof path === 'symbol') {
return [path]
}

if (path.includes('[') || path.includes(']') || path.includes('"') || path.includes("'")) {
return complexStringToPath(path)
}

return path === '' ? [''] : path.split('.')
}

function baseGet(obj: unknown, path: (string | number | symbol)[]): unknown {
let current = obj
for (let i = 0; i < path.length; i++) {
if (!isObjectLike(current)) {
return undefined
}
const key = path[i]
if (!Object.prototype.hasOwnProperty.call(current, key)) {
return undefined
}
current = (current as Record<string | number | symbol, unknown>)[key]
}
return current
}

export function get<T = unknown>(
object: unknown,
path: string | symbol | (string | number)[],
defaultValue?: T,
): T | undefined {
if (object == null) {
return defaultValue
}

const arrPath = castPath(path)
const result = baseGet(object, arrPath)
return result === undefined ? defaultValue : (result as T)
}

export default get
Loading