Skip to content

use dynamically generated block size; get live updating working #11

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

Merged
merged 3 commits into from
Nov 18, 2017
Merged
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
11 changes: 7 additions & 4 deletions .babelrc.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
const is = env => process.env.NODE_ENV === env;

const TEST = is('test');
const PRODUCTION = is('production');

module.exports = {
presets: [
[
'@babel/env',
{
modules: is('test') ? 'commonjs' : false,
modules: TEST ? 'commonjs' : false,
targets: {
node: 'current'
}
Expand All @@ -19,10 +22,10 @@ module.exports = {
[
'emotion',
{
extractStatic: is('production'),
sourceMap: is('production')
extractStatic: PRODUCTION,
sourceMap: PRODUCTION
}
],
'polished'
].concat(is('production') ? ['@babel/transform-runtime'] : [])
].concat(PRODUCTION ? ['@babel/transform-runtime'] : [])
};
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
dist/
node_modules/
.DS_Store

7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# algorithm-playground

## Credits

Without the work of these excellent folks, the algorithms you see visualized would have been written by me (but not as well). I sincerely thank them for their work!

- http://blog.benoitvallon.com/sorting-algorithms-in-javascript/sorting-algorithms-in-javascript-all-the-code/
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"emotion": "~8.0.10",
"emotion-theming": "~8.0.10",
"lodash.camelcase": "~4.3.0",
"lodash.debounce": "~4.0.8",
"normalize.css": "~7.0.0",
"polished": "~1.9.0",
"proxy-polyfill": "~0.1.7",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import fs from 'fs';
import path from 'path';
import camelCase from 'lodash.camelcase';

const EXCLUDE = [/^__/, /^\./, /index\.js/];

const base = path.join(__dirname, '..');
const files = fs.readdirSync(base).filter(file => !/^__/.test(file));
const files = fs
.readdirSync(base)
.filter(file => !EXCLUDE.some(expr => expr.test(file)));

const algorithms = files.map(file => {
const [name] = file.split('.');
Expand Down
File renamed without changes.
50 changes: 0 additions & 50 deletions src/algorithms/general/__tests__/fibonacci.js

This file was deleted.

40 changes: 0 additions & 40 deletions src/algorithms/general/fibonacci.js

This file was deleted.

7 changes: 2 additions & 5 deletions src/algorithms/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,8 @@ const req = require.context('.', true, /\.js$/);
const keys = req.keys().filter(key => !exclude.some(expr => expr.test(key)));

keys.forEach(key => {
const [folder, name] = key.replace('./', '').split('/');
algorithms[folder] = {
...(algorithms[folder] || {}),
[camelCase(name.replace(/\..+/, ''))]: req(key)
};
const [name] = key.replace('./', '').split('.');
algorithms[camelCase(name.replace(/\..+/, ''))] = req(key);
});

export default algorithms;
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
// http://learnjswith.me/quick-sort-in-javascript/
function partition(items, left, right) {
function partition(arr, left, right) {
// create pivot as middle value
const pivot = items[Math.floor((right + left) / 2)];
const pivot = arr[Math.floor((right + left) / 2)];

let i = left; // start left and go right towards pivot
let j = right; // start right and go left towards pivot

while (i <= j) {
while (items[i] < pivot) {
while (arr[i] < pivot) {
i++;
}
while (items[j] > pivot) {
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
// swap values using destructuring
[items[i], items[j]] = [items[j], items[i]];
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
j--;
}
}
return i;
}

export function quickSort(items, left = 0, right = items.length - 1) {
export function quickSort(arr, left = 0, right = arr.length - 1) {
let index;
if (items.length > 1) {
if (arr.length > 1) {
// create the partition (split the array)
index = partition(items, left, right);
index = partition(arr, left, right);

if (left < index - 1) {
quickSort(items, left, index - 1);
quickSort(arr, left, index - 1);
}
if (index < right) {
quickSort(items, index, right);
quickSort(arr, index, right);
}
}
return items;
return arr;
}
File renamed without changes.
8 changes: 3 additions & 5 deletions src/canvas.worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@ const observable = (arr, callback) =>
apply: function(target, thisArg, argumentsList) {
return thisArg[target].apply(this, argumentList);
},
deleteProperty: function(target, property) {
console.log('Deleted %s', property);
return true;
},
set: function(target, index, value, receiver) {
target[index] = value;
callback([parseInt(index, 10), value]);
Expand All @@ -26,7 +22,9 @@ if (typeof onmessage !== 'undefined') {

let changes = [];

const observableArr = observable(row, arr => changes.push(arr));
const updateChanges = update => changes.push(update);

const observableArr = observable(row, updateChanges);

const sorted = sortFunction(observableArr);

Expand Down
57 changes: 40 additions & 17 deletions src/components/AlgorithmPreview/components/Canvas/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import React, { Component } from 'react';
import styled from 'react-emotion';
import debounce from 'lodash.debounce';
import Play from 'react-icons/lib/md/play-arrow';
import Replay from 'react-icons/lib/md/replay';

import {
createGrid,
createRow,
updateRow,
updateRowAtPosition
} from '../../util';
import { createGrid, updateRowAtPosition } from '../../util';
import { delay, pRequestAnimationFrame, sortRow } from '../../../../util';
import { SCALE_IN } from '../../../../style';

Expand Down Expand Up @@ -47,25 +43,37 @@ const StyledIcon = component => styled(component)`
`;

class CanvasComponent extends Component {
state = {
context: null,
grid: [],
height: 400,
width: 250,
inProgress: false,
sorted: false
};
constructor(props) {
super(props);

this.state = {
context: null,
grid: [],
height: 400,
width: 250,
inProgress: false,
sorted: false
};

this.handleResize = debounce(this.handleResize, 50);
}

componentDidMount() {
this.setState({
context: this.canvas.getContext('2d'),
height: this.container.clientHeight,
width: this.container.clientWidth
});

window.addEventListener('resize', this.handleResize);
}

componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}

componentWillReceiveProps({ sortFunction }) {
if (this.props.sortFunction !== sortFunction) {
if (!this.props.sortFunction || this.props.sortFunction !== sortFunction && this.state.sorted) {
this.resetGrid();
this.setState({
inProgress: false
Expand Down Expand Up @@ -93,6 +101,16 @@ class CanvasComponent extends Component {
}
};

handleResize = () => {
this.setState(
{
height: this.container.clientHeight,
width: this.container.clientWidth
},
() => this.resetGrid()
);
};

sortGrid() {
return pRequestAnimationFrame(async () => {
return await Promise.all(
Expand All @@ -101,8 +119,13 @@ class CanvasComponent extends Component {

let updateIndex = 0;
while (updateIndex < updates.length) {
const [index, block] = updates[updateIndex];
updateRowAtPosition(this.state.context)(rowIndex, index, block);
const [blockIndex, hue] = updates[updateIndex];
updateRowAtPosition(this.state.context)({
rowIndex,
blockIndex,
width: this.state.width,
hue
});
await delay(0);
updateIndex += 1;
}
Expand Down
Loading