[Javascript] Lambda calculus [WAS: OT: Test]

Mike Dougherty mdougherty at pbp.com
Thu Oct 16 11:51:44 CDT 2008


On Thu, Oct 16, 2008 at 1:00 AM, Paul Novitski <paul at juniperwebcraft.com> wrote:
> Can you show us some examples using JavaScript that you've written
> with an explanation of what they do?

assumption(s):
template = "from: <<fromUser>>  to: <<toUser>> subject: <<subject>>";
N = { fromUser: "MikeD"
        ,toUser: "Paul"
        ,subject: "example"
        }

/* iterating through tree of messaging nodes */
while( N ){
/* create a function that closes over the current object (in this case N)
    and returns a function for use in a regex .replace() operation */
var replacer = function( oRef ){
  return function(str,p1,p2,offset,s){ return oRef[ p1 ]; };
  };
	
/* take the template, find each occurrence of a "mergecode"
and pass the mergecode found to the function
that is returned by giving the N object to the "replacer" function */
var rendered = template.replace(
   /(?:<<)([^>]*)(?:>>)/gi
  ,replacer(N)
  );

// do something now with the string in 'rendered'
// [ next N... ]
} /* end: while(N) */

In a previous project I first used .match() to get a list of
mergecodes, then iterated through the matches and made a global
replacement for each match.  That strategy may have been more
readable, but conceptually would perform worse as the number of
mergecodes and the size of the template increases.  For this case, I
already had a complex node tree in memory anyway.  This example uses a
much simpler template.  I'm also working on implementing a method to
execute functions of the node object for multivalued properties (like
multiple "To:" on an email) - so the template mergecode can contain a
function reference rather than a simple property reference.

While researching this solution (chatting with [freenode] ##javascript
IRC channel) I thought this technique might be a slick way to
implement an i18n character replacement - all it would require is an
object to act as an index of character mappings, and a regex to find
index keys to lookup.  Of course, I haven't implemented that yet so I
have no idea what devil-in-the-details would be encountered.

Comments?  Questions?  (other than "Are you crazy?" as both a comment
and rhetorical question)



More information about the Javascript mailing list