Skip to content

Instantly share code, notes, and snippets.

@dshaw
Created July 27, 2011 20:52
Show Gist options
  • Select an option

  • Save dshaw/1110346 to your computer and use it in GitHub Desktop.

Select an option

Save dshaw/1110346 to your computer and use it in GitHub Desktop.
Restore a flattened structure to a hash
// 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;
}
@dshaw
Copy link
Copy Markdown
Author

dshaw commented Jul 27, 2011

Nice.

Copy link
Copy Markdown

ghost commented Jul 27, 2011

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 }

@dshaw
Copy link
Copy Markdown
Author

dshaw commented Jul 27, 2011

Thanks, @substack. That's delightful. You going to office hours tomorrow?

@ciaranj
Copy link
Copy Markdown

ciaranj commented Jul 27, 2011

Thats pretty nice, but my noddy test I was using suggests that its still slower than my option ?

https://gist.github.com/1110433

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment