|
|
|
|
|
by danielnicholas
1771 days ago
|
|
For those not familiar with the JSP style alluded to in the comments, and its contrast to the "traditional style," here's an example of a function that splits a string into words. The "traditional" version was shown by a famous computer scientist in a conference talk a few years ago; I translated it to JS to provide some anonymity :-). JSP's claim to greater clarity is based on the correspondence between the code blocks and the structure being processed: the body of the outer loop processes a group (of gap and word); the body of the inner loops process a gap and a word respectively. The traditional style, in contrast, is like a state machine, and can't be viewed structurally---you need to think about what's happening at each point. This makes it harder to modify the code (eg, by adding something that happens once per word, which is now in two places) and often leads to bugs. This same structural clarity is why, in my view, code that uses list functionals like map/reduce is usually more comprehensible than traditional imperative code. // JSP version of a split function
split_jsp = function (s) {
words = [];
i = 0;
while (i < s.length) {
while (is_white (s[i]))
i++;
word = "";
while (is_alpha (s[i]))
word += s[i++];
if (word.length > 0) words.push(word);
}
return words;
}
// "traditional" version of a split function
split_traditional = function (s) {
words = [];
word = "";
for (i = 0; i < s.length; i++) {
ch = s[i];
if (is_white (ch)) {
if (word != "") words.push (word)
word = "";
}
else
word += ch;
}
if (word != "")
words.push (word);
return words;
}
is_white = ch => (ch == ' ' || ch == '\t' || ch == '\n')
is_alpha = ch => ch != undefined && (/[a-zA-Z]/).test(ch)
|
|