main.js (1974B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2019 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isObject = require( '@stdlib/assert/is-object' ); 24 var isFunction = require( '@stdlib/assert/is-function' ); 25 var defineMemoizedProperty = require( './../../define-memoized-property' ); 26 27 28 // MAIN // 29 30 /** 31 * Defines a memoized read-only object property. 32 * 33 * ## Notes 34 * 35 * - Read-only properties are **enumerable** and **non-configurable**. 36 * 37 * @param {Object} obj - object on which to define the property 38 * @param {(string|symbol)} prop - property name 39 * @param {Function} fcn - function whose return value will be memoized and set as the property value 40 * @throws {TypeError} first argument must be an object 41 * @throws {TypeError} third argument must be a function 42 * 43 * @example 44 * var obj = {}; 45 * 46 * function foo() { 47 * return 'bar'; 48 * } 49 * 50 * setMemoizedReadOnly( obj, 'foo', foo ); 51 * 52 * var v = obj.foo; 53 * // returns 'bar' 54 */ 55 function setMemoizedReadOnly( obj, prop, fcn ) { 56 if ( !isObject( obj ) ) { 57 throw new TypeError( 'invalid argument. First argument must be an object. Value: `' + obj + '`.' ); 58 } 59 if ( !isFunction( fcn ) ) { 60 throw new TypeError( 'invalid argument. Third argument must be a function. Value: `' + fcn + '`.' ); 61 } 62 defineMemoizedProperty( obj, prop, { 63 'configurable': false, 64 'enumerable': true, 65 'writable': false, 66 'value': fcn 67 }); 68 } 69 70 71 // EXPORTS // 72 73 module.exports = setMemoizedReadOnly;