Last active
May 25, 2020 12:27
-
-
Save jec006/5c507587a7041520b3ea53d6a72db089 to your computer and use it in GitHub Desktop.
A wrapper around the base js Object to make iterating and other basic functions easier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let test = usefulHash({test: [1,2,3], dude: 'hi'}) | |
test.forEach(function(k, v) { console.log(`${k}, ${v}`) }) | |
test['zombies'] = true | |
test.forEach(function(k, v) { console.log(`2: ${k}, ${v}`) }) | |
console.log(test.keys()) | |
console.log(test.values()) | |
test2 = test.merge({josh: 'cool'}) | |
console.log(test2.keys()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function usefulHash(initialHash) { | |
let base = {} | |
let baseKeys = Object.keys(base) | |
let methods = {} | |
var hsh = Object.assign(initialHash, methods) | |
function userKey(k) { | |
return !baseKeys.includes(k) && !Object.keys(methods).includes(k) | |
} | |
methods.forEach = function(cb) { | |
return this.keys().forEach((k) => { | |
return cb(k, this[k]) | |
}) | |
} | |
methods.map = function(cb) { | |
return this.keys().map((k) => { | |
return cb(k, this[k]) | |
}) | |
} | |
methods.keys = function() { | |
return Object.keys(this).filter(userKey) | |
} | |
methods.values = function() { | |
return this.map((k) => { return this[k] }) | |
} | |
methods.merge = function(otherHsh) { | |
return hsh = Object.assign(this, otherHsh) | |
} | |
hsh = Object.assign(initialHash, methods) | |
return hsh | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment