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

keys 유틸을 추가합니다. #5

Merged
merged 4 commits into from
Nov 4, 2024
Merged
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
9 changes: 9 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// only for vite, tsup
// remember, this is not barrel file.
const moduleMap = {
isEmpty: './src/isEmpty.ts',
size: './src/size.ts',
keys: './src/keys.ts',
} as const

export default moduleMap
12 changes: 12 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@
"types": "./dist/isEmpty.d.ts",
"default": "./dist/isEmpty.js"
}
},
"./size": {
"import": {
"types": "./dist/size.d.ts",
"default": "./dist/size.js"
}
},
"./keys": {
"import": {
"types": "./dist/keys.d.ts",
"default": "./dist/keys.js"
}
}
},
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion src/isEmpty.bench.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import _isEmpty from 'lodash/isEmpty'

Check warning on line 1 in src/isEmpty.bench.ts

View workflow job for this annotation

GitHub Actions / lint

Import name `_isEmpty` must match one of the following formats: camelCase, PascalCase
import {bench, describe} from 'vitest'

import isEmpty from './isEmpty'
Expand All @@ -25,7 +25,7 @@

const ITERATIONS = 10000

describe('isEmpty', () => {
describe('isEmpty performance', () => {
bench('hidash', () => {
for (let i = 0; i < ITERATIONS; i++) {
testCases.forEach((testCase) => {
Expand Down
89 changes: 89 additions & 0 deletions src/keys.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import _keys from 'lodash/keys'

Check warning on line 1 in src/keys.bench.ts

View workflow job for this annotation

GitHub Actions / lint

Import name `_keys` must match one of the following formats: camelCase, PascalCase
import {bench, describe} from 'vitest'

import {keys} from './keys'

const testCases = [
// null & undefined
null,
undefined,

// Arrays
[],
[1, 2, 3],
Array(1000).fill(1),
[...Array(1000).keys()],

// Objects
{},
{a: 1, b: 2},
Object.create(null),
Object.create(
{},
{
a: {value: 1, enumerable: true},
b: {value: 2, enumerable: false},
},
),

// Array-like objects
{length: 2, 0: 'a', 1: 'b'},
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
{length: 1000, ...Array(1000).fill(1)},

// String objects
Object(''),
Object('hello'),

// Other cases
new Date(),
new Map([
['a', 1],
['b', 2],
]),
new Set([1, 2, 3]),

// Objects with prototype
Object.create(
{inherited: true},
{
own: {value: true, enumerable: true},
},
),

// Large object
{
...Object.fromEntries(
Array(1000)
.fill(0)
.map((_, i) => [`key${i}`, i]),
),
},

// Object with symbols
{[Symbol('test')]: 'value', regular: 'key'},

// Sparse array
Object.assign(Array(1000), {1: 'a', 500: 'b', 999: 'c'}),
]

const ITERATIONS = 1000

describe('keys performance', () => {
bench('hidash', () => {
for (let i = 0; i < ITERATIONS; i++) {
testCases.forEach((testCase) => {
keys(testCase)
})
}
})

bench('lodash', () => {
for (let i = 0; i < ITERATIONS; i++) {
testCases.forEach((testCase) => {
_keys(testCase)
})
}
})
})
133 changes: 133 additions & 0 deletions src/keys.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import _keys from 'lodash/keys'

Check warning on line 1 in src/keys.test.ts

View workflow job for this annotation

GitHub Actions / lint

Import name `_keys` must match one of the following formats: camelCase, PascalCase
import {describe, test, expect} from 'vitest'

import {keys} from './keys'

describe('keys function', () => {
test('returns empty array for null and undefined', () => {
expect(keys(null)).toEqual([])
expect(keys(undefined)).toEqual([])
})

test('returns array indices for array', () => {
expect(keys([])).toEqual([])
expect(keys(['a', 'b', 'c'])).toEqual(['0', '1', '2'])
expect(keys(new Array(3))).toEqual(['0', '1', '2'])
})

test('returns own enumerable keys for objects', () => {
expect(keys({})).toEqual([])
expect(keys({a: 1, b: 2})).toEqual(['a', 'b'])
expect(keys(Object.create(null))).toEqual([])
})

test('handles array-like objects correctly', () => {
const arrayLike = {0: 'a', 1: 'b', 2: 'c', length: 3}
expect(keys(arrayLike)).toEqual(['0', '1', '2'])

const htmlCollection = {
0: 'div',
1: 'span',
length: 2,
item: (_: number) => null,
}
expect(keys(htmlCollection)).toEqual(['0', '1', 'item'])
})

test('returns empty array for primitive values', () => {
expect(keys(42)).toEqual([])
expect(keys(true)).toEqual([])
expect(keys(Symbol('test'))).toEqual([])
})

test('handles string objects correctly', () => {
const strObj = Object('hello')
expect(keys(strObj)).toEqual(['0', '1', '2', '3', '4'])
})

test('handles prototype properties correctly', () => {
function TestClass() {
this.a = 1
this.b = 2
}
TestClass.prototype.c = 3

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const obj = new (TestClass as any)()
expect(keys(obj)).toEqual(['a', 'b'])
})

test('handles non-enumerable properties correctly', () => {
const obj = Object.create(
{},
{
a: {value: 1, enumerable: true},
b: {value: 2, enumerable: false},
},
)
expect(keys(obj)).toEqual(['a'])
})

test('handles sparse arrays correctly', () => {
const sparseArray = Array(3)
sparseArray[1] = 'b'
expect(keys(sparseArray)).toEqual(['0', '1', '2'])
})

test('handles array with additional properties', () => {
const arr = ['a', 'b']

// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(arr as any).prop = 'value'
expect(keys(arr)).toEqual(['0', '1', 'prop'])
})

test('handles large objects efficiently', () => {
const largeObj: Record<string, number> = {}
for (let i = 0; i < 10000; i++) {
largeObj[`key${i}`] = i
}
expect(keys(largeObj).length).toBe(10000)
expect(keys(largeObj)[0]).toBe('key0')
expect(keys(largeObj)[9999]).toBe('key9999')
})

test('handles large arrays efficiently', () => {
const largeArray = new Array(10000).fill(0)
const result = keys(largeArray)
expect(result.length).toBe(10000)
expect(result[0]).toBe('0')
expect(result[9999]).toBe('9999')
})

test('handles inherited enumerable properties correctly', () => {
const proto = {inherited: true}
const obj = Object.create(proto)
obj.own = true
expect(keys(obj)).toEqual(['own'])
})

test('handles Object.prototype modifications safely', () => {
const originalToString = Object.prototype.toString
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(Object.prototype as any).malicious = 'bad'
const obj = {a: 1, b: 2}
expect(keys(obj)).toEqual(['a', 'b'])
} finally {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (Object.prototype as any).malicious
// eslint-disable-next-line no-extend-native
Object.prototype.toString = originalToString
}
})

test('handles objects with symbols correctly', () => {
const symbol = Symbol('test')
const obj = {
[symbol]: 'symbol',
regular: 'value',
}
expect(keys(obj)).toEqual(['regular'])
})
})
89 changes: 89 additions & 0 deletions src/keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import {isArrayLike} from './internal'

const nativeKeys = Object.keys
const isArray = Array.isArray

export function keys(object: unknown): string[] {
// null/undefined 빠른 처리
if (object == null) {
return []
}

const obj = Object(object)

// 순수 배열과 추가 속성이 있는 배열 처리
if (isArray(obj)) {
const plainKeys = nativeKeys(obj)
const len = obj.length

// 배열 길이와 키 개수가 같으면 추가 속성이 없는 경우
if (plainKeys.length === len) {
const result = new Array(len)
let idx = 0
while (idx < len) {
result[idx] = String(idx++)
}
return result
}

const result = new Array(plainKeys.length)
let idx = 0

while (idx < len) {
result[idx] = String(idx++)
}

// 추가 속성 채우기
for (const key of plainKeys) {
const keyNum = +key
if (isNaN(keyNum) || keyNum >= len) {
result[idx++] = key
}
}

return result
}

if (isArrayLike(obj)) {
const plainKeys = nativeKeys(obj)
const len = obj.length

if (plainKeys.length === 1 && plainKeys[0] === 'length') {
const result = new Array(len)
let idx = 0
while (idx < len) {
result[idx] = String(idx++)
}
return result
}

let extraKeysCount = 0

for (const key of plainKeys) {
const keyNum = +key
if (key !== 'length' && (isNaN(keyNum) || keyNum >= len)) {
extraKeysCount++
}
}

const result = new Array(len + extraKeysCount)
let idx = 0

while (idx < len) {
result[idx] = String(idx++)
}

if (extraKeysCount > 0) {
for (const key of plainKeys) {
const keyNum = +key
if (key !== 'length' && (isNaN(keyNum) || keyNum >= len)) {
result[idx++] = key
}
}
}

return result
}

return nativeKeys(obj)
}
2 changes: 1 addition & 1 deletion src/size.bench.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import _size from 'lodash/size'

Check warning on line 1 in src/size.bench.ts

View workflow job for this annotation

GitHub Actions / lint

Import name `_size` must match one of the following formats: camelCase, PascalCase
import {bench, describe} from 'vitest'

import size from './size'
Expand Down Expand Up @@ -30,7 +30,7 @@

const ITERATIONS = 10000

describe('size', () => {
describe('size performance', () => {
bench('hidash', () => {
for (let i = 0; i < ITERATIONS; i++) {
testCases.forEach((testCase) => {
Expand Down
8 changes: 2 additions & 6 deletions tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import {defineConfig} from 'tsup'

import type {Options} from 'tsup'

const entries: Options['entry'] = {
isEmpty: './src/isEmpty.ts',
} as const
import moduleMap from './index'

export default defineConfig({
entry: entries,
entry: moduleMap,
dts: {only: true},
Comment on lines 5 to 7
Copy link
Member

Choose a reason for hiding this comment

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

근데 이거 vite plugin dts 안쓰신 이유 이쓸까여?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

ㅋㅋㅋ 습관적으로.. 이거 다음 PR에서 바꿀게요

format: 'esm',
outDir: './dist',
Expand Down
6 changes: 3 additions & 3 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import preserveDirectives from 'rollup-preserve-directives'
import {defineConfig} from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'

import moduleMap from './index'

const SUPPORT_TARGETS = browserslistToEsbuild()

export default defineConfig({
Expand All @@ -30,9 +32,7 @@ export default defineConfig({
build: {
outDir: 'dist',
lib: {
entry: {
isEmpty: './src/isEmpty.ts',
},
entry: moduleMap,
},
rollupOptions: {
// if neccessary
Expand Down
Loading