3 ms·
The author is misrepresenting imperative code [0]. Instead of the 42 lines of code he thinks is imperative, but really is already functional-compatible, this is
by idlewan 12y ago
The author is misrepresenting imperative code [0].
Instead of the 42 lines of code he thinks is imperative, but really is already functional-compatible, this is what I would write:
var getIncompleteTaskSummariesForMember_imperative = function(memberName) {
return fetchData().then(function(data) {
var tasks = data.tasks;
var results = [];
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
if (task.member == memberName && !task.complete) {
results.push({
id: task.id,
dueDate: task.dueDate,
title: task.title,
priority: task.priority
})
}
}
results.sort(function(first, second) {
return first.dueDate - second.dueDate;
});
return results;
});
}
Still longer than the 10 lines of functional code, but a much more fair comparison.
[0]: http://scott.sauyet.com/Javascript/Talk/2014/01/FuncProgTalk/#slide-123 http://scott.sauyet.com/Javascript/Talk/2014/01/FuncProgTalk...
- the_imp 12y agoI was bothered by the presented functional implementation; it seemed to use a whole pile of library-specific functions to do the same things base JavaScript already does, just expressed slightly differently. This would be the code I'd write for the same task, pure JS assuming that fetchData returns an ES6 Promise: var getIncompleteTaskSummariesForMember = function(memberName) { return fetchData().then(function(data) { return data.tasks .filter(function(task) { return (task.member == memberName && !task.complete); }) .map(function(task) { return { id: task.id, dueDate: task.dueDate, title: task.title, priority: task.priority }; }) .sort(function(first, second) { return first.dueDate - second.dueDate; }); }, function(reason) { console.log(reason); }); }; Now, does that count as functional? I'm not sure I really care, but it's certainly JavaScript-ish.