DanielXMoore / Civet

A TypeScript superset that favors more types and less typing
https://civet.dev
MIT License
1.55k stars 33 forks source link

Object and advanced array comprehensions #439

Open edemaine opened 1 year ago

edemaine commented 1 year ago

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.

STRd6 commented 1 year ago

Spreads could also apply to object results as well.

edemaine commented 1 year ago

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.

gwhitney commented 1 year ago

+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.