Created
June 27, 2021 09:49
-
-
Save koshuang/90e9e2d6186f27d74da6901b59054184 to your computer and use it in GitHub Desktop.
This file contains 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 _ = require('lodash'); | |
const primary = { colors: ['#123454', '#123223'] }; | |
const info = { colors: ['#EEFF44', '#FF2211'] }; | |
const success = { colors: ['#773388', '#AA3322'] }; | |
const original = [{ primary: primary.colors }, { info: info.colors }, { success: success.colors }]; | |
const expected = { | |
primary: primary.colors, | |
info: info.colors, | |
success: success.colors, | |
}; | |
const log = { | |
describe(str) { | |
console.log(`describe: ${str}`); | |
}, | |
it(str) { | |
console.log(`\t it ${str}`); | |
}, | |
assertEquals(str) { | |
console.log(`\t\tResult: ${str}`); | |
}, | |
error(str) { | |
console.log(`\t\tResult: ${str}`); | |
}, | |
}; | |
test(); | |
function test() { | |
// assertEquals(expected, actual); | |
describe('mergeArrayToObject', function() { | |
it('should return a empty object when input is undefined', function() { | |
const actual = mergeArrayToObject(); | |
assertEquals({}, actual); | |
}); | |
it('should return a empty object when input is null', function() { | |
const actual = mergeArrayToObject(null); | |
assertEquals({}, actual); | |
}); | |
it('should return a empty object when input is an empty array', function() { | |
const actual = mergeArrayToObject([]); | |
assertEquals({}, actual); | |
}); | |
it('should merge object in array to final object', function() { | |
const actual = mergeArrayToObject(original); | |
assertEquals(expected, actual); | |
}); | |
it('should throw an error when input is not an array', function() { | |
assertError(function() { | |
mergeArrayToObject({}); | |
}); | |
}); | |
}); | |
} | |
function mergeArrayToObject(arr) { | |
const myArray = arr || []; | |
if (!Array.isArray(myArray)) { | |
throw new Error('Input is not an array'); | |
} | |
const result = myArray.reduce(function(previous, obj) { | |
return { | |
...previous, | |
...obj, | |
}; | |
}, {}); | |
return result; | |
} | |
function describe(description, fn) { | |
log.describe(description); | |
fn(); | |
} | |
function it(sentence, fn) { | |
log.it(sentence); | |
fn(); | |
} | |
function assertEquals(expected, actual) { | |
if (_.isEqual(expected, actual)) { | |
log.assertEquals('Passed'); | |
} else { | |
log.error(`${JSON.stringify(actual)} is not expected as ${JSON.stringify(expected)}`); | |
} | |
} | |
function assertError(fn, message = '') { | |
try { | |
fn(); | |
log.error('Expected an error'); | |
} catch (error) { | |
log.assertEquals('Passed'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment