Skip to content
This repository was archived by the owner on Nov 7, 2020. It is now read-only.

Commit 0e9d517

Browse files
committed
Add solutions to string tests.
1 parent 098336f commit 0e9d517

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

app/strings.js

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
if (typeof define !== 'function') { var define = require('amdefine')(module); }
2+
3+
define(function() {
4+
return {
5+
reduceString: function(str, amount) {
6+
var outputString = '';
7+
var character;
8+
var inputStrArray = str.split('');
9+
10+
// we use this object to keep a count of the number of times
11+
// each character appears in the string
12+
var characterCount = {};
13+
14+
for (var i = 0, len = inputStrArray.length; i < len; i++) {
15+
character = inputStrArray[i];
16+
17+
// if the character isn't in our counting object yet,
18+
// then this is the first occurrence
19+
if (typeof characterCount[character] === 'undefined') {
20+
characterCount[character] = 1;
21+
}
22+
23+
// otherwise, we already have it, so we add one to our count
24+
else {
25+
characterCount[character] = characterCount[character] + 1;
26+
}
27+
28+
// anytime our count comes in below the amount specified, we
29+
// include that character in our output
30+
if (characterCount[character] <= amount) {
31+
outputString += character;
32+
}
33+
}
34+
35+
return outputString;
36+
},
37+
38+
wordWrap: function(str, cols) {
39+
var words = str.split(' ');
40+
var outputString = '';
41+
var word;
42+
var currentLength = 0;
43+
44+
for (var i = 0, len = words.length; i < len; i++) {
45+
word = words[i];
46+
currentLength += word.length;
47+
48+
// if its the first word, then we don't need a separator
49+
if (i === 0) {
50+
separator = '';
51+
}
52+
53+
// if we've gone past our `cols` length, then we start a new line
54+
else if (currentLength > cols) {
55+
currentLength = word.length;
56+
separator = '\n';
57+
}
58+
59+
// otherwise, we haven't gone over the line length and we separate
60+
// the words with a space
61+
else {
62+
separator = ' ';
63+
}
64+
65+
outputString += separator + word;
66+
}
67+
68+
return outputString;
69+
},
70+
71+
reverseString: function(str) {
72+
return str.split('').reverse().join('');
73+
}
74+
};
75+
});

0 commit comments

Comments
 (0)