Ramda — R.adjust

Kyle Tilman
2 min readJul 3, 2017

--

R.adjust is a simple function. It leads a simple life. It wakes up, slightly moves everything in it’s room all day, and then goes to sleep knowing it has accomplished a successful day.

Imagine a list of people:

const yearPeople = [["John", 18], ["Cindy", 82], ["Barb", 54]];

Each “Person” is a tuple of name and age in years.

What if we needed to adjust all the years to months? We could map through them (not even going to pretend there is a for/while loop solution).

const yearPeople2MonthPeople = ([n,y]) => [n, y*12];
const monthPeople = yearPeople.map(yearPeople2MonthPeople);

This works and is a fine solution but I see a couple unnecessary complexities.

  1. We only care about one value but we have to play with all of them.
  2. To test yearPeople2MonthPeople we would need to create a fake person.

This is where R.adjust shines!

Given a function, and index and a list, R.adjust will apply the function to the item at the given index in the list and return a new list.

const yearPeople = [["John", 18], ["Cindy", 82], ["Barb", 54]];
const years2months = y => y*12;
const monthPeople = yearPeople.map(R.adjust(years2months, 1));

We can simplify this more with a Ramda function I haven’t written about but is extremely simple, R.multiply. It does what you think.

const yearPeople = [["John", 18], ["Cindy", 82], ["Barb", 54]];
const years2months = R.multiply(12);
const monthPeople = yearPeople.map(R.adjust(years2months, 1));

This function feels like it’s most useful when dealing with tuple type data. The group that built ramda-adjunct found a good use for R.adjust .

It’s a function that renames keys in an object. First it breaks the object into key, value tuples (or pairs) than adjusts the first item using the supplied function and then smashes the pairs back together in an object.

— Edit —

I actually used R.adjust in a project today. I created the equivalent of _.mapValues.

const mapValues = (fn, obj) => R.pipe(
R.clone,
R.toPairs,
R.adjust(fn, 1),
R.fromPairs
);
mapValues(R.add(2), {a:1,b:2}) // {a:3, b:4}

— /Edit —

You could use R.adjust on strings as well. Those are like collections of characters.

const capitalize = R.pipe(R.adjust(c => c.toUpperCase(), 0), R.join(''));capitalize('omg') // 'Omg'

Thats the story for the simple R.adjust.

--

--