Transcript from the "Impurity Solution: Wrappers" Lesson
>> Kyle Simpson: Okay, let's talk about the solution to part one of the impurity exercise. So we said we wanna take this getStudentsByName function, we're gonna modify it and move it. So I'm just gonna copy and then move it up here. And we're gonna end up wanting to wrap it around our sortStudentsByName, so I'll just kind of indent it here.
[00:00:26] And remember, the reason we want to wrap getStudentsByName around sortStudentsByName, sortStudentsByName is a function that has impurity in it. And for the purposes of this exercise, for whatever reason, we can't modify it. We can't change it. But we can contain the impurity so that it doesn't leak out to the rest of the scope.
[00:00:46] If we reduce the surface area of that impurity, then we improve the overall program readability and maintainability. So we do wanna pass in, you'll notice down here, we are passing in the outer list of students, the original list of students. We'll pass that list in. And we know that that is the thing that's gonna get modified.
[00:01:09] So if we wanna prevent it from being modified, we've gotta make our local copy of students be, our local reference be a copy of students, not an actual reference to the original outer one. So if we left it alone, this wouldn't do anything to prevent the side effects.
[00:01:26] So let's actually make a copy of the students array. And that can be done very simply with just the slice method. That makes us a shallow copy of an array. So now our students parameter is pointing at a local copy of that array, not the outer global array.
[00:01:45] That then allows us to simply call return sortStudentsByName.
>> Kyle Simpson: Which is going to end up producing a side effect but only on our local one, not on the global one. And we return the results, since it returns students, we return the result. And let's test to make sure that that works.
[00:02:09] I will paste this in and run it. And what we see is that the first five tests produce true, and the last five tests produce true. These are still false because that's what we're gonna handle in part two.