diff --git a/README.md b/README.md index f0a7e80..85246ce 100644 --- a/README.md +++ b/README.md @@ -33,4 +33,8 @@ 5. [有时间限制的Promise对象](src/promiseandtime/promise-time-limit.ts) 6. [有时间限制的缓存](src/promiseandtime/cache-with-time-limit.ts) 7. [函数防抖](src/promiseandtime/debounce.ts) -8. [并行执行异步函数](src/promiseandtime/execute-asynchronous-functions-in-parallel.ts) \ No newline at end of file +8. [并行执行异步函数](src/promiseandtime/execute-asynchronous-functions-in-parallel.ts) + +## JSON + +1. [判断对象是否为空](src/json/is-object-empty.ts) \ No newline at end of file diff --git a/src/json/is-object-empty.ts b/src/json/is-object-empty.ts new file mode 100644 index 0000000..a0d53e4 --- /dev/null +++ b/src/json/is-object-empty.ts @@ -0,0 +1,18 @@ +type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; +type Obj = Record | JSONValue[] + +/** + * 给定一个对象或数组,判断它是否为空。 + * + * 一个空对象不包含任何键值对。 + * 一个空数组不包含任何元素。 + * 你可以假设对象或数组是通过 JSON.parse 解析得到的。 + * @link https://leetcode.cn/problems/is-object-empty/description/?envType=study-plan-v2&envId=30-days-of-javascript + * @param obj + */ +export function isEmpty(obj: Obj): boolean { + for (const _ in obj) { + return false; + } + return true; +} \ No newline at end of file diff --git a/test/json/is-object-empty.test.ts b/test/json/is-object-empty.test.ts new file mode 100644 index 0000000..d0f0f4e --- /dev/null +++ b/test/json/is-object-empty.test.ts @@ -0,0 +1,14 @@ +import {describe, expect, test} from "vitest"; +import {isEmpty} from "@/json/is-object-empty"; + +describe('Test object is empty', () => { + test('Test case 1', () => { + expect(isEmpty({"x": 5, "y": 42})).toBeFalsy() + }) + test('Test case 2', () => { + expect(isEmpty({})).toBeTruthy() + }) + test('Test case 3', () => { + expect(isEmpty([null, false, 0])).toBeFalsy() + }) +}) \ No newline at end of file