Head Tail Init and Last
CodeWars Kata 7
by trentHarlem
HTML
<p>
| HEAD | <----------- TAIL --------- |<br/>
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br/>
| ----------- INIT ---------------- | LAST |<br/>
<br/>
head [x] = x<br/>
tail [x] = []<br/>
init [x] = []<br/>
last [x] = x<br/>
</p>
JavaScript
// Create 4 functions. Return the appropriate value(s) without mutating the original array
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(arr)
// by themselves the .shift() and .pop() methods will mutate the original array.
//const head = arr => arr.shift()
//const last = arr => arr.pop()
// .slice() and .filter() create a new array and thus leaves the original array unchanged.
//. function 1. return the 'Head' (index 0) of the array
const head = arr => arr.slice().shift()
// function 2. return the 'Tail' (index 1 - to end) of the array
const tail = arr => arr.filter((x,i) => i !== 0)
// function 3. return the 'Tail' (index 1 - to end) of the array
const init = arr => arr.filter((x,i) => i !== arr.length-1)
//. function 4. return the 'Last' index of the array
const last = arr => arr.slice().pop()
console.log('head', head(arr))
//console.log(arr)
console.log('tail', tail(arr))
//console.log(arr)
console.log('init', init(arr))
//console.log(arr)
console.log('last', last(arr))
console.log(arr)