Created
July 27, 2011 20:52
-
-
Save dshaw/1110346 to your computer and use it in GitHub Desktop.
Restore a flattened structure to a hash
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
| // I use this to reconstitute the values returned by HGETALL ( http://redis.io/commands/hgetall ). | |
| function rehash (values) { | |
| var hash = {} | |
| , isKey = true | |
| , key; | |
| if (!Array.isArray(values)) return hash; | |
| values.forEach(function(value) { | |
| if (isKey) { | |
| key = value; | |
| hash[key] = null; | |
| } else { | |
| hash[key] = value; | |
| } | |
| isKey = !isKey; | |
| }); | |
| return hash; | |
| } |
Author
Nice.
You can write it using a reduce without any intermediate state:
function rehash (xs) {
if (!Array.isArray(xs)) return {}
else return xs.reduce(function (acc, x, i) {
if (i % 2 == 0) acc[x] = xs[i+1]
return acc;
}, {})
}
console.dir(rehash([ 'a', 1, 'b', 2, 'c', 3 ]));{ a: 1, b: 2, c: 3 }
Author
Thanks, @substack. That's delightful. You going to office hours tomorrow?
Thats pretty nice, but my noddy test I was using suggests that its still slower than my option ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The docs for hgetall suggest the list will be contiguous so it should be fine?