String compression algorithm using functional JavaScript











up vote
2
down vote

favorite












I've written an algo to compress a string



eg. aabcbbba to a2bcb3a



I'm pretty new to functional programming, I feel it's easier to debug and learn from functional code if you're good at it already, but total opposite if you're not.



I'm wondering how I can make this code cleaner and more functional.



I feel like there's gotta be a better way to do compressCharacters without the need of an array or a result variable (perhaps substituting forEach with something else) as well as reducing the lines of code in groupCharacters






const signature = `aabcbbba`;

const compressString = signature => {
return compressCharacters(groupCharacters(signature));
}

const groupCharacters = signature => {
let newSignature = "", arr = ;

// convert signature to an array
let result = [...signature].reduce((accumulator, element, index) => {

// check if last letter in accumulator matches the current element
if (accumulator[accumulator.length -1] !== element) {
// add the accumulator string into an array
arr.push(accumulator);
// clear the newSignature string and set it to current element
newSignature = element;
} else {
// if it doesn't match, add it to the accumulator
newSignature = accumulator += element;
}

// check if it's the last item - add to array
if (index === signature.length - 1) arr.push(element);

// return newSignature to accumulator
return newSignature;
})

return arr;
}

const compressCharacters = arr => {
let newArray = ;

let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))

return newArray.join("");
}

compressString(signature);












share|improve this question




























    up vote
    2
    down vote

    favorite












    I've written an algo to compress a string



    eg. aabcbbba to a2bcb3a



    I'm pretty new to functional programming, I feel it's easier to debug and learn from functional code if you're good at it already, but total opposite if you're not.



    I'm wondering how I can make this code cleaner and more functional.



    I feel like there's gotta be a better way to do compressCharacters without the need of an array or a result variable (perhaps substituting forEach with something else) as well as reducing the lines of code in groupCharacters






    const signature = `aabcbbba`;

    const compressString = signature => {
    return compressCharacters(groupCharacters(signature));
    }

    const groupCharacters = signature => {
    let newSignature = "", arr = ;

    // convert signature to an array
    let result = [...signature].reduce((accumulator, element, index) => {

    // check if last letter in accumulator matches the current element
    if (accumulator[accumulator.length -1] !== element) {
    // add the accumulator string into an array
    arr.push(accumulator);
    // clear the newSignature string and set it to current element
    newSignature = element;
    } else {
    // if it doesn't match, add it to the accumulator
    newSignature = accumulator += element;
    }

    // check if it's the last item - add to array
    if (index === signature.length - 1) arr.push(element);

    // return newSignature to accumulator
    return newSignature;
    })

    return arr;
    }

    const compressCharacters = arr => {
    let newArray = ;

    let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))

    return newArray.join("");
    }

    compressString(signature);












    share|improve this question


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I've written an algo to compress a string



      eg. aabcbbba to a2bcb3a



      I'm pretty new to functional programming, I feel it's easier to debug and learn from functional code if you're good at it already, but total opposite if you're not.



      I'm wondering how I can make this code cleaner and more functional.



      I feel like there's gotta be a better way to do compressCharacters without the need of an array or a result variable (perhaps substituting forEach with something else) as well as reducing the lines of code in groupCharacters






      const signature = `aabcbbba`;

      const compressString = signature => {
      return compressCharacters(groupCharacters(signature));
      }

      const groupCharacters = signature => {
      let newSignature = "", arr = ;

      // convert signature to an array
      let result = [...signature].reduce((accumulator, element, index) => {

      // check if last letter in accumulator matches the current element
      if (accumulator[accumulator.length -1] !== element) {
      // add the accumulator string into an array
      arr.push(accumulator);
      // clear the newSignature string and set it to current element
      newSignature = element;
      } else {
      // if it doesn't match, add it to the accumulator
      newSignature = accumulator += element;
      }

      // check if it's the last item - add to array
      if (index === signature.length - 1) arr.push(element);

      // return newSignature to accumulator
      return newSignature;
      })

      return arr;
      }

      const compressCharacters = arr => {
      let newArray = ;

      let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))

      return newArray.join("");
      }

      compressString(signature);












      share|improve this question















      I've written an algo to compress a string



      eg. aabcbbba to a2bcb3a



      I'm pretty new to functional programming, I feel it's easier to debug and learn from functional code if you're good at it already, but total opposite if you're not.



      I'm wondering how I can make this code cleaner and more functional.



      I feel like there's gotta be a better way to do compressCharacters without the need of an array or a result variable (perhaps substituting forEach with something else) as well as reducing the lines of code in groupCharacters






      const signature = `aabcbbba`;

      const compressString = signature => {
      return compressCharacters(groupCharacters(signature));
      }

      const groupCharacters = signature => {
      let newSignature = "", arr = ;

      // convert signature to an array
      let result = [...signature].reduce((accumulator, element, index) => {

      // check if last letter in accumulator matches the current element
      if (accumulator[accumulator.length -1] !== element) {
      // add the accumulator string into an array
      arr.push(accumulator);
      // clear the newSignature string and set it to current element
      newSignature = element;
      } else {
      // if it doesn't match, add it to the accumulator
      newSignature = accumulator += element;
      }

      // check if it's the last item - add to array
      if (index === signature.length - 1) arr.push(element);

      // return newSignature to accumulator
      return newSignature;
      })

      return arr;
      }

      const compressCharacters = arr => {
      let newArray = ;

      let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))

      return newArray.join("");
      }

      compressString(signature);








      const signature = `aabcbbba`;

      const compressString = signature => {
      return compressCharacters(groupCharacters(signature));
      }

      const groupCharacters = signature => {
      let newSignature = "", arr = ;

      // convert signature to an array
      let result = [...signature].reduce((accumulator, element, index) => {

      // check if last letter in accumulator matches the current element
      if (accumulator[accumulator.length -1] !== element) {
      // add the accumulator string into an array
      arr.push(accumulator);
      // clear the newSignature string and set it to current element
      newSignature = element;
      } else {
      // if it doesn't match, add it to the accumulator
      newSignature = accumulator += element;
      }

      // check if it's the last item - add to array
      if (index === signature.length - 1) arr.push(element);

      // return newSignature to accumulator
      return newSignature;
      })

      return arr;
      }

      const compressCharacters = arr => {
      let newArray = ;

      let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))

      return newArray.join("");
      }

      compressString(signature);





      const signature = `aabcbbba`;

      const compressString = signature => {
      return compressCharacters(groupCharacters(signature));
      }

      const groupCharacters = signature => {
      let newSignature = "", arr = ;

      // convert signature to an array
      let result = [...signature].reduce((accumulator, element, index) => {

      // check if last letter in accumulator matches the current element
      if (accumulator[accumulator.length -1] !== element) {
      // add the accumulator string into an array
      arr.push(accumulator);
      // clear the newSignature string and set it to current element
      newSignature = element;
      } else {
      // if it doesn't match, add it to the accumulator
      newSignature = accumulator += element;
      }

      // check if it's the last item - add to array
      if (index === signature.length - 1) arr.push(element);

      // return newSignature to accumulator
      return newSignature;
      })

      return arr;
      }

      const compressCharacters = arr => {
      let newArray = ;

      let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))

      return newArray.join("");
      }

      compressString(signature);






      javascript functional-programming compression






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      200_success

      127k15148410




      127k15148410










      asked yesterday









      totalnoob

      1394




      1394






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote













          Style notes




          • Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks.

          • In compressCharacters newArray should be a constant. In groupCharacters arr should be a constant.

          • Consistent naming is important. Your naming is all over the place. You call a string, characters (in compressCharacters), string (in compressString), signature, and e in the forEach. A character you call element. You abbreviate an array to arr in one function and call it newArray in another. Most of the names are describing the type and not the abstracted data that they hold.

          • Don't add useless or redundant code. In compressCharacters you create a variable result that you do nothing with. Not to mention that forEach does not have a return defined. Also result in groupCharacters is never used.

          • Don't declare variables outside the scope that they are to be used. newSignature is only used inside reduce but declared outside the callback.


          Functional programing means that functions should not have side effect (change the state of anything outside the function's scope.) The reduce callback uses the array arr which breaks the no side effects rule. And the forEach pushes to arr which is also outside the forEach callbacks scope (use map or reduce in that case).



          Applying the above you would get something like the following code.



          const groupRuns = str => [...str].reduce((groups, char) => {
          const last = groups.length - 1;
          if (last < 0 || groups[last][0] !== char) { groups.push(char) }
          else { groups[last] += char }
          return groups;
          }, );

          const concatGroups = groups => groups.reduce((str, g) =>
          str + (g.length > 2 ? g[0] + g.length : g)
          , "");

          const compressString = str => concatGroups(groupRuns(str));

          const signature = `aabcbbbaaaaaabcccccdddddddbbba`;
          compressString(signature);


          Note that rather than add numbers to groups of size 2 the group must be 3 or larger.






          share|improve this answer























          • g.length > 2 is wrong: it fails to transform aa to a2 as specified.
            – 200_success
            8 hours ago










          • @200_success As I pointed out.
            – Blindman67
            8 hours ago










          • shouldn't concatGroups also be delimited with brackets and returns?
            – totalnoob
            7 hours ago










          • @totalnoob It is not required, in fact groupRuns can do without the return. However I should have moved the returning object to the same line. I will update it now.
            – Blindman67
            4 hours ago










          • doesn't that go against "Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks."?
            – totalnoob
            1 hour ago


















          up vote
          -3
          down vote













          I am not sure which answer is better. but I would've done it this way:



          var arrElement, arr= , tempElement = "", compressedStrng ="", counter = 1;

          function CompressString(strng) {
          arr = strng.split(''); //splitting the string to an array of chars
          for (arrElement of arr) { //looping in this array
          if (tempElement == ""){ //if first element
          tempElement = arrElement;
          compressedStrng += arrElement;
          }else{
          if (tempElement == arrElement){ //if array element is repeating add one to the counter below
          counter ++;
          } else{
          if (counter > 1){
          compressedStrng += counter;
          counter = 1;
          }
          tempElement = arrElement;
          compressedStrng += arrElement;
          }
          }
          }
          return compressedStrng;
          }

          CompressString('aabcbbba');
          console.log (CompressString('aabcbbba')); //It will display a2bcb3a


          let me know if you need any clarifications






          share|improve this answer










          New contributor




          DrDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.








          We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.














          • You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
            – Toby Speight
            12 hours ago










          • Can you please explain more what I need to do? I don't understand this: "Please edit to show what aspects of the question code prompted you to write this version" The user asked: "I'm wondering how I can make this code cleaner and more functional." I gave my humble opinion on how this code can be better, stating that I am not sure if it is better or not ( cause i haven't tested it)
            – DrDev
            12 hours ago






          • 2




            Just presenting suggested new code isn't really a review. A good review explains why you suggest each change (does it improve readability, or performance, or correctness?) so that the asker can make an informed decision on which suggestions to adopt, and so their future code is informed by choices made here. A code dump without any of that explanation has much lower value to the asker and to the community.
            – Toby Speight
            11 hours ago






          • 1




            Not only that, but this doesn't look like functional programming at all. You'd at least want to explain why you're disregarding the tag.
            – Toby Speight
            11 hours ago











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207518%2fstring-compression-algorithm-using-functional-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest
































          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote













          Style notes




          • Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks.

          • In compressCharacters newArray should be a constant. In groupCharacters arr should be a constant.

          • Consistent naming is important. Your naming is all over the place. You call a string, characters (in compressCharacters), string (in compressString), signature, and e in the forEach. A character you call element. You abbreviate an array to arr in one function and call it newArray in another. Most of the names are describing the type and not the abstracted data that they hold.

          • Don't add useless or redundant code. In compressCharacters you create a variable result that you do nothing with. Not to mention that forEach does not have a return defined. Also result in groupCharacters is never used.

          • Don't declare variables outside the scope that they are to be used. newSignature is only used inside reduce but declared outside the callback.


          Functional programing means that functions should not have side effect (change the state of anything outside the function's scope.) The reduce callback uses the array arr which breaks the no side effects rule. And the forEach pushes to arr which is also outside the forEach callbacks scope (use map or reduce in that case).



          Applying the above you would get something like the following code.



          const groupRuns = str => [...str].reduce((groups, char) => {
          const last = groups.length - 1;
          if (last < 0 || groups[last][0] !== char) { groups.push(char) }
          else { groups[last] += char }
          return groups;
          }, );

          const concatGroups = groups => groups.reduce((str, g) =>
          str + (g.length > 2 ? g[0] + g.length : g)
          , "");

          const compressString = str => concatGroups(groupRuns(str));

          const signature = `aabcbbbaaaaaabcccccdddddddbbba`;
          compressString(signature);


          Note that rather than add numbers to groups of size 2 the group must be 3 or larger.






          share|improve this answer























          • g.length > 2 is wrong: it fails to transform aa to a2 as specified.
            – 200_success
            8 hours ago










          • @200_success As I pointed out.
            – Blindman67
            8 hours ago










          • shouldn't concatGroups also be delimited with brackets and returns?
            – totalnoob
            7 hours ago










          • @totalnoob It is not required, in fact groupRuns can do without the return. However I should have moved the returning object to the same line. I will update it now.
            – Blindman67
            4 hours ago










          • doesn't that go against "Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks."?
            – totalnoob
            1 hour ago















          up vote
          1
          down vote













          Style notes




          • Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks.

          • In compressCharacters newArray should be a constant. In groupCharacters arr should be a constant.

          • Consistent naming is important. Your naming is all over the place. You call a string, characters (in compressCharacters), string (in compressString), signature, and e in the forEach. A character you call element. You abbreviate an array to arr in one function and call it newArray in another. Most of the names are describing the type and not the abstracted data that they hold.

          • Don't add useless or redundant code. In compressCharacters you create a variable result that you do nothing with. Not to mention that forEach does not have a return defined. Also result in groupCharacters is never used.

          • Don't declare variables outside the scope that they are to be used. newSignature is only used inside reduce but declared outside the callback.


          Functional programing means that functions should not have side effect (change the state of anything outside the function's scope.) The reduce callback uses the array arr which breaks the no side effects rule. And the forEach pushes to arr which is also outside the forEach callbacks scope (use map or reduce in that case).



          Applying the above you would get something like the following code.



          const groupRuns = str => [...str].reduce((groups, char) => {
          const last = groups.length - 1;
          if (last < 0 || groups[last][0] !== char) { groups.push(char) }
          else { groups[last] += char }
          return groups;
          }, );

          const concatGroups = groups => groups.reduce((str, g) =>
          str + (g.length > 2 ? g[0] + g.length : g)
          , "");

          const compressString = str => concatGroups(groupRuns(str));

          const signature = `aabcbbbaaaaaabcccccdddddddbbba`;
          compressString(signature);


          Note that rather than add numbers to groups of size 2 the group must be 3 or larger.






          share|improve this answer























          • g.length > 2 is wrong: it fails to transform aa to a2 as specified.
            – 200_success
            8 hours ago










          • @200_success As I pointed out.
            – Blindman67
            8 hours ago










          • shouldn't concatGroups also be delimited with brackets and returns?
            – totalnoob
            7 hours ago










          • @totalnoob It is not required, in fact groupRuns can do without the return. However I should have moved the returning object to the same line. I will update it now.
            – Blindman67
            4 hours ago










          • doesn't that go against "Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks."?
            – totalnoob
            1 hour ago













          up vote
          1
          down vote










          up vote
          1
          down vote









          Style notes




          • Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks.

          • In compressCharacters newArray should be a constant. In groupCharacters arr should be a constant.

          • Consistent naming is important. Your naming is all over the place. You call a string, characters (in compressCharacters), string (in compressString), signature, and e in the forEach. A character you call element. You abbreviate an array to arr in one function and call it newArray in another. Most of the names are describing the type and not the abstracted data that they hold.

          • Don't add useless or redundant code. In compressCharacters you create a variable result that you do nothing with. Not to mention that forEach does not have a return defined. Also result in groupCharacters is never used.

          • Don't declare variables outside the scope that they are to be used. newSignature is only used inside reduce but declared outside the callback.


          Functional programing means that functions should not have side effect (change the state of anything outside the function's scope.) The reduce callback uses the array arr which breaks the no side effects rule. And the forEach pushes to arr which is also outside the forEach callbacks scope (use map or reduce in that case).



          Applying the above you would get something like the following code.



          const groupRuns = str => [...str].reduce((groups, char) => {
          const last = groups.length - 1;
          if (last < 0 || groups[last][0] !== char) { groups.push(char) }
          else { groups[last] += char }
          return groups;
          }, );

          const concatGroups = groups => groups.reduce((str, g) =>
          str + (g.length > 2 ? g[0] + g.length : g)
          , "");

          const compressString = str => concatGroups(groupRuns(str));

          const signature = `aabcbbbaaaaaabcccccdddddddbbba`;
          compressString(signature);


          Note that rather than add numbers to groups of size 2 the group must be 3 or larger.






          share|improve this answer














          Style notes




          • Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks.

          • In compressCharacters newArray should be a constant. In groupCharacters arr should be a constant.

          • Consistent naming is important. Your naming is all over the place. You call a string, characters (in compressCharacters), string (in compressString), signature, and e in the forEach. A character you call element. You abbreviate an array to arr in one function and call it newArray in another. Most of the names are describing the type and not the abstracted data that they hold.

          • Don't add useless or redundant code. In compressCharacters you create a variable result that you do nothing with. Not to mention that forEach does not have a return defined. Also result in groupCharacters is never used.

          • Don't declare variables outside the scope that they are to be used. newSignature is only used inside reduce but declared outside the callback.


          Functional programing means that functions should not have side effect (change the state of anything outside the function's scope.) The reduce callback uses the array arr which breaks the no side effects rule. And the forEach pushes to arr which is also outside the forEach callbacks scope (use map or reduce in that case).



          Applying the above you would get something like the following code.



          const groupRuns = str => [...str].reduce((groups, char) => {
          const last = groups.length - 1;
          if (last < 0 || groups[last][0] !== char) { groups.push(char) }
          else { groups[last] += char }
          return groups;
          }, );

          const concatGroups = groups => groups.reduce((str, g) =>
          str + (g.length > 2 ? g[0] + g.length : g)
          , "");

          const compressString = str => concatGroups(groupRuns(str));

          const signature = `aabcbbbaaaaaabcccccdddddddbbba`;
          compressString(signature);


          Note that rather than add numbers to groups of size 2 the group must be 3 or larger.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 4 hours ago

























          answered 8 hours ago









          Blindman67

          6,3241521




          6,3241521












          • g.length > 2 is wrong: it fails to transform aa to a2 as specified.
            – 200_success
            8 hours ago










          • @200_success As I pointed out.
            – Blindman67
            8 hours ago










          • shouldn't concatGroups also be delimited with brackets and returns?
            – totalnoob
            7 hours ago










          • @totalnoob It is not required, in fact groupRuns can do without the return. However I should have moved the returning object to the same line. I will update it now.
            – Blindman67
            4 hours ago










          • doesn't that go against "Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks."?
            – totalnoob
            1 hour ago


















          • g.length > 2 is wrong: it fails to transform aa to a2 as specified.
            – 200_success
            8 hours ago










          • @200_success As I pointed out.
            – Blindman67
            8 hours ago










          • shouldn't concatGroups also be delimited with brackets and returns?
            – totalnoob
            7 hours ago










          • @totalnoob It is not required, in fact groupRuns can do without the return. However I should have moved the returning object to the same line. I will update it now.
            – Blindman67
            4 hours ago










          • doesn't that go against "Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks."?
            – totalnoob
            1 hour ago
















          g.length > 2 is wrong: it fails to transform aa to a2 as specified.
          – 200_success
          8 hours ago




          g.length > 2 is wrong: it fails to transform aa to a2 as specified.
          – 200_success
          8 hours ago












          @200_success As I pointed out.
          – Blindman67
          8 hours ago




          @200_success As I pointed out.
          – Blindman67
          8 hours ago












          shouldn't concatGroups also be delimited with brackets and returns?
          – totalnoob
          7 hours ago




          shouldn't concatGroups also be delimited with brackets and returns?
          – totalnoob
          7 hours ago












          @totalnoob It is not required, in fact groupRuns can do without the return. However I should have moved the returning object to the same line. I will update it now.
          – Blindman67
          4 hours ago




          @totalnoob It is not required, in fact groupRuns can do without the return. However I should have moved the returning object to the same line. I will update it now.
          – Blindman67
          4 hours ago












          doesn't that go against "Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks."?
          – totalnoob
          1 hour ago




          doesn't that go against "Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks."?
          – totalnoob
          1 hour ago












          up vote
          -3
          down vote













          I am not sure which answer is better. but I would've done it this way:



          var arrElement, arr= , tempElement = "", compressedStrng ="", counter = 1;

          function CompressString(strng) {
          arr = strng.split(''); //splitting the string to an array of chars
          for (arrElement of arr) { //looping in this array
          if (tempElement == ""){ //if first element
          tempElement = arrElement;
          compressedStrng += arrElement;
          }else{
          if (tempElement == arrElement){ //if array element is repeating add one to the counter below
          counter ++;
          } else{
          if (counter > 1){
          compressedStrng += counter;
          counter = 1;
          }
          tempElement = arrElement;
          compressedStrng += arrElement;
          }
          }
          }
          return compressedStrng;
          }

          CompressString('aabcbbba');
          console.log (CompressString('aabcbbba')); //It will display a2bcb3a


          let me know if you need any clarifications






          share|improve this answer










          New contributor




          DrDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.








          We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.














          • You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
            – Toby Speight
            12 hours ago










          • Can you please explain more what I need to do? I don't understand this: "Please edit to show what aspects of the question code prompted you to write this version" The user asked: "I'm wondering how I can make this code cleaner and more functional." I gave my humble opinion on how this code can be better, stating that I am not sure if it is better or not ( cause i haven't tested it)
            – DrDev
            12 hours ago






          • 2




            Just presenting suggested new code isn't really a review. A good review explains why you suggest each change (does it improve readability, or performance, or correctness?) so that the asker can make an informed decision on which suggestions to adopt, and so their future code is informed by choices made here. A code dump without any of that explanation has much lower value to the asker and to the community.
            – Toby Speight
            11 hours ago






          • 1




            Not only that, but this doesn't look like functional programming at all. You'd at least want to explain why you're disregarding the tag.
            – Toby Speight
            11 hours ago















          up vote
          -3
          down vote













          I am not sure which answer is better. but I would've done it this way:



          var arrElement, arr= , tempElement = "", compressedStrng ="", counter = 1;

          function CompressString(strng) {
          arr = strng.split(''); //splitting the string to an array of chars
          for (arrElement of arr) { //looping in this array
          if (tempElement == ""){ //if first element
          tempElement = arrElement;
          compressedStrng += arrElement;
          }else{
          if (tempElement == arrElement){ //if array element is repeating add one to the counter below
          counter ++;
          } else{
          if (counter > 1){
          compressedStrng += counter;
          counter = 1;
          }
          tempElement = arrElement;
          compressedStrng += arrElement;
          }
          }
          }
          return compressedStrng;
          }

          CompressString('aabcbbba');
          console.log (CompressString('aabcbbba')); //It will display a2bcb3a


          let me know if you need any clarifications






          share|improve this answer










          New contributor




          DrDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.








          We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.














          • You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
            – Toby Speight
            12 hours ago










          • Can you please explain more what I need to do? I don't understand this: "Please edit to show what aspects of the question code prompted you to write this version" The user asked: "I'm wondering how I can make this code cleaner and more functional." I gave my humble opinion on how this code can be better, stating that I am not sure if it is better or not ( cause i haven't tested it)
            – DrDev
            12 hours ago






          • 2




            Just presenting suggested new code isn't really a review. A good review explains why you suggest each change (does it improve readability, or performance, or correctness?) so that the asker can make an informed decision on which suggestions to adopt, and so their future code is informed by choices made here. A code dump without any of that explanation has much lower value to the asker and to the community.
            – Toby Speight
            11 hours ago






          • 1




            Not only that, but this doesn't look like functional programming at all. You'd at least want to explain why you're disregarding the tag.
            – Toby Speight
            11 hours ago













          up vote
          -3
          down vote










          up vote
          -3
          down vote









          I am not sure which answer is better. but I would've done it this way:



          var arrElement, arr= , tempElement = "", compressedStrng ="", counter = 1;

          function CompressString(strng) {
          arr = strng.split(''); //splitting the string to an array of chars
          for (arrElement of arr) { //looping in this array
          if (tempElement == ""){ //if first element
          tempElement = arrElement;
          compressedStrng += arrElement;
          }else{
          if (tempElement == arrElement){ //if array element is repeating add one to the counter below
          counter ++;
          } else{
          if (counter > 1){
          compressedStrng += counter;
          counter = 1;
          }
          tempElement = arrElement;
          compressedStrng += arrElement;
          }
          }
          }
          return compressedStrng;
          }

          CompressString('aabcbbba');
          console.log (CompressString('aabcbbba')); //It will display a2bcb3a


          let me know if you need any clarifications






          share|improve this answer










          New contributor




          DrDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          I am not sure which answer is better. but I would've done it this way:



          var arrElement, arr= , tempElement = "", compressedStrng ="", counter = 1;

          function CompressString(strng) {
          arr = strng.split(''); //splitting the string to an array of chars
          for (arrElement of arr) { //looping in this array
          if (tempElement == ""){ //if first element
          tempElement = arrElement;
          compressedStrng += arrElement;
          }else{
          if (tempElement == arrElement){ //if array element is repeating add one to the counter below
          counter ++;
          } else{
          if (counter > 1){
          compressedStrng += counter;
          counter = 1;
          }
          tempElement = arrElement;
          compressedStrng += arrElement;
          }
          }
          }
          return compressedStrng;
          }

          CompressString('aabcbbba');
          console.log (CompressString('aabcbbba')); //It will display a2bcb3a


          let me know if you need any clarifications







          share|improve this answer










          New contributor




          DrDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer








          edited 14 hours ago





















          New contributor




          DrDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered 14 hours ago









          DrDev

          1033




          1033




          New contributor




          DrDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          DrDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          DrDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.



          We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.




          We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.













          • You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
            – Toby Speight
            12 hours ago










          • Can you please explain more what I need to do? I don't understand this: "Please edit to show what aspects of the question code prompted you to write this version" The user asked: "I'm wondering how I can make this code cleaner and more functional." I gave my humble opinion on how this code can be better, stating that I am not sure if it is better or not ( cause i haven't tested it)
            – DrDev
            12 hours ago






          • 2




            Just presenting suggested new code isn't really a review. A good review explains why you suggest each change (does it improve readability, or performance, or correctness?) so that the asker can make an informed decision on which suggestions to adopt, and so their future code is informed by choices made here. A code dump without any of that explanation has much lower value to the asker and to the community.
            – Toby Speight
            11 hours ago






          • 1




            Not only that, but this doesn't look like functional programming at all. You'd at least want to explain why you're disregarding the tag.
            – Toby Speight
            11 hours ago


















          • You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
            – Toby Speight
            12 hours ago










          • Can you please explain more what I need to do? I don't understand this: "Please edit to show what aspects of the question code prompted you to write this version" The user asked: "I'm wondering how I can make this code cleaner and more functional." I gave my humble opinion on how this code can be better, stating that I am not sure if it is better or not ( cause i haven't tested it)
            – DrDev
            12 hours ago






          • 2




            Just presenting suggested new code isn't really a review. A good review explains why you suggest each change (does it improve readability, or performance, or correctness?) so that the asker can make an informed decision on which suggestions to adopt, and so their future code is informed by choices made here. A code dump without any of that explanation has much lower value to the asker and to the community.
            – Toby Speight
            11 hours ago






          • 1




            Not only that, but this doesn't look like functional programming at all. You'd at least want to explain why you're disregarding the tag.
            – Toby Speight
            11 hours ago
















          You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
          – Toby Speight
          12 hours ago




          You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
          – Toby Speight
          12 hours ago












          Can you please explain more what I need to do? I don't understand this: "Please edit to show what aspects of the question code prompted you to write this version" The user asked: "I'm wondering how I can make this code cleaner and more functional." I gave my humble opinion on how this code can be better, stating that I am not sure if it is better or not ( cause i haven't tested it)
          – DrDev
          12 hours ago




          Can you please explain more what I need to do? I don't understand this: "Please edit to show what aspects of the question code prompted you to write this version" The user asked: "I'm wondering how I can make this code cleaner and more functional." I gave my humble opinion on how this code can be better, stating that I am not sure if it is better or not ( cause i haven't tested it)
          – DrDev
          12 hours ago




          2




          2




          Just presenting suggested new code isn't really a review. A good review explains why you suggest each change (does it improve readability, or performance, or correctness?) so that the asker can make an informed decision on which suggestions to adopt, and so their future code is informed by choices made here. A code dump without any of that explanation has much lower value to the asker and to the community.
          – Toby Speight
          11 hours ago




          Just presenting suggested new code isn't really a review. A good review explains why you suggest each change (does it improve readability, or performance, or correctness?) so that the asker can make an informed decision on which suggestions to adopt, and so their future code is informed by choices made here. A code dump without any of that explanation has much lower value to the asker and to the community.
          – Toby Speight
          11 hours ago




          1




          1




          Not only that, but this doesn't look like functional programming at all. You'd at least want to explain why you're disregarding the tag.
          – Toby Speight
          11 hours ago




          Not only that, but this doesn't look like functional programming at all. You'd at least want to explain why you're disregarding the tag.
          – Toby Speight
          11 hours ago


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207518%2fstring-compression-algorithm-using-functional-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest




















































































          Popular posts from this blog

          Сан-Квентин

          8-я гвардейская общевойсковая армия

          Алькесар