algosort
Version:
This node package is for all javascript developers who are interested in sorting algorithms. This package gives you the possibility to choose between many different sorting algorithms. This package will output a two dimensional array of all numbers in dif
642 lines (604 loc) • 21 kB
JavaScript
// modules are defined as an array
// [ module function, map of requires ]
//
// map of requires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the require for previous bundles
(function(modules, entry, mainEntry, parcelRequireName, globalName) {
/* eslint-disable no-undef */
var globalObject =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
/* eslint-enable no-undef */
// Save the require from previous bundle to this closure if any
var previousRequire =
typeof globalObject[parcelRequireName] === 'function' &&
globalObject[parcelRequireName];
var cache = previousRequire.cache || {};
// Do not use `require` to prevent Webpack from trying to bundle this call
var nodeRequire =
typeof module !== 'undefined' &&
typeof module.require === 'function' &&
module.require.bind(module);
function newRequire(name, jumped) {
if (!cache[name]) {
if (!modules[name]) {
// if we cannot find the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire =
typeof globalObject[parcelRequireName] === 'function' &&
globalObject[parcelRequireName];
if (!jumped && currentRequire) {
return currentRequire(name, true);
}
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) {
return previousRequire(name, true);
}
// Try the node require function if it exists.
if (nodeRequire && typeof name === 'string') {
return nodeRequire(name);
}
var err = new Error("Cannot find module '" + name + "'");
err.code = 'MODULE_NOT_FOUND';
throw err;
}
localRequire.resolve = resolve;
localRequire.cache = {};
var module = (cache[name] = new newRequire.Module(name));
modules[name][0].call(
module.exports,
localRequire,
module,
module.exports,
this
);
}
return cache[name].exports;
function localRequire(x) {
return newRequire(localRequire.resolve(x));
}
function resolve(x) {
return modules[name][1][x] || x;
}
}
function Module(moduleName) {
this.id = moduleName;
this.bundle = newRequire;
this.exports = {};
}
newRequire.isParcelRequire = true;
newRequire.Module = Module;
newRequire.modules = modules;
newRequire.cache = cache;
newRequire.parent = previousRequire;
newRequire.register = function(id, exports) {
modules[id] = [
function(require, module) {
module.exports = exports;
},
{},
];
};
Object.defineProperty(newRequire, 'root', {
get: function() {
return globalObject[parcelRequireName];
},
});
globalObject[parcelRequireName] = newRequire;
for (var i = 0; i < entry.length; i++) {
newRequire(entry[i]);
}
if (mainEntry) {
// Expose entry point to Node, AMD or browser globals
// Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
var mainExports = newRequire(mainEntry);
// CommonJS
if (typeof exports === 'object' && typeof module !== 'undefined') {
module.exports = mainExports;
// RequireJS
} else if (typeof define === 'function' && define.amd) {
define(function() {
return mainExports;
});
// <script>
} else if (globalName) {
this[globalName] = mainExports;
}
}
})({"5EnSf":[function(require,module,exports) {
var HMR_HOST = null;
var HMR_PORT = 1234;
var HMR_SECURE = false;
var HMR_ENV_HASH = "d751713988987e9331980363e24189ce";
module.bundle.HMR_BUNDLE_ID = "db2a8f19f28dffc13c4d65df5ef14ffa";
// @flow
/*global HMR_HOST, HMR_PORT, HMR_ENV_HASH, HMR_SECURE*/
/*::
import type {
HMRAsset,
HMRMessage,
} from '@parcel/reporter-dev-server/src/HMRServer.js';
interface ParcelRequire {
(string): mixed;
cache: {|[string]: ParcelModule|};
hotData: mixed;
Module: any;
parent: ?ParcelRequire;
isParcelRequire: true;
modules: {|[string]: [Function, {|[string]: string|}]|};
HMR_BUNDLE_ID: string;
root: ParcelRequire;
}
interface ParcelModule {
hot: {|
data: mixed,
accept(cb: (Function) => void): void,
dispose(cb: (mixed) => void): void,
// accept(deps: Array<string> | string, cb: (Function) => void): void,
// decline(): void,
_acceptCallbacks: Array<(Function) => void>,
_disposeCallbacks: Array<(mixed) => void>,
|};
}
declare var module: {bundle: ParcelRequire, ...};
declare var HMR_HOST: string;
declare var HMR_PORT: string;
declare var HMR_ENV_HASH: string;
declare var HMR_SECURE: boolean;
*/
var OVERLAY_ID = '__parcel__error__overlay__';
var OldModule = module.bundle.Module;
function Module(moduleName) {
OldModule.call(this, moduleName);
this.hot = {
data: module.bundle.hotData,
_acceptCallbacks: [],
_disposeCallbacks: [],
accept: function (fn) {
this._acceptCallbacks.push(fn || (function () {}));
},
dispose: function (fn) {
this._disposeCallbacks.push(fn);
}
};
module.bundle.hotData = undefined;
}
module.bundle.Module = Module;
var checkedAssets, /*: {|[string]: boolean|}*/
acceptedAssets, /*: {|[string]: boolean|}*/
/*: {|[string]: boolean|}*/
assetsToAccept;
function getHostname() {
return HMR_HOST || (location.protocol.indexOf('http') === 0 ? location.hostname : 'localhost');
}
function getPort() {
return HMR_PORT || location.port;
}
// eslint-disable-next-line no-redeclare
var parent = module.bundle.parent;
if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
var hostname = getHostname();
var port = getPort();
var protocol = HMR_SECURE || location.protocol == 'https:' && !(/localhost|127.0.0.1|0.0.0.0/).test(hostname) ? 'wss' : 'ws';
var ws = new WebSocket(protocol + '://' + hostname + (port ? ':' + port : '') + '/');
// $FlowFixMe
ws.onmessage = function (event) /*: {data: string, ...}*/
{
checkedAssets = {
/*: {|[string]: boolean|}*/
};
acceptedAssets = {
/*: {|[string]: boolean|}*/
};
assetsToAccept = [];
var data = /*: HMRMessage*/
JSON.parse(event.data);
if (data.type === 'update') {
// Remove error overlay if there is one
removeErrorOverlay();
let assets = data.assets.filter(asset => asset.envHash === HMR_ENV_HASH);
// Handle HMR Update
var handled = false;
assets.forEach(asset => {
var didAccept = asset.type === 'css' || asset.type === 'js' && hmrAcceptCheck(module.bundle.root, asset.id, asset.depsByBundle);
if (didAccept) {
handled = true;
}
});
if (handled) {
console.clear();
assets.forEach(function (asset) {
hmrApply(module.bundle.root, asset);
});
for (var i = 0; i < assetsToAccept.length; i++) {
var id = assetsToAccept[i][1];
if (!acceptedAssets[id]) {
hmrAcceptRun(assetsToAccept[i][0], id);
}
}
} else {
window.location.reload();
}
}
if (data.type === 'error') {
// Log parcel errors to console
for (let ansiDiagnostic of data.diagnostics.ansi) {
let stack = ansiDiagnostic.codeframe ? ansiDiagnostic.codeframe : ansiDiagnostic.stack;
console.error('🚨 [parcel]: ' + ansiDiagnostic.message + '\n' + stack + '\n\n' + ansiDiagnostic.hints.join('\n'));
}
// Render the fancy html overlay
removeErrorOverlay();
var overlay = createErrorOverlay(data.diagnostics.html);
// $FlowFixMe
document.body.appendChild(overlay);
}
};
ws.onerror = function (e) {
console.error(e.message);
};
ws.onclose = function (e) {
if (undefined !== 'test') {
console.warn('[parcel] 🚨 Connection to the HMR server was lost');
}
};
}
function removeErrorOverlay() {
var overlay = document.getElementById(OVERLAY_ID);
if (overlay) {
overlay.remove();
console.log('[parcel] ✨ Error resolved');
}
}
function createErrorOverlay(diagnostics) {
var overlay = document.createElement('div');
overlay.id = OVERLAY_ID;
let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, monospace; z-index: 9999;">';
for (let diagnostic of diagnostics) {
let stack = diagnostic.codeframe ? diagnostic.codeframe : diagnostic.stack;
errorHTML += `
<div>
<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">
🚨 ${diagnostic.message}
</div>
<pre>
${stack}
</pre>
<div>
${diagnostic.hints.map(hint => '<div>' + hint + '</div>').join('')}
</div>
</div>
`;
}
errorHTML += '</div>';
overlay.innerHTML = errorHTML;
return overlay;
}
function getParents(bundle, id) /*: Array<[ParcelRequire, string]>*/
{
var modules = bundle.modules;
if (!modules) {
return [];
}
var parents = [];
var k, d, dep;
for (k in modules) {
for (d in modules[k][1]) {
dep = modules[k][1][d];
if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
parents.push([bundle, k]);
}
}
}
if (bundle.parent) {
parents = parents.concat(getParents(bundle.parent, id));
}
return parents;
}
function updateLink(link) {
var newLink = link.cloneNode();
newLink.onload = function () {
if (link.parentNode !== null) {
// $FlowFixMe
link.parentNode.removeChild(link);
}
};
newLink.setAttribute('href', // $FlowFixMe
link.getAttribute('href').split('?')[0] + '?' + Date.now());
// $FlowFixMe
link.parentNode.insertBefore(newLink, link.nextSibling);
}
var cssTimeout = null;
function reloadCSS() {
if (cssTimeout) {
return;
}
cssTimeout = setTimeout(function () {
var links = document.querySelectorAll('link[rel="stylesheet"]');
for (var i = 0; i < links.length; i++) {
// $FlowFixMe[incompatible-type]
var href = /*: string*/
links[i].getAttribute('href');
var hostname = getHostname();
var servedFromHMRServer = hostname === 'localhost' ? new RegExp('^(https?:\\/\\/(0.0.0.0|127.0.0.1)|localhost):' + getPort()).test(href) : href.indexOf(hostname + ':' + getPort());
var absolute = (/^https?:\/\//i).test(href) && href.indexOf(window.location.origin) !== 0 && !servedFromHMRServer;
if (!absolute) {
updateLink(links[i]);
}
}
cssTimeout = null;
}, 50);
}
function hmrApply(bundle, /*: ParcelRequire*/
asset) /*: HMRAsset*/
{
var modules = bundle.modules;
if (!modules) {
return;
}
if (asset.type === 'css') {
reloadCSS();
return;
}
let deps = asset.depsByBundle[bundle.HMR_BUNDLE_ID];
if (deps) {
var fn = new Function('require', 'module', 'exports', asset.output);
modules[asset.id] = [fn, deps];
} else if (bundle.parent) {
hmrApply(bundle.parent, asset);
}
}
function hmrAcceptCheck(bundle, /*: ParcelRequire*/
id, /*: ParcelRequire*/
/*: string*/
depsByBundle) /*: ?{ [string]: { [string]: string } }*/
{
var modules = bundle.modules;
if (!modules) {
return;
}
if (depsByBundle && !depsByBundle[bundle.HMR_BUNDLE_ID]) {
// If we reached the root bundle without finding where the asset should go,
// there's nothing to do. Mark as "accepted" so we don't reload the page.
if (!bundle.parent) {
return true;
}
return hmrAcceptCheck(bundle.parent, id, depsByBundle);
}
if (checkedAssets[id]) {
return;
}
checkedAssets[id] = true;
var cached = bundle.cache[id];
assetsToAccept.push([bundle, id]);
if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
return true;
}
return getParents(module.bundle.root, id).some(function (v) {
return hmrAcceptCheck(v[0], v[1], null);
});
}
function hmrAcceptRun(bundle, /*: ParcelRequire*/
id) /*: string*/
{
var cached = bundle.cache[id];
bundle.hotData = {};
if (cached && cached.hot) {
cached.hot.data = bundle.hotData;
}
if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
cached.hot._disposeCallbacks.forEach(function (cb) {
cb(bundle.hotData);
});
}
delete bundle.cache[id];
bundle(id);
cached = bundle.cache[id];
if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
cached.hot._acceptCallbacks.forEach(function (cb) {
var assetsToAlsoAccept = cb(function () {
return getParents(module.bundle.root, id);
});
if (assetsToAlsoAccept && assetsToAccept.length) {
assetsToAccept.push.apply(assetsToAccept, assetsToAlsoAccept);
}
});
}
acceptedAssets[id] = true;
}
},{}],"66MIe":[function(require,module,exports) {
var _indexJs = require("./index.js");
class Bar {
constructor(width, height, posx, posy) {
this.width = width;
this.height = height;
this.posx = posx;
this.posy = posy;
}
draw(ctx, color) {
ctx.fillStyle = color;
ctx.fillRect(this.posx, this.posy, this.width, this.height);
}
}
document.addEventListener('DOMContentLoaded', () => {
let graphs = document.querySelectorAll('.algosort');
graphs.forEach(graph => {
if (document.getElementsByClassName('algosort')[0].toString() === "[object HTMLCanvasElement]") {
let width = graph.getAttribute("width");
let height = graph.getAttribute("height");
width = width.substring(0, width.length - 2);
height = height.substring(0, height.length - 2);
let ctx = graph.getContext("2d");
let barNumber;
if (graph.getAttribute("bars") > 2 && graph.getAttribute("bars") < 1000) {
barNumber = graph.getAttribute("bars");
} else {
ctx.font = '20px sans-serif';
ctx.fillText(`The number of bars must be less than 1000 and more than 2! Current bar number: ${graph.getAttribute("bars")}`, 10, 30);
console.error(`The number of bars must be less than 1000 and more than 2! Current bar number: ${graph.getAttribute("bars")}`);
barNumber = 0;
}
let bars = new Array(parseInt(barNumber));
function drawBars(i) {
bars[i].draw(ctx, graph.getAttribute("barColor"));
}
var numbers = [];
for (let i = 0; i < barNumber; i++) {
let barHeight = Math.random() * height;
numbers.push(barHeight);
}
var sortedNumbers = _indexJs.algosort({
algorithm: graph.getAttribute("algorithm"),
numbers: numbers,
output: graph.getAttribute("output")
});
let speed;
if (graph.getAttribute("speed") > 10 && graph.getAttribute("speed") < 10000) {
speed = graph.getAttribute("speed");
} else {
ctx.font = '20px sans-serif';
ctx.fillText(`The speed value must be less than 10000 and more than 10! Current speed value: ${graph.getAttribute("speed")}`, 10, 30);
console.error(`The speed value must be less than 10000 and more than 10! Current speed value: ${graph.getAttribute("speed")}`);
speed = false;
}
function animation(i) {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, width, height);
for (let j = 0; j < sortedNumbers[i].length; j++) {
bars[j] = new Bar(width / barNumber, sortedNumbers[i][j], width / barNumber * j, height - sortedNumbers[i][j]);
drawBars(j);
}
if (i < sortedNumbers.length - 1) {
setTimeout(() => {
i++;
animation(i);
}, graph.getAttribute("speed"));
} else {
console.log("Sorted!");
}
}
if (sortedNumbers !== `"${graph.getAttribute("output")}" is no valid output option! \n\n Output options: "afterEachNumber", "afterEachRun" and "afterAllRuns"` && speed != false && bars.length > 1 && sortedNumbers !== `There is no algorithm called ${graph.getAttribute("algorithm")}! \n\n Algorithm options: "bubblesort" and "selectionsort"`) {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, width, height);
console.log(sortedNumbers);
animation(0);
} else if (sortedNumbers === `There is no algorithm called ${graph.getAttribute("algorithm")}! \n\n Algorithm options: "bubblesort" and "selectionsort"`) {
ctx.font = '20px sans-serif';
ctx.fillText(`There is no algorithm called "${graph.getAttribute("algorithm")}"!`, 10, 30);
}
} else {
document.body.innerHTML = `<h1>The html object must be a canvas!</h1>`;
console.error("The html object must be a canvas!");
}
});
});
},{"./index.js":"5rkFb"}],"5rkFb":[function(require,module,exports) {
const bubblesortAlgorithm = require('../algorithms/bubblesort.js');
const selectionsortAlgorithm = require('../algorithms/selectionsort.js');
function algosort(options) {
if (options.algorithm == null)
options.algorithm = `bubblesort`;
if (options.output == null)
options.output = `afterEachNumber`;
if (options.numbers != null)
if (options.algorithm === `bubblesort`)
return bubblesortAlgorithm.bubblesort(options.numbers, 0, options.output, 0);
else if (options.algorithm === `selectionsort`)
return selectionsortAlgorithm.selectionsort(options.numbers, 0, options.output, 0);
else
return `There is no algorithm called ${options.algorithm}! \n\n Algorithm options: "bubblesort" and "selectionsort"`;
else
return `You need to enter an array of numbers!`;
}
module.exports.algosort = algosort;
},{"../algorithms/bubblesort.js":"6RNAy","../algorithms/selectionsort.js":"3Wd1E"}],"6RNAy":[function(require,module,exports) {
var sortedNumbers = [];
var arrayOfArrays = [];
exports.bubblesort = function(numbers, i, output, testIndicator) {
if (output === "afterEachNumber")
sortedNumbers = sortedNumbers.concat(numbers);
else if (output === "afterEachRun") {
if (i == 0)
sortedNumbers = sortedNumbers.concat(numbers);
} else if (output === "afterAllRuns") {
if (testIndicator == numbers.length-1)
sortedNumbers = sortedNumbers.concat(numbers);
} else
return `"${output}" is no valid output option! \n\n Output options: "afterEachNumber", "afterEachRun" and "afterAllRuns"` ;
if (numbers[i] > numbers[i+1]) {
var smallerNumber = numbers[i+1];
numbers[i+1] = numbers[i];
numbers[i] = smallerNumber;
testIndicator = 0;
} else {
testIndicator++;
}
if (testIndicator < numbers.length) {
if (i < numbers.length-2) {
i++;
this.bubblesort(numbers, i, output, testIndicator);
} else {
this.bubblesort(numbers, 0, output, testIndicator);
}
} else {
for (var i=0; i<sortedNumbers.length; i+=numbers.length) {
arrayOfArrays.push(sortedNumbers.slice(i,i+numbers.length));
}
}
return arrayOfArrays;
}
},{}],"3Wd1E":[function(require,module,exports) {
var sortedNumbers = [];
var arrayOfArrays = [];
exports.selectionsort = function (numbers, i, output, testIndicator) {
if (output === "afterEachNumber") {
sortedNumbers = sortedNumbers.concat(numbers);
if (testIndicator == numbers.length-1)
console.log('In This case the output is the same as with the option "afterEachRun", because of other algorithm structure!');
} else if (output === "afterEachRun") {
sortedNumbers = sortedNumbers.concat(numbers);
if (testIndicator == numbers.length-1)
console.log('In This case the output is the same as with the option "afterEachNumber", because of other algorithm structure!');
} else if (output === "afterAllRuns") {
if (testIndicator == numbers.length-1)
sortedNumbers = sortedNumbers.concat(numbers);
} else
return `"${output}" is no valid output option! \n\n Output options: "afterEachNumber", "afterEachRun" and "afterAllRuns"` ;
var min = i;
for (var j = i; j < numbers.length; j++){
if (numbers[j] <= numbers[min]){
min = j;
}
}
var smallestNumber = numbers[min];
numbers[min] = numbers[i];
numbers[i] = smallestNumber;
testIndicator++;
if (testIndicator < numbers.length) {
if (i < numbers.length) {
i++;
this.selectionsort(numbers, i, output, testIndicator);
} else {
console.error("There is an error!");
}
} else {
for (var i=0; i<sortedNumbers.length; i+=numbers.length) {
arrayOfArrays.push(sortedNumbers.slice(i,i+numbers.length));
}
}
return arrayOfArrays;
}
},{}]},["5EnSf","66MIe"], "66MIe", "parcelRequirec073")
//# sourceMappingURL=index.5ef14ffa.js.map