Search code examples
javascriptangularjslodashmemoization

Using lodash _.memoize combine with _.random


I saw this code written by someone (in angularjs), and I want to know how this work (just ask for my knowledge):

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

and extra HTML for view (changeVisibility and visibility are used):

<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>

Can someone tell me? Thanks a lot.


Solution

  • I believe it hides some of the content if it rolled a 0 in the visibility function. Basically, it has a small chance of 1/X to be hidden, where X is the highest range in _.random(0,X). It stores this generated number in cache for a particular index with _.memoize (possibly to reduce $digest cycle executables for each watcher).

    Here is a similar code to see how it works (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>