Skip to content

Commit e136ac0

Browse files
committed
optimized createFromHexString
1 parent ad5f051 commit e136ac0

File tree

1 file changed

+6
-9
lines changed

1 file changed

+6
-9
lines changed

lib/bson/objectid.js

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -285,22 +285,19 @@ var convertToHex = function(bytes) {
285285
*/
286286
ObjectID.createFromHexString = function createFromHexString (string) {
287287
// Throw an error if it's not a valid setup
288-
if(typeof string === 'undefined' || string != null && string.length != 24)
288+
if(typeof string === 'undefined' || string != null && string.length != 24) {
289289
throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
290-
291-
var length = string.length;
292-
293-
if(length > 12*2) {
294-
throw new Error('Id cannot be longer than 12 bytes');
295290
}
296291

292+
// Use Buffer.from method if available
293+
if(hasBufferType) return new ObjectID(Buffer.from(string, 'hex'));
294+
297295
// Calculate lengths
298-
var sizeof = length >> 1;
299-
var array = new _Buffer(sizeof);
296+
var array = new _Buffer(12);
300297
var n = 0;
301298
var i = 0;
302299

303-
while (i < length) {
300+
while (i < 24) {
304301
array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]
305302
}
306303

0 commit comments

Comments
 (0)