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:

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

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

This node last updated October 9, 2024 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