diff --git a/src/docs/blog/4.md b/src/docs/blog/4.md index ea141e8..5fe1d90 100644 --- a/src/docs/blog/4.md +++ b/src/docs/blog/4.md @@ -54,6 +54,95 @@ const arr2 = [4, 5, 6] console.log(myConcat(0, arr1, arr2)) // [0, 1, 2, 3, 4, 5, 6] ``` +## Array.prototype.copyWithin() + +```js +function copyWithin(arr, target, start, end) { + const len = arr.length + const copy = [] + const copyLen = end - start + + target = Math.floor(target) + start = Math.floor(start) + end = Math.floor(end) + + if (target >= len || start >= len || end < start) { + return arr + } + + if (target < -len) { + target = 0 + } + else if (target < 0) { + target = target + len + } + + if (start < -len) { + start = 0 + } + else if (start < 0) { + start = start + len + } + + if (end < -len) { + end = 0 + } + else if (end < 0) { + end = end + len + } + else if (end > len) { + end = len + } + + for (let i = start; i < end; i++) { + copy[copy.length] = arr[i] + } + + for (let i = 0; i < copyLen; i++) { + arr[target++] = copy[i] + if (target === len) { + break + } + } + + return arr +} + +const arr = ['a', 'b', 'c', 'd', 'e'] +console.log(copyWithin(arr, 3, 2, 5)) // ['a', 'b', 'c', 'c', 'd'] +``` + +## Array.prototype.entries() + +```js +function myEntries(arr) { + const len = arr.length + const entries = [] + + for (let i = 0; i < len; i++) { + entries.push(arr[i]) + } + + entries[Symbol.iterator] = () => { + let index = 0 + return { + next: () => + index < values.length + ? { value: [index, entries[index++]], done: false } + : { value: undefined, done: true }, + } + } + + return entries +} + +// test +const arr = [1, 2, 3] +for (const [k, v] of myEntries(arr)) { + console.log(k, v) // 0 1 \n 1 2 \n 2 3 +} +``` + ## Array.prototype.every() ```js