Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, October 17, 2011

CSV parser in JavaScript

I wanted a JavaScript based CSV parser. I couldn't find a good one (that would allow multi-character delimiters, and text qualifiers), so I wrote it. The textToArray function should run under any js implementation; but the demonstration of it is written for a ringojs environment.

Call textToArray with a line of delimited text, and the delimiter and text qualifier you're expecting to find; it will give back an array of the elements it finds.
var textToArray = function (txtLine, del, txtQual) {
    "use strict";
    var datArr = [], newStr = "";
    while (txtLine.length > 0) {
        if (txtLine.substr(0, txtQual.length) === txtQual) {
            // get quoted block
            newStr = txtLine.substr(0, txtQual.length + txtLine.indexOf(txtQual, txtQual.length));
            datArr.push(newStr.substr(txtQual.length, newStr.length - txtQual.length * 2));
        }
        else {
            // get data block
            if (txtLine.indexOf(del) !== -1) {
                newStr = txtLine.substr(0, txtLine.indexOf(del));
            } else {
                newStr = txtLine;
            }
            datArr.push(newStr);
        }
        txtLine = txtLine.substr(newStr.length + del.length, txtLine.length);
    }
    return datArr;
};


var fs = require('fs');
var con = require('console');
var del = ";;";
var txtQual = "\"\""; // a pair of quotes.
var file = fs.open('D:/ringojs-0.8/test.txt');
var line = "";
for (line in file) {
    con.log(textToArray(line, del, txtQual).join("---"));
}

Tuesday, September 27, 2011

Sane coding templates for javascript

It's just craziness. Apparently it's possible to treat JavaScript like a real programming language. Very exciting stuff, given that it seems to be becoming the ethernet of programming languages - despite many and varied shortcomings it's versatility, ubiquity, and low barriers to entry are likely to ensure it sees off any competitors.

Here ( http://www.crockford.com/javascript/private.html ) is a handy clip and keep guide of how to implement common object orientation patterns. James Crockford's excellent musing continue through to inheritance too, http://javascript.crockford.com/inheritance.html

Make no mistake, I don't love Javascript, but it's got a lot of momentum. We (the technically involved population) should embrace patterns of Javascript use that will make it sustainable into the future. We need to embrace the sane subset of the language's use.

node.js is good; mongodb and couchdb are stubbornly continuing to exist, and web browsers (whether on smart phones, or desktops) aren't going anywhere. Javascript is a fact, get used to it.