Solution Review

Review with explanations. (3 min. read)

assoc

We learned that a pure function must follow 2 rules

  1. Same inputs => same outputs
  2. No side-effects

assoc currently mutates the input object, which is a side-effect.

Press + to interact
const assoc = (key, value, object) => {
object[key] = value;
};

Cure it by cloning the input and merging the desired properties.

Press + to interact
const assoc = (key, value, object) => ({
...object,
[key]: value
});

getNames

Press + to interact
const getNames = (users) => {
console.log('getting names!');
return users.map((user) => user.name);
};

This was sort of a trick question. getNames is pure if you remove console.log.

Press + to interact
const getNames = (users) => {
return users.map((user) => user.name);
};

You can now refactor it to a single-line statement, if you prefer.

Press + to interact
const getNames = (users) => users.map((user) => user.name);

append

Press + to interact
const append = (item, list) => {
list.push(item);
return list;
};

This is impure because it mutates the input list. Like assoc, you can return a clone with the desired output.

Press + to interact
const append = (item, list) => [...list, item];

sortAscending

Press + to interact
const sortAscending = (numbers) => numbers
.sort((a, b) => a > b);

Once again we’re using an impure Array method, sort. Cloning the input purifies us right up.


Press + to interact
const sortAscending = (numbers) => [...numbers]
.sort((a, b) => a > b);