Skip to content

0.21.0: negative array slicing #362

@He-Pin

Description

@He-Pin

std.slice([0,1,2,3], -1, null, null) should give [3] but get [0,1,2,3] in sjsonnet

refs: google/jsonnet#1222 (comment)

refs: google/jsonnet#1093
refs: CertainLach/jrsonnet#117

  slice(indexable, index, end, step)::
    local invar =
      // loop invariant with defaults applied
      {
        indexable: indexable,
        index:
          if index == null
          then 0
          else
            if index < 0
            then std.max(0, std.length(indexable) + index)
            else index,
        end:
          if end == null
          then std.length(indexable)
          else
            if end < 0
            then std.length(indexable) + end
            else end,
        step:
          if step == null
          then 1
          else step,
        length: std.length(indexable),
        type: std.type(indexable),
      };
    assert invar.step >= 0 : 'got [%s:%s:%s] but negative steps are not supported' % [invar.index, invar.end, invar.step];
    assert step != 0 : 'got %s but step must be greater than 0' % step;
    assert std.isString(indexable) || std.isArray(indexable) : 'std.slice accepts a string or an array, but got: %s' % std.type(indexable);
    local build(slice, cur) =
      if cur >= invar.end || cur >= invar.length then
        slice
      else
        build(
          if invar.type == 'string' then
            slice + invar.indexable[cur]
          else
            slice + [invar.indexable[cur]],
          cur + invar.step
        ) tailstrict;
    build(if invar.type == 'string' then '' else [], invar.index),

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions