World's Simplest Code Generator: implemented in pure Javascript
secretGeek .:dot Nuts about dot Net:.
home .: about .: sign up .: sitemap .: secretGeek RSS

World's Simplest Code Generator: implemented in pure Javascript

worlds simplest code generator implemented in pure javascript

Last night I was stuck using an old laptop, with no dev tools and no internet connection.

A machine without dev tools is like a pub without beer, i lamented, when i suddenly remembered Douglas Crockford's essay 'Javascript, the world's most misunderstood programming language.'

So I fired up notepad and set about re-writing "the world's simplest code generator" -- in pure javascript this time.

This was a fun and liberating exercise: programming without any tool support (remember Chucky Petzold's Does Visual Studio Rot The Mind?).

There were a few unexpected delights and challenges, that i'll talk about now. If you want to use (or bookmark) this new, faster version of the WSCG, i've polished it up a little and uploaded it to here:

world's simplest code generator (javascript edition)

the core of the program is hardly ten lines long, two simple functions:

function calculate() {
  //split the data into an array of rows
  var dataRows = $('txtData').value.split($('rowDelim').value);
  for (var i = 0; i < dataRows.length;i++) {
    //apply the pattern to each row
    result += apply($('txtPattern').value, dataRows[i], $('fieldDelim').value) + '\r\n';
  }
} 
function apply(pattern, row, fieldDelim) {
  //split the row into an array of fields
  var fields = rows.split(fieldDelim);
  for (var col = fields.length; col > 0; col --) {
    //replace '$1' with fields[0]... and so on for each field.
    //(applied in descending order, so that, for example, '$10' isn't mis-interpreted as '$1')
    pattern = pattern.replace(new RegExp('\\$' + col, "g") , trim(fields[col-1]));		 
  }   
  return pattern;
}

The actual code is spaced out a little more (lines aren't nearly so long)

Because it requires no postbacks, this version of the WSCG is the fastest yet. It doesn't have all the features of the previous version but i think i can use eval() to make it far more powerful yet.

Now something else I've been thinking though, is that I'd love to rewrite this in F#. Anyone care to help out? A silverlight implementation would also be fun. I've written a powershell version (in one horribly long line...) and i should blog that some time.

(Side bar: there was a good hanselminutes about F# recently, where Robert Pickering was interviewed.)

As it turns out, the thing I found hardest about writing this without internet access was testing the seemingly simple regular expressions used in the little 'trim' functions i had to write:

function ltrim(input) 
{
   //if it starts with spaces... remove them!
   return input.replace(/^\s+/gm,'')
}
function rtrim(input) 
{
   //if it ends with spaces... remove them!
   return input.replace(/\s+$/gm,'')
}
function trim(input) {
  //trim spaces from the front and the back of the string.
  return ltrim(rtrim(input));
}

If I'd had internet access, I would've used David Seruyange's excellent regex testing tool.

One last thing: it felt unnatural to write a descending for statement:

  for (var col = fields.length; col > 0; col --) 

Have gotten very used to foreach.





'Matt Casto' on Wed, 15 Aug 2007 10:26:39 GMT, sez:

Hurray! Another version of my favorite programming tool on the internet. You need to take away your internet access more often!

I hadn't seen that regex testing tool before. I've added it to my links and I'll find it helpful for quick regex verification. I usually use Regulator which I keep on a thumb drive. In fact, most of my development tools I have as portable application or installs stored on my thumb drive so I don't ever end up on a machine without any development tools.



'Des Traynor' on Wed, 15 Aug 2007 11:12:30 GMT, sez:

Nice work, I've been using WSCG for a while now.

I wrote a Javascript based Code to HTML converter, which has but a subset of your functionality. Basically you can throw any type of code into the first box, and you will get XHTML for it in the third box.
http://destraynor.com/c2h.html



'Simon' on Wed, 15 Aug 2007 13:15:52 GMT, sez:

You love it! I love the WSCG, and this does improve it one notch more. Well done.



'Andrew Webb' on Wed, 15 Aug 2007 14:06:18 GMT, sez:

Also on Javascript:

http://www.codinghorror.com/blog/archives/000857.html



'David Stone' on Wed, 15 Aug 2007 16:05:47 GMT, sez:

Javscript 1.7 actually has a foreach:

for(var x in myArray)
{
//yadda yadda yadda
}

Even works in IE 7. :)



'lb' on Wed, 15 Aug 2007 21:05:12 GMT, sez:

thanks for the feedback! glad to know the WSCG is still in use (i don't watch its traffic or usage... i used to but, gave up a while back)

I use it for all sorts of things myself.

@Des -- hey i've tinkered with that tool of yours. Some things I'd ask for, 1: a link on that page that tells us where to give feedback. 2: personally i'd like it if leading spaces get converted to non-breaking spaces. 3: I'm pretty wary of using the 'pre' tag as it stops a long line from wrapping which can destroy page layout/templates etc. 4: colour coding!! come on des! you can do it... only have to infer the language, and parse for all known operators/keywords/comment types etc. 5: compile the entered code and highlight any errors. 6: okay, number 5 went too far.

@David -- ah thanks!!



'Raj Chaudhuri' on Thu, 16 Aug 2007 06:36:57 GMT, sez:

You didn't mention wanting to do a CMD.EXE version, so I did one.

http://rajch.spaces.live.com/




name


website (optional)


enter the word:
 

comment (HTML not allowed)


All viewpoints welcome. But the right to delete any post for any reason is reserved. Don't make me do it. Comments may be republished, emailed to your loved ones or printed and used as toilet paper. Who reads this legal bit anyhow?

TimeSnapper is a life analysis system that stores and plays-back your computer use. It makes timesheet recording a breeze, helps you recover lost work and shows you how to sharpen your act.

TimeSnapper won last year's Developer Competition at Larkware.com, and is used by over 10,000 people.

Articles

A face-melting DSL that allows programming ON the iPhone (and iPad) A face-melting DSL that allows programming ON the iPhone (and iPad)
The secretGeek Disaster Recovery plan The secretGeek Disaster Recovery plan
Save KNVTn! Before it's too late Save KNVTn! Before it's too late
The Ultimate Agent of WERF Destruction The Ultimate Agent of WERF Destruction
The new prisoner's dilemma The new prisoner's dilemma
Original Premise for a road movie Original Premise for a road movie
What's a better game than Devshop? What's a better game than Devshop?
DevShop: The Cool Game that Makes Development Look Fun DevShop: The Cool Game that Makes Development Look Fun
Should be purple Should be purple
Kitchen Agile Kitchen Agile
Perhaps Perhaps "Go" is the new Visual Basic
zen-coding: turn those CSS selectors upside down zen-coding: turn those CSS selectors upside down
Debugging: It's all about finding Albuquerque. Debugging: It's all about finding Albuquerque.
The Real-Time online JQuery Editor The Real-Time online JQuery Editor
HTML5, a 3 minute guide HTML5, a 3 minute guide
Developer Codpieces Developer Codpieces
Agile for one: The Personal Story 'Wall' In Action Agile for one: The Personal Story 'Wall' In Action
Never work with thick people. Never work with thick people.
Cosmo: project status panel Cosmo: project status panel
Windows Search in Japan Windows Search in Japan
Project Management Zen Project Management Zen
Continuous Integration, Plugins and Going Too Far Continuous Integration, Plugins and Going Too Far
The Rules of Stand Up The Rules of Stand Up
Sydney International Airport: Stupid, Criminal, or Criminally Stupid? Sydney International Airport: Stupid, Criminal, or Criminally Stupid?
God No! ...The ReBuilder God No! ...The ReBuilder
Matt, The Office Mortar Matt, The Office Mortar
'Outlook style' rules for Subversion 'Outlook style' rules for Subversion
Really deep linking: Url + regex Really deep linking: Url + regex
hExcel -- A Hexagonal Spreadsheet hExcel -- A Hexagonal Spreadsheet
Is the remote control a thing of the past? Is the remote control a thing of the past?
The Utterly Thorough Guide To Awesome Application Compatibility on Windows 7. The Utterly Thorough Guide To Awesome Application Compatibility on Windows 7.
Astounding Hyperlinked Noticeboard Astounding Hyperlinked Noticeboard
Three Questions About Each Bug You Find Three Questions About Each Bug You Find
Recursing over the Pareto Principle... Recursing over the Pareto Principle...
Sometimes, The Better You Program, The Worse You Communicate. Sometimes, The Better You Program, The Worse You Communicate.

Archives .: secretGeek :: Complete Archives
TimeSnapper -- Automated Screenshot Journal TimeSnapper.com    
Version 3.3: true productivity boost

Next Action NextAction
Managing the top of your mind

World's Simplest Code Generator (html edition) World's Simplest Code Generator

25 steps for building a Micro-ISV 25 steps for building a Micro-ISV
3 minute guides -- babysteps in new technologies: powershell, JSON, watir, F# 3 Minute Guide Series
Universal Troubleshooting checklist Universal Troubleshooting Checklist
Top 10 SecretGeek articles Top 10 SecretGeek articles
ShinyPower (help with Powershell) ShinyPower
Now at CodePlex

Realtime CSS Editor, in a browser RealTime Online CSS Editor
Gradient Maker -- a tool for making background images that blend from one colour to another. Forget photoshop, this is the bomb. Gradient Maker


[powered by Google] 


How to be depressed How to be depressed
You are not inadequate.



Recommended Reading

The Best Software Writing I
The Business Of Software (Eric Sink)

Recommended blogs

Jeff Atwood
Reginald Braithwaite
Joseph Cooney
Phil Haack
Scott Hanselman
Julia Lerman
Rhys Parry
Joel Pobar
OJ Reeves
Eric Sink
Joel Spolsky
Des Traynor

Aggregated Links

programming.reddit.com
dzone
dot net kicks

Human Link Machines

interesting finds
a continuous learner's weblog
arjan's world
n links today
new and notable
morning coffee
learning .net
weekly link post
(my del.icio.us account)

LinkedIn profile
 
home .: about .: sign up .: sitemap .: secretGeek RSS .: © Leon Bambrick 2006 .: privacy

home .: about .: sign up .: sitemap .: RSS .: © Leon Bambrick 2006 .: privacy