Functional Javascript?
03/27/15
So, I went to a TucsonJS meetup last week, and the talk was titled Functional Javascript.
Programming functionally isn't something I'm particularly familiar with, but I did read Learn You a Haskell For Great Good and it introduced those concepts fairly well. I think. I can't really be sure because I didn't start using those concepts after learning them.
Anyways, I bring this up now because I recently started working on making a find/replace script in node javascript. I had a "working" script before but I accidentally destroyed it and a lot of other scripts when I fed it the wrong arguments.
While rewriting it something clicked in my head. I didn't need to check the state of variables, I could just attempt to use a variable one way and if it failed, use it some default way. Last time I wrote this script, I would check if the file input was a directory, and if it was, I would iterate through each item in the directory and check for file or directory status, and then go through each file and find/replace the input find/replace strings, and so on and so forth. This time, I just fed the paths into fs.readdir and fs.readFile and just return if an error occurred.
recursiveDirectory = function (fullpath) {
fs.readdir(fullpath, function (err, dirlist) {
if (err) {
return;
}
dirlist.forEach(function (base) {
var path = require("path"),
newPath = path.join(fullpath, base);
recursiveDirectory(newPath);
});
});
fs.readFile(fullpath, "utf-8", function (err, data) {
if (err) {
return;
}
console.log(fullpath);
console.log(data);
});
};
Basically, I let a type error happen without there actually being types, and then would just pretend the function wasn't called. Which kinda feels like a javascript way of doing a haskell-like thing, but my javascript is still in its infancy and my haskell hasn't even been born yet.
Anyways, this ended up being much cleaner and easier to debug code. I always thought verifying variables was better than letting errors happen, but I suppose it's true that sometimes "it's easier to ask for forgiveness than for permission". And in this case, as it should be, the easy thing is right.
I hope.