Agent Zebra Agent Zebra - 3 months ago 13
Javascript Question

Issue with creating a reusable method

What's the best way to refactor the following randomizing code into a reusable method? I want to put this part into a reusable method ==>

$scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)];


I tried the following and it's not working:

function randTarotImg(){
$scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)];
}
$scope.onClick = function() {
randTarotImg();
};


Here's the relevant code block:

.controller('TarotCtrl', function ($scope) {

$scope.tarotImg = [];
for (var i=1;i<=6;i++) {
$scope.tarotImg.push(i);
}

$scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)];

$scope.onClick = function() {
$scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)];
};

})

Answer

var arr = [1,2,3,4,5,6,7,8];

function getRandomElement(arr) {
  return arr[Math.floor(Math.random()*arr.length)];
}

console.log(getRandomElement(arr));

In your case:

.controller('TarotCtrl', function($scope) {

  $scope.tarotImg = [];
  for (var i = 1; i <= 6; i++) {
    $scope.tarotImg.push(i);
  }

  function getRandomElement(arr) {
    return arr[Math.floor(Math.random()*arr.length)];
  }

  $scope.randTarotImg = getRandomElement($scope.tarotImg);

  $scope.onClick = function() {
    $scope.randTarotImg = getRandomElement($scope.tarotImg);
  };

});
Comments