-
Notifications
You must be signed in to change notification settings - Fork 171
/
hash.go
1313 lines (1124 loc) · 35.4 KB
/
hash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package vm
import (
"bytes"
"fmt"
"reflect"
"sort"
"strings"
"github.com/goby-lang/goby/vm/classes"
"github.com/goby-lang/goby/vm/errors"
)
// HashObject represents hash instances
// Hash is a collection of key-value pair, which works like a dictionary.
// Hash literal is represented with curly brackets `{ }` like `{ key: value }`.
// Each key of the hash is unique and cannot be duplicate within the hash.
// Adding a leading space and a trailing space within curly brackets are preferable.
//
// - **Key:** an alphanumeric word that starts with alphabet, without containing space and punctuations.
// Underscore `_` can also be used within the key.
// String literal like "mickey mouse" cannot be used as a hash key.
// The internal key is actually a String and **not a Symbol** for now (TBD).
// Thus only a String object or a string literal should be used when referencing with `[ ]`.
//
// ```ruby
// a = { balthazar1: 100 } # valid
// b = { 2melchior: 200 } # invalid
// x = 'balthazar1'
//
// a["balthazar1"] # => 100
// a[x] # => 100
// a[balthazar1] # => error
// ```
//
// - **value:** String literal and objects (Integer, String, Array, Hash, nil, etc) can be used.
//
// **Note:**
// - The order of key-value pairs are **not** preserved.
// - Operator `=>` is not supported.
// - `Hash.new` is not supported.
type HashObject struct {
*baseObj
Pairs map[string]Object
// See `[]` and `[]=` for the operational explanation of the default value.
Default Object
}
// Class methods --------------------------------------------------------
func builtinHashClassMethods() []*BuiltinMethodObject {
return []*BuiltinMethodObject{
{
Name: "new",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
return t.vm.initUnsupportedMethodError(sourceLine, "#new", receiver)
},
},
}
}
// Instance methods -----------------------------------------------------
func builtinHashInstanceMethods() []*BuiltinMethodObject {
return []*BuiltinMethodObject{
{
// Retrieves the value (object) that corresponds to the key specified.
// When a key doesn't exist, `nil` is returned, or the default, if set.
//
// ```Ruby
// h = { a: 1, b: "2", c: [1, 2, 3], d: { k: 'v' } }
// h['a'] #=> 1
// h['b'] #=> "2"
// h['c'] #=> [1, 2, 3]
// h['d'] #=> { k: 'v' }
//
// h = { a: 1 }
// h['c'] #=> nil
// h.default = 0
// h['c'] #=> 0
// h #=> { a: 1 }
// h['d'] += 2
// h #=> { a: 1, d: 2 }
// ```
//
// @return [Object]
Name: "[]",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 1 argument. got: %d", len(args))
}
i := args[0]
key, ok := i.(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, i.Class().Name)
}
h := receiver.(*HashObject)
value, ok := h.Pairs[key.value]
if !ok {
if h.Default != nil {
return h.Default
}
return NULL
}
return value
},
},
{
// Associates the value given by `value` with the key given by `key`.
// Returns the `value`.
//
// ```Ruby
// h = { a: 1, b: "2", c: [1, 2, 3], d: { k: 'v' } }
// h['a'] = 1 #=> 1
// h['b'] = "2" #=> "2"
// h['c'] = [1, 2, 3] #=> [1, 2, 3]
// h['d'] = { k: 'v' } #=> { k: 'v' }
// ```
//
// @return [Object] The value
Name: "[]=",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
// First arg is index
// Second arg is assigned value
if len(args) != 2 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 2 arguments. got: %d", len(args))
}
k := args[0]
key, ok := k.(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, k.Class().Name)
}
h := receiver.(*HashObject)
h.Pairs[key.value] = args[1]
return args[1]
},
},
{
// Passes each (key, value) pair of the collection to the given block. The method returns
// true if the block ever returns a value other than false or nil.
//
// ```ruby
// a = { a: 1, b: 2 }
//
// a.any? do |k, v|
// v == 2
// end # => true
// a.any? do |k, v|
// v
// end # => true
// a.any? do |k, v|
// v == 5
// end # => false
// a.any? do |k, v|
// nil
// end # => false
//
// a = {}
//
// a.any? do |k, v|
// true
// end # => false
// ```
Name: "any?",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
if blockFrame == nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, errors.CantYieldWithoutBlockFormat)
}
hash := receiver.(*HashObject)
if blockIsEmpty(blockFrame) {
return FALSE
}
if len(hash.Pairs) == 0 {
t.callFrameStack.pop()
}
for stringKey, value := range hash.Pairs {
objectKey := t.vm.InitStringObject(stringKey)
result := t.builtinMethodYield(blockFrame, objectKey, value)
/*
TODO: Discuss this behavior
```ruby
{ key: "foo", bar: "baz" }.any? do |k, v|
true
break
end
```
The block returns nil because of the break.
But in Ruby the final result is nil, which means the block's result is completely ignored
*/
if blockFrame.IsRemoved() {
return NULL
}
if result.Target.isTruthy() {
return TRUE
}
}
return FALSE
},
},
{
// Returns empty hash (no key-value pairs)
//
// ```Ruby
// { a: "Hello", b: "World" }.clear # => {}
// {}.clear # => {}
// ```
//
// @return [Boolean]
Name: "clear",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
h.Pairs = make(map[string]Object)
return h
},
},
{
// Return the default value of this Hash.
//
// ```Ruby
// h = { a: 1 }
// h.default #=> nil
// h.default = 2
// h.default #=> 2
// ```
//
// @return [Object]
Name: "default",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expected 0 argument, got: %d", len(args))
}
hash := receiver.(*HashObject)
if hash.Default == nil {
return NULL
}
return hash.Default
},
},
{
// Set the default value of this Hash.
// Arrays/Hashes are not accepted, since they're unsafe.
//
// ```Ruby
// h = { a: 1 }
// h['c'] #=> nil
// h.default = 2
// h['c'] #=> 2
// h.default = [] #=> ArgumentError
// ```
//
// @return [Object]
Name: "default=",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expected 1 argument, got %d", len(args))
}
// Arrays and Hashes are generally a mistake, since a single instance would be used for all the accesses
// via default.
switch args[0].(type) {
case *HashObject, *ArrayObject:
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Arrays and Hashes are not accepted as default values")
}
hash := receiver.(*HashObject)
hashDefault := args[0]
hash.Default = hashDefault
return hashDefault
},
},
{
// Remove the key from the hash if key exist
//
// ```Ruby
// h = { a: 1, b: 2, c: 3 }
// h.delete("b") # => { a: 1, c: 3 }
// ```
//
// @return [Hash]
Name: "delete",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 1 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
d := args[0]
deleteKey, ok := d.(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, d.Class().Name)
}
deleteKeyValue := deleteKey.value
if _, ok := h.Pairs[deleteKeyValue]; ok {
delete(h.Pairs, deleteKeyValue)
}
return h
},
},
{
// Deletes every key-value pair from the hash for which block evaluates to anything except
// false and nil.
//
// Returns the hash.
//
// ```Ruby
// { a: 1, b: 2}.delete_if do |k, v| v == 1 end # => { b: 2 }
// { a: 1, b: 2}.delete_if do |k, v| 5 end # => { }
// { a: 1, b: 2}.delete_if do |k, v| false end # => { a: 1, b: 2}
// { a: 1, b: 2}.delete_if do |k, v| nil end # => { a: 1, b: 2}
// ```
//
// @return [Hash]
Name: "delete_if",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
if blockFrame == nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, errors.CantYieldWithoutBlockFormat)
}
hash := receiver.(*HashObject)
if blockIsEmpty(blockFrame) {
return hash
}
if len(hash.Pairs) == 0 {
t.callFrameStack.pop()
}
// Note that from the Go specification, https://golang.org/ref/spec#For_statements,
// it's safe to delete elements from a Map, while iterating it.
for stringKey, value := range hash.Pairs {
objectKey := t.vm.InitStringObject(stringKey)
result := t.builtinMethodYield(blockFrame, objectKey, value)
booleanResult, isResultBoolean := result.Target.(*BooleanObject)
if isResultBoolean {
if booleanResult.value {
delete(hash.Pairs, stringKey)
}
} else if result.Target != NULL {
delete(hash.Pairs, stringKey)
}
}
return hash
},
},
{
// Extracts the nested value specified by the sequence of idx objects by calling `dig` at
// each step, returning nil if any intermediate step is nil.
//
// ```Ruby
// { a: 1 , b: 2 }.dig(:a) # => 1
// { a: {}, b: 2 }.dig(:a, :b) # => nil
// { a: {}, b: 2 }.dig(:a, :b, :c) # => nil
// { a: 1, b: 2 }.dig(:a, :b) # => TypeError: Expect target to be Diggable
// ```
//
// @return [Object]
Name: "dig",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) == 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expected 1+ arguments, got 0")
}
hash := receiver.(*HashObject)
value := hash.dig(t, args, sourceLine)
return value
},
},
{
// Calls block once for each key in the hash (in sorted key order), passing the
// key-value pair as parameters.
// Returns `self`.
//
// ```Ruby
// h = { b: "2", a: 1 }
// h.each do |k, v|
// puts k.to_s + "->" + v.to_s
// end
// # => a->1
// # => b->2
// ```
//
// @return [Hash]
Name: "each",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 arguments. got: %d", len(args))
}
if blockFrame == nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, errors.CantYieldWithoutBlockFormat)
}
h := receiver.(*HashObject)
if len(h.Pairs) == 0 {
t.callFrameStack.pop()
} else {
keys := h.sortedKeys()
for _, k := range keys {
v := h.Pairs[k]
strK := t.vm.InitStringObject(k)
t.builtinMethodYield(blockFrame, strK, v)
}
}
return h
},
},
{
// Loop through keys of the hash with given block frame. It also returns array of
// keys in alphabetical order.
//
// ```Ruby
// h = { a: 1, b: "2", c: [1, 2, 3], d: { k: 'v' } }
// h.each_key do |k|
// puts k
// end
// # => a
// # => b
// # => c
// # => d
// ```
//
// @return [Array]
Name: "each_key",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
if blockFrame == nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, errors.CantYieldWithoutBlockFormat)
}
h := receiver.(*HashObject)
if len(h.Pairs) == 0 {
t.callFrameStack.pop()
}
keys := h.sortedKeys()
var arrOfKeys []Object
for _, k := range keys {
obj := t.vm.InitStringObject(k)
arrOfKeys = append(arrOfKeys, obj)
t.builtinMethodYield(blockFrame, obj)
}
return t.vm.InitArrayObject(arrOfKeys)
},
},
{
// Loop through values of the hash with given block frame. It also returns array of
// values of the hash in the alphabetical order of its key
//
// ```Ruby
// h = { a: 1, b: "2", c: [1, 2, 3], d: { k: "v" } }
// h.each_value do |v|
// puts v
// end
// # => 1
// # => "2"
// # => [1, 2, 3]
// # => { k: "v" }
// ```
//
Name: "each_value",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
if blockFrame == nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, errors.CantYieldWithoutBlockFormat)
}
h := receiver.(*HashObject)
if len(h.Pairs) == 0 {
t.callFrameStack.pop()
}
keys := h.sortedKeys()
var arrOfValues []Object
for _, k := range keys {
value := h.Pairs[k]
arrOfValues = append(arrOfValues, value)
t.builtinMethodYield(blockFrame, value)
}
return t.vm.InitArrayObject(arrOfValues)
},
},
{
// Returns true if hash has no key-value pairs
//
// ```Ruby
// {}.empty? # => true
// { a: 1 }.empty? # => false
// ```
//
// @return [Boolean]
Name: "empty?",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
if h.length() == 0 {
return TRUE
}
return FALSE
},
},
{
// Returns true if hash is exactly equal to another hash
//
// ```Ruby
// { a: "Hello", b: "World" }.eql?(1) # => false
// ```
//
// @return [Boolean]
Name: "eql?",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 1 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
c := args[0]
compare, ok := c.(*HashObject)
if ok && reflect.DeepEqual(h, compare) {
return TRUE
}
return FALSE
},
},
{
// Returns a value from the hash for the given key. If the key can’t be found, there are several
// options: With no other arguments, it will raise an ArgumentError exception; if default is
// given, then that will be returned; if the optional code block is specified, then that will be
// run and its result returned.
//
// ```Ruby
// h = { "spaghetti" => "eat" }
// h.fetch("spaghetti") #=> "eat"
// h.fetch("pizza") #=> ArgumentError
// h.fetch("pizza", "not eat") #=> "not eat"
// h.fetch("pizza") do |el| "eat " + el end #=> "eat pizza"
// ```
//
// @return [Object]
Name: "fetch",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if !(len(args) == 1 || len(args) == 2) {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expected 1 or 2 arguments, got %d", len(args))
} else if len(args) == 2 && blockFrame != nil {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "The default argument can't be passed along with a block")
}
hash := receiver.(*HashObject)
key, ok := args[0].(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, key.Class().Name)
}
value, ok := hash.Pairs[key.value]
if ok {
if blockFrame != nil {
t.callFrameStack.pop()
}
return value
}
if len(args) == 2 {
return args[1]
}
if blockFrame != nil {
return t.builtinMethodYield(blockFrame, key).Target
}
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "The value was not found, and no block has been provided")
},
},
{
// Returns an array containing the values associated with the given keys but also raises
// ArgumentError when one of keys can’t be found.
//
// ```Ruby
// h = { cat: "feline", dog: "canine", cow: "bovine" }
//
// h.fetch_values("cow", "cat") #=> ["bovine", "feline"]
// h.fetch_values("cow", "bird") # raises ArgumentError
// h.fetch_values("cow", "bird") do |k| k.upcase end #=> ["bovine", "BIRD"]
// ```
//
// @return [ArrayObject]
Name: "fetch_values",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) == 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expected 1+ arguments, got 0")
}
values := make([]Object, len(args))
hash := receiver.(*HashObject)
blockFramePopped := false
for index, objectKey := range args {
stringKey, ok := objectKey.(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, objectKey.Class().Name)
}
value, ok := hash.Pairs[stringKey.value]
if !ok {
if blockFrame != nil {
value = t.builtinMethodYield(blockFrame, objectKey).Target
blockFramePopped = true
} else {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "There is no value for the key `%s`, and no block has been provided", stringKey.value)
}
}
values[index] = value
}
if blockFrame != nil && !blockFramePopped {
t.callFrameStack.pop()
}
return t.vm.InitArrayObject(values)
},
},
{
// Returns true if the key exist in the hash. Currently, it can only input string
// type object.
//
// ```Ruby
// h = { a: 1, b: "2", c: [1, 2, 3], d: { k: "v" } }
// h.has_key?("a") # => true
// h.has_key?("e") # => false
// # TODO: Support Symbol Type Key Input
// h.has_key?(:b) # => true
// h.has_key?(:f) # => false
// ```
//
// @return [Boolean]
Name: "has_key?",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 1 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
i := args[0]
input, ok := i.(*StringObject)
if !ok {
return t.vm.InitErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, i.Class().Name)
}
if _, ok := h.Pairs[input.value]; ok {
return TRUE
}
return FALSE
},
},
{
// Returns true if the value exist in the hash.
//
// ```Ruby
// h = { a: 1, b: "2", c: [1, 2, 3], d: { k: "v" } }
// h.has_value?(1) # => true
// h.has_value?(2) # => false
// h.has_value?("2") # => true
// h.has_value?([1, 2, 3]) # => true
// h.has_value?({ k: "v" }) # => true
// ```
//
// @return [Boolean]
Name: "has_value?",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 1 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
for _, v := range h.Pairs {
if reflect.DeepEqual(v, args[0]) {
return TRUE
}
}
return FALSE
},
},
{
// Returns an array of keys (in arbitrary order)
//
// ```Ruby
// { a: 1, b: "2", c: [3, true, "Hello"] }.keys
// # => ["c", "b", "a"] or ["b", "a", "c"] ... etc
// ```
//
// @return [Boolean]
Name: "keys",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
var keys []Object
for k := range h.Pairs {
keys = append(keys, t.vm.InitStringObject(k))
}
return t.vm.InitArrayObject(keys)
},
},
{
// Returns the number of key-value pairs of the hash.
//
// ```Ruby
// h = { a: 1, b: "2", c: [1, 2, 3], d: { k: 'v' } }
// h.length #=> 4
// ```
//
// @return [Integer]
Name: "length",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
return t.vm.InitIntegerObject(h.length())
},
},
{
// Returns a new hash with the results of running the block once for every value.
// This method does not change the keys and the receiver hash values.
//
// ```Ruby
// h = { a: 1, b: 2, c: 3 }
// result = h.map_values do |v|
// v * 3
// end
// h # => { a: 1, b: 2, c: 3 }
// result # => { a: 3, b: 6, c: 9 }
// ```
//
// @return [Boolean]
Name: "map_values",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
if blockFrame == nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, errors.CantYieldWithoutBlockFormat)
}
h := receiver.(*HashObject)
if blockIsEmpty(blockFrame) {
return h
}
result := make(map[string]Object)
if len(h.Pairs) == 0 {
t.callFrameStack.pop()
}
for k, v := range h.Pairs {
result[k] = t.builtinMethodYield(blockFrame, v).Target
}
return t.vm.InitHashObject(result)
},
},
{
// Returns the number of key-value pairs of the hash.
//
// ```Ruby
// h = { a: 1, b: "2", c: [1, 2, 3] }
// h.merge({ b: "Hello", d: "World" })
// # => { a: 1, b: "Hello", c: [1, 2, 3], d: "World" }
// ```
//
// @return [Hash]
Name: "merge",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) < 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect at least 1 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
result := make(map[string]Object)
for k, v := range h.Pairs {
result[k] = v
}
for _, obj := range args {
hashObj, ok := obj.(*HashObject)
if !ok {
return t.vm.InitErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.HashClass, obj.Class().Name)
}
for k, v := range hashObj.Pairs {
result[k] = v
}
}
return t.vm.InitHashObject(result)
},
},
{
// Returns a new hash consisting of entries for which the block does not return false
// or nil.
//
// ```ruby
// a = { a: 1, b: 2 }
//
// a.select do |k, v|
// v == 2
// end # => { a: 1 }
// a.select do |k, v|
// 5
// end # => { a: 1, b: 2 }
// a.select do |k, v|
// nil
// end # => { }
// a.select do |k, v|
// false
// end # => { }
// ```
Name: "select",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
if blockFrame == nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, errors.CantYieldWithoutBlockFormat)
}
destinationPairs := map[string]Object{}
if blockIsEmpty(blockFrame) {
return t.vm.InitHashObject(destinationPairs)
}
sourceHash := receiver.(*HashObject)
if len(sourceHash.Pairs) == 0 {
t.callFrameStack.pop()
}
for stringKey, value := range sourceHash.Pairs {
objectKey := t.vm.InitStringObject(stringKey)
result := t.builtinMethodYield(blockFrame, objectKey, value)
if result.Target.isTruthy() {
destinationPairs[stringKey] = value
}
}
return t.vm.InitHashObject(destinationPairs)
},
},
{
// Returns an array of keys (in arbitrary order)
//
// ```Ruby
// { a: 1, b: "2", c: [3, true, "Hello"] }.sorted_keys
// # => ["a", "b", "c"]
// { c: 1, b: "2", a: [3, true, "Hello"] }.sorted_keys
// # => ["a", "b", "c"]
// { b: 1, c: "2", a: [3, true, "Hello"] }.sorted_keys
// # => ["a", "b", "c"]
// { b: 1, c: "2", b: [3, true, "Hello"] }.sorted_keys
// # => ["b", "c"]
// ```
//
// @return [Boolean]
Name: "sorted_keys",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
h := receiver.(*HashObject)
sortedKeys := h.sortedKeys()
var keys []Object
for _, k := range sortedKeys {
keys = append(keys, t.vm.InitStringObject(k))
}
return t.vm.InitArrayObject(keys)
},
},
{
// Returns two-dimensional array with the key-value pairs of hash. If specified true
// then it will return sorted key value pairs array
//
// ```Ruby
// { a: 1, b: 2, c: 3 }.to_a
// # => [["a", 1], ["c", 3], ["b", 2]] or [["b", 2], ["c", 3], ["a", 1]] ... etc
// { a: 1, b: 2, c: 3 }.to_a(true)
// # => [["a", 1], ["b", 2], ["c", 3]]
// { b: 1, a: 2, c: 3 }.to_a(true)
// # => [["a", 2], ["b", 1], ["c", 3]]
// { b: 1, a: 2, a: 3 }.to_a(true)
// # => [["a", 3], ["b", 1]]
// ```
//
// @return [Array]
Name: "to_a",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
h := receiver.(*HashObject)