From 22e1857728f008bb7498eb7709ce47714b73de59 Mon Sep 17 00:00:00 2001 From: zhabinka Date: Wed, 9 Jan 2019 01:06:27 +0300 Subject: [PATCH] Corrected regular expression --- .../run-length-encoding/run-length-encoding.js | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/javascript/run-length-encoding/run-length-encoding.js b/javascript/run-length-encoding/run-length-encoding.js index ac6a676..c4a4a79 100644 --- a/javascript/run-length-encoding/run-length-encoding.js +++ b/javascript/run-length-encoding/run-length-encoding.js @@ -1,15 +1,8 @@ const encode = (str) => { - const iter = (s, arr) => { - if (s.length === 0) { - return arr; - } - const regex = new RegExp(`${s[0]}+`); - const charsGroup = s.match(regex)[0]; - - return iter(s.substr(charsGroup.length), arr.concat(charsGroup)); - }; - - const groups = iter(str, []); + if (str === '') { + return str; + } + const groups = str.match(/(.)\1*/g); return groups .map(el => (el.length === 1 ? el : `${el.length}${el[0]}`))