You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.3 KiB

3 months ago
  1. # define-lazy-prop [![Build Status](https://travis-ci.org/sindresorhus/define-lazy-prop.svg?branch=master)](https://travis-ci.org/sindresorhus/define-lazy-prop)
  2. > Define a [lazily evaluated](https://en.wikipedia.org/wiki/Lazy_evaluation) property on an object
  3. Useful when the value of a property is expensive to generate, so you want to delay the computation until the property is needed. For example, improving startup performance by deferring nonessential operations.
  4. ## Install
  5. ```
  6. $ npm install define-lazy-prop
  7. ```
  8. ## Usage
  9. ```js
  10. const defineLazyProp = require('define-lazy-prop');
  11. const unicorn = {
  12. // …
  13. };
  14. defineLazyProp(unicorn, 'rainbow', () => expensiveComputation());
  15. app.on('user-action', () => {
  16. doSomething(unicorn.rainbow);
  17. });
  18. ```
  19. ## API
  20. ### defineLazyProp(object, propertyName, fn)
  21. #### object
  22. Type: `Object`
  23. Object to add property to.
  24. #### propertyName
  25. Type: `string`
  26. Name of the property to add.
  27. #### fn
  28. Type: `Function`
  29. Called the first time `propertyName` is accessed. Expected to return a value.
  30. ## Related
  31. - [lazy-value](https://github.com/sindresorhus/lazy-value) - Create a lazily evaluated value
  32. - [import-lazy](https://github.com/sindresorhus/import-lazy) - Import a module lazily
  33. - [p-lazy](https://github.com/sindresorhus/p-lazy) - Create a lazy promise
  34. ## License
  35. MIT © [Sindre Sorhus](https://sindresorhus.com)