Lodash 정리하기 : _.shuffleSelf()

sturrxxl·2021년 2월 18일
0

Lodash 정리하기

목록 보기
3/3

_.shuffleSelf

_.shuffleSelf(array,[number])

array의 값들 중에 number의 수의 값을 랜덤으로 뽑아서 반환

1 - array - 섞을 배열 전달
2 - number ( option ) - 랜덤으로 뽑을 값의 수
    ↑ 없을 경우 array.length

  return   배열

lodash shuffleSelf

lodash 예제

_.shuffleSelf([1,2,4,3,4],3);
// 호출할때마다 값이 바뀜!
// => [ 2, 4, 3 ]
// => [ 3, 4, 1 ] 
// =>  . . .

_.shuffleSelf

function shuffleSelf(array, size) {
  var index = -1,
      length = array.length,
      lastIndex = length - 1;

  size = size === undefined ? length : size;
   // size( 두번째인자 )가 없으면 array의 length가 size가 된다
   // => array전체의 값들이 랜덤하게 섞여서 반환된다
  while (++index < size) {
    // baseRandom은 아래에 설명!!
    var rand = baseRandom(index, lastIndex),
        value = array[rand];
    	// baseRandom로 얻은 array의 랜덤한 index값을 value라는 변수에 할당하고
    array[rand] = array[index];
     	// 랜덤한 index의 값을 array[index]에 저장한다.
    array[index] = value;
    	//array[index]에 baseRandom로 얻은 array의 랜덤한 index값을 넣는다
  }
  array.length = size; 
  //length를 랜덤으로 뽑을 값의 수로 변경
 
  // 그럴일은 없겠지만 만약에 size가 4인데 length가 3이라면 빈 배열값이 들어가 length를 4로 맞춰준다
  return array;
}

_.baseRandom

랜덤한 값을 반환
인자로 주어진 upper - lower 로 최대값을 정하고,
+1을 해주어 최소값이 0이아닌 1이 되도록 해주며,
lower을 더해주어 lower보다 작은수가 나오지 않도록 한다. (?)

  const nativeRandom = Math.random, 
        nativeFloor = Math.floor
  
  function baseRandom(lower, upper) {
    return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
    // 작은수 + 올림 ( 랜덤값 * ( 큰수 + 작은수 + 1 ) )
  }

랜덤한 값을 뽑는 방식은 알겠는데 왜 lower을 더해주는지 이유는 아직 파악 못했다.....🤢
profile
프론트 개발자가 되는 과정

0개의 댓글