/**
* Please use TypeScript/JS to answer question
* Welcome to answer with unit testing code if you can
*
* After you finish coding, please push to your GitHub account and share the link with us.
*/
// Please write a function to reverse the following nested input value into output value
// Input:
const inputValue: Object = {
aa: {
bb: {
cc: {
dd: {
ee: {
ff: {
gg: {
hh: 'final',
},
},
},
},
},
},
},
};
// Output:
const outputValue: Object = {
final: {
hh: {
ff: {
ee: {
dd: {
cc: {
bb: {
aa: 'final',
},
},
},
},
},
},
},
};
// way 1
let keys: string[] = []
function getKeys(obj): void {
Object.keys(obj).forEach(key => {
keys.push(key)
if (typeof obj[key] === 'object') {
getKeys(obj[key])
} else {
keys.push(obj[key])
}
})
}
function getOutputValue(): void {
let res = keys[0]
for (let i = 1; i < keys.length; i++) {
let key = keys[i];
res = {
[key]: res,
};
}
return res;
}
console.log('getOutputValue => ', getOutputValue());
// way 2 遞迴: first output can be next input
/*
* originalObj: original obj
* result: new result
* count: check if first time
*/
function _getKeys(originalObj, result, count): Object {
// console.log('_getKeys', obj, result, count);
return Object.keys(originalObj).map((key) => {
// console.log('map => ', key, obj[key]);
if (typeof originalObj[key] === 'object') {
// first time
if (count === 0) {
return _getKeys(originalObj[key], key, count += 1);
}
let _result = {
[key]: result
}
return _getKeys(originalObj[key], _result, count += 1);
} else {
// last key value
return {
[originalObj[key]]: {
key: result,
},
};
}
})[0];
}
let result = _getKeys(inputValue, undefined, 0);
console.log('result => ', result);
文章標籤
全站熱搜
留言列表