|
| 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 currentLength = 0; |
| 42 | + var word; |
| 43 | + var separator; |
| 44 | + |
| 45 | + for (var i = 0, len = words.length; i < len; i++) { |
| 46 | + word = words[i]; |
| 47 | + currentLength += word.length; |
| 48 | + |
| 49 | + // if its the first word, then we don't need a separator |
| 50 | + if (i === 0) { |
| 51 | + separator = ''; |
| 52 | + } |
| 53 | + |
| 54 | + // if we've gone past our `cols` length, then we start a new line |
| 55 | + else if (currentLength > cols) { |
| 56 | + currentLength = word.length; |
| 57 | + separator = '\n'; |
| 58 | + } |
| 59 | + |
| 60 | + // otherwise, we haven't gone over the line length and we separate |
| 61 | + // the words with a space |
| 62 | + else { |
| 63 | + separator = ' '; |
| 64 | + } |
| 65 | + |
| 66 | + outputString += separator + word; |
| 67 | + } |
| 68 | + |
| 69 | + return outputString; |
| 70 | + }, |
| 71 | + |
| 72 | + reverseString: function(str) { |
| 73 | + return str.split('').reverse().join(''); |
| 74 | + } |
| 75 | + }; |
| 76 | +}); |
0 commit comments