Created
July 5, 2016 01:21
-
-
Save nathanmarks/a284a8c9a8c926bcd79c7a2a93427dbc to your computer and use it in GitHub Desktop.
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
import React, {Component, PropTypes} from 'react'; | |
import Perf from 'react-addons-perf'; | |
import {find} from 'src/utils/helpers'; | |
import RandomWords from 'random-words'; | |
/** | |
* TimeWaster | |
* WIP Component | |
*/ | |
export default class TimeWaster extends Component { | |
static propTypes = { | |
children: PropTypes.any, | |
loops: PropTypes.number, | |
onComplete: PropTypes.func, | |
testFn: PropTypes.func, | |
testProp: PropTypes.string, | |
}; | |
static defaultProps = { | |
loops: 100, | |
testFn: () => RandomWords(1)[0], | |
testProp: 'data-test-prop', | |
}; | |
componentWillMount() { | |
this.setTestProp(); | |
} | |
componentDidMount() { | |
this.runTest().then(() => this.endTest()); | |
} | |
setTestProp(cb = () => {}) { | |
const {testProp, testFn} = this.props; | |
this.setState({ | |
[testProp]: testFn(), | |
}, cb); | |
} | |
runTest() { | |
let i = 0; | |
Perf.start(); | |
return new Promise((resolve) => { | |
const execTest = () => { | |
i++; | |
setTimeout(() => { | |
if (i < this.props.loops) { | |
this.setTestProp(execTest); | |
} else { | |
Perf.stop(); | |
resolve(Perf); | |
} | |
}, 10); | |
}; | |
execTest(); | |
}); | |
} | |
endTest() { | |
const measurements = Perf.getLastMeasurements(); | |
const wasted = Perf.getWasted(measurements); | |
const summary = {}; | |
summary.hasWastedTime = function(component) { | |
const result = find(wasted, (n) => n.key.indexOf(`> ${component}`)); | |
if (result) { | |
return `${result.key} wasted ${result.inclusiveRenderDuration}ms across ${result.renderCount} renders`; | |
} | |
return false; | |
}; | |
return this.props.onComplete(summary); | |
} | |
render() { | |
const {children, testProp} = this.props; | |
const testValue = this.state[testProp]; | |
return React.cloneElement(React.Children.only(children), { | |
[testProp]: testValue, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment