Type PooledClass (#7578)

This one was really interesting to type as it's doing a lot of unusual JavaScript. Fortunately flow is now pretty kick ass and I've been able to mostly type it. The only missing piece is that it won't check the constructor arguments.

If you are a fb employee, you can follow the discussion here: https://www.facebook.com/groups/flowtype/permalink/1132359430146004/
This commit is contained in:
Christopher Chedeau
2016-08-28 10:43:13 -07:00
committed by GitHub
parent fa9869b5a0
commit 19b8eadb24
2 changed files with 20 additions and 10 deletions
+2 -3
View File
@@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CallbackQueue
* @flow
*/
'use strict';
@@ -101,6 +102,4 @@ Object.assign(CallbackQueue.prototype, {
});
PooledClass.addPoolingTo(CallbackQueue);
module.exports = CallbackQueue;
module.exports = PooledClass.addPoolingTo(CallbackQueue);
+18 -7
View File
@@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule PooledClass
* @flow
*/
'use strict';
@@ -90,6 +91,8 @@ var standardReleaser = function(instance) {
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
type Pooler = any;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
@@ -99,8 +102,16 @@ var DEFAULT_POOLER = oneArgumentPooler;
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function(CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
var addPoolingTo = function<T>(
CopyConstructor: Class<T>,
pooler: Pooler,
): Class<T> & {
getPooled(/* arguments of the constructor */): T;
release(): void;
} {
// Casting as any so that flow ignores the actual implementation and trusts
// it to match the type we declared
var NewKlass = (CopyConstructor: any);
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
@@ -112,11 +123,11 @@ var addPoolingTo = function(CopyConstructor, pooler) {
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler,
oneArgumentPooler: (oneArgumentPooler: Pooler),
twoArgumentPooler: (twoArgumentPooler: Pooler),
threeArgumentPooler: (threeArgumentPooler: Pooler),
fourArgumentPooler: (fourArgumentPooler: Pooler),
fiveArgumentPooler: (fiveArgumentPooler: Pooler),
};
module.exports = PooledClass;