Advertisement
CLooker

Untitled

Apr 24th, 2018
641
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // imperative, state mutation, no separation of side effects
  2. (function latinize(phrase){
  3.     let phraseArray = phrase.split(' ');
  4.    
  5.     const reducer = phraseArray.reduce((accumulator, currentValue) => {
  6.         let firstLetter = currentValue.substring(0,1);
  7.         let rest = currentValue.substring(1);
  8.         let latin = 'ay ';
  9.  
  10.         accumulator += rest + firstLetter + latin;
  11.  
  12.         return accumulator
  13.     }, (''))
  14.        
  15.     console.log(reducer)
  16.    
  17.  
  18. })('quick brown fox')
  19.  
  20. // declarative, no state mutation, separation of side effects
  21. // both my examples do the same thing
  22.  
  23. const latinize = phrase => (
  24.   phrase.split(' ').reduce((newPhrase, word) => {
  25.     const [ first, ...rest ] = word;
  26.     return `${newPhrase} ${rest.join('')}${first}ay`
  27.   }, '').trim()
  28. )
  29.  
  30. console.log(latinize('quick brown fox'))
  31.  
  32. const latinize = phrase => (
  33.   phrase.split(' ').reduce((newPhrase, word, i) => {
  34.     const [ first, ...rest ] = word
  35.     return i === 0
  36.       ? `${rest.join('')}${first}ay`
  37.       : `${newPhrase} ${rest.join('')}${first}ay`
  38.   }, '')
  39. )
  40.  
  41. console.log(latinize('quick brown fox'))
  42.  
  43. // another version of your solution that incorporates some of what I did
  44. // that might be more understandable to you
  45.  
  46. (function latinize(phrase) {
  47.   const latin = "ay ";
  48.  
  49.   const newPhrase = phrase.split(" ").reduce((accumulator, currentValue) => {
  50.     const firstLetter = currentValue.substring(0, 1);
  51.     const rest = currentValue.substring(1);
  52.  
  53.     return accumulator + rest + firstLetter + latin;
  54.   }, "");
  55.  
  56.   console.log(newPhrase);
  57. })("quick brown fox");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement