From c557338b02658880d8b893ded3d3c3611e29d67c Mon Sep 17 00:00:00 2001 From: Rohit Tanwar Date: Sun, 31 Dec 2017 17:26:28 +0530 Subject: [PATCH] add sampleSize --- snippets/sampleSize.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 snippets/sampleSize.md diff --git a/snippets/sampleSize.md b/snippets/sampleSize.md new file mode 100644 index 000000000..ef4ca3e63 --- /dev/null +++ b/snippets/sampleSize.md @@ -0,0 +1,19 @@ +### sampleSize + +Returns the length of string. + +```js +const sampleSize = (arr,n=1) => { + let m = arr.length; + while (m) { + const i = Math.floor(Math.random() * m--); + [arr[m], arr[i]] = [arr[i], arr[m]]; + } + return arr.slice(0,n) +} +``` + +```js +sampleSize([1,2,3],2); // [3,1] +sampleSize([1,2,3],4); // [2,3,1] +```