Last active
May 30, 2019 01:46
-
-
Save congnt24/a1f1b5d95bfa78df01116f7a001552ba to your computer and use it in GitHub Desktop.
solution for excel app
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
function polishPostfix(str) { | |
let arr = str.split(' '); | |
let st = []; | |
for (let item of arr) { | |
// console.log(st, item); | |
let a; | |
switch (item) { | |
case '+': | |
st.push(st.pop() * 1 + st.pop() * 1); | |
break; | |
case '-': | |
a = st.pop(); | |
st.push(st.pop() - a); | |
break; | |
case '*': | |
st.push(st.pop() * st.pop()); | |
break; | |
case '/': | |
a = st.pop(); | |
st.push(st.pop() / a); | |
break; | |
default: | |
st.push(item); | |
break; | |
} | |
} | |
return st.pop(); | |
} | |
function deRef(key, str, obj, tmp = []) { | |
// console.log(str); | |
if (!isNaN(str)) { | |
return str | |
} | |
let arr = str.split(' '); | |
let len = arr.length; | |
let ar2 = []; | |
for (let i = 0; i < len; i++) { | |
let item = arr[i]; | |
if (['+', '-', '*', '/'].includes(item) || !isNaN(item)) { | |
ar2.push(item); | |
} else { | |
if (key === item) { | |
throw `Circular dependency between ${key} and ${tmp[0]} detected`; | |
} | |
tmp.push(item); | |
ar2.push(deRef(key, obj[item], obj, tmp)); | |
} | |
} | |
return ar2.join(' '); | |
} | |
function excel(n, obj) { | |
try { | |
let keys = Object.keys(obj); | |
for (let key of keys) { | |
let value = obj[key]; | |
if (isNaN(value)) {//string | |
obj[key] = polishPostfix(deRef(key, value, obj)); | |
} | |
} | |
for (let key of keys){ | |
console.log(key); | |
console.log(obj[key]); | |
} | |
} catch (e) { | |
console.log(e); | |
} | |
} | |
excel(3, { | |
A1: 5, | |
A2: 'A1 5 * B1 +', | |
B1: 6 | |
}); | |
console.log('---------------'); | |
excel(3, { | |
A1: 5, | |
A2: 'A1 5 * B2 +', | |
B1: 6, | |
B2: 'B1 C1 /', | |
C1: 2 | |
}); | |
console.log('---------------'); | |
excel(2, { | |
A1: 'A2 2 *', | |
A2: 'A1 5 +' | |
}); | |
console.log('---------------'); | |
excel(4, { | |
A1: 'B2 2 *', | |
A2: 'B1 5 +', | |
B1: 'B2 2 +', | |
B2: 'A1 1 *' | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment