mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
mruby-array-ext: refactor ary_compact to use ary_compact_bang
This removes code duplication by making ary_compact call ary_compact_bang on a duplicated array, centralizing the compaction logic. It also reorders the functions to remove the need for a forward declaration. Co-authored-by: Gemini <gemini@google.com>
This commit is contained in:
@@ -191,31 +191,6 @@ ary_slice_bang(mrb_state *mrb, mrb_value self)
|
||||
return ary;
|
||||
}
|
||||
|
||||
/*
|
||||
* call-seq:
|
||||
* ary.compact -> new_ary
|
||||
*
|
||||
* Returns a copy of `self` with all `nil` elements removed.
|
||||
*
|
||||
* [ "a", nil, "b", nil, "c", nil ].compact
|
||||
* #=> [ "a", "b", "c" ]
|
||||
*/
|
||||
|
||||
static mrb_value
|
||||
ary_compact(mrb_state *mrb, mrb_value self)
|
||||
{
|
||||
mrb_value ary = mrb_ary_new(mrb);
|
||||
mrb_int len = RARRAY_LEN(self);
|
||||
|
||||
for (mrb_int i = 0; i < len; i++) {
|
||||
mrb_value v = RARRAY_PTR(self)[i];
|
||||
if (!mrb_nil_p(v)) {
|
||||
mrb_ary_push(mrb, ary, v);
|
||||
}
|
||||
}
|
||||
return ary;
|
||||
}
|
||||
|
||||
/*
|
||||
* call-seq:
|
||||
* ary.compact! -> ary or nil
|
||||
@@ -247,6 +222,24 @@ ary_compact_bang(mrb_state *mrb, mrb_value self)
|
||||
return self;
|
||||
}
|
||||
|
||||
/*
|
||||
* call-seq:
|
||||
* ary.compact -> new_ary
|
||||
*
|
||||
* Returns a copy of `self` with all `nil` elements removed.
|
||||
*
|
||||
* [ "a", nil, "b", nil, "c", nil ].compact
|
||||
* #=> [ "a", "b", "c" ]
|
||||
*/
|
||||
|
||||
static mrb_value
|
||||
ary_compact(mrb_state *mrb, mrb_value self)
|
||||
{
|
||||
mrb_value ary = mrb_ary_dup(mrb, self);
|
||||
ary_compact_bang(mrb, ary);
|
||||
return ary;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* call-seq:
|
||||
|
||||
Reference in New Issue
Block a user