DeepEquals

Example for Kolya's test

by Anton

JavaScript

test('Mixed types 1', 'a', 1, false);
test('Mixed types 2', '1', 1, false);
test('Mixed types 3', [1], 1, false);
test('Mixed types 4', [2], { key: 'value' }, false);
test('Mixed types 5', { key: 'value' }, [2], false);
test('Equal strings', 'a', 'a', true);
test('Diff strings', 'a', 'b', false);
test('Equal nums', 5, 5, true);
test('Diff nums', 2, -7, false);
test('Equal arrs 1', [1,2], [1,2], true);
test('Equal arrs 2', ['a','bc'], ['a','bc'], true);
test('Diff arrs 1', [1,2], [1,2,3], false);
test('Diff arrs 2', [1,2], [1,3], false);
test('Diff arrs 3', ['a','b'], ['a',3], false);
test('Equal objs 1', { a: 1, b: 'b' }, { a: 1, b: 'b' }, true);
test('Equal objs 2', { a: 1, b: 'b' }, { b: 'b', a: 1 }, true);
test('Diff objs 1', { a: 1 }, { a: 1, b: 'b' }, false);
test('Diff objs 1', { a: 1 }, {}, false);
test('Equal deep arr', 
	[1, { b: 2, c: 3}, 'string'], 
    [1, { b: 2, c: 3}, 'string'], 
    true);
test('Diff deep arr', 
	[1, { b: 2, c: 3}, 'string'], 
    [1, { b: 2, c: 3, d: 4 }, 'string'], 
    false);
test('Equal deep obj', 
	{ a: 1, b: [2, 3], c: 4}, 
    { a: 1, b: [2, 3], c: 4}, 
    true);
test('Diff deep obj', 
	{ a: 1, b: [2, 3, 5], c: 4}, 
    { a: 1, b: [2, 3], c: 4}, 
    false);


// -----------------------------------------
function test(title, one, two, expected) {
	const res = deepEquals(one, two);
    const color = res === expected ? 'green' : 'red';
	
    document.write(`<div style="color:${color}">
    	${title}: need ${expected}, got ${res}
    </div>`);
}

// return true if equals, false otherwise
function deepEquals(one, two) {
	const typeOne = typeof one;
    console.log(typeOne);
    
    if(typeOne !== typeof two) return false;
    
    switch(typeOne) {
    	// Simple values
    	case 'string':
        case 'number':
        	return one === two;
        	break;
            
        case 'object':
        	const isOneArray = one instanceof Array;
            const isTwoArray = two instanceof Array;
        	if(isOneArray ||...