A Legacy Notes Developer's journey into madness.

Extending Tommy Valand’s clearMap() function

Devin Olson  August 14 2012 07:46:02 AM
Tommy Valand posted a wonderfully simple function for clearing scoped variables a couple of years ago.  

I had a need to conditionally clear certain elements from my applicationScope.   In my case, if the applicationScope contained an element which matched a certain key then I needed to clear it.

Instead of writing code which would do exactly that, I decided to create a generic function which utilized Regular Expression processing to do what I needed.  And instead of creating a completely new function, I decided to extend Tommy's original function by adding an optional argument.  

Here is my function, please use as you wish.  (Note: This function makes use of my @IsBlank() function, you will either need to add that to your code or use your own method to test for blank strings).  

function clearMap(map:Map, keypattern:String):boolean {
/*
 clearMap

 Clears elements from a map.

 
 @param map: The map for which to clear elements.

 @param keypattern: RegEx pattern to match keys. If exists then only elements matching this pattern will be cleared. [opptional]

 @return: Flag indicating if the map was successfully cleared.

*/
 if (map == null) { return false; }
 if (@IsBlank(keypattern)) {
         // clear the entire map
         var iterator:Iterator = map.keySet().iterator();
         while (iterator.hasNext()) {
                 map.remove(iterator.next());
         } // while (iterator.hasNext())                

         return true;
                 
 } else {
         // search for patterns to clear
         var regex:RegExp = new RegExp(keypattern);
         var keys:Array = new Array();  // container for matched keys
         var iterator:Iterator = map.keySet().iterator();
         while (iterator.hasNext()) {
                 var entry:Map.Entry = iterator.next();
                 if (regex.test(entry)) { keys.push(entry); }
         } // while (iterator.hasNext())
                 
         var result:boolean = false;
         for (var i=0; i<keys.length; i++) {
                 map.remove(keys[i]);
                 result true;
         } // for (var i=0; i<keys.length; i++)
                 
         return result;
 } // if (@IsBlank(keypattern))
} // clearMap



Example Use:

Assume you had placed a bunch of customer content into the applicationScope using keys like "customer.name", "customer.address", "customer.phone", etc.   Assume also you had many other values in applicationScope (user info, order info, whatever).    If you wanted to clear all the customer info from applicationScope, but nothing else, you can accomplish this with the following single line of code:

clearMap(applicationScope, "^customer.");


Hope this helps!
-Devin.

Comments
No Comments Found

Discussion for this entry is now closed.