Archive for the ‘All’ Category
Thursday, February 10th, 2011
I was playing around with unscrambling words recently, and decided to implement a solver in JavaScript. I called it wordsolver.js.
Demo
There is a wordsolver demo on my site. Try typing in URESMTA or something to see all the words that get unscrambled.
Code
All code can be found in the wordsolver repository on github. In particular, here is the file that does all the heavy lifting. It is all available under the MIT license.
How does it perform?
Smoother than I expected it to. The load time for the dictionaries can be pretty slow (they are anywhere from 1.7MB to 2.6MB depending on the dictionary), but once it loads, it finds words pretty fast and tries to cache results. Warning: it will probably crash an iPhone while trying to load the dictionary array into memory
Posted in Algorithms, All, Open Source, Web Development | Tags: javascript, unscramble, words | No Comments »
Thursday, December 16th, 2010
I presented at the Columbia MO web developer meetup on 12/15/2010. I talked about HTML canvas and JavaScript FileReader, Instant Sprite, JavaScript image processing, and other topics.
The slides for the talk are available at http://briangrinstead.com/canvasslides.
More details about the monthly meeting.
Posted in All, Web Development | No Comments »
Monday, November 29th, 2010
I read a nice write up on on JSON and JSONP by Angus Croll. He provided a sample implementation of a safe JSONP library.
The library is concise and does the trick for a single connection, but I found it didn’t handle multiple connections. It would overwrite a single global callback, so if you had connections of varying speeds, you would undoubtedly get errors. For instance, “Request 1″ is very slow, and “Request 2″ gets finished before it. When “Request 1″ gets finished, it uses the callback for “Request 2″. This actually happened the first time I loaded it up and ran it. Not good.
Here is a simple updated version that takes care of that particular problem.
/*
An implementation of: http://javascriptweblog.wordpress.com/2010/11/29/json-and-jsonp/
that handles multiple connections at once (don't want to replace the global callback if second
request is sent after the first, but returns before.
*/
(function(global) {
var evalJSONP = function(callback) {
return function(data) {
var validJSON = false;
if (typeof data == "string") {
try {validJSON = JSON.parse(data);} catch (e) {
/*invalid JSON*/}
} else {
validJSON = JSON.parse(JSON.stringify(data));
window.console && console.warn(
'response data was not a JSON string');
}
if (validJSON) {
callback(validJSON);
} else {
throw("JSONP call returned invalid or empty JSON");
}
}
};
var callbackCounter = 0;
global.saferJSONP = function(url, callback) {
var fn = 'JSONPCallback_' + callbackCounter++;
global[fn] = evalJSONP(callback);
url = url.replace('=JSONPCallback', '=' + fn);
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = url;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
};
})(this);
To test it out:
var obamaTweets = "http://www.twitter.com/status/user_timeline/BARACKOBAMA.json?count=5&callback=JSONPCallback";
saferJSONP(obamaTweets, function(data) {console.log(data[0].text)});
var reddits = "http://www.reddit.com/.json?limit=1&jsonp=JSONPCallback";
saferJSONP(reddits , function(data) {console.log(data.data.children[0].data.title)});
If you are really worried about multiple global objects JSONPCallback_1, JSONPCallback_2, etc – you could store them all in an array instead. Like this:
(function(global) {
var evalJSONP = function(callback) {
return function(data) {
var validJSON = false;
if (typeof data == "string") {
try {validJSON = JSON.parse(data);} catch (e) {
/*invalid JSON*/}
} else {
validJSON = JSON.parse(JSON.stringify(data));
window.console && console.warn(
'response data was not a JSON string');
}
if (validJSON) {
callback(validJSON);
} else {
throw("JSONP call returned invalid or empty JSON");
}
}
};
var callbackCounter = 0;
global.JSONPCallbacks = [];
global.saferJSONP = function(url, callback) {
var count = callbackCounter++;
global.JSONPCallbacks[count] = evalJSONP(callback);
url = url.replace('=JSONPCallback', '=JSONPCallbacks[' + count + ']');
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = url;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
};
})(this);
Posted in All, Web Development | Tags: javascript, json, jsonp | 2 Comments »
Friday, November 19th, 2010
I’ve been working on a project to make generating CSS Sprites faster and easier. It is called Instant Sprite, and available at http://instantsprite.com. You can drop the images right into the browser (or open them up in a file input) and it generates the sprite in the browser, with no file uploads. You can check it out and use some sample images provided if you don’t have any images available.
Instant Sprite uses HTML Canvas and the FileReader interface to read images from your hard drive – this prevents you from having to zip up all the images before passing them off to the sprite generator. You can also preview your changes to CSS tweaks in real time, so you don’t have to resubmit if the file match regex isn’t doing what you want.
I’d like to give credit to Aaron Barker for helping out with a lot of feedback and UI suggestions.
I made it for myself so that generating sprites was easier, but put it online because I think it might be useful to others, too.
Posted in All, Open Source, Web Development | Tags: canvas, css sprite, css sprite generator, filereader, instantsprite, javascript | No Comments »
Sunday, November 14th, 2010
I am working on project that needs to read local files. This relies on the FileReader interface, and I couldn’t find any JavaScript libraries to help out with common usage for this, so I made one.
FileReader is a JavaScript interface that allows you to read local files as binary. This is available in supported browsers when a user drags and drops files into a browser window or selects files from an input with a type of file. See the FileReader specification for more information.
filereader.js is a wrapper for accessing this functionality. It can be called using:
FileReaderJS.setupInput(fileInput, opts);
FileReaderJS.setupDrop(dropbox, opts);
If you use jQuery, you can access these calls with:
$("#fileInput").fileReaderJS(opts);
$("#dropbox").fileReaderJS(opts);
To see the full range of options and functionality, view the readme.
filereader.js is available under the MIT License. See the full filereader.js code or the single file raw javascript source on github.
You can see an example project using filereader.js on Instant Sprite, a browser based CSS Sprite Generator that I am working on. Try dragging images onto the body, or clicking to add multiple image files to see what is possible.
Posted in All, Open Source, Plugins, Web Development | Tags: filereader, html, javascript, jquery | No Comments »
Wednesday, September 15th, 2010
When I first wrote the A* Search in JavaScript article I knew there were some things that could make the pathfinding faster. I didn’t know realize that it would be this much faster. Here are my (totally unscientific) results:
| Observed Speed of A* Search on Chrome 6.0.472.55 on OS X |
| # rows |
original |
updated |
| 100 |
700-2500ms (wildly variant) |
5-10ms |
| 50 |
160ms |
5-10ms |
| 15 |
0-5ms |
0-2ms |
Here’s What Changed
I got some feedback about using a heap or a priority queue instead of a list (basically keep the open items in sorted order the whole time so we can just grab it off of the top instead of needing to traverse the whole list every time. As predicted, this makes a huge difference as the number of nodes goes up, but may actually be a little slower for a very low number of nodes because of the overhead of keeping them sorted. I found a binary heap implementation from http://eloquentjavascript.net/appendix2.html and put it in.
Also, I realized two places that I was traversing lists that could be avoided. Getting rid of extra traversals (especially ones that ran inside nested loops) made a very big difference in performance.
- I was keeping all of the nodes inside a closed list, which required traversing that list every time to see if it was already closed. This was replaced with a simple bit on the node to track if it had been closed.
- I was checking to see if a node was visited already by seeing if it was in the open list. This was replaced by a simple bit to see if it had been visited.
Old Pseudocode
push startNode onto openList
while(openList is not empty) {
currentNode = find lowest f in openList
if currentNode is final, return the successful path
push currentNode onto closedList and remove from openList
foreach neighbor of currentNode {
if neighbor is not in openList {
save g, h, and f then save the current parent
add neighbor to openList
}
if neighbor is in openList but the current g is better than previous g {
save g and f, then save the current parent
}
}
Updated Pseudocode (* lines have changed)
* push startNode onto openHeap
while(openList is not empty) {
* currentNode = pop from openHeap
if currentNode is final, return the successful path
* set currentNode as closed
foreach neighbor of currentNode {
* if neighbor is not set visited {
* save g, h, and f then save the current parent and set visited
* add neighbor to openHeap
}
if neighbor is in openList but the current g is better than previous g {
save g and f, then save the current parent
* reset position in openHeap (since f changed)
}
}
I also did some general cleanup, getting rid of dependancies on the demo, and I split out the code so that the search function can be used standalone (taking a two dimensional array as a parameter), so if someone just wanted the optimized astar search, you could call it like so:
<script type='text/javascript' src='graph.js'></script>
<script type='text/javascript' src='astar.js'></script>
<script type='text/javascript'>
var graph = new Graph([
[0,0,0,0], // 0 is open, 1 is wall
[1,0,0,1],
[1,1,0,0]
]);
var start = graph.nodes[0][0];
var end = graph.nodes[1][2];
var result = astar.search(graph.nodes, start, end);
// result is an array containing the shortest path
</script>
What Could Make It Better?
Last time I posted about this, I got a lot of feedback (mostly about how slow it was). If anyone reading this knows of anything that could make it better, let me know.
Source Code (direct links)
astar.js |
graph.js |
demo.js |
astar-list.js (old implementation)
Posted in Algorithms, All, Plugins, Web Development | Tags: algorithm, astar, javascript, pathfinding, performance, programming, search | 11 Comments »
Tuesday, August 10th, 2010
Sometimes, I want to have a JavaScript event that doesn’t fire until the native event stops firing for a short timeout. I’ve needed to use that pattern in almost every project I have worked on.
For example, you want to use JavaScript to resize an iframe to 100% height when the window resizes. The resize() event can fire dozens of times, and calculating and setting the new height can slow down your page. I used to implement it like this (notice the extra global variable and indentation with the anonymous function):
var timeout;
function doResize(e) {
clearTimeout(timeout);
timeout = setTimeout(function() {
// run some code
}, 200);
}
$(function() {
$(window).bind("resize",doResize);
});
I wrote a plugin to make this pattern easier, it is called “bindWithDelay”. The source code is online, as is a mini project page with a demo.
This is what the same code looks like with the plugin:
function doResize(e) {
// run some code
}
$(function() {
$(window).bindWithDelay("resize", doResize, 200);
});
Posted in All, Open Source, Plugins, Web Development | Tags: bindwithdelay, event binding, javascript, jquery, plugin | No Comments »
Thursday, July 30th, 2009
I wrote an article, Make Table Rows Sortable Using jQuery UI Sortable on the Foliotek Development Blog about a problem that I ran into when trying to set up a basic sortable table using jQuery UI. The columns would collapse down once the dragging began.

This was fixed by adjusting the helper object for the sortable function. Check out the [article][] for all the details, but here is a sample of the code if you are just looking for the solution:
// Return a helper with preserved width of cells
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
$("#sort tbody").sortable({
helper: fixHelper
}).disableSelection();
Posted in All, Web Development | Tags: cell, development, html, javascript, jquery, jquery-ui, programming, sortable, table | 3 Comments »
Tuesday, July 21st, 2009
I had used C# for at least a year before I found out a couple of nice shorthand ways to convert types. These are the is and as expressions, and using them can help make your code more readable.
The is Expression
The is expression will return true if the provided expression is non-null and can be cast to the specific type.
private string GetDisplayField(object val)
{
if (val is string)
{
string text = (string)val;
return "Value was text: " + text;
}
else if (val is DateTime)
{
DateTime time = (DateTime)val;
return "Value was date: " + time.ToShortDateString();
}
return "Could not match type";
}
The as Expression
The as expression will try to cast the object into the given type, and returns an object of that type if the cast was successful, or return null if unsuccessful.
This buys a little bit more functionality for you, as it assigns the variable with an already casted value if successful. It is functionally equivalent to: expression is type ? (type)expression : (type)null
private string GetDisplayField(object val)
{
string text = val as string;
DateTime? time = val as DateTime?;
if (text != null)
{
return "Value was text: " + text;
}
if (time.HasValue)
{
return "Value was date: " + time.Value.ToShortDateString();
}
return "Could not match type";
}
Testing out the functions
Console.WriteLine(GetDisplayField(1)); // Output: "Could not match type"
Console.WriteLine(GetDisplayField("Hello")); // Output: "Value was text: Hello"
Console.WriteLine(GetDisplayField(DateTime.Now)); // Output: "Value was date: 7/21/2009"
They are both readable ways to perform a type conversion – but pick one or the other! Using both of them is redundant.
Posted in All, Web Development | Tags: asp.net, csharp, programming, snippet, tips | 1 Comment »
Wednesday, July 15th, 2009
Or: Binding Events Inside of a Loop with jQuery
I wrote an article on the Foliotek Development Blog about saving the state of a variable inside a closure that is not executed immediately. For example, functions passed into event binding or setTimeout(). Here is a quick rundown of the problem and the solution (using the jQuery library).
The Problem
$(function() {
$("body").append("<ul id='container'></ul>");
for (var i = 0; i < 5; i++)
{
var $item = $("<li />").text("Item " + i);
$("#container").append($item);
$item.click(function() {
alert("You clicked number " + i); // always "You clicked number 5"
});
}
});
The Solution
$(function() {
$("body").append("<ul id='container'></ul>");
for (var i = 0; i < 5; i++)
{
var $item = $("<li />").text("Item " + i);
$("#container").append($item);
(function() { // Closure here here instead of "bindItem()"
var ind = i;
$item.click(function() {
alert("You clicked number " + ind); // Works as expected
});
})(); // Execute immediately
}
});
The solution uses an immediately executing function to create a new scope and declare a variable “ind” that is reserved a new space in memory instead of simply referencing “i”. Check out the full article for more details.
Posted in All, Web Development | Tags: closure, event binding, event handling, javascript, jquery, loop, variable scope | 3 Comments »