convert a string of a math formula to Object Tree in Javascript?
a function that converts a math string passed as a prop (with the operations +
, -
, /
, *
)
by returning an object that contains pieces of the math string, in an ordered/better way easier to loop on it then.
test cases if you need them:
Example 1: Basic Math (same operation)
N | Input (string) | Output (object) |
---|---|---|
1 | 1 | { values: [1], operation: null } |
2 | 1+1 | { values: [1,1], operation: "+" } |
3 | 1+2+3 | { values: [1,2,3], operation: "+" } |
4 | 3-2-1 | { values: [3,2,1], operation: "-" } |
5 | 10*80 | { values: [10,80], operation: "*" } |
6 | 100/10 | { values: [100,10], operation: "/" } |
Example 2: Formula with 2 operations
➡️ + and - samples
N1
input: 1+1-1
output:
{
values: [
{
values: [1, 1],
operation: "+",
},
1,
],
operation: "-",
};
N2
input: 3+2-1+5
output:
{
values: [
{
values: [
{
values: [3, 2],
operation: "+",
},
1,
],
operation: "-",
},
5,
],
operation: "+",
};
N3
input: 3+2-1+5+10+7
output:
{
values: [
{
values: [
{
values: [3, 2],
operation: "+",
},
1,
],
operation: "-",
},
5,
10,
7
],
operation: "+",
};
➡️ + and / samples
N4
input: 1+2/3
output:
{
values: [
1,
{
values: [2, 3],
operation: "/",
},
],
operation: "+",
};
N5
input: 2/3+1
output:
{
values: [
{
values: [2, 3],
operation: "/",
},
1,
],
operation: "+",
};
N6
input: 1/2+3/4+5/6
output:
{
values: [
{
values: [1, 2],
operation: "/",
},
{
values: [3, 4],
operation: "/",
},
{
values: [5, 6],
operation: "/",
},
],
operation: "+",
};
N7
input: 1/2/3/4/5+6+7+8/9+10/11
output:
{
values: [
{
values: [1, 2, 3, 4, 5],
operation: "/",
},
6,
7,
{
values: [8, 9],
operation: "/",
},
{
values: [10, 11],
operation: "/",
},
],
operation: "+",
};
➡️ / and - samples
N8
input: 1-2/3
output:
{
values: [
1,
{
values: [2, 3],
operation: "/",
},
],
operation: "-",
};
➡️ / and * samples
N9
input: 10/2*5
output:
{
values: [
{
values: [10, 2],
operation: "/",
},
5,
],
operation: "*",
};
Example 3: Formula with 4 operations
N1
input: 10/2*5+1-1*5/3+2*4
output:
{
values: [
{
values: [
{
values: [10, 2],
operation: "/",
},
5,
],
operation: "*",
},
1,
{
values: [
{
values: [-1, 5],
operation: "*",
},
3,
],
operation: "/",
},
{
values: [2, 4],
operation: "*",
},
],
operation: "+",
};
Example 4: Formula with () parenthesis
...
Comments
Post a Comment