Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. String.prototype.hashify = function () {
  2. const arr = this.toString().split('');
  3. let obj = {};
  4. let previousKey, currentKey;
  5.  
  6. for (let i=0; i<arr.length; i++) {
  7.  
  8. currentKey = arr[i];
  9.  
  10. if (!obj[currentKey]) {
  11. if (i < arr.length -1) {
  12. obj[currentKey] = [arr[i+1]];
  13. }
  14. } else {
  15. console.log('ELSE', i);
  16. obj[previousKey].push(arr[i+1]);
  17. }
  18. if (i === arr.length - 1) {
  19. console.log('LAST', currentKey);
  20. obj[currentKey] = [arr[0]];
  21. }
  22. previousKey = currentKey;
  23. console.log(obj);
  24. }
  25.  
  26. // console.log(obj);
  27. return obj;
  28.  
  29.  
  30. };
  31.  
  32. console.log('raracrceaec'.hashify());
  33.  
  34.  
  35. // Correct results is {"r":["a","r"],"a":["c","r"],"c":["e","a"],"e":"c"} - Expected: 'true', instead got: 'false'
  36.  
  37.  
  38. /**
  39. '123456'.hashify() == {"1":"2","2":"3","3":"4","4":"5","5":"6","6":"1"} // The last char will be key for 1st
  40. char
  41. '11223'.hashify() == {"1":["1","2"],"2":["2","3"],"3":"1"} // when duplicates exist, group them in an array
  42. // i.e. 1 is key for next char 1, that 1 is key for next char 2, but 1 is already in the hash, so add 2 to key 1
  43. 'Codewars'.hashify() == {"C":"o","o":"d","d":"e","e":"w","w":"a","a":"r","r":"s","s":"C"}
  44.  
  45. **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement