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);
javascript functional-programming compression
add a comment |
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);
javascript functional-programming compression
add a comment |
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);
javascript functional-programming compression
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
javascript functional-programming compression
edited yesterday
200_success
127k15148410
127k15148410
asked yesterday
totalnoob
1394
1394
add a comment |
add a comment |
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. IngroupCharacters
arr
should be a constant. - Consistent naming is important. Your naming is all over the place. You call a string, characters (in
compressCharacters
), string (incompressString
),signature
, ande
in theforEach
. A character you callelement
. You abbreviate an array toarr
in one function and call itnewArray
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 variableresult
that you do nothing with. Not to mention thatforEach
does not have a return defined. Alsoresult
ingroupCharacters
is never used. - Don't declare variables outside the scope that they are to be used.
newSignature
is only used insidereduce
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.
g.length > 2
is wrong: it fails to transformaa
toa2
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 factgroupRuns
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
add a comment |
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
New contributor
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
add a comment |
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. IngroupCharacters
arr
should be a constant. - Consistent naming is important. Your naming is all over the place. You call a string, characters (in
compressCharacters
), string (incompressString
),signature
, ande
in theforEach
. A character you callelement
. You abbreviate an array toarr
in one function and call itnewArray
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 variableresult
that you do nothing with. Not to mention thatforEach
does not have a return defined. Alsoresult
ingroupCharacters
is never used. - Don't declare variables outside the scope that they are to be used.
newSignature
is only used insidereduce
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.
g.length > 2
is wrong: it fails to transformaa
toa2
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 factgroupRuns
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
add a comment |
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. IngroupCharacters
arr
should be a constant. - Consistent naming is important. Your naming is all over the place. You call a string, characters (in
compressCharacters
), string (incompressString
),signature
, ande
in theforEach
. A character you callelement
. You abbreviate an array toarr
in one function and call itnewArray
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 variableresult
that you do nothing with. Not to mention thatforEach
does not have a return defined. Alsoresult
ingroupCharacters
is never used. - Don't declare variables outside the scope that they are to be used.
newSignature
is only used insidereduce
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.
g.length > 2
is wrong: it fails to transformaa
toa2
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 factgroupRuns
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
add a comment |
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. IngroupCharacters
arr
should be a constant. - Consistent naming is important. Your naming is all over the place. You call a string, characters (in
compressCharacters
), string (incompressString
),signature
, ande
in theforEach
. A character you callelement
. You abbreviate an array toarr
in one function and call itnewArray
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 variableresult
that you do nothing with. Not to mention thatforEach
does not have a return defined. Alsoresult
ingroupCharacters
is never used. - Don't declare variables outside the scope that they are to be used.
newSignature
is only used insidereduce
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.
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. IngroupCharacters
arr
should be a constant. - Consistent naming is important. Your naming is all over the place. You call a string, characters (in
compressCharacters
), string (incompressString
),signature
, ande
in theforEach
. A character you callelement
. You abbreviate an array toarr
in one function and call itnewArray
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 variableresult
that you do nothing with. Not to mention thatforEach
does not have a return defined. Alsoresult
ingroupCharacters
is never used. - Don't declare variables outside the scope that they are to be used.
newSignature
is only used insidereduce
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.
edited 4 hours ago
answered 8 hours ago
Blindman67
6,3241521
6,3241521
g.length > 2
is wrong: it fails to transformaa
toa2
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 factgroupRuns
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
add a comment |
g.length > 2
is wrong: it fails to transformaa
toa2
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 factgroupRuns
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
add a comment |
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
New contributor
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
add a comment |
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
New contributor
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
add a comment |
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
New contributor
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
New contributor
edited 14 hours ago
New contributor
answered 14 hours ago
DrDev
1033
1033
New contributor
New contributor
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
add a comment |
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
add a comment |
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password