Alex
Alex

Reputation: 159

What's the correct way to merge the code into one loop?

This is my origin code, I would like to merge them into one loop

//1
if (eventUuidList.nonEmpty) {
  eventUuidTransactionTableCondition = for {
    eventUuid <- eventUuidList
    eventUuidTransactionTableConditionSet =
      s"${SQLColumnHelper.EVENT_INFO_STRUCT_NAME}.${SQLColumnHelper.EVENT_UUID} = '".concat(eventUuid).concat("'")
  } yield eventUuidTransactionTableConditionSet
  eventUuidTransactionTableConditionSet = "and ".concat(eventUuidTransactionTableCondition.reduce(_.concat(" or ").concat(_)))
}
//2
if (eventUuidList.nonEmpty) {
  eventUuidExceptionTableCondition = for {
    eventUuid <- eventUuidList
    eventUuidExceptionTableConditionSet =
      s"${SQLColumnHelper.EVENT_INFO_STRUCT_NAME}.${SQLColumnHelper.EVENT_UUID} != '".concat(eventUuid).concat("'")
  } yield eventUuidExceptionTableConditionSet
  eventUuidExceptionTableConditionSet = "and ".concat(eventUuidExceptionTableCondition.reduce(_.concat(" and ").concat(_)))
}

The different for these two parts are those lines (the first has = and the second !=):

//1
s"${SQLColumnHelper.EVENT_INFO_STRUCT_NAME}.${SQLColumnHelper.EVENT_UUID} = '".concat(eventUuid).concat("'")
eventUuidTransactionTableConditionSet = "and ".concat(eventUuidTransactionTableCondition.reduce(_.concat(" or ").concat(_)))
//2
s"${SQLColumnHelper.EVENT_INFO_STRUCT_NAME}.${SQLColumnHelper.EVENT_UUID} != '".concat(eventUuid).concat("'")
eventUuidExceptionTableConditionSet = "and ".concat(eventUuidExceptionTableCondition.reduce(_.concat(" and ").concat(_)))

I moved both parts into the same block. Is what I have below the correct way to do that? Or there is a better solution?

var eventUuidTransactionTableConditionSet, eventUuidExceptionTableConditionSet  = " "

if (eventUuidList.nonEmpty) {
  val both = eventUuidList.map( eventUuid =>
              s"${SQLColumnHelper.EVENT_INFO_STRUCT_NAME}.${SQLColumnHelper.EVENT_UUID} = '".concat(eventUuid).concat("'") ->
              s"${SQLColumnHelper.EVENT_INFO_STRUCT_NAME}.${SQLColumnHelper.EVENT_UUID} != '".concat(eventUuid).concat("'"))

  val (eventUuidTransactionTableCondition, eventUuidExceptionTableCondition) = both.unzip

  eventUuidExceptionTableConditionSet = "and ".concat(eventUuidTransactionTableCondition.mkString(" or "))
  eventUuidExceptionTableConditionSet = "and ".concat(eventUuidExceptionTableCondition.mkString(" and "))
}

Upvotes: 0

Views: 71

Answers (1)

jwvh
jwvh

Reputation: 51271

There are so many things wrong with this code it's hard to know where to begin. But to your question...

Why not create a tuple of the 2 string interpolations and then unzip them?

val both = eventUuidList.map(id => s"blahblah = '${id}'" ->
                                   s"blahblah != '${id}'")

val (eventUuidTransactionTableCondition
    ,eventUuidExceptionTableCondition) = both.unzip

Upvotes: 2

Related Questions