Skip to content
Advertisement

How can i limit array size in type script?

const arrPassword = []
const passarrayLength = 5


function addPassword(passwd) {
  if(arrPassword.length === passarrayLength)
  {
    arrPassword.shift()
  }

  arrPassword.push(passwd)
  console.log(arrPassword.length)
  console.log(arrPassword)
}

addPassword('Pass')
addPassword('Pass2')
addPassword('Pass3')
addPassword('Pass4')
addPassword('Pass5')
addPassword('Pass6')
addPassword('Pass7')
addPassword('Pass8')
addPassword('Pass9')
addPassword('Pass10')

I have a few cases where I want to store objects like user password history in an Array of objects to ensure he has not used the password in the last 5 times for example. My question is can I specify an array of objects with a size of 5 and then just push new passwords to array and any object in the array above size set would be discarded ? Or do I have to do this my self where I count the objects in my Array and if it is = max size I pop the oldest one before I push the new object to array ? Based on the research I did typescript or javascript does not have a fixed array size, I can specify a array of 3 5 objects but will need to assign all 5 and even so the push would make it 6 objects as there is no limit. So what would be the best approach to handle this ?

I included some basic concept i cam up with

Advertisement

Answer

When i need a functionality and there happens to be no such a functionality, the first thing that i think is “what am i missing?”.

In this particular case all you need to do is to take the last passarrayLength many items from your arrPassword array and reassign it to the arrPassword array like;

arrPassword = arrPassword.slice(-passarrayLength);

like

[1,2,3].slice(-5);             // <- [1,2,3]
[1,2,3,4,5,6,7,8,9].slice(-5); // <- [5,6,7,8,9]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement