@ del-wang/ 等数
JavaScript 的深浅等同比较
安装
npm install -D @del-wang/equals
使用量
import { shallowEqual, deepEqual } from "@del-wang/equals";
// Shallow comparison - only first level
const obj1 = { a: 1, b: { x: 2 } };
const obj2 = { a: 1, b: { x: 2 } };
console.log(shallowEqual(obj1, obj2)); // false (different object references)
const sharedRef = { x: 2 };
const obj3 = { a: 1, b: sharedRef };
const obj4 = { a: 1, b: sharedRef };
console.log(shallowEqual(obj3, obj4)); // true (same reference)
// Deep comparison - all levels
console.log(deepEqual(obj1, obj2)); // true (deep equality)
反应集成
这个 shallowEqual 函数是 不变 以反应的内部执行, 完美地优化反应组件:
import { shallowEqual } from "@del-wang/equals";
import { useEffect, useRef } from "react";
function useCustomHook(props: object) {
const prevProps = useRef(props);
useEffect(() => {
if (!shallowEqual(prevProps.current, props)) {
// Only execute when props actually change
prevProps.current = props;
}
});
}
业绩
- 浅等价: O(n) - 仅一级属性
- 深等号: O(m) - 所有嵌入属性
建议使用 shallowEqual 在大多数反应情景中,除非特别需要进行深度比较.
许可证
麻省理工学院许可证 2025-Present 王德尔