Skip to content

Instantly share code, notes, and snippets.

@jec006
Last active May 25, 2020 12:27
Show Gist options
  • Save jec006/5c507587a7041520b3ea53d6a72db089 to your computer and use it in GitHub Desktop.
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
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())
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