JSFiddle - React, Tailwind, and code Playground
by vla
JavaScript
/***************************************************************
/* Blocks by Vlad Yazhbin, 2/9/15
/* Features:
/* * A very memory-efficient block tracking application.
/* * Does not require knowledge of how many blocks you want ahead of time.
/* * Change how many locations you want to print out at run-time.
/* * Supports "unlimited" blocks, memory limited by the # of blocks not in default location.
/* * Only blocks that are not at default locations are tracked.
/* Uses a dictionary to look up the location a particular block is in:
/* * Key is empty if the block is somewhere in the original location (at any level).
/* Uses a dictionary to store a stack (array) of blocks at a location:
* Key is empty (and stack not defined) if a block is in its original location.
* Block is "virtual" (not in stack) when both a) it's at the bottom level of
b) the original location.
/* Usage:
/* var blocks = Blocks() or var blocks = new Blocks()
/* blocks.move(5, 1) or blocks.moveCommands("move 5 to 1 move 6 to 1"...)
/* blocks.print(15) to print contents of the first 15 locations
/* blocks.print() without parameter defaults to 10
**************************************************************/
var Blocks = function () {
//we should know where a block is (which stack to look in) to find it quickly
//we will use a dictionary to track differences, to minimize space
//we also need a stack for every group of blocks
var blocksToLocations = {};
var getBlockLocation = function (block) {
//block's location not in dictionary? It's the default, that's why
if (typeof (blocksToLocations[block]) === 'undefined') {
return block;
} else {
return blocksToLocations[block];
}
};
var updateBlockLocation = function (block, newLocation) {
//block is going to its default location? Delete the key from dictionary, otherwise update it
if (block == newLocation) {
...