TAG | jsoq

I’ve been focusing more and more on my port of Ling-to-Objects, Jsoq the past few weeks. It’s still in really early stages and I’m not quite sure about it’s actual usefulness but I’m learning a lot about JavaScript and having a ton of fun along the way!
Jsoq deals with arrays a lot. About 95% of it’s use cases involve either looping through, altering, or creating arrays. Having a ton of for loops in my code just seems so… not right. For loops have always seemed dirty to me. They just aren’t elegant enough.
Here is your normal, average, everyday for loop in Javascript.
var array = "1,2,3,4,5,6,7,8,9,10".split(',');
for(var i = -1, l = array.length; ++i < l;) {
alert(array[i]);
}
This works. It’s reliable and gets the message across. But what if we needed to loop over an array and get all the items that matched a condition? Using a for loop the code could look something like:
var array = [ 1, 2, 3, 4, 5, 1, 2, 3, 4 ];
var results = [];
var condition = function(i) { return i%2 == 0; };
for(var itt = -1, len = array.length; ++itt < len;) {
if( condition(array[itt]) ) {
results.push(array[itt]);
}
}
This does work, I’ve written code like this many times before, and while technically there isn’t anything wrong with it I think there is still room for improvement.
Jsoq is going to be handling arrays all over the place so the solution to this problem needs to be simple.
Here’s what I need:
- to loop over an entire collection and perform an action on each item.
- If that action produces a result, the item is to be pushed into an array and returned to after the loop is done
- Also: it needs to be readable, someone else coming along should be able to determine what this thing is doing without too much difficulty. So I had my work cut out for me.
.
A few hours later I had a decent function that I could use to replace a lot of the for loops I had. After some more refactoring I was able to wipe them all out and replace them with calls to enumerateOver(). Here is the latest version from source control:
function enumerateOver(collection, work) {
var result = [], val = [];
if (isArray(collection)) {
try {
for (var i = -1, l = collection.length; ++i < l;) {
result = work(collection[i], i);
if (typeof result !== "undefined" && result != null) {
val.push(result);
}
}
}catch (e) {
if (e != jsoq.$break) throw(e);
}
if (val.length > 0) {
return val;
}
}else {
try {
val = work(collection, 0);
}
catch (e) {
if (e != jsoq.$break) throw(e);
}
if (typeof val !== 'undefined') {
return val;
}
}
return result == null ? [] : result;
}
And here is the code to replace the for loops above, re-written to use enumerateOver()
var results2 = enumerateOver(array, function(i, c) {
return i%2 == 0;
});
So by implmenting this function I was able to come up with a more readable, testable and streamlined codebase. Is this suitable for everyone? Definitely not, but I did it for a few reasons:
- Like I mentioned before. I’ve never been at ease with
forloops and being able to replace them all with calls to a single function was a huge win for me - The normal use-case didn’t fit right. I needed to not only iterate over arrays but also return the results of work performed on those items. Doing this the “regular” way just wouldn’t work (see previous reason)
- I thought this was a fun problem to solve
If you have any feedback, good, bad, or indifferent add a comment!
code · Javascript · jsoq · Open Source
During the first round of development for JSOQ I needed a faster way to test than unit-tests alone could provide. What I needed was a dirt-simple page that I could run in a browser, enter some JavaScript code, click a button and see it execute.
I built the initial JSOQ Console (which is still included with the JSOQ source code) in about 20 minutes and it increased my productivity by 10x.
It was much faster to test JSOQ functions with the JSOQ Console than it had been with unit-tests. As a result I was able to prototype new functionality in about 1/2 the time.
I’ve finally moved v0.2 of the Jsoq Console to my blog here so you can use it to quickly test out your own JavaScript code!
How it works is pretty straight forward. If you’ve got a snippet of JavaScript, be it jQuery (for the moment jQuery is the only external library that is supported but that will change soon), JSOQ or any other javascript code, you can run it with the JSOQ Console.
Just navigate to http://tinyurl.com/jsoqconsole or http://codeimpossible.com/jsoq for those of you that like to type, paste your code into the textarea at the top of the page, press “Run” and your code will run!
So enjoy! If you get confused there are also samples that will show you how to use the more “advanced” features. Also, drop a comment or share the console with others if you thought it was useful!
So, yeah I originally started writing this article back in september when I was about mid-way through JSOQ. Some things have changed since then and I’ve tried to keep the post up-to-date. Enjoy!
Also, another similar library has come out recently: JSINQ which is a really feature-rich LINQ to Object implementation in Javascript. Really bad-ass stuff.
The Elevator Pitch:
JSOQ is an open-source pet project of mine that lets you easily access the data that you need from large collections in JavaScript. It was developed over a two week period in September of 2008 and is currently at version 1.1.
Everyone probably just shrugged and said “so??” Well let me show you.
Lets assume that you have the following JSON string from another web application like, say twitter search results for example:
{"results":[
{
"text":"Just another day at the office",
"to_user_id":null,
"from_user":"codeimpossible",
"id":1194587890,
"from_user_id":1316793,
"iso_language_code":"en",
"profile_image_url":"www.path.to.image.us",
"created_at":"Tue, 10 Feb 2009 05:47:33 +0000"
},
{
"text":"@spolsky thats easy! http:\/\/tinyurl.com\/2z42bs",
"to_user_id":1357501,
"to_user":"spolsky",
"from_user":"codeimpossible",
"id":1194582705,
"from_user_id":1316793,
"iso_language_code":"en",
"profile_image_url":"www.path.to.image.us",
"created_at":"Tue, 10 Feb 2009 05:44:51 +0000"
}
]}
In the sample above we only have two results but JSOQ has been tested to work with collections of tens of thousands of items.
The JSON object we have here is perfectly fine if we watned to show a whole bunch of data to the end user, but what if I only wanted to show the search results after a certain date? Or what if I only wanted the text from each message that was typed to this “spolsky” character?
To accomplish this in “straight” javascript I’d be looking at writing a lot of loops and if/else code and then I would still have all these extra properties that I don’t even need.
JSOQ allows me to query a javascript object or collection of objects using a specified criteria and return only the properties/methods I want.
So lets go with the second option. Let’s get all the .text members from all the messages that were sent to the “spolsky” user.
var search_results = eval(our_json_result);
var result = null;
with(jsoq) {
result = From(search_results.results)
.query('text')
.where(function(i) {
return i.to_user === "spolsky";
});
}
And now our result object is filled with a bunch of other objects that would look something like:
{
text: "@spolsky thats easy! http:\/\/tinyurl.com\/2z42bs"
}
Pretty simple eh? For more information on JSOQ please check back here in the near future or contribute to the google code repository.
