Skip to content

Feature/more operations #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions canvas.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@



(function () {
const SAMPLE_EXPRESSIONS = [
'(a + b)*c - (x - y)/z',
Expand All @@ -10,19 +7,22 @@
'(a - b) * (c + d) / z',
'(a * b) - (x / y)'
]
var canvas = document.querySelector('canvas')
var c = canvas.getContext('2d')
function clearCanvas() { c.clearRect(0, 0, canvas.width, canvas.height) }
const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d');

function clearCanvas() {
c.clearRect(0, 0, canvas.width, canvas.height)
}

document.getElementById('generate-tree').addEventListener('click', () => {
var expression = document.getElementById('expression-input').value
let expression = document.getElementById('expression-input').value;
if (typeof expression !== 'undefined' && null != expression) {
expression = expression.replace(/\s+/g, '')
expression = expression.toLowerCase()
var postfix = infixToPostfix(expression);

const postfix = infixToPostfix(expression);
if (null !== postfix) {
try {
var root = constructTree(postfix)
const root = constructTree(postfix);
setCoordinates(root)
clearCanvas()
canvas.height = document.getElementById('canvas-container').offsetHeight;
Expand Down Expand Up @@ -52,18 +52,17 @@
})();



function displayErrorMessage() {
Swal.fire({
icon: 'error',
title: 'Invalid expression',
html: `
<div style="font-size:1.1em;text-align: left;margin:0px 0px 0px 60px;">
<div style="font-size:1.1em;text-align: left;margin:0 0 0 60px;">
- You may only use these brackets ( ). <br/>
- Use * for multiplication and / for division. <br/>
- Valid operators and operands are:<br/>
<div style="margin-left: 10px;">
<i>Operators</i>: <b>[+ - * / ]</b><br/>
<i>Operators</i>: <b>[+ - * / ^]</b><br/>
<i>Operands</i>: Any alphabetic letter.
</div>
</div>
Expand Down
44 changes: 22 additions & 22 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,41 @@

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>Expression Tree Generator</title>
<!--start favicon meta deta-->
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="theme-color" content="#ffffff">
<link href="favicon.ico" rel="icon" type="image/x-icon"/>
<meta content="#ffffff" name="theme-color">
<!--end favicon metadata-->

<link rel="stylesheet" href="app.css">
<link href="app.css" rel="stylesheet">
</head>

<body>

<div class="contact-section">
<div class="inner-width">
<h1>Expression Tree Generator</h1>
<div class="inner-input-container" style="text-align: left;">
<span>Current Expression:</span>
<input type="text" class="name" id='expression-input' placeholder="e.g (x + y)*z - (t / w)">
</div>

<div class="buttons">
<button id="generate-tree">Generate</button>
<button id="clear-tree">Clear</button>
</div>
<div class="contact-section">
<div class="inner-width">
<h1>Expression Tree Generator</h1>
<div class="inner-input-container" style="text-align: left;">
<span>Current Expression:</span>
<input class="name" id='expression-input' placeholder="e.g (x + y)*z - (t / w)" type="text">
</div>

<div class="buttons">
<button id="generate-tree">Generate</button>
<button id="clear-tree">Clear</button>
</div>
</div>

<div id="canvas-container">
<canvas></canvas>
</div>
</div>

<div id="canvas-container">
<canvas></canvas>
</div>

<a class="github-link" href="https://github.com/lnogueir/expression-tree-gen">
<img src="GitHub_Logo.png" />
</a>
<a class="github-link" href="https://github.com/lnogueir/expression-tree-gen">
<img src="GitHub_Logo.png" alt="GitHub_Logo"/>
</a>

</body>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
Expand Down
124 changes: 61 additions & 63 deletions infixToPostfix.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,76 @@

const ALPHA_BIT = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
const OPERATORS = "^*()/+-"
const NUMBERS = "0123456789"

function isBracketed(expr) {
var stack = []
for (var i = 0; i < expr.length; i++) {
if ('(' === expr[i]) {
stack.push('(')
} else if (')' === expr[i]) {
stack.pop()
if (stack.length === 0) {
if (i !== expr.length - 1) {
return false
} else {
return true
const stack = [];
for (let i = 0; i < expr.length; i++) {
if ('(' === expr[i]) {
stack.push('(')
} else if (')' === expr[i]) {
stack.pop()
if (stack.length === 0) {
return i === expr.length - 1;
}
}
}
}
}
return false;
return false;
}

function isValidExpression(expr) {
if (expr.length < 3) {
return false;
}
for (var i = 0; i < expr.length; i++) {
if ('abcdefghijklmnopqrstuvwxyz*()/+-'.indexOf(expr[i]) === -1) {
return false;
if (expr.length < 3) {
return false;
}
}
try {
while ("(" === expr[0] && ")" === expr[expr.length - 1]) {
if (isBracketed(expr)) {
expr = expr.substring(1, expr.length - 1);
} else break;
for (let i = 0; i < expr.length; i++) {
if ((ALPHA_BIT+OPERATORS+NUMBERS).indexOf(expr[i]) === -1) {
return false;
}
}
var res = math.parse(expr);
if ((typeof res.implicit === 'undefined') || res.fn.indexOf('unary') !== -1) {
return false;
try {
while ("(" === expr[0] && ")" === expr[expr.length - 1]) {
if (isBracketed(expr)) {
expr = expr.substring(1, expr.length - 1);
} else break;
}
const res = math.parse(expr);
return !((typeof res.implicit === 'undefined') || res.fn.indexOf('unary') !== -1);

} catch (ex) {
return false;
}
return true;
}
catch (ex) {
return false;
}
}

function infixToPostfix(expression) {
if (!isValidExpression(expression)) {
return null;
}
const prec = { "*": 3, "/": 3, "-": 2, "+": 2, "(": 1 }
op_stack = []
postfixList = []
tokens = expression.split('')
for (const token of tokens) {
if ("abcdefghijklmnopqrstuvwxyz".indexOf(token) !== -1) {
postfixList.push(token)
} else if ("(" === token) {
op_stack.push(token)
} else if (")" === token) {
var top_op_token = op_stack.pop()
while (top_op_token !== '(') {
postfixList.push(top_op_token)
top_op_token = op_stack.pop()
}
} else {
var peek_elem = op_stack.slice(-1)[0];
while (op_stack.length > 0 && (prec[peek_elem] >= prec[token])) {
if (!isValidExpression(expression)) {
return null;
}
const prec = {"^": 4, "*": 3, "/": 3, "-": 2, "+": 2, "(": 1}
let op_stack = []
let postfixList = []
let tokens = expression.split('')
for (const token of tokens) {
if ((ALPHA_BIT+NUMBERS).indexOf(token) !== -1) {
postfixList.push(token)
} else if ("(" === token) {
op_stack.push(token)
} else if (")" === token) {
let top_op_token = op_stack.pop();
while (top_op_token !== '(') {
postfixList.push(top_op_token)
top_op_token = op_stack.pop()
}
} else {
let peek_elem = op_stack.slice(-1)[0];
while (op_stack.length > 0 && (prec[peek_elem] >= prec[token])) {
postfixList.push(op_stack.pop())
peek_elem = op_stack.slice(-1)[0];
}
op_stack.push(token)
}
}
while (op_stack.length > 0) {
postfixList.push(op_stack.pop())
peek_elem = op_stack.slice(-1)[0];
}
op_stack.push(token)
}
}
while (op_stack.length > 0) {
postfixList.push(op_stack.pop())
}
return postfixList
return postfixList
}
65 changes: 33 additions & 32 deletions tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,44 +37,49 @@ function Node(value) {
}

function drawEdgeAnimated(origin_x, origin_y, destine_x, destine_y, ctx, resolve) {
const vertices = [{ x: origin_x, y: origin_y }, { x: destine_x, y: destine_y }]
const vertices = [{x: origin_x, y: origin_y}, {x: destine_x, y: destine_y}]
const N = 35;
var waypoints = [];
for (var i = 1; i < vertices.length; i++) {
var pt0 = vertices[i - 1];
var pt1 = vertices[i];
var dx = pt1.x - pt0.x;
var dy = pt1.y - pt0.y;
for (var j = 0; j <= N; j++) {
var x = pt0.x + dx * j / N;
var y = pt0.y + dy * j / N;
waypoints.push({ x: x, y: y });
const waypoints = [];
for (let i = 1; i < vertices.length; i++) {
const pt0 = vertices[i - 1];
const pt1 = vertices[i];
const dx = pt1.x - pt0.x;
const dy = pt1.y - pt0.y;
for (let j = 0; j <= N; j++) {
const x = pt0.x + dx * j / N;
const y = pt0.y + dy * j / N;
waypoints.push({x: x, y: y});
}
}
var t = 1
let t = 1;

function resolveCallback(callback) {
function animate() {
if (t < waypoints.length - 1) { requestAnimationFrame(animate) }
else { callback() }
if (t < waypoints.length - 1) {
requestAnimationFrame(animate)
} else {
callback()
}
ctx.beginPath();
ctx.moveTo(waypoints[t - 1].x, waypoints[t - 1].y);
ctx.lineTo(waypoints[t].x, waypoints[t].y);
ctx.stroke();
t++;
}

return animate
}

requestAnimationFrame(resolveCallback(resolve))
}

function constructTree(postfix) {
const OPERATORS = ['*', '/', '-', '+']
var stack = []
var root = null;
var current;
var shift = false;
for (var i = postfix.length - 1; i >= 0; i--) {
const OPERATORS = ['^', '*', '/', '-', '+']
const stack = [];
let root = null;
let current;
let shift = false;
for (let i = postfix.length - 1; i >= 0; i--) {
if (null === root) {
current = new Node(postfix[i]);
root = current;
Expand All @@ -99,31 +104,26 @@ function constructTree(postfix) {
}

function getSize(root) {
var size = 0
let size = 0;

function countSize(root) {
if (null != root) {
size++;
countSize(root.left)
countSize(root.right)
}
}

countSize(root);
return size;
}

function print_coords(root) {
if (null != root) {
print_coords(root.left)
console.log(root.value, root.x, root.y)
print_coords(root.right)
}
}

function setCoordinates(root) {
var i = 0
let i = 0;
const OFFSET = 50
const size = getSize(root)
const canvas_mid_point = window.innerWidth / 2;

function setCoordinates(subt, depth) {
if (null != subt) {
setCoordinates(subt.left, depth + 1)
Expand All @@ -133,6 +133,7 @@ function setCoordinates(root) {
setCoordinates(subt.right, depth + 1)
}
}

setCoordinates(root, 0)
}

Expand All @@ -143,10 +144,10 @@ async function drawTree(root, context) {
if (null != root.left) {
await new Promise(resolve => root.drawEdge(context, root.left.x, root.left.y, true, resolve))
}
drawTree(root.left, context)
await drawTree(root.left, context)
if (null != root.right) {
await new Promise(resolve => root.drawEdge(context, root.right.x, root.right.y, false, resolve))
}
drawTree(root.right, context)
await drawTree(root.right, context)
}
}