2023-04-24

 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.

Solution

This is the answer I came up with:

// typescript

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

  let lastElement = arr.pop()

  return [lastElement, ...arr]
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAJzlAhlApgCnc5ALkQEED0BPAHnTAoD4BKRAbwChFEZhE8CA6ADZYwAcygALRAF5ZiAAzMWKLFBDIk+ZIgC+bDomFRD6AM5QAosIC2I49MRb+ABzjOcjfZ2Sr1SANqCZpY2dgA0iPxRWgC6bHpsEAimcMJCcKI4Bt5omLj+AEwRAMwRACwRAKwRAIwxnswA9I2I-jURRYiliBWIlXFAA

Webmentions & Comments

Copyright © Paramdeo Singh · Built with Jekyll in 🇬🇾 · All Rights Reserved

[ this node is permanently morphing last updated on 28 May 2023 ]

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