JavaScript algorithms with solutions part 1

September 10, 2018 javascript JavaScript

1.Repeat a string

Example


    function repeatString(str,num){
      ...
      }
    console.log(repeatString('hi there',4)); // hi therehi therehi therehi there

My Solution:

    
    function repeatString(str,num){
      return num<=0 ?"":str+repeatString(str,num-1)
      }
    
  

Other solution:

    
    function repeatString(str,num){
      if (num<=0) {
        return ''
      }
      return str.repeat(num)
      }
    
  

2.Truncate a string

Example

    
    function truncateString(str,num){
      ...
      }
    console.log(truncateString('moetez',1)) // m...
    console.log(truncateString('moetez',9)) // moetez
  
        

My Solution:

    
    function truncateString(str, num) {
      if (str.length > num && num > 3) {
        return `${str.slice(0, num - 3)}...`
      } else if (str.length > num && num <= 3) {
        return `${str.slice(0, num)}...`
      }
      return str
    }    
      
        

Other solution:

    
    function truncateString(str, num) {
      if (str.length > num) {
        return `${str.slice(0, num>3?num-3:num)}...`
      }
      return str
    }
      
        

3.Return the length of the longest word in a string

Example

    
    function longestWordLength(str) {
      ...
    }
    console.log(longestWordLength('moetez is learning')) // 8
  

My Solution:

        
    function longestWordLength(str) {
      const words = str.split(' ')
      let maxLength = 0
      for (const word of words) {
        if (word.length > maxLength) {
          maxLength = word.length
        }
      }
      return maxLength
    }
          
        

Other solution:

        
    function longestWordLength(str) {
      return str.split(' ').reduce((x,y)=>{
        return Math.max(x,y.length)
      },0)
    }
          
        

4.Reverse a string

Example

    
    function reverseString(str) {
    ...
    }
    console.log(reverseString('moetez is learning')) // gninrael si zeteom
      
        

My Solution:

        
    function reverseString(str) {
      return str.split('').reverse().join('')
    }
            

Other solution:

        
    function reverseString(str) {
      let newString=''
      for (let index = str.length-1; index >=0; index--) {
        newString+=str[index]
      }
      return newString
    }
          

5.Factorialize a Number

Example

        
    function factorialize(num) {
      ...
    }
    console.log(factorialize(4)) // 24
        

My Solution:

        
    function factorialize(num) {
      if (num < 0) return -1
      return num===0?1:num*factorialize(num-1)
    }
        
        

Other solution:

        
    function factorialize(num) {
      let result=1
      for (let index = num; index >0; index--) {
        result*=index
      }
      return result
    }
     

6.Palindromes

Example

        
    function palindrome(str) {
    }
    console.log(palindrome("eye")) // true
       

My Solution:

        
    function palindrome(str) {
      const newStr = str.split('').reverse().join('')
      if (str.toLowerCase()==newStr.toLowerCase()) {
        return true
      }else{
        return false
      }
    }
        

7.Title Case

Example

        
    function titleCase(str) {
      ...
    }
      
    console.log(titleCase("I am the last one")) // I Am The Last One
        

My Solution:

        
    function titleCase(str) {
      const newStr=str.split(' ').map((word)=>{
      return word.replace(word[0],word[0].toUpperCase())
      })
      return newStr.join(' ')
      }
          

Other solutions:

        
    function titleCase(str) {
      return str.toLowerCase().replace(/(^|\s)\S/g,(letter)=>letter.toUpperCase())
    }
        
        
    function titleCase(str) {
      str=str.split(' ')
      for (let index = 0; index < str.length; index++) {
        str[index]=str[index].toLowerCase().split('')
        str[index][0]=str[index][0].toUpperCase()
        str[index]=str[index].join('')
        
      }
      return str.join(' ')
    }
         

8.Return the largest numbers in arrays

Example

        
    const NumbersArray=[
    [742,12,340],
    [678,500,1002],
    [15,80,63,666]
    ]
    function largestNumber(array) {
      ...
    }
    console.log(largestNumber(NumbersArray)) // [ 742, 1002, 666 ] 
     

My Solution:

        
    function largestNumber(array) {
    const largest=array.map(array=>{
      return array.reduce(( acc, cur ) => Math.max( acc, cur))
    })
    return largest
    }
    

Other solutions:

        
    function largestNumber(array) {
      let results=[]
      for (let index = 0; index < array.length; index++) {
        let maxNumber = array[index][0]
        for (let index2 = 0; index2 < array[index].length; index2++) {
          if (array[index][index2]>maxNumber) {
            maxNumber=array[index][index2]
          }
        }
        results[index]=maxNumber
      }
      return results
      }
           
        
    function largestNumber(array) {
      const largest=array.map(array=>{
        return array.reduce(( acc, cur ) => (cur>acc)?cur:acc)
      })
      return largest
      }
           
        
    function largestNumber(array) {
      return array.map(Function.apply.bind(Math.max,null))
    }
             

9.Confirm the ending

Example

        
    function confirmEnding(str,ending) {
      ...
    }    
    console.log(confirmEnding('moetez','z')) //true
       

My Solution:

        
    function confirmEnding(str,ending) {
      return str.slice(str.length-ending.length)==ending
    }
        

Other solutions:

        
    function confirmEnding(str,ending) {
      return str.substr(-ending.length)==ending
    }
         

10.Chunky Monkey

Example

        
    function chunky(array,size) {
      ...
    }
    console.log(chunky(['a','b','c','d'],2)) // [ [ 'a', 'b' ], [ 'c', 'd' ] ]
       

My Solution:

        
    function chunky(array, size) {
      let total = 0
      let newArray = []
      while (total < array.length) {
        newArray.push(array.slice(total, total + size))
        total += size
      }
      return newArray
    }
        

Other solutions:

        
    function chunky(array,size) {
      let temp=[]
      let result=[]
      for (let index = 0; index < array.length; index++) {
        if (index%size!==size-1) {
          temp.push(array[index])
        }else{
          temp.push(array[index])
          result.push(temp)
          temp=[]
        }
        
      }
      return result
        
      }
          
        
    function chunky(array,size) {
      let result=[]
      for (let index = 0; index < array.length; index+=size) {
        result.push(array.slice(index,index+size))
      }
      return result
    }
    
        
    function chunky(array, size) {
      let newArray = []
      while (array.length) {
        newArray.push(array.splice(0,size))
      }
      return newArray
    }
    
algorithmsjavascript