Last active
May 28, 2017 13:08
-
-
Save muratgozel/e916259cea2578bfb8f68cc681b88813 to your computer and use it in GitHub Desktop.
Javascript equality checker.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const isEqual = function(inputs = []) { | |
// Checks an element if js object. | |
const isObject = function(data) { | |
return Object.prototype.toString.call(data) === '[object Object]'; | |
}; | |
// Sorts given object by its keys. | |
const sortObjectByKey = function(obj) { | |
if (!obj) return {}; | |
return Object.keys(obj).sort().reduce((initialVal, item) => { | |
initialVal[item] = !Array.isArray(obj[item]) && | |
typeof obj[item] === 'object' | |
? sortObjectByKey(obj[item]) | |
: obj[item]; | |
return initialVal; | |
}, {}); | |
}; | |
// Checks equality of all elements in the input against each other. Returns true | false | |
return ( | |
inputs | |
.map( | |
input => | |
typeof input == 'undefined' | |
? undefined | |
: isObject(input) | |
? JSON.stringify(sortObjectByKey(input)) | |
: JSON.stringify(input) | |
) | |
.reduce( | |
(prevValue, input) => | |
prevValue === '' || prevValue === input ? input : false, | |
'' | |
) !== false | |
); | |
}; | |
// Tests (Made with Jest test framework.) | |
test('String equality check', () => { | |
expect(isEqual(['murat'])).toEqual(true); | |
expect(isEqual(['murat', 'john', 'doe'])).toEqual(false); | |
expect(isEqual(['murat', 'murat', 'murat'])).toEqual(true); | |
}); | |
test('Float equality check', () => { | |
expect(isEqual([7.89, 3.45])).toEqual(false); | |
expect(isEqual([7, 7.50])).toEqual(false); | |
expect(isEqual([7.50, 7.50])).toEqual(true); | |
expect(isEqual([7, 7])).toEqual(true); | |
expect(isEqual([0.34, 0.33])).toEqual(false); | |
expect(isEqual([0.33, 0.33])).toEqual(true); | |
}); | |
test('Array equality check', () => { | |
expect(isEqual([[1, 2, 3], [1, 2, 3]])).toEqual(true); | |
expect(isEqual([[1, 3], [1, 2, 3]])).toEqual(false); | |
expect(isEqual([['murat', 18], ['murat', 18]])).toEqual(true); | |
}); | |
test('Object equality check', () => { | |
let obj1 = { | |
name: 'murat', | |
age: 18 | |
}; | |
let obj2 = { | |
name: 'murat', | |
age: 18 | |
}; | |
let obj3 = { | |
age: 18, | |
name: 'murat' | |
}; | |
let obj4 = { | |
name: 'murat', | |
age: 18, | |
occupation: 'nothing' | |
}; | |
expect(isEqual([obj1, obj2])).toEqual(true); | |
expect(isEqual([obj1, obj2, obj3])).toEqual(true); | |
expect(isEqual([obj1, obj2, obj3, obj4])).toEqual(false); | |
}); | |
test('Weird equality checks', () => { | |
expect(isEqual(['', {}])).toEqual(false); | |
expect(isEqual([0, '0'])).toEqual(false); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment