Skip to content

Commit

Permalink
question: fromTo
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelriosoliveira committed Feb 12, 2024
1 parent 432a2e4 commit 71bf639
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ I started this in the [issue #176](https://buttondown.email/cassidoo/archive/we-
- [334 - letters](src/2024/334-letters)
- [335 - flip](src/2024/335-flip)
- [337 - daysBetween](src/2024/337-daysBetween)
- [339 - fromTo](src/2024/339-fromTo)
</details>

## Installing & Running
Expand Down
26 changes: 26 additions & 0 deletions src/2024/339-fromTo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# fromTo

Interview question of the [issue #339 of rendezvous with cassidoo](https://buttondown.email/cassidoo/archive/youve-got-to-love-whats-yours-alicia-keys/).

## The Question

**Write a function that produces a generator that produces values in a range.**

Example:

```js
let range = fromTo(0,3)

> range()
0
> range()
1
> range()
2
> range()
null
```

## Installing & Running

Just `pnpm i` to install all dependencies and then `pnpm t` to run the tests!
35 changes: 35 additions & 0 deletions src/2024/339-fromTo/fromTo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { getDirection, fromTo } from './fromTo';

describe('#getDirection', () => {
it('should positive direction', () => {
expect(getDirection(0, 3)).toBe(1);
expect(getDirection(0, 0)).toBe(1);
});

it('should negative direction', () => {
expect(getDirection(3, 0)).toBe(-1);
});
});

describe('#fromTo', () => {
it('should generate values in the specified range', () => {
const range = fromTo(0, 3);
expect(range()).toBe(0);
expect(range()).toBe(1);
expect(range()).toBe(2);
expect(range()).toBeNull();
});

it('should generate values in single-step range', () => {
const range = fromTo(0, 0);
expect(range()).toBeNull();
});

it('should generate values in an inverse range', () => {
const range = fromTo(3, 0);
expect(range()).toBe(3);
expect(range()).toBe(2);
expect(range()).toBe(1);
expect(range()).toBeNull();
});
});
30 changes: 30 additions & 0 deletions src/2024/339-fromTo/fromTo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
Write a function that produces a generator that produces values in a range.
Example:
let range = fromTo(0,3)
> range()
0
> range()
1
> range()
2
> range()
null
*/

export function getDirection(from: number, to: number) {
return (-1) ** Number(from > to);
}

export function fromTo(from: number, to: number): () => number | null {
const direction = getDirection(from, to);
from -= direction;

return () => {
from += direction;
return from === to ? null : from;
};
}

0 comments on commit 71bf639

Please sign in to comment.