From 02778658b583a9ed428eaa39c1cf31fb40635a18 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 1 Sep 2019 21:54:34 -0500 Subject: [PATCH] Add Generate Random Integers as a javascript til --- README.md | 3 ++- javascript/generate-random-integers.md | 30 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 javascript/generate-random-integers.md diff --git a/README.md b/README.md index eeeb9ac..bdc4ad7 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_841 TILs and counting..._ +_842 TILs and counting..._ --- @@ -290,6 +290,7 @@ _841 TILs and counting..._ - [Fill An Input With A Ton Of Text](javascript/fill-an-input-with-a-ton-of-text.md) - [for...in Iterates Over Object Properties](javascript/for-in-iterates-over-object-properties.md) - [Freeze An Object, Sorta](javascript/freeze-an-object-sorta.md) +- [Generate Random Integers](javascript/generate-random-integers.md) - [Get The Location And Size Of An Element](javascript/get-the-location-and-size-of-an-element.md) - [Get The Time Zone Of The Client Computer](javascript/get-the-time-zone-of-the-client-computer.md) - [Globally Install A Package With Yarn](javascript/globally-install-a-package-with-yarn.md) diff --git a/javascript/generate-random-integers.md b/javascript/generate-random-integers.md new file mode 100644 index 0000000..4fc76ee --- /dev/null +++ b/javascript/generate-random-integers.md @@ -0,0 +1,30 @@ +# Generate Random Integers + +JavaScript's `Math` module has a built-in `random` function. + +```javascript +> Math.random(); +0.4663311937101857 +``` + +It can be used to generate random floats between 0 and 1. + +If you want integers, though, you're going to have to build your own function. + +```javascript +function getRandomInt(max) { + return Math.floor(Math.random() * Math.floor(max)); +} + +> getRandomInt(10); +1 +> getRandomInt(10); +7 +> getRandomInt(10); +2 +``` + +This function allows you to randomly generate numbers between `0` (inclusive) +and `max`, a number you specify (exclusive). + +[source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)