This repository was archived by the owner on Aug 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathruby.coffee
11806 lines (9455 loc) · 308 KB
/
ruby.coffee
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
###
RubyJS Alpha 0.8.0-beta1
Copyright (c) 2012 Sebastian Burkhard
All rights reserved.
http://www.rubyjs.org/LICENSE.txt
###
root = global ? window
# TODO: link rubyjs/_r directly to RubyJS.RubyJS.prototype.box
# this is a suboptimal solution as of now.
root.RubyJS = (obj, recursive, block) ->
RubyJS.box(obj, recursive, block)
RubyJS.VERSION = '0.8.0-beta1'
# noConflict mode for R
previousR = root.R if root.R?
RubyJS.noConflict = ->
root.R = previousR
RubyJS
# Alias to RubyJS
root.R = RubyJS
RubyJS.extend = (obj, mixin) ->
obj[name] = method for name, method of mixin
obj
RubyJS.include = (mixin, replace = false) ->
for name, method of mixin.prototype
if replace
@prototype[name] = method
else
@prototype[name] = method unless @prototype[name]
mixin
if typeof(exports) != 'undefined'
exports.R = R
exports.RubyJS = RubyJS
########################################
# Private methods of RubyJS base object
########################################
# helper method to get an arguments object
#
# @return [Arguments]
# @private
#
RubyJS.argify = -> arguments
# Creates a wrapper method that calls a functional style
# method with this as the first arguments. Tries to avoid apply.
#
# callFunctionWithThis(_s.ljust)
# // creates a function similar to this:
# // function (len, pad) {
# // return _s.ljust(this, len, pad)
# // }
#
# This can be used to extend native classes/prototypes with functional
# methods.
#
# String.prototype.capitalize = callFunctionWithThis(_s.capitalize)
# "foo".capitalize() // => "Foo"
#
# @private
#
RubyJS.callFunctionWithThis = callFunctionWithThis = (func) ->
() ->
a = arguments
switch arguments.length
when 0 then func(this)
when 1 then func(this, a[0])
when 2 then func(this, a[0], a[1])
when 3 then func(this, a[0], a[1], a[2])
when 4 then func(this, a[0], a[1], a[2], a[3])
when 5 then func(this, a[0], a[1], a[2], a[3], a[4])
when 6 then func(this, a[0], a[1], a[2], a[3], a[4], a[5])
# Slow fallback when passed more than 6 arguments.
else func.apply(null, [this].concat(nativeSlice.call(arguments, 0)))
# RubyJS specific helper methods
# @private
RubyJS.ensure_args_length = __ensure_args_length = (args, length) ->
throw R.ArgumentError.new() unless args.length is length
# Finds, removes and returns the last block/function in arguments list.
# This is a destructive method.
#
# @example Use like this
# foo = (args...) ->
# console.log( args.length ) # => 2
# block = __extract_block(args)
# console.log( args.length ) # => 1
# other = args[0]
#
# @private
#
RubyJS.extract_block = __extract_block = (args) ->
idx = args.length
while --idx >= 0
return args.pop() if args[idx]?.call?
null
# Native classes, to avoid naming conflicts inside RubyJS classes.
nativeArray = Array
nativeNumber = Number
nativeObject = Object
nativeRegExp = RegExp
nativeString = String
ObjProto = Object.prototype
StrProto = String.prototype
ArrProto = Array.prototype
nativeToString = ObjProto.toString
nativeStrSlice = StrProto.slice
nativeStrMatch = StrProto.match
nativeJoin = ArrProto.join
nativeSort = ArrProto.sort
nativeSlice = ArrProto.slice
nativeUnshift = ArrProto.unshift
nativePush = ArrProto.push
# TODO: create BlockNone class that coerces multiple yield arguments into array.
# @abstract
class Block
# Block.create returns a different implementation of Block (BlockMulti,
# BlockSingle) depending on the arity of block.
#
# If no block is given returns a BlockArgs callback, that returns
# a single block argument.
#
@create: (block, thisArg) ->
if block?.call? #block_given
if block.length != 1
new BlockMulti(block, thisArg)
else
new BlockSingle(block, thisArg)
else
new BlockArgs(block, thisArg)
# handles block argument splatting
# reverse_each([[1,2]], (a,b) -> )
# if block has multiple arguments, returns a wrapper
# function that applies arguments to block instead of passing.
# Otherwise it returns the block itself.
@splat_arguments: (block) ->
if block.length > 1
(item) ->
if typeof item is 'object' && __isArr(item)
block.apply(null, item)
else
block(item)
else
block
# @private
class BlockArgs
constructor: (@block, @thisArg) ->
invoke: (args) ->
RCoerce.single_block_args(args, @block)
# @private
class BlockMulti
constructor: (@block, @thisArg) ->
args: (args) ->
if args.length > 1 then nativeSlice.call(args) else args[0]
# @param args array or arguments
invoke: (args) ->
if args.length > 1
@block.apply(@thisArg, args)
else
arg = args[0]
if typeof arg is 'object' && __isArr(arg)
@block.apply(@thisArg, arg)
else
@block.call(@thisArg, arg)
invokeSplat: ->
@block.apply(@thisArg, arguments)
# for blocks with arity 1
# @private
class BlockSingle
constructor: (@block, @thisArg) ->
args: (args) ->
args[0]
invoke: (args) ->
@block.call(@thisArg, args[0])
invokeSplat: ->
@block.apply(@thisArg, arguments)
R.Block = Block
R.blockify = __blockify = Block.create
# Breaker is a class for adding support to breaking out of functions
# that act like loops. Because we mimick ruby block/procs/lambdas by passing
# functions, so neither break nor return would work in JS.
#
# @see RubyJS.Kernel#catch_break
#
# @example Breaking loops
# sum = R('')
# R.catch_break( breaker ) -> # breaker is a new Breaker instance
# R('a').upto('f') (chr) ->
# breaker.break() if chr.equals('d')
# sum.append(chr)
# # => 'abc'
#
# @example Breaking out and return a value
# R.catch_break( breaker ) -> # breaker is a new Breaker instance
# R(1).upto(100) (i) ->
# breaker.break('foo') if i.equals(81)
# # => 'foo'
#
#
#
class RubyJS.Breaker
constructor: (@return_value = null) ->
# Breaks out of the loop by throwing itself. Accepts a return value.
#
# @example Breaking out and return a value
# R.catch_break( breaker )
# breaker.break('foo')
# # => 'foo'
#
# @param value Return value
#
break: (return_value) ->
@return_value = return_value
throw this
handle_break: (e) ->
if this is e
return (e.return_value)
else
throw e
# methods are included in RubyJS classes. Most notably the Base object R.
class RubyJS.Kernel
# A method to easily check whether an object is a RubyJS object with CoffeeScript.
#
# foo.rubyjs?
#
rubyjs: -> true
# TODO: find a better name for box.
# TODO: handle the case when calling R(true, -> ), R({}, -> )
box: (obj, recursive, block) ->
# R(null) should simply return null. At a later point maybe an
# instance of NilClass
return obj unless obj?
# typeof with JS primitive is very fast. Handle primitives first
# for performance reasons.
if typeof obj is 'object'
# Is obj already a RubyJS object? Check if rubyjs method exists.
# has to be after typeof, checking for a member/method on a primitive
# will "convert it to an object", what makes it slow.
return obj if obj.rubyjs?
_v = obj.valueOf()
if typeof _v isnt 'object'
# take care of [object String] and [object Number]
obj = _v
else
if R.Array.isNativeArray(obj)
# Small performance improvement. which probably should be somewhere else.
object_type = '[object Array]'
else
object_type = nativeToString.call(obj)
# check primitives first
if typeof obj is 'number'
# Numeric.typecast returns a float or fixnum.
obj = RubyJS.Numeric.typecast(obj)
else if typeof obj is 'string'
obj = new R.String(obj)
# To stay lean we do not wrap booleans for now:
# else if primitive_type is 'boolean'
# Array and Regexp should be the first to be checked. String and
# Numbers are in most cases already taken care for, but have to be checked
# again in case a primitive wrappers are passed.
else if object_type is '[object Array]'
obj = new R.Array(obj, recursive is true)
else if object_type is '[object RegExp]'
obj = R.Regexp.try_convert(obj)
# TODO: if at this point obj is not rubyjs, raise error.
# Handles the case R(1, -> )
if typeof recursive is 'function'
block = recursive
recursive = false
if typeof block is 'function'
# Call the block with obj as receiver, so that the block has context
# of the just converted obj. R('a', -> @capitalize()).
obj = block.call(obj)
if obj is null or obj is undefined
# specifically convert undefined to null
obj = null
else if obj.to_native?
obj = obj.to_native(true)
# else it is a native object or primitive, and should be left alone.
return obj
# Equivalent to %w[] in Ruby
#
# Creates an R.Array of R.String for every word separated by space.
#
# @example:
# R.w('foo bar baz') # => ['foo', 'bar', 'baz']
# R.w('foo\nbar') # => ['foo\nbar']
# R.w('') # => ['']
#
w: (str) ->
new R.String(str).split(/\s+/)
# Shortcut for creating a R.Range.
#
# @example
# R.r(0,4) # => (0..4)
# R.r(0,4, true) # => (0...4)
#
# @alias #rng
#
r: (a,b,excluding) ->
if excluding is true # note: true not truethy
R.Range.new(a,b, true)
else
R.Range.new(a,b)
# Shortcut for creating floats
f: (flt) ->
new R.Float(flt)
# Shortcut for creating Ranges
rng: @prototype.r
catch_break: (block, context = this) ->
breaker = new R.Breaker()
try
return block.call(context, breaker)
catch e
return breaker.handle_break(e)
$Array: (obj, recursive = false) ->
if recursive is true
R.Array.new( @box(e) for e in obj )
else
R.Array.new(obj)
arr_r: (obj) ->
new RArray(R(e) for e in obj)
# TODO: Remove from code
$Array_r: (obj) ->
@$Array(obj, true)
$Float: (obj) ->
obj = @box(obj)
throw R.TypeError.new() if obj == null
throw R.TypeError.new() unless obj.to_f?
if obj.is_float?
obj
else if obj.is_string?
stripped = obj.strip()
if stripped.valid_float()
new R.Float(+stripped.to_native().replace(/_/g, ''))
else
throw R.ArgumentError.new()
else if obj.rubyjs?
new R.Float(obj.to_native())
else # is not a R object
new R.Float(obj)
$Integer: (obj) ->
obj = R(obj)
throw R.TypeError.new() unless obj?
# throw R.TypeError.new() unless obj.to_i?
if obj.is_integer?
obj
else if obj.is_string?
stripped = obj.strip()
if stripped.valid_float()
new R.Fixnum(Math.floor(+stripped.to_native().replace(/_/g, '')))
else
throw R.ArgumentError.new()
else if obj.rubyjs?
# throw R.TypeError.new() unless obj.to_i?
new R.Fixnum(Math.floor(obj.to_native()))
else # is not a R object
new R.Fixnum(Math.floor(obj))
$Integer: @prototype.$Integer
$String: (obj) -> R.String.try_convert(obj) or throw(R.TypeError.new())
$Range: (start,end,exclusive) ->
R.Range.new(start,end,exclusive)
puts: (obj) ->
console.log(obj.valueOf())
rand: (limit) ->
r = R(Math.random())
if limit then r.multiply(limit).to_i() else r
__enumerate = (func, args) ->
ary = []
args.push () ->
if arguments.length > 1
ary.push(nativeSlice.call(arguments, 0))
else
ary.push(arguments[0])
func.apply(null, args)
ary
__random = (limit) ->
Math.floor( Math.random() * (limit + 1) )
__rand = RubyJS.Kernel.prototype.rand
########################################
# Public methods of RubyJS base object
########################################
# adds all methods to the global R object
for own name, method of RubyJS.Kernel.prototype
RubyJS[name] = method
#
RubyJS['$~'] = null
#
RubyJS['$,'] = null
#
RubyJS['$;'] = "\n"
#
RubyJS['$/'] = "\n"
RubyJS.inspect = (obj) ->
if obj is null or obj is 'undefined'
'null'
else if obj.inspect?
obj.inspect()
else if _a.isArray(obj)
"[#{obj}]"
else
obj
# Adds useful methods to the global namespace.
#
# e.g. _proc, _puts, _truthy, _inspect, _falsey
#
RubyJS.pollute_global_with_kernel = (prefix = "_") ->
args = [
'w', 'fn', 'proc', 'puts', 'truthy', 'falsey', 'inspect'
]
for name in args
root[prefix + name] = R[name]
null
# Adds the _a, _n, etc shortcuts to the global namespace.
#
RubyJS.pollute_global_with_shortcuts = (prefix = "_") ->
shortcuts =
_arr: 'a'
_num: 'n'
_str: 's'
_itr: 'i'
_enum: 'e'
_hsh: 'h'
_time: 't'
for k,v of shortcuts
R[prefix + v] = R[k]
root[prefix + v] = R[k]
null
# Adds RubyJS methods to JS native classes.
#
# RubyJS.i_am_feeling_evil()
# ['foo', 'bar'].rb_map(proc('rb_reverse')).rb_sort()
# # =>['oof', 'rab']
#
RubyJS.god_mode = (prefix = 'rb_') ->
overwrites = [
[Array.prototype, _arr],
[Number.prototype, _num],
[String.prototype, _str],
[Date.prototype, _time]
]
for [proto, methods] in overwrites
for name, func of methods
new_name = prefix + name
if typeof func == 'function'
if proto[new_name] is undefined
do (new_name, func) ->
# The following is 100x faster than slicing.
proto[new_name] = callFunctionWithThis(func)
else if prefix == '' && proto['rb_'+new_name]
console.log("#{proto}.#{new_name} exists. skipped.")
true
# proc() is the equivalent to symbol to proc functionality of Ruby.
#
# proc accepts additional arguments which are passed to the block.
#
# @note proc() calls methods and not properties
#
# @example
#
# R.w('foo bar').map( R.proc('capitalize') )
# R.w('foo bar').map( R.proc('ljust', 10) )
#
RubyJS.proc = (key) ->
if arguments.length == 1
# Wrapper block doesnt need to mangle arguments
(el) ->
fn = el[key]
if typeof fn is 'function'
fn.call(el)
else if fn is undefined
# RELOADED: dont use R()
R(el)[key]().valueOf()
else
fn
else
args = nativeSlice.call(arguments, 1)
# Wrapper block that mangles arguments
(el) ->
fn = el[key]
if typeof fn is 'function'
el[key].apply(el, args)
else
# no method found, now check if it exists in rubyjs equivalent
el = R(el)
el[key].apply(el, args).valueOf()
RubyJS.fn = (func) ->
(el) ->
arguments[0] = el
func.apply(null, arguments)
# Check wether an obj is falsey according to Ruby
#
# RubyJS.falsey(null) // => true
# RubyJS.falsey(false) // => true
# RubyJS.falsey(undefined) // => true
# RubyJS.falsey(0) // => false
# RubyJS.falsey("0") // => false
# RubyJS.falsey(-1) // => false
#
RubyJS.falsey = (obj) ->
obj is false or obj is null or obj is undefined
# Check wether an obj is truthy according to Ruby
#
# RubyJS.truthy(null) // => false
# RubyJS.truthy(false) // => false
# RubyJS.truthy(undefined) // => false
# RubyJS.truthy(0) // => true
# RubyJS.truthy("0") // => true
# RubyJS.truthy(-1) // => true
#
RubyJS.truthy = (obj) ->
!__falsey(obj)
RubyJS.respond_to = (obj, function_name) ->
obj[function_name] != undefined
# Compares to objects.
#
# // => true
# R.is_equal(1,1)
# R.is_equal(1, new Number(1))
# R.is_equal(1, {valueOf: function () {return 1;}})
# R.is_equal(1, {equals: function (n) {return n === 1;}})
#
RubyJS.is_equal = (a, b) ->
return true if a is b
if typeof a is 'object'
if a.equals?
a.equals(b)
else if __isArr(a)
_arr.equals(a,b)
else if a.valueOf?
a.valueOf() is b.valueOf()
else
false
else if typeof b is 'object'
if b.equals?
b.equals(a)
else if __isArr(b)
_arr.equals(a,b)
else if b.valueOf?
b.valueOf() is a.valueOf()
else
false
else
# for elements that are literals
a is b
RubyJS.is_eql = (a, b) ->
if typeof a is 'object'
a.eql(b)
else if typeof b is 'object'
b.eql(a)
else
a is b
__falsey = R.falsey
__truthy = R.truthy
__equals = R.is_equal
errors = [
'ArgumentError'
'RegexpError'
'TypeError'
'KeyError'
'IndexError'
'FloatDomainError'
'RangeError'
'StandardError'
'ZeroDivisionError'
'NotSupportedError'
'NotImplementedError'
]
for error in errors
do (error) ->
errorClass = class extends Error
errorClass.new = -> new RubyJS[error](error)
RubyJS[error] = this["R"+error] = errorClass
# Singleton class for type coercion inside RubyJS.
#
# @private
RubyJS.coerce = _coerce =
native: (obj) ->
if typeof obj != 'object'
obj
else
obj.valueOf()
str: (obj) ->
_err.throw_type() if obj == null
obj = obj.valueOf() if typeof obj is 'object'
# throw new R.TypeError("#{obj} is not a valid string") unless typeof obj is 'string'
_err.throw_type() unless typeof obj is 'string'
obj
try_str: (obj) ->
return obj if typeof obj is 'string'
obj = obj.valueOf() if obj isnt null
return obj if typeof obj is 'string'
null
num: (obj) ->
_err.throw_type() if obj == null
obj = obj.valueOf() if typeof obj is 'object'
# throw new R.TypeError("#{obj} is not a valid num") unless typeof obj is 'number'
_err.throw_type() unless typeof obj is 'number'
obj
int: (obj) ->
_err.throw_type() if obj == null
obj = obj.valueOf() if typeof obj is 'object'
# throw new R.TypeError("#{obj} is not a valid int") unless typeof obj is 'number'
_err.throw_type() unless typeof obj is 'number'
Math.floor(obj)
isArray: nativeArray.isArray or (obj) ->
nativeToString.call(obj) is '[object Array]'
is_arr: (obj) ->
typeof obj is 'object' && obj != null && _coerce.isArray(obj.valueOf())
is_str: (obj) ->
return true if typeof obj is 'string'
typeof obj is 'object' && obj != null && typeof obj.valueOf() is 'string'
is_rgx: (obj) ->
return false unless obj?
nativeToString.call(obj.valueOf()) is '[object RegExp]'
arr: (obj) ->
_err.throw_type() if obj == null
_err.throw_type() if typeof obj != 'object'
obj = obj.valueOf()
_err.throw_type() unless _coerce.isArray(obj)
obj
split_args: (args, offset) ->
arg_len = args.length
ary = []
idx = offset
while idx < arg_len
el = args[idx]
ary.push(el) unless el is undefined
idx += 1
ary
# Use call_with when you want to delegate a method call to a functional one
# when the original method has flexible length of arguments.
#
# @example
# class RString
# # new RString("foo").count('o')
# # new RString("foo").count('o', 'of')
# count: () ->
# __call( _str.count, @__native__, arguments)
#
call_with: (func, thisArg, args) ->
a = args
switch args.length
when 0 then func(thisArg)
when 1 then func(thisArg, a[0])
when 2 then func(thisArg, a[0], a[1])
when 3 then func(thisArg, a[0], a[1], a[2])
when 4 then func(thisArg, a[0], a[1], a[2], a[3])
when 5 then func(thisArg, a[0], a[1], a[2], a[3], a[4])
when 6 then func(thisArg, a[0], a[1], a[2], a[3], a[4], a[5])
# Slow fallback when passed more than 6 arguments.
else func.apply(null, [thisArg].concat(nativeSlice.call(args, 0)))
cmp: (a, b) ->
if typeof a isnt 'object' and typeof a is typeof b
if a is b
0
else
if a < b then -1 else 1
else
if __isArr(a)
_arr.cmp(a, b)
else
a = R(a)
throw 'NoMethodError' unless a.cmp?
a.cmp(b)
cmpstrict: (a, b) ->
if typeof a is typeof b and typeof a isnt 'object'
if a is b
0
else
if a < b then -1 else 1
else
a = R(a)
throw 'NoMethodError' unless a.cmp?
cmp = a.cmp(b)
_err.throw_argument() if cmp is null
cmp
__str = _coerce.str
__int = _coerce.int
__num = _coerce.num
__arr = _coerce.arr
__isArr = _coerce.is_arr
__isStr = _coerce.is_str
__isRgx = _coerce.is_rgx
__call = _coerce.call_with
__cmp = _coerce.cmp
__cmpstrict = _coerce.cmpstrict
__try_str = _coerce.try_str
_err =
throw_argument: (msg) ->
throw RArgumentError.new(msg)
throw_type: (msg) ->
throw RTypeError.new(msg)
throw_index: (msg) ->
throw RIndexError.new(msg)
throw_not_implemented: (msg) ->
throw RNotImplementedError.new(msg)
throw_key: (msg) ->
throw RKeyError.new(msg)
class NumericMethods
cmp: (num, other) ->
if num is other then 0 else null
# Returns true if num is NaN.
#
# @example
# _n.nan(2) // => false
# _n.nan('test') // => true
# _n.nan(true) // => false
# _n.nan(NaN) // => true
#
# @return [Boolean]
#
nan: (num) ->
isNaN(num)
# Returns the absolute value of num.
#
# @example
# _n.abs(12) // => 12
# _n.abs(-34.56) // => 34.56
#
# @return [Number]
#
abs: (num) ->
if num < 0 then (- num) else num
# Returns square of num.
#
# @example
# _n.abs2(2) // => 4
# _n.abs2(-4) // => 16
#
# @return [Number]
#
abs2: (num) ->
return num if _num.nan(num)
Math.pow(num, 2)
# Returns the smallest Integer greater than or equal to num. Class Numeric achieves this by converting itself to
# a Float then invoking Float#ceil.
#
# @example
# _n.ceil(1) // => 1
# _n.ceil(1.2) // => 2
# _n.ceil(-1.2) // => -1
# _n.ceil(-1) // => -1
#
# @return [Number]
#
ceil: (num) ->
Math.ceil(num)
# Returns an array with quotient and modulus as a result of division num by other.
#
# @example
# _n.divmod(8, 4) // => [2, 0]
# _n.divmod(13, 4) // => [3, 1]
# _n.divmod(-8.5, -4) // => [2, -0.5]
#
# @return [Array]
#
divmod: (num, other) ->
quotient = Math.floor(num / other)
modulus = num % other
[quotient, modulus]
# Returns array from num to stop (inclusive) when passed no block.
# When passed a block, iterates block by passing decreasing values from num to stop (inclusive).
#
# @example
# var print = function(i) { console.log(i);}
#
# _n.downto(3, 1, print) // => 3\n 2\n 1\n 3
# _n.downto(3, 1) // => [3, 2, 1]
#
# @return [Array] or Number
#
downto: (num, stop, block) ->
return __enumerate(_num.downto, [num, stop]) unless block?.call?
stop = Math.ceil(stop)
idx = num
while idx >= stop
block( idx )
idx -= 1
num
# Returns true if num and other are the same type (or can be converted to the same type) and have equal values.
#
# @example
# _n.eql(1, 1.0) // => true
# _n.eql(2, 1) // => false
# _n.eql(3.5, 2) // => false
#
# @return [Boolean]
#
eql: (num, other) ->
num == other
# Returns the largest integer less than or equal to num.
#
# @example
# _n.floor(1.5) // => 1
# _n.floor(-1) // => -1
# _n.floor(-2.5) // => -3
#