From faea6efe7855178dee63d85caaedd12932929678 Mon Sep 17 00:00:00 2001 From: Mary Date: Tue, 11 Dec 2018 17:15:31 -0500 Subject: [PATCH] Update strComp.js --- chapter01/1.6 - String Compression/strComp.js | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/chapter01/1.6 - String Compression/strComp.js b/chapter01/1.6 - String Compression/strComp.js index 2d0e776..44b7281 100644 --- a/chapter01/1.6 - String Compression/strComp.js +++ b/chapter01/1.6 - String Compression/strComp.js @@ -22,4 +22,25 @@ var strComp = function(string) { // Test console.log('aaaaaa', strComp('aaaaaa'), 'a6'); -console.log('aabcccccaaa', strComp('aabcccccaaa'), 'a2b1c5a3'); \ No newline at end of file +console.log('aabcccccaaa', strComp('aabcccccaaa'), 'a2b1c5a3'); + +//Another solution + +function compression(str) { + var counter = 1; + var result = ''; + for (var i = 0; i < str.length; i++) { + if (str.charAt(i) === str.charAt(i + 1)) { + counter+=1; + } else { + result += str.charAt(i) + counter.toString(); + counter = 1; + } + } + + if (result.length < str.length ) { + return result; + } else { + return str; + } +}