Remove nested arrays in javascript using the prototype library

I have been playing with some drawing code in javascript, storing coordinates and using them later on in the application. My list of coordinates is of the form [ [id1, x1, y1, width1, height1], [id2, x2, y2, width2, height2],…]. A requirement of the application is that a user can delete a set of coordinates from the list. Using prototype.js, I created a simple function to remove the nested array based on the id.

// remove an array from the list based on the id
function remove(id, list) {
    return $A(list).map( 
        function(arr) {
            if ( $A(arr).first() == id ) { return ; }
            else { return arr; }

In your favorite editor, this function can be a one-liner, but spacing helps here for clarity and formatting on the page. Onward! So what's happening? The first thing we do is wrap list with the $A() call to ensure we have access to the extensions prototype gives us for arrays (I'm calling the parameter a list because I'm on an Erlang kick and it has infiltrated my core!). Once extended, we call the map function to iterate through the list and apply the supplied function to each element in the list (in this case it is a list of arrays, so each element passed to the supplied function will be an array as well). Within the supplied function, we are dealing with a single array of the form [id, x, y, width, height], so $A(arr).first() returns the id of the array. This value is compared to the value of the id parameter and if it matches, returns nothing, or 'undefined' in Javascript. If the ids don't match, it returns the array unaltered. As the map function iterates through the list, a new list is created containing the results of the supplied function. So the return value of the map function call is an array. We then call the compact function on the resulting array, which removes any undefined values from the array, essentially leaving only those arrays that did not have the id passed in. This function is fairly specialized; the requirements for the function are fairly specific. A more general function could be written but that is an exercise left to the reader.

Recursive FTP

So you want to download some files from an ftp server, but they are contained in more than one subdirectory. With a straight ftp client, you would have to recurse through all of the directories and mget each directory's contents manually. Never fear, though, there is a little utility that can help - wget. > wget -r . If the ftp site allows anonymous logins, you can omit the user:pass portion. This will get everything…it is left as an exercise to the reader to customize the command.

Drop down menus

As we all know (actually, many probably don't know) Internet Explorer has claimed many hours of developer time trying to get a feature working with the quirks of IE. One quirk that I've dealt with recently was the :hover pseudo-class and its implementation across various browsers. The most notable quirk is that IE only supports the :hover on anchor tags (<a>). What's a fella to do when he wants a drop down menu that displays the sub-menu when the mouse is hovering over an li element? Write some Javascript to aid IE in rendering the drop-down effect properly. The first draft of our menu is here. If you are unfortunate enough to be using IE, you probably won't see the sub-menu items. So how do we negotiate this? With a little extra class, and some Javascript. The second draft of our menu can be found here. The differences to note:

  • The li:hover rule is now accompanied by a li.over as well
  • The function fixHover()
  • The function init()

So we added a rule that says any ul with a parent li with a class of over will also get the styling that a ul with a parent with li:hover gets; in this case - display the underlying ul. Next, we added a function (fixHover) that took an element, and retrieved all of it's immediate children nodes. We then iterate through the list of children, basically adding two events, "mouseover" and "mouseout", to for each element to observe. For "mouseover" events, append the classname "over" to the element; on "mouseout" events, remove the "over" classname. The essence here is that :hover is the CSS equivalent of observing the "mouseover" and "mouseout" events. The draw back to our solution is that if Javascript is turned off, the sub-menus remain hidden from the user. NOTE: I am not a designer, so the purpose of this article is to merely illustrate the ability to apply hover-type functionality to any element on the page in IE and not showcase my ability to make things look nice. Another feature to mention is the init function and the Event.observe() call, which calls the init function after the window has finished loading the page. This is a must because we cannot apply the "mouseover" and "mouseout" event observations until the nodes have been created in the DOM. Best to leave this until the window has loaded. Both of the functions rely on the prototype.js library to retrieve the child nodes, iterate through the nodes, and attach events to the nodes. It is possible to do this without prototype or with another library, but I leave it up to the reader to translate this code to their library of choice.

Sweet Battery

I'm a big fan of green living and when noteworthy technology comes along that enables green principles to be adopted by the masses, I'm all for it. Such is the case today, when I read, via EcoGeek, about a fuel cell being developed by researchers at Saint Louis University that runs on sugary liquids (ah ha, the double meaning of the title is revealed!). The hook from the SLU press release:

Juicing up your cell phone or iPod may take on a whole new meaning in the future. Researchers at Saint Louis University have developed a fuel cell battery that runs on virtually any sugar source - from soft drinks to tree sap - and has the potential to operate three to four times longer on a single charge than conventional lithium ion batteries, they say.

Now, I'm all for this kind of technology making it into mainstream commercial applications; my reservations come in when I see tree sap being listed as a potential source. I'm a big fan of real maple syrup and it already costs an arm and a leg. Should it be found that sap from the maple (especially the sugar maple, duh) is the best fuel source, I may have to hurt something, as the demand for these fuel cells would raise the price of syrup even more. So let's pull for soda, which we really shouldn't be drinking anyway, or some alternative source of sugar to be the front runner in the fuel cell's source, and not maple tree sap. Whatever the source, I am excited about these fuel cells. I wonder, though, at this sentence: "Like other fuel cells, the sugar battery contains enzymes that convert fuel - in this case, sugar - into electricity, leaving behind water as a main byproduct." At first, the reaction is, "Great, water is the by-product; who doesn't love that". I wonder what the other byproducts are though. Hopefully not a contaminant of some kind, as that would really mar the greenness of the fuel cell. I guess the wise thing to do is to watch carefully as this technology progresses and keep a foot on the ground when listening to the hype of any "100% green" technology.

Pi Day 2007

Happy Pi Day (3-14, duh). Search pi for sequences of numbers, like your birthday, SSN, phone number, etc here. The page also has a good bit of Pi trivia.

Slow Down and Smell The...Food?

Gluttony is probably the sin I indulge in the most and, at this point in my life, I'm able to eat what I want at whatever quantity I want. This does not mean I am an undiscerning eater. Quite the contrary, I enjoy quality food and wish I was better at cooking those fancy meals. While fast food certainly kept me fed during school, now that I am out and bringing home a paycheck, I came to the decision that fast food really has nothing to offer me anymore. I ate it for the quantity to price ratio, to help keep some weight on my body for sports. Without that high demand for energy, quantity really has become a non-issue. Another aspect of eating I feel fortunate in is that I haven't really met a food I didn't like. There are exceptions (like White Castle, but I have the fast-food-embargo card to play there now), but they really boil down to badly prepared food, not the food item itself. So I challenge myself when I eat to either order or make something I have not had before. This is most challenging at Thai restaurants, as I love Pad Thai; usually, those I'm eating with order it and I can get something else, knowing I'll probably get the end of their plates when they have become full. My cooking abilities are quite meager at this point. The hardest part for me is that I don't like to cook for just myself. So if a certain someone could return from New Zealand, perhaps the pots and pans would get more varied use! That situation will be rectified soon, so I'll be able to crack into that Joy of Cooking cookbook and create some tasty treats. One aspect of cooking I hadn't really considered before was the origin of the ingredients. Just go the the Schnucks or Shop and Save and pick up your ingredients, right? Well, not necessarily. Part of green living is working to use nature and the environment in a sustainable way, but also doing it in a way that still benefits people in other ways. It was in thinking about how to shop for food that would be raised in a "green" way that I came across an organization that is striving to promote this way of thinking. Their motto: "…counteract fast food and fast life, the disappearance of local food traditions and people's dwindling interest in the food they eat, where it comes from, how it tastes and how our food choices affect the rest of the world." Their name: Slow Food International. Always in search of getting more out of my experiences, I think this organization brings quite a bit of education to the table (pun intended), teaching people about the hows, whys, whats, and whens of the foods they eat. It seems pretty obvious that supporting the local farmer's markets and co-ops. Search Google Maps for farmer's markets near your zipcode and you'll probably find a few; I found 6 within 10 miles of me. Who knew? I do, now. So here's to making and experiencing good food, knowing that you are being responsible to yourself, your local community, and the ecosystem. It certainly makes things taste better knowing you're contributing to those causes.

Crazy addictive game

Flow In Games provides quite an adventure in gaming. It is no secret that I am not a big player of mainstream console and computer games, and games like Flow confirm that I am not missing out. The combination of visual, aural, and tactical elements creates quite a pleasant experience. I hardly noticed that I had wasted three hours playing! The rules are simple (like most fun games) - eat and evolve, kill or be killed. I think this is a great game for kids because it requires some anticipation and coordination skills to time attacks and strike at the food. I know many more of my hours will be spent playing.

Clean up once in a while

Perfect. Last night, amidst the snow and wind, Jason and I went to Gabriel's and got his old washer and dryer. Nothing says dedication to clean laundry like moving a washer and dryer at 10:30pm in sub-freezing temperatures with snow falling all around you. The roads were bad enough that going over 25mph caused fishtailing - with the washer and dryer over the rear wheels. Other than one minor glitch and some configuration adjustments, the duo is in place and busy with action. Finally, I don't have to leave the house to do laundry. With my new-found cleaning apparatus on my mind, wouldn't you know it; on reddit today, this hilarious commercial for IKEA: The commercial Yikes

Sobering Video

Over on NewsTrust, a report on a 17 year old's documentary film has caused quite a discussion on race. Mimicking the experiment performed back in the 1950's to prove "separate but equal" was not equal, the young filmmaker found how little things have changed in 50 years. The newsstory is here.