Implement the accumulate
operation, which, given a collection and an
operation to perform on each element of the collection, returns a new
collection containing the result of applying that operation to each element of
the input collection.
Given the collection of numbers:
And the operation:
x => x * x
)Your code should be able to produce the collection of squares:
Check out the test suite to see the expected function signature.
Keep your hands off that collect/map/fmap/whatchamacallit functionality provided by your standard library! Solve this one yourself using other basic tools instead.
Go through the setup instructions for TypeScript to install the necessary dependencies:
https://exercism.io/tracks/typescript/installation
Install assignment dependencies:
$ yarn install
Execute the tests with:
$ yarn test
In the test suites all tests but the first have been skipped.
Once you get a test passing, you can enable the next one by changing xit
to
it
.
Conversation with James Edward Gray II https://twitter.com/jeg2
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
import accumulate from './accumulate'
describe('accumulate()', () => {
it('accumulation empty', () => {
const accumulator = (e: number): number => e * e
expect(accumulate([], accumulator)).toEqual([])
})
it('accumulate squares', () => {
const accumulator = (n: number): number => n * n
const result = accumulate([1, 2, 3], accumulator)
expect(result).toEqual([1, 4, 9])
})
it('accumulate upcases', () => {
const accumulator = (word: string): string => word.toUpperCase()
const result = accumulate('hello world'.split(/\s/), accumulator)
expect(result).toEqual(['HELLO', 'WORLD'])
})
it('accumulate reversed strings', () => {
const accumulator = (word: string): string => word.split('').reverse().join('')
const result = accumulate('the quick brown fox etc'.split(/\s/), accumulator)
expect(result).toEqual(['eht', 'kciuq', 'nworb', 'xof', 'cte'])
})
it('accumulate recursively', () => {
const result = accumulate('a b c'.split(/\s/), (char: string) => accumulate('1 2 3'.split(/\s/), (digit: string) => char + digit))
expect(result).toEqual([['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3']])
})
})
function accumulate<T, U>(arr: Array<T>, f: (v: T) => U): Array<U> {
return arr.map((v: T, _: number) => f(v));
}
export default accumulate;
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Level up your programming skills with 3,108 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors. Exercism is 100% free forever.
Sign up Learn More