Skip to content

Instantly share code, notes, and snippets.

@muslemomar
Last active June 28, 2022 15:59
Show Gist options
  • Save muslemomar/e1f6224ff5b3f8e443c48c2f699b106b to your computer and use it in GitHub Desktop.
Save muslemomar/e1f6224ff5b3f8e443c48c2f699b106b to your computer and use it in GitHub Desktop.
Create a fixed length array
let arr = [];
arr.maxLength = 3;
Array.prototype.pushLimited = function(elem) {
if (this.length === this.maxLength) {
throw new Error('max length exceeded');
} else {
this.push(elem);
}
}
arr.pushLimited('A');
arr.pushLimited('B');
arr.pushLimited('C');
arr.pushLimited('D');
arr.pushLimited('E');
console.log(arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment