Last active
October 3, 2018 02:21
-
-
Save fortil/be86e8daf433d7f45ded4d94daf84c27 to your computer and use it in GitHub Desktop.
S-Expression to binary tree in JavaScript
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
function SExpression(nodes) { | |
if (!/(\(|\))+/g.test(nodes)) { | |
return 'E5' | |
} | |
let a = nodes.split(' ').map(i => i.replace(/\(|\)/g, '').split(',')) | |
let keyPair = a.map(i => i[0]) | |
let valuePair = a.map(i => i[1]) | |
let aE1 = keyPair.reduce((prev, curr) => { | |
prev[curr] = (prev[curr] || 0) + 1 | |
return prev | |
}, {}) | |
const E1 = Object.values(a).filter(e => e > 2) | |
if (E1.length) { | |
return 'E1' | |
} | |
let aE2 = (Array.from(new Set(a.map(e => JSON.stringify(e))))).map(e => JSON.parse(e)) | |
if (aE2.length < a.length) { | |
return 'E2' | |
} | |
let aE4 = keyPair.filter(key => !valuePair.includes(key)) | |
if (aE4.length > 2) { | |
return 'E4' | |
} | |
let aE3 = Array.from(new Set(valuePair)) | |
if (aE3.length < valuePair.length) { | |
return 'E3' | |
} | |
let root = aE4[0] | |
let routes = getObj(a, root) | |
return getNodes(routes, root) | |
} | |
function getNodes(obj, key) { | |
return `(${key}${Object.keys(obj).reduce((prev, curr) => { | |
if (Object.keys(obj[curr]).length) { | |
prev += getNodes(obj[curr], curr) | |
} else { | |
prev += `(${curr})` | |
} | |
return prev | |
}, ``)})` | |
} | |
function getObj(a, key) { | |
return a.reduce((prev, curr) => { | |
if (curr[0] === key) { | |
prev[curr[1]] = getObj(a, curr[1]) | |
} | |
return prev | |
}, {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment