Javascript - deepEqual Comparison

后端 未结 8 1295
囚心锁ツ
囚心锁ツ 2020-12-05 05:21

Question (From Eloquent Javascript 2nd Edition, Chapter 4, Exercise 4):

Write a function, deepEqual, that takes two values and returns true only if th

8条回答
  •  半阙折子戏
    2020-12-05 06:00

    Feel that this version is a bit more readable (easier to comprehend). The logic is very similar with the top answer though. (ES6 this time)

    function deepEqual(obj1, obj2) {
    
        if(obj1 === obj2) // it's just the same object. No need to compare.
            return true;
    
        if(isPrimitive(obj1) && isPrimitive(obj2)) // compare primitives
            return obj1 === obj2;
    
        if(Object.keys(obj1).length !== Object.keys(obj2).length)
            return false;
    
        // compare objects with same number of keys
        for(let key in obj1)
        {
            if(!(key in obj2)) return false; //other object doesn't have this prop
            if(!deepEqual(obj1[key], obj2[key])) return false;
        }
    
        return true;
    }
    
    //check if value is primitive
    function isPrimitive(obj)
    {
        return (obj !== Object(obj));
    }
    

    By the way, there is a cheater version of deep equal which works like a charm)) However, it's approximately 1.6 times slower.

    As noticed by zero298, this approach is sensitive to the properties ordering and shouldn't be taken seriously

    function cheatDeepEqual(obj1, obj2)
    {
        return JSON.stringify(obj1) === JSON.stringify(obj2);
    }
    

提交回复
热议问题