diff --git a/docs/modules/Zipper.ts.md b/docs/modules/Zipper.ts.md index 91fafed..e9b12eb 100644 --- a/docs/modules/Zipper.ts.md +++ b/docs/modules/Zipper.ts.md @@ -47,6 +47,7 @@ Added in v0.1.6 - [length](#length) - [make](#make) - [map](#map) +- [mapWithIndex](#mapwithindex) - [modify](#modify) - [move](#move) - [of](#of) @@ -320,6 +321,16 @@ Added in v0.1.6 Added in v0.1.6 +# mapWithIndex + +**Signature** + +```ts +(f: (i: number, a: A) => B) => (fa: Zipper) => Zipper +``` + +Added in v0.1.17 + # modify Applies `f` to the focus and update with the result. @@ -425,7 +436,11 @@ Added in v0.1.6 **Signature** ```ts -export const zipper: Applicative1 & Foldable1 & Traversable1 & Comonad1 = ... +export const zipper: Applicative1 & + Foldable1 & + Traversable1 & + Comonad1 & + FunctorWithIndex1 = ... ``` Added in v0.1.6 diff --git a/src/Zipper.ts b/src/Zipper.ts index 1228313..d434186 100644 --- a/src/Zipper.ts +++ b/src/Zipper.ts @@ -25,6 +25,7 @@ import { Show } from 'fp-ts/lib/Show' import { pipe, pipeable } from 'fp-ts/lib/pipeable' import { Foldable1 } from 'fp-ts/lib/Foldable' import { Traversable1 } from 'fp-ts/lib/Traversable' +import { FunctorWithIndex1 } from 'fp-ts/lib/FunctorWithIndex' declare module 'fp-ts/lib/HKT' { interface URItoKind { @@ -268,7 +269,11 @@ export function getMonoid(M: Monoid): Monoid> { /** * @since 0.1.6 */ -export const zipper: Applicative1 & Foldable1 & Traversable1 & Comonad1 = { +export const zipper: Applicative1 & + Foldable1 & + Traversable1 & + Comonad1 & + FunctorWithIndex1 = { URI, map: (z, f) => make(z.lefts.map(f), f(z.focus), z.rights.map(f)), of, @@ -295,10 +300,18 @@ export const zipper: Applicative1 & Foldable1 & Traversable1 & Co return M.concat(M.concat(lefts, f(fa.focus)), rights) }, traverse, - sequence + sequence, + mapWithIndex: (fa, f) => { + const l = fa.lefts.length + return make( + fa.lefts.map((a, i) => f(i, a)), + f(l, fa.focus), + fa.rights.map((a, i) => f(l + 1 + i, a)) + ) + } } -const { ap, apFirst, apSecond, duplicate, extend, foldMap, map, reduce, reduceRight } = pipeable(zipper) +const { ap, apFirst, apSecond, duplicate, extend, foldMap, map, reduce, reduceRight, mapWithIndex } = pipeable(zipper) export { /** @@ -336,5 +349,9 @@ export { /** * @since 0.1.6 */ - reduceRight + reduceRight, + /** + * @since 0.1.17 + */ + mapWithIndex } diff --git a/test/Zipper.ts b/test/Zipper.ts index 8908abf..f86f0c6 100644 --- a/test/Zipper.ts +++ b/test/Zipper.ts @@ -215,4 +215,12 @@ describe('Zipper', () => { ) ) }) + + it('mapWithIndex', () => { + const fa = Z.make(['a', 'b'], 'c', ['d']) + assert.deepStrictEqual( + Z.zipper.mapWithIndex(fa, (i, a) => a + i), + Z.make(['a0', 'b1'], 'c2', ['d3']) + ) + }) })