Search⌘ K
AI Features

Solution Review

Understand how to review and refactor JavaScript functions to follow pure function principles, including cloning inputs and eliminating side effects. Discover techniques to maintain purity while using common methods like assoc, append, and sort, enhancing your functional programming skills with Ramda.

We'll cover the following...

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.

Javascript (babel-node)
const assoc = (key, value, object) => {
object[key] = value;
};

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

Javascript (babel-node)
const assoc = (key, value, object) => ({
...object,
[key]: value
});

getNames

Javascript (babel-node)
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.

Javascript (babel-node)
const getNames = (users) => {
return users.map((user) => user.name);
};

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

Javascript (babel-node)
const getNames = (users) => users.map((user) => user.name);

append

Javascript (babel-node)
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.

Javascript (babel-node)
const append = (item, list) => [...list, item];

sortAscending

Javascript (babel-node)
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.


Javascript (babel-node)
const sortAscending = (numbers) => [...numbers]
.sort((a, b) => a > b);