1
private def updateData(
  oldData: Seq[Data], 
  authorised: Boolean, 
  removeItemList: Seq[String]
): Seq[Data] = {
    if (!authorised) {
      oldData.map { data =>
        val props: Option[JsObject] = data.props.map { 
          props => props.as[JsObject] - removeItemList(0) - removeItemList(1) - removeItemList(2) 
        }
        data.copy(props = props)
      }
    } else {
      oldData
    }
  }

Can we improve this code? so it's work with removeItemList length > 3.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Laleet
  • 41
  • 4
  • 1
    There is a lot of irrelevant code here (e.g. `authorised` test), and some of the types are not defined. It would really help if you just showed the actual operation you are trying to perform as a simple function including the relevant types. – Tim Jul 29 '20 at 07:15
  • 1
    What JSON library are you using? – Yann Jul 29 '20 at 07:16
  • @Yann import play.api.libs.json.JsObject – Laleet Jul 29 '20 at 07:50

1 Answers1

3

The trick is to, for every item in removeItemList, remove it from the JsObject which resulted from the last removal.

This is the very definition of a fold:

removeItemList.foldLeft(props.as[JsObject]) { (jso, v) => jso - v }
  • we use props.as[JsObject] as the start value
  • for every item in removeItemList, we combine it with the current value with the combining function
  • the combining function removes the item from the current value
Levi Ramsey
  • 18,884
  • 1
  • 16
  • 30