react-native/Libraries/Utilities/defineLazyObjectProperty.js
Tim Yung de6ab1c6f4 RN: Implement defineLazyObjectProperty
Reviewed By: sahrens

Differential Revision: D3500318

fbshipit-source-id: 275c5b9a2b747174fb23b80896e2270eb2131e4b
2016-06-29 16:43:17 -07:00

62 lines
1.5 KiB
JavaScript

/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule defineLazyObjectProperty
* @flow
*/
'use strict';
/**
* Defines a lazily evaluated property on the supplied `object`.
*/
function defineLazyObjectProperty<T>(
object: Object,
name: string,
descriptor: {
get: () => T,
enumerable?: boolean,
writable?: boolean,
},
): void {
const {get} = descriptor;
const enumerable = descriptor.enumerable !== false;
const writable = descriptor.writable !== false;
let value;
let valueSet = false;
function getValue(): T {
// WORKAROUND: A weird infinite loop occurs where calling `getValue` calls
// `setValue` which calls `Object.defineProperty` which somehow triggers
// `getValue` again. Adding `valueSet` breaks this loop.
if (!valueSet) {
setValue(get());
}
return value;
}
function setValue(newValue: T): void {
value = newValue;
valueSet = true;
Object.defineProperty(object, name, {
value: newValue,
configurable: true,
enumerable,
writable,
});
}
Object.defineProperty(object, name, {
get: getValue,
set: setValue,
configurable: true,
enumerable,
});
}
module.exports = defineLazyObjectProperty;