Skip to content

Instantly share code, notes, and snippets.

@lap00zza
Last active November 10, 2018 13:36
Show Gist options
  • Select an option

  • Save lap00zza/187906a7999e672b2b5ab24fa6e5d028 to your computer and use it in GitHub Desktop.

Select an option

Save lap00zza/187906a7999e672b2b5ab24fa6e5d028 to your computer and use it in GitHub Desktop.

Revisions

  1. lap00zza revised this gist Nov 10, 2018. 1 changed file with 6 additions and 6 deletions.
    12 changes: 6 additions & 6 deletions shiftArray.js
    Original file line number Diff line number Diff line change
    @@ -1,12 +1,12 @@
    // +by shift left
    // -by shift right
    const shiftArray = (arr, by) => {
    const _by = (by | 0) % arr.length;
    const rest = by > 0 ? arr.slice(0, _by) : arr.slice(_by);
    return arr.map(
    (_, i) => arr[i + _by] !== undefined
    ? arr[i + _by]
    : rest.shift()
    const _by = (by | 0) % arr.length;
    const rest = by > 0 ? arr.slice(0, _by) : arr.slice(_by);
    return arr.map(
    (_, i) => arr[i + _by] !== undefined
    ? arr[i + _by]
    : rest.shift()
    );
    };

  2. lap00zza revised this gist Nov 10, 2018. No changes.
  3. lap00zza created this gist Nov 10, 2018.
    18 changes: 18 additions & 0 deletions shiftArray.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    // +by shift left
    // -by shift right
    const shiftArray = (arr, by) => {
    const _by = (by | 0) % arr.length;
    const rest = by > 0 ? arr.slice(0, _by) : arr.slice(_by);
    return arr.map(
    (_, i) => arr[i + _by] !== undefined
    ? arr[i + _by]
    : rest.shift()
    );
    };

    // Example:
    // const arr = [1, 2, 3, 4]
    // shiftArray(arr, 1) -> [2, 3, 4, 1]
    // shiftArray(arr, 2) -> [3, 4, 1, 2]
    // shiftArray(arr, -1) -> [4, 1, 2, 3]
    // shiftArray(arr, -2) -> [3, 4, 1, 2]