Skip to content

Instantly share code, notes, and snippets.

@gamedevsam
Last active December 31, 2021 18:59
Show Gist options
  • Save gamedevsam/5804b7c7791f66002433029de6ddb491 to your computer and use it in GitHub Desktop.
Save gamedevsam/5804b7c7791f66002433029de6ddb491 to your computer and use it in GitHub Desktop.
A contrived example showing how a problem can be solved with classes or with functions in JS
/**
* This example compares how one might go about converting an array to a string using classes or functions:
*/
const EXAMPLE_DATA = ['This', 'is', 'a', 'contrived', 'example'];
/**
* In this first example we use a class to hold our array and a method to transform it into a string:
*/
class ArrayToStringClass {
constructor(array) {
this.data = array;
}
process() {
let result = '';
for (const entry of this.data) {
result += entry + ' ';
}
return result;
}
}
// Outputs: "This is a contrived example"
const processor = new ArrayToStringClass(EXAMPLE_DATA);
console.log(processor.process());
/**
* In this second example we use a method of the array prototype called reduce and pass an anonymous function that does the array transformation.
*/
function arrayToStringReduce(array) {
return array.reduce((accumulator, entry) => {
return accumulator + entry + ' ';
}, '')
}
// Outputs: "This is a contrived example"
console.log(arrayToStringReduce(EXAMPLE_DATA));
/**
* In this final example we implement the same logic without using any methods, to give the reader a better understanding of what Array.prototype.reduce is doing.
*/
function combineEntries(previous, next) {
return previous + next + ' ';
}
function arrayToStringSimple(array, processEntryFn, accumulator = '') {
for(const entry of array) {
accumulator = processEntryFn(accumulator, entry);
}
return accumulator;
}
// Outputs: "This is a contrived example"
console.log(arrayToStringSimple(EXAMPLE_DATA, combineEntries));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment