Class: Opal::Nodes::HashNode

Inherits:
Base show all
Defined in:
opal/lib/opal/nodes/hash.rb

Constant Summary

Constants included from Helpers

Opal::Nodes::Helpers::BASIC_IDENTIFIER_RULES, Opal::Nodes::Helpers::ES3_RESERVED_WORD_EXCLUSIVE, Opal::Nodes::Helpers::ES51_RESERVED_WORD, Opal::Nodes::Helpers::IMMUTABLE_PROPS

Instance Attribute Summary

Attributes inherited from Base

#compiler, #type

Instance Method Summary collapse

Methods inherited from Base

#add_gvar, #add_ivar, #add_local, #add_temp, children, #children, #compile_to_fragments, #error, #expr, #expr?, #expr_or_nil, #fragment, handle, handlers, #helper, #in_while?, #initialize, #process, #push, #recv, #recv?, #s, #scope, #stmt, #stmt?, #unshift, #while_loop, #with_temp, #wrap

Methods included from Helpers

#current_indent, #empty_line, #indent, #js_falsy, #js_truthy, #js_truthy_optimize, #line, #lvar_to_js, #mid_to_jsid, #property, #valid_name?, #variable

Constructor Details

This class inherits a constructor from Opal::Nodes::Base

Instance Method Details

#compileObject



26
27
28
29
30
31
32
33
34
# File 'opal/lib/opal/nodes/hash.rb', line 26

def compile
  keys, values = keys_and_values

  if simple_keys? keys
    compile_hash2 keys, values
  else
    compile_hash
  end
end

#compile_hashObject



36
37
38
39
40
41
42
43
44
45
# File 'opal/lib/opal/nodes/hash.rb', line 36

def compile_hash
  helper :hash

  children.each_with_index do |child, idx|
    push ', ' unless idx == 0
    push expr(child)
  end

  wrap '$hash(', ')'
end

#compile_hash2(keys, values) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'opal/lib/opal/nodes/hash.rb', line 47

def compile_hash2(keys, values)
  hash_obj, hash_keys = {}, []
  helper :hash2

  keys.size.times do |idx|
    key = keys[idx][1].to_s.inspect
    hash_keys << key unless hash_obj.include? key
    hash_obj[key] = expr(values[idx])
  end

  hash_keys.each_with_index do |key, idx|
    push ', ' unless idx == 0
    push "#{key}: "
    push hash_obj[key]
  end

  wrap "$hash2([#{hash_keys.join ', '}], {", "})"
end

#keys_and_valuesObject



8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'opal/lib/opal/nodes/hash.rb', line 8

def keys_and_values
  keys, values = [], []

  children.each_with_index do |obj, idx|
    if idx.even?
      keys << obj
    else
      values << obj
    end
  end

  [keys, values]
end

#simple_keys?(keys) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'opal/lib/opal/nodes/hash.rb', line 22

def simple_keys?(keys)
  keys.all? { |key| [:sym, :str].include? key.type }
end