Skip to content

Commit

Permalink
update docs
Browse files Browse the repository at this point in the history
  • Loading branch information
hojas committed Jul 1, 2024
1 parent 9c79c2a commit 96aa7e7
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/docs/blog/4.md
Original file line number Diff line number Diff line change
Expand Up @@ -489,3 +489,69 @@ function myReduce(arr, cb, initialValue) {
const arr = [1, 2, 3, 4, 5]
console.log(myReduce(arr, (a, b) => a + b)) // 15
```

## Array.prototype.reduceRight()

```js
function myReduceRight(arr, cb, initialValue) {
const len = arr.length
let i = initialValue === undefined ? len - 2 : len - 1
initialValue = initialValue === undefined ? arr[len - 1] : initialValue
let accumulator = initialValue

for (; i >= 0; i--) {
accumulator = cb.call(undefined, accumulator, arr[i], arr)
}
return accumulator
}

// test
const arr = [1, 2, 3, 4, 5]
console.log(myReduceRight(arr, (a, b) => a + b)) // 15
```

## Array.prototype.reverse()

```js
function myReverse(arr) {
const len = arr.length
const res = []

for (let i = len - 1; i >= 0; i--) {
res[res.length] = arr[i]
}

for (let i = 0; i < len; i++) {
arr[i] = res[i]
}

return arr
}

// test
const arr = [1, 2, 3, 4, 5]
myReverse(arr)
console.log(arr) // [5, 4, 3, 2, 1]
```

## Array.prototype.shift()

```js
function myShift(arr) {
const len = arr.length
const res = arr[0]

for (let i = 1; i < len; i++) {
arr[i - 1] = arr[i]
}

arr.length = len - 1

return res
}

// test
const arr = [1, 2, 3, 4, 5]
console.log(myShift(arr)) // 1
console.log(arr) // [2, 3, 4, 5]
```

0 comments on commit 96aa7e7

Please sign in to comment.