Skip to content

Instantly share code, notes, and snippets.

@galElmalah
Last active June 11, 2020 09:53
Show Gist options
  • Save galElmalah/a227a2b12557d4c799adfc2a57e4a422 to your computer and use it in GitHub Desktop.
Save galElmalah/a227a2b12557d4c799adfc2a57e4a422 to your computer and use it in GitHub Desktop.
putting it all together
const canvas = document.querySelector("canvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
const ctx = canvas.getContext("2d");
const ACTIONS = {
SORT: "SORT",
COMPARE: "COMPARE",
SWAP: "SWAP",
};
const actionsMap = {
[ACTIONS.SORT]: (action, members) => members[action.data].sorted(),
[ACTIONS.SWAP]: (action, members) => {
const [i, j] = action.data;
let tmp = members[i].getValue();
members[i].setValue(members[j].getValue(), "red");
members[j].setValue(tmp, "yellow");
},
[ACTIONS.COMPARE]: (action, members) => {
const [i, j] = action.data;
members[i].setColor("blue");
members[j].setColor("blue");
},
};
const shuffledArrayInRange = (bottom = 1, top = 30) => {
const arr = [];
for (let i = bottom; i < top; i++) arr.push(i);
return arr.sort((a, b) => (Math.random() > 0.5 ? 1 : -1));
};
const bubbleSort = (array, onAction) => {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
onAction({ type: ACTIONS.COMPARE, data: [j, j + 1] });
if (array[j] > array[j + 1]) {
let tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
onAction({ type: ACTIONS.SWAP, data: [j, j + 1] });
}
}
onAction({ type: ACTIONS.SORT, data: array.length - i - 1 });
}
return array;
};
function ArrayMember(x, y, width, height, color = "gray") {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
this.draw = () => {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
this.resetColor = () => this.setColor("gray");
this.setColor = (color) => {
if (!this.isSorted()) {
this.color = color;
}
};
this.isSorted = () => this.color === "green";
this.sorted = () => (this.color = "green");
this.setValue = (v, color) => {
if (!this.isSorted()) {
this.height = v;
this.setColor(color);
}
};
this.getValue = (v) => this.height;
}
const randomArray = shuffledArrayInRange();
const arrayMembers = randomArray.map((v, i) => {
return new ArrayMember(10 * i + i, 0, 10, v * 5);
});
const drawAll = () => arrayMembers.forEach((m) => m.draw());
drawAll();
let ticks = 0;
const speed = 50;
bubbleSort(randomArray, (action) => {
ticks++;
setTimeout(() => {
actionsMap[action.type](action, arrayMembers);
ctx.clearRect(0, 0, innerWidth, innerHeight);
drawAll(arrayMembers);
arrayMembers.forEach((m) => m.resetColor());
}, ticks * speed);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment