These are chat archives for ramda/ramda

24th
Jan 2019
Andreas Herd
@mendrik
Jan 24 08:20
hey, given an array of objects and an array of primitive values, how can I update a specific property in each of the objects with an index-corresponding value from the other array?
Riku Tiira
@rikutiira
Jan 24 08:45
@mendrik R.zipWith((a, b) => R.mergeLeft(a, { propertyName: b }), a1, a2)
Andreas Herd
@mendrik
Jan 24 08:54
hmm that's cool, thanks
luckyalvinyc
@luckyalvinyc
Jan 24 12:01

hi guys, im pretty new to Ramda (FP in general)

my question is, how to find the next closest number in an array? so far this is what my solution looks like:

const greaterThan = t => x => x > t

const list = [7, 6, 5, 4, 3, 2, 1]

const closestTo = target => R.pipe(
  R.takeWhile(greaterThan(target)),
  R.last
)

const getClosestNumber = closestTo(4)

getClosestNumber(list) // => 5

assuming that the array is in descending order

Alex Deas
@alex-deas_gitlab
Jan 24 12:37
In FP when you want to process a data structure and return a value it’s called a fold (reduce in JS and Ramda). So this can be implemented by passing a function which will take a parameter of the current closest value and compare it to the next value in the list to see which one is closer. With plain JS it can be implemented something like:
const myVar = 5;
const list = [1, 2, 3, 4, 5, 6, 7, 8];

const comparison = (last, next) => {
  if (!last) {
    return next;
  } else {
    Math.abs(myVar - next) < Math.abs(myVar - last) ? next : last,
  }
};

list.reduce(comparison, 0)
This isn’t assuming anything about the order and will iterate over the whole array
It could be optimised by providing an escape hatch that will prevent the comparison if the value is equal to the one passed in
luckyalvinyc
@luckyalvinyc
Jan 24 12:41
@alex-deas_gitlab thank you for the insights!
luckyalvinyc
@luckyalvinyc
Jan 24 12:47
@alex-deas_gitlab but i think this will return 5 instead of 6
Alex Deas
@alex-deas_gitlab
Jan 24 12:51
It would, so you’d just need to change the comparison function to have the logic you need
luckyalvinyc
@luckyalvinyc
Jan 24 12:55
@alex-deas_gitlab doesn't have effect either
Alex Deas
@alex-deas_gitlab
Jan 24 13:01
@luckyalvinyc What is it that’s not working correctly ?
Ah sorry, just noticed that there should be a return in that else statement
The reduction works by passing the last returned value as the first parameter to the next iteration
luckyalvinyc
@luckyalvinyc
Jan 24 13:21

Ah sorry, just noticed that there should be a return in that else statement

still returning 5 instead of 6

Alex Deas
@alex-deas_gitlab
Jan 24 13:23
Yes because you’ll need to alter the implementation logic to fit your requirements
The implementation I provided should find the closest value, which will be the same as the input if one exists in the list
luckyalvinyc
@luckyalvinyc
Jan 24 13:25
@alex-deas_gitlab yes