Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sethschori/e1d085c34be9588737e1fdaf247dacc0 to your computer and use it in GitHub Desktop.
Save sethschori/e1d085c34be9588737e1fdaf247dacc0 to your computer and use it in GitHub Desktop.
https://repl.it/C1T0/105 created by sethopia
/*
PUSH POP
Write your own versions of Push and Pop
Push takes two arguments, an array, and a value to add to that array. The function should return the array modified to include the new value.
push([8,2,3,4], 5)
// -> [8,2,3,4,5]
Pop is a function that manipulates an array. You can think of it like the opposite of push. It takes the last thing off the array and returns it
var arr = [1,2,3,4];
pop(arr)
// -> 4
While it returns the last thing in the array, it also removes it from the array. If you inspect `arr` after calling pop, it will be `[1,2,3]`.
*/
function push(arr, val) {
var newArr = arr.slice();
newArr[arr.length] = val;
return newArr;
}
/*
NOTE: The suggested way to write the function (see below) is to use splice method, which modifies the array it's called
on. So could use returnVal = arr.splice(arr.length - 1, 1). returnVal would be an array, so we'd need to return
returnVal[0].
Here's another set of suggested solutions:
function push(arr, val) {
arr[arr.length] = val;
return arr;
}
function pop(arr) {
var val = arr[arr.length-1];
arr.length--; // Here they're shortening the array with length property instead of using delete.
return val;
}
*/
function pop(arr) {
var returnVal = arr[arr.length - 1];
delete(arr[arr.length - 1]); // why does this delete the last array element in global scope
arr = []; // when this does not delete any elements in global scope?
return returnVal;
}
var testArr = [8,2,3,4];
var modArr = push(testArr,5);
console.log("push values below");
console.log(testArr);
console.log(modArr);
var testArr2 = [1,2,3,4];
var myReturnVal = pop(testArr2);
console.log("\npop values below");
console.log(myReturnVal);
console.log(testArr2);
Native Browser JavaScript
push values below
[ 8, 2, 3, 4 ]
[ 8, 2, 3, 4, 5 ]
pop values below
4
[ 1, 2, 3 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment