From ba325526aeee106cbf372fb8427b6b6cbe790b81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Mon, 1 Jul 2019 00:43:52 +0200 Subject: [PATCH] Use `Array.apply` to repeat a loop In JavaScript we cannot easily repeat something N times, and CoffeeScript's range loop compiles into complex JavaScript. We could also use `Array.from({ length: N })`, but that's not supported by old browsers like Internet Explorer 11. --- app/assets/javascripts/managers.js.coffee | 15 +++++++-------- app/assets/javascripts/polls.js.coffee | 10 +++------- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/app/assets/javascripts/managers.js.coffee b/app/assets/javascripts/managers.js.coffee index b0d33ad81..9e112900c 100644 --- a/app/assets/javascripts/managers.js.coffee +++ b/app/assets/javascripts/managers.js.coffee @@ -3,14 +3,13 @@ App.Managers = generatePassword: -> - chars = "aAbcdeEfghiJkmnpqrstuUvwxyz23456789" - pass = "" - x = 0 - while x < 12 - i = Math.floor(Math.random() * chars.length) - pass += chars.charAt(i) - x++ - return pass + possible_chars = "aAbcdeEfghiJkmnpqrstuUvwxyz23456789" + + chars = Array.apply(null, length: 12).map -> + i = Math.floor(Math.random() * possible_chars.length) + possible_chars.charAt(i) + + chars.join("") togglePassword: (type) -> $("#user_password").prop "type", type diff --git a/app/assets/javascripts/polls.js.coffee b/app/assets/javascripts/polls.js.coffee index 6b7cae960..0dae792b0 100644 --- a/app/assets/javascripts/polls.js.coffee +++ b/app/assets/javascripts/polls.js.coffee @@ -2,14 +2,10 @@ App.Polls = generateToken: -> - token = "" - rand = "" - for n in [0..5] - rand = Math.random().toString(36).substr(2) # remove `0.` - token = token + rand + strings = Array.apply(null, length: 6).map -> + Math.random().toString(36).substr(2) # remove `0.` - token = token.substring(0, 64) - return token + strings.join("").substring(0, 64) replaceToken: (token) -> $(".js-question-answer").each ->