lodash.sampleSize - need help in understanding the code

1.1k views Asked by At

Need your help in understanding the code.. If I use sampleSize function from lodash in my program its working fine as expected. But when I use the code of sampleSize(https://github.com/lodash/lodash/blob/master/sampleSize.js) directly in my program its not working as expected. Main issue is, in that code we are not restricting 'result' to have only 'n' elements. so length of 'array' and length of 'result' is same, which is incorrect. I rewrite the program to give expected result.but still want to understand lodash.sampleSize how its working. Thanks!!

Here is my code

sampleSize(array, n) {
        const length = array == null ? 0 : array.length
        if (!length || n < 1) {
            return []
            }
            n = n > length ? length : n
            //console.log("n is",n)
            let index = -1
            //const lastIndex = n - 1
            const result = array.slice()
            while (++index < n) {
                const rand = index + Math.floor(Math.random() * (length - index ))
                //console.log("rand is",rand)
                const value = result[rand]
                result[rand] = result[index]
                result[index] = value
            }
            //console.log("result is",result.slice(0,n))
            return result.slice(0,n)
    }
0

There are 0 answers