Skip to content

Commit

Permalink
Optimize and fix sorting in bencode_dictionary.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kami committed May 30, 2011
1 parent 30eea81 commit e917a5b
Showing 1 changed file with 11 additions and 23 deletions.
34 changes: 11 additions & 23 deletions lib/util/bencode.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,33 +57,21 @@ var bencode_list = function(list) {
};

var bencode_dictionary = function(dictionary) {
var key, value, temp;
var encoded = [];
var keys, key, i, len;
var encoded = '';

encoded.push('d');
for (key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
value = dictionary[key];
keys = Object.keys(dictionary);
keys.sort();

encoded.push(sprintf('%s%s', bencode_string(key), bencode(value)));
}
encoded += 'd';
for (i = 0, len = keys.length; i < len; i++) {
key = keys[i];
value = dictionary[key];
encoded += bencode_string(key) + bencode(value);
}

// Sort the dictionary items by the key name in alphabetic order
temp = encoded.splice(1);
temp.sort(function(a, b) {
var key_a, key_b;

key_a = a.substr(a.indexOf(':') + 1);
key_b = b.substr(b.indexOf(':') + 1);

return key_a.localeCompare(key_b);
});

encoded = encoded.concat(temp);
encoded.push('e');

return encoded.join('');
encoded += 'e';
return encoded;
};

/**
Expand Down

0 comments on commit e917a5b

Please sign in to comment.