24 Apr 2023

Write a Rotate Function that Moves the Last Element to the Beginning of an Array

Taken from Execute Program

Write a rotate function. It should move the last element to the beginning of the array. The function should modify the original array.

You’ll need to handle the special case when an array is empty (with a length of 0.) When rotate gets an empty array, it should also return an empty array.


This is the answer I came up with:

function rotate(arr: Array<any>) {
  if (arr.length === 0) { return arr }

  let lastElement = arr.pop()

  return [lastElement, ...arr]


Solution tested in REPL:


Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated November 7, 2023 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems