Problem with the ComplexNumber exercise in JavaScript

I just finished the complex number exercise in JavaScript. It passed and I published it. Then I looked at the first of the Community Solutions, and now I want to unpublish it because I now think that it’s wrong…I looked at 5 or 6 other solutions and they all did it my ‘wrong’ way. The exercise asks you to implement functions to perform a few basic arithmetic operations on members of a ComplexNumbers class. The exercises in the test file always perform the operation on a newly created ComplexNumber, and expect as an answer a newly created ComplexNumber, so we return this new number, suitably modified, without ever updating the real and imaginary parts of the original number, meaning that if our functions are called to update an already existent number, the update comes back as a new number and the existent number retains its old values. That first solution actually updates the real and imaginary values and returns ‘this’. In an actual implementation, one would probably provide separate routes for whether you want one behavior or the other. I wouldn’t want actual updates for things like absolute value, but I would want it for things like the four basic arithmetic functions.

What is it that you’re proposing that the maintainers change about the exercise?

Include an exercise that updates a pre-defined class member: my solution would fail that.

Since this isn’t in the Javascript forum, I’m CCing @SleeplessByte and @Cool-Katt. They can discuss this further as the track maintainers.

This exercise was adapted from an immutable track, so indeed: it is intended that each operation creates a new number instead of modifying what is there. In “real production code”, this is very common as well – especially if you are adopting “copy-on-write”.

I think we do have plenty exercise where modification / mutation is expected.

1 Like

Thanks for showing me where this can be useful.
But may I suggest that the Readme should point out this limitation?
For instance, outside of the class I created an object, myCN { 0:cn0, …}, and poor cn0 was then abandoned. The ‘update’, cn0 = cn0.add(cn3), where cn3 is another member of the class, would create a new copy that wouldn’t communicate with myCN

Maybe a test could be added to make sure the original number isn’t mutated. The tests drive your implementation, not the instructions, so it seems strange that the instructions would make a point of immutability when the tests don’t necessarily enforce immutability at the moment.

1 Like

Yes, there may be one in problem spec already, but if not, probably a good additional (with scenario immutability)

1 Like

I would also vote in favour of adding a test for immutability and then amending the instructions.

(Merry Christmas btw)

2 Likes