We know very well how these functions work in Javascript. So, here I am going to write immutable implementations for the same functions as per my understanding. Please do comment your suggestions/concerns/questions. I will always happy to update this article.
function pop(arr) {
let newArr = [...arr];
newArr.length = arr.length - 1;
return newArr;
}
function push(arr, ...item) {
const newArr = [...arr];
if (item.length >= 1) {
for (let i = 0; i < item.length; i++) {
newArr[newArr.length] = item[i];
}
}
return newArr;
}
function shift(arr) {
[a, ...b] = arr;
return b;
}
function unshift(arr, ...item) {
const newArr = [];
if (item.length >= 1) {
for (let i = 0; i < item.length; i++) {
newArr[i] = item[i];
}
}
newArr.push(...arr);
return newArr;
}
Thank you! Happy Reading!
💎 Love to see your response
- Like - You reached here means. I think, I deserve a like.
- Comment - We can learn together.
- Share - Makes others also find this resource useful.
- Subscribe / Follow - to stay up to date with my daily articles.
- Encourage me - You can buy me a Coffee
Let's discuss further.
- Just DM @urstrulyvishwak
-
Or mention
@urstrulyvishwak
Discussion (0)