Civet icon indicating copy to clipboard operation
Civet copied to clipboard

Object and advanced array comprehensions

Open edemaine opened this issue 2 years ago • 3 comments

Object comprehensions

(based on Python's dict comprehensions)

obj := {for item of list
   [item.key]: item
   [item.key.toLowerCase()]: item
}
---
const obj = (()=>{const results = {}
  for (const item of list) {
    Object.assign(results, {
      [item.key]: item,
      [item.key.toLowerCase()]: item,
    })
  }
})()

Array flattening via spreads

array := for item of list
  if Array.isArray item
    ...item
  else
    item.toString()
---
const array = (()=>{const results = []
  for (const item of list) {
    if (Array.isArray(item)) {
      results.push(...item)
    } else {
      results.push(item.toString())
    }
  }
})()

This could also be achieved via for.value.push(...item); continue given #362, but this seems like more natural notation.

edemaine avatar Mar 08 '23 16:03 edemaine

Spreads could also apply to object results as well.

STRd6 avatar Mar 08 '23 16:03 STRd6

Another application would be the ability to flatten the results of nested for loops. Ideally we could simplify the output to not construct an intermediate array, as follows:

array := for sublist of list
  ...for item of sublist
    item ** 2
---
const array = (function(){const results = []
  for (const sublist of list) {
    for (const item of sublist) {
      results.push(item ** 2)
    }
  }
})()

This gives us a very flexible equivalent of Janet's seq primitive.

edemaine avatar Apr 14 '23 16:04 edemaine

+1 on the object comprehensions: looks/feels totally natural, and with significant Python exposure prior to any Java/TypeScript, something I've been feeling the lack of basically since day 1.

gwhitney avatar Oct 04 '23 03:10 gwhitney