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. Incivility is not tolerated, such comments are deleted.

 

I'm the co-author of TimeSnapper, 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.

 

NimbleText - FREE text manipulation and data extraction

NimbleText is a Powerful FREE Tool

I wrote this, and use it every day for:

  • extracting data from text
  • manipulating text
  • generating code

It makes you look awesome. You should use NimbleText, you handsome devil!

 

Articles

The Canine Pyramid The Canine Pyramid
Humans: A Tragedy. Humans: A Tragedy.
ACK! ACK!
OfficeQuest... Gamification for the Office Suite OfficeQuest... Gamification for the Office Suite
New product launch: NimbleSET New product launch: NimbleSET
Programming The Robot from Diary of a Wimpy Kid Programming The Robot from Diary of a Wimpy Kid
Happy new year 2014 Happy new year 2014
Downtime as a service Downtime as a service
The Shape of Your Irrationality The Shape of Your Irrationality
This is why I don't go to nice restaurants any more. This is why I don't go to nice restaurants any more.
A flowchart of what programmers do at work all day A flowchart of what programmers do at work all day
The Telepresent Man. The Telepresent Man.
Interview with an Ex-Microsoftie. Interview with an Ex-Microsoftie.
CRUMBS! Commandline navigation tool for Powershell CRUMBS! Commandline navigation tool for Powershell
Little tool for making Amazon affiliate links Little tool for making Amazon affiliate links
Extracting a Trello board as markdown Extracting a Trello board as markdown
hgs: Manage Lots of Mercurial Projects Simultaneously hgs: Manage Lots of Mercurial Projects Simultaneously
You Must Get It! You Must Get It!
AddDays: A Very Simple Date Calculator AddDays: A Very Simple Date Calculator
Google caught in a lie. Google caught in a lie.
NimbleText 2.0: More Than Twice The Price! NimbleText 2.0: More Than Twice The Price!
A Computer Simulation of Creative Work, or 'How To Get Nothing Done' A Computer Simulation of Creative Work, or 'How To Get Nothing Done'
NimbleText 1.9 -- BoomTown! NimbleText 1.9 -- BoomTown!
Line Endings. Line Endings.
**This** is how you pivot **This** is how you pivot
Art of the command-line helper Art of the command-line helper
Go and read a book. Go and read a book.
Slurp up mega-traffic by writing scalable, timeless search-bait Slurp up mega-traffic by writing scalable, timeless search-bait
Do *NOT* try this Hacking Script at home Do *NOT* try this Hacking Script at home
The 'Should I automate it?' Calculator The 'Should I automate it?' Calculator

Archives Complete secretGeek Archives

TimeSnapper -- Automated Screenshot Journal TimeSnapper: automatic screenshot journal

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 little schemer


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

Recommended blogs

Jeff Atwood
Joseph Cooney
Phil Haack
Scott Hanselman
Julia Lerman
Rhys Parry
Joel Pobar
OJ Reeves
Eric Sink

InfoText - amazing search for SharePoint
LogEnvy - event logs made sexy
Computer, Unlocked. A rapid computer customization resource
Aussie Bushwalking
BrisParks :: best parks for kids in brisbane
PhysioTec, Brisbane Specialist Physiotherapy & Pilates
 
home .: about .: sign up .: sitemap .: secretGeek RSS .: © Leon Bambrick 2006 .: privacy

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