Last active
March 20, 2020 18:12
-
-
Save ericraio/a290bc2c4857f8dd2ae5344306ec178b to your computer and use it in GitHub Desktop.
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
process.stdin.resume(); | |
process.stdin.setEncoding('utf8'); | |
var util = require('util'); | |
var input = ""; | |
process.stdin.on('data', function (text) { | |
input += text; | |
}); | |
const _ = require("underscore"); | |
/** | |
* Checks if it is passed a plain object | |
* @param {any} obj | |
* @returns {boolean} | |
*/ | |
let isPlainObject = obj => | |
Object.prototype.toString.call(obj) === '[object Object]'; | |
/** | |
* Sorts an array that contains stringified integers | |
* @param {Array<String>} arr | |
* @returns {Array<number>} | |
*/ | |
let sortStringsArrayAsIntegers = arr => { | |
const parsedArr = arr.map(item => | |
isPositiveInt(item) ? parseInt(item) : item | |
); | |
return parsedArr.slice(0).sort((a, b) => { | |
if (a > b) { | |
return 1; | |
} else if (a < b) { | |
return -1; | |
} | |
return 0; | |
}); | |
}; | |
let isPositiveInt = val => /^\d+$/.test(val); | |
let isKeysIntegers = (keys) => _.all(keys, key => isPositiveInt(key)) | |
let hasMissingNumbers = (arr) => { | |
if(!isKeysIntegers(arr)) { | |
return arr; | |
} | |
if(parseInt(arr[0], 10) === 1) { return arr; } | |
let sparse = arr.reduce((sparse, i) => (sparse[i]=1,sparse), []); | |
let results = [...sparse.keys()].filter(i => i && !sparse[i]) | |
return results.length > 0 | |
} | |
let processIntegerKeys = (obj) => { | |
if(Array.isArray(obj)) { | |
if(hasMissingNumbers(obj)) { | |
return obj; | |
} else { | |
return obj.sort() | |
} | |
} | |
const keys = Object.keys(obj); | |
if(isKeysIntegers(keys)) { | |
if(hasMissingNumbers(keys)) { | |
return obj; | |
} else { | |
return sortStringsArrayAsIntegers(new Array(...Object.values(obj))); | |
} | |
} | |
} | |
function transformObject(obj) { | |
let output = {}; | |
const keys = Object.keys(obj); | |
if(isKeysIntegers(keys)) { | |
return processIntegerKeys(obj) | |
} | |
if(isPlainObject(obj)) { | |
_.each(obj, (value, key) => { | |
if(!isPlainObject(value)) { | |
output[key] = value; | |
} | |
if(isPlainObject(value)) { | |
if(hasMissingNumbers(Object.keys(value))) { | |
output[key] = value; | |
} else { | |
const values = Object.values(value); | |
const x = _.partition(values, val => typeof val === "string"); | |
output[key] = [...x[0], transformObject(x[1][0])] | |
} | |
} | |
}) | |
} | |
return output; | |
} | |
process.stdin.on('end', function () { | |
console.log(JSON.stringify(transformObject(JSON.parse(input)))); | |
}); 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment