Do u have an example of FP vs OOP? tweet
Any example would be contrived, and will not adequately illustrate the fundamental philosophical differences between OOP and functional programming. For much more on pros and cons of OOP vs Functional programming, see "The Two Pillars of JavaScript" Part 1 (OOP) and Part 2 (Functional Programming).
OOP collection.append()
:
var collection = function collection(arr) {
return {
elements: [].slice.call(arr || []),
append: function append(arr) {
this.elements = this.elements.concat(arr || []);
return this;
}
};
};
var a = collection([1,2,3]);
var b = a.append(['a', 'b', 'c']);
console.log(a, b);
/*
A: { elements: [ 1, 2, 3, 'a', 'b', 'c' ],
append: [Function: append] }
B: { elements: [ 1, 2, 3, 'a', 'b', 'c' ],
append: [Function: append] }
*/
console.log(b === a); // true
Functional collection.append()
:
var collection = function collection(arr) {
return {
elements: [].slice.call(arr || []),
append: function append(arr) {
var newCollection = this.elements.concat(arr || []);
return collection(newCollection);
}
};
};
var a = collection([1,2,3]);
var b = a.append(['a', 'b', 'c']);
console.log(a, b);
/*
A: { elements: [ 1, 2, 3 ], append: [Function: append] }
B: { elements: [ 1, 2, 3, 'a', 'b', 'c' ],
append: [Function: append] }
*/
console.log(b === a); // false