Home > Enterprise >  Round get array slice roundly except on array value with same order
Round get array slice roundly except on array value with same order

Time:06-28

I want to get array slice w/o one element that coming as argument, but slice should be rounded. See example for better understanding.

type Positions = "top" | "right" | "bottom" | "left"

const fn = (place : Positions) => {
 const POSITIONS = ["top", "right", "bottom", "left"]
 return getSlice(positions, place) 
}

fn("top") // -> ["right","bottom", "left"]
fn("right") // -> ["bottom", "left", "top"]
fn("bottom") // -> ["left", "top", "right"]
fn("right") // -> ["bottom", "left", "top"]

Should works with any array length

CodePudding user response:

You can grab the index from where you want to slice the array.

Then create two arrays one to right and one to left using slice and then concat them.

const fn = (place) => {
  const positions = ["top", "right", "bottom", "left"];
  const index = positions.indexOf(place);
  return positions.slice(index   1).concat(positions.slice(0, index));
};

console.log(fn("top")); // ["right","bottom", "left"]
console.log(fn("right")); // ["bottom", "left", "top"]
console.log(fn("bottom")); // ["left", "top", "right"]
console.log(fn("left")); // ['top', 'right', 'bottom']

Typescript snippet below:

type Positions = "top" | "right" | "bottom" | "left";

const fn = (place: Positions): Positions[] => {
  const positions: Positions[] = ["top", "right", "bottom", "left"];
  const index = positions.indexOf(place);
  return positions.slice(index   1).concat(positions.slice(0, index));
};

console.log(fn("top")); // ["right","bottom", "left"]
console.log(fn("right")); // ["bottom", "left", "top"]
console.log(fn("bottom")); // ["left", "top", "right"]
console.log(fn("left")); // ['top', 'right', 'bottom']

Note: This answer assumes that the place passed to fn is one of "top", "right", "bottom", "left".

CodePudding user response:

You can build this atop a more generic cycle function, which just cycles an array starting at a given index. Our main function can then find the index in the array of the given value. If it's found, we call cycle. If not, we return a copy of the original array.

It looks like this:

const cycle = (xs, n) =>
  [... xs .slice (n), ... xs .slice (0, n)]

const getSlice = (xs, x, i = xs .indexOf (x)) =>
  i > -1 ? cycle (xs, i) .slice (1) : [...xs] 

const positions = ["top", "right", "bottom", "left"]

; [...positions, "middle"] .forEach (
  pos => console .log (`"${pos}" ==> ${JSON.stringify(getSlice (positions, pos))}`)
)

  • Related