Skip to content

Instantly share code, notes, and snippets.

@0chroma
Last active September 20, 2022 01:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 0chroma/4e7181171151c2fe7dba to your computer and use it in GitHub Desktop.
Save 0chroma/4e7181171151c2fe7dba to your computer and use it in GitHub Desktop.
var HashTable = function(name){
this.name = name;
this.table = {};
}
HashTable.prototype.get = function(key){
return this.table[key];
}
HashTable.prototype.set = function(key, value){
return this.table[key] = value;
}
var table = new HashTable("my table");
table.set("foo", "bar");
console.log(table.get("foo"));
/*
This isn't truly functional since in Javascript
objects/arrays are mutable and functions can
have side effects. But this is generally how
functional code would be written assuming immutability.
*/
var HashTable = {
new: function(name){
return {table: {}, name: name}
},
get: function(state, key){
return state.table[key];
},
set: function(state, key, value){
state.table[key] = value;
return state
}
}
var table = HashTable.new("my table");
table = HashTable.set(table, "foo", "bar");
console.log(HashTable.get(table, "foo"));
/*
Instead of using a `this` keyword, object state
is stored externally and we use our `HashTable`
object to update it. In each function we make a change
to the state and return the new state at the end.
Functional programming is great because saving and loading
state of objects is dead simple. In this case we can just do
JSON.stringify(table) and save the resulting string to a file
or send it over HTTP. Then JSON.parse(table) to load it.
You can't do this as easily with class based code.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment