gkz / LiveScript

LiveScript is a language which compiles to JavaScript. It has a straightforward mapping to JavaScript and allows you to write expressive code devoid of repetitive boilerplate. While LiveScript adds many features to assist in functional style programming, it also has many improvements for object oriented and imperative programming.
http://livescript.net
MIT License
2.31k stars 155 forks source link

Subscript operator `[]` as function #975

Open KSXGitHub opened 7 years ago

KSXGitHub commented 7 years ago

LiveScript input

([] key) object
([] index) array
([]) key object
([]) index array

JavaScript output

object[key]
array[index]
vendethiel commented 7 years ago

Doesn't (.) work?

KSXGitHub commented 7 years ago

@vendethiel I already know that there is a (.), but (. name) obj results obj.name in JavaScript, not obj[name] — which is what I wanted

dk00 commented 7 years ago

How about (.(name)) obj?

(.name) obj
(.(name)) obj

compiles to

(function(it){
  return it.name;
})(obj);
(function(it){
  return it[name];
})(obj);
KSXGitHub commented 7 years ago

@dk00 Thanks. I didn't know about this. I still think ([] name) is more intuitive though 😸

tcrowe commented 6 years ago

If you're trying to achieve a similar result to your example you can use this for now.

arr = [1 2 3]

console.log arr.1
# 2

index = 1
console.log (-> it[index]) arr
# 2

obj =
  title: 'I <3 Tomatoes'
  description: 'My garden secrets...'

key = 'title'
console.log (-> it[key]) obj
# I <3 Tomatoes

Magically it is there. 😸

pepkin88 commented 6 years ago

(.[name]) works too, if you prefer square brackets.

Array/object slice works the same way:

(.[1 2 3])
(.{id})