使用 lodash _.memoize 结合 _.random

Using lodash _.memoize combine with _.random

看到有人写的这段代码(在angularjs),想知道这是怎么实现的(求教):

    $scope.changeVisibility = function() {
        $scope.visibility = _.memoize(function() {
            return !!_.random(0, 4);
        });
    };
    $scope.changeVisibility()

和额外的 HTML 用于视图(使用了 changeVisibility 和 visibility):

<button ng-click="changeVisibility()">Visibility change</button>
<div class="row">
  <div class="col" visible="visibility(1)">
    1. Row, 1. Col
  </div>

  <div class="col" visible="visibility(2)">
    Mark Hane<br>
    28 yearold<br>
    234 SG
  </div>

  <div class="col" visible="visibility(3)">
    <div class="row"  ng-if="visibility(3)">
      1. Row, 3. Col, 1. Row --  1<br>
      1. Row, 3. Col, 1. Row --  2
    </div>
    <div class="row"  ng-if="visibility(3)">
      1. Row, 3. Col, 2. Row --  1<br>
      1. Row, 3. Col, 2. Row --  2<br>
      1. Row, 3. Col, 2. Row --  3
    </div>
  </div>
</div>
... so on to  visibility(9)
</div>
</html>

有人可以告诉我吗?非常感谢。

如果它在 visibility 函数中滚动 0,我相信它 隐藏了 一些内容。基本上,它有1/X的小几率被隐藏,其中X是_.random(0,X)中的最高范围。它将生成的数字存储在 缓存 中,用于具有 _.memoize 的特定索引(可能减少每个观察者的 $digest 循环可执行文件)。

下面是一个类似的代码,看看它是如何工作的 (Plunker):

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<body ng-app="app">
  <div ng-controller="myCtrl">
    <button ng-click="changeVisibility()">Visibility change</button>
    <div ng-repeat="i in [1,2,3,4,5,6,7,8,9,10]">
      visibility({{$index+1}}) - {{visibility($index+1)}}
      <span ng-if="visibility($index+1)">- [i c u]</span>
    </div>
  </div>
  <script>
    var app = angular.module('app', []);
    app.controller('myCtrl', function($scope) {
      $scope.changeVisibility = function() {
        $scope.visibility = _.memoize(function() {
          return !!_.random(0, 10);
        });
      };
      $scope.changeVisibility(); // initialise 
    });
  </script>
</body>

</html>