LiveScript icon indicating copy to clipboard operation
LiveScript copied to clipboard

Subscript operator `[]` as function

Open KSXGitHub opened this issue 7 years ago • 6 comments

LiveScript input

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

JavaScript output

object[key]
array[index]

KSXGitHub avatar Aug 10 '17 07:08 KSXGitHub

Doesn't (.) work?

vendethiel avatar Aug 10 '17 08:08 vendethiel

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

KSXGitHub avatar Aug 10 '17 08:08 KSXGitHub

How about (.(name)) obj?

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

compiles to

(function(it){
  return it.name;
})(obj);
(function(it){
  return it[name];
})(obj);

dk00 avatar Aug 10 '17 11:08 dk00

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

KSXGitHub avatar Aug 10 '17 12:08 KSXGitHub

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

tcrowe avatar Sep 27 '17 21:09 tcrowe

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

Array/object slice works the same way:

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

pepkin88 avatar Mar 20 '18 23:03 pepkin88