keepLast

keepLast

  • (num: number) => (sequence: Sequence) => Sequence
  1. Keep the last num elements of a sequence

    const keepLastThree = keepLast(3)
    
    keepLastThree(['a', 'b', 'c', 'd']) // is ['b', 'c', 'd']
    keepLastThree('abcd') // is 'bcd'
    keepLastThree(['a']) // is ['a']
    const keepLastThree = keepLast(3)
    
    keepLastThree(['a', 'b', 'c', 'd']) // is ['b', 'c', 'd']
    keepLastThree('abcd') // is 'bcd'
    keepLastThree(['a']) // is ['a']
    
    const keepLastThree = keepLast(3)
    
    keepLastThree(['a', 'b', 'c', 'd']) // is ['b', 'c', 'd']
    keepLastThree('abcd') // is 'bcd'
    keepLastThree(['a']) // is ['a']
    const keepLastThree = keepLast(3)
    
    keepLastThree(['a', 'b', 'c', 'd']) // is ['b', 'c', 'd']
    keepLastThree('abcd') // is 'bcd'
    keepLastThree(['a']) // is ['a']
    
  2. Sometimes we have ordered data and only care about the last elements. Below, we have a list of soccer teams ordered by league placement. The last three teams have to move to the lower league. Let's list them.

    const teamsByPlacement = [
      'Manchester United',
      'Tottenham Hotspur',
      'West Ham United',
      'Ipswich Town',
      'Leicester City',
      'Southampton',
    ]
    
    const getRelegatedTeams = keepLast(3)
    const relegatedTeams = getRelegatedTeams(teamsByPlacement)
    console.log(relegatedTeams)
    // is [
    //   Ipswich Town
    //   Leicester City
    //   Southampton
    // ]
    const teamsByPlacement = [
      'Manchester United',
      'Tottenham Hotspur',
      'West Ham United',
      'Ipswich Town',
      'Leicester City',
      'Southampton',
    ]
    
    const getRelegatedTeams = keepLast(3)
    const relegatedTeams = getRelegatedTeams(teamsByPlacement)
    console.log(relegatedTeams)
    // is [
    //   Ipswich Town
    //   Leicester City
    //   Southampton
    // ]
    
    const teamsByPlacement = [
      'Manchester United',
      'Tottenham Hotspur',
      'West Ham United',
      'Ipswich Town',
      'Leicester City',
      'Southampton',
    ]
    
    const getRelegatedTeams = keepLast(3)
    const relegatedTeams = getRelegatedTeams(
      teamsByPlacement
    )
    console.log(relegatedTeams)
    // is [
    //   Ipswich Town
    //   Leicester City
    //   Southampton
    // ]
    const teamsByPlacement = [
      'Manchester United',
      'Tottenham Hotspur',
      'West Ham United',
      'Ipswich Town',
      'Leicester City',
      'Southampton',
    ]
    
    const getRelegatedTeams = keepLast(3)
    const relegatedTeams = getRelegatedTeams(
      teamsByPlacement
    )
    console.log(relegatedTeams)
    // is [
    //   Ipswich Town
    //   Leicester City
    //   Southampton
    // ]