Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

07-string-reverse-solition.js #18

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion javascript/solutions/07-string-reverse-solition.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
// .reverse() is an Array built in method, String does not have it.
// to use it, we have to turn our string in an array, reverse and then join it again.

const revertString = (str) => str.split("").reverse().join("");
const revertString = (str) => str.split("").reverse().join("");

// Alternative less elegant solution: Take the input string, iterate backwards through the string & build the reversed string with concat.

const reverseString = str => {

let reversed = "";
let i = str.length - 1; // Remove from the for loop for efficiency.

for (i; i > -1; i--) {
reversed += str[i]; // concat chars to the reversed string. str[i] starts at the last character, so the output is a reversed string.
}
};