Created
August 23, 2018 12:25
-
-
Save avaly/14c4521d45ccd173b72a8044bdc1888c to your computer and use it in GitHub Desktop.
benchmark-propsOrId.js
This file contains 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
const _ = require('lodash'); | |
const mongoose = require('mongoose'); | |
const Benchmark = require('benchmark'); | |
const { ObjectId } = mongoose.Types; | |
const isObjectId = (id) => id instanceof ObjectId; | |
function withCond(props, value) { | |
return _.cond([ | |
[isObjectId, _.toString], | |
[_.isObject, _.partialRight(_.pick, props)], | |
[_.stubTrue, _.identity] | |
])(value); | |
} | |
function vanilla(props, value) { | |
if (isObjectId(value)) { | |
return value.toString(); | |
} | |
if (_.isObject(value)) { | |
return _.pick(value, props); | |
} | |
return value; | |
} | |
const ID = new ObjectId('01234567890123456789abcd'); | |
const OBJECT = { | |
foo: 'bar', | |
_id: ID | |
}; | |
const suite = new Benchmark.Suite(); | |
suite | |
.add('withCond', () => { | |
withCond(ID.toString()); | |
withCond(['foo', '_id'], OBJECT); | |
withCond(['foo', '_id'], ID); | |
}) | |
.add('vanilla', () => { | |
vanilla(ID.toString()); | |
vanilla(['foo', '_id'], OBJECT); | |
vanilla(['foo', '_id'], ID); | |
}) | |
.on('cycle', (event) => { | |
console.log(String(event.target)); | |
}) | |
.run(); |
Author
avaly
commented
Aug 23, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment