Skip to content

Commit

Permalink
feat(fill): support function value
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 26, 2018
1 parent 23b32b1 commit af268c8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/fill.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
function fill<T>(
arr: T[],
value?: (value?: T, index?: number) => any,
start?: number,
end?: number
): any[]

function fill(
arr: any[],
value?: any,
start?: number,
end?: number
): any[]

/**
* 使用 value 来填充(替换) arr,从 start 位置开始, 到 end 位置结束(但不包括 end 位置)。
*
Expand All @@ -7,13 +21,22 @@
* @param [end=arr.length] 结束位置
* @returns 填充改变后的数组
*/
export default function fill(arr: any[], value?: any, start: number = 0, end: number = arr.length): any[] {
function fill(
arr: any[],
value?: any,
start: number = 0,
end: number = arr.length
): any[] {
const valueIsFunction = typeof value === 'function'
const newArr = arr.slice()
const arrLength = newArr.length
start = Math.max(0, start < 0 ? arrLength + start : start)
end = Math.min(arrLength, end < 0 ? arrLength + end : end)
while (start < end) {
newArr[start++] = value
newArr[start] = valueIsFunction ? value(arr[start], start) : value
start++
}
return newArr
}

export default fill
3 changes: 3 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,9 @@ describe('fill', () => {
expect(vtils.fill(emptyArr, '*', 3, 2)).toEqual([undefined, undefined, undefined])
expect(vtils.fill(emptyArr, '*', -2, -3)).toEqual([undefined, undefined, undefined])
})
test('value 为函数', () => {
expect(vtils.fill(emptyArr, (value, i) => i + 1)).toEqual([1, 2, 3])
})
})

describe('has', () => {
Expand Down

0 comments on commit af268c8

Please sign in to comment.