Skip to content

Instantly share code, notes, and snippets.

@hatemogi
Created December 14, 2022 03:39
Show Gist options
  • Save hatemogi/7d792fdbff33da3f53a2a978dbe5a77e to your computer and use it in GitHub Desktop.
Save hatemogi/7d792fdbff33da3f53a2a978dbe5a77e to your computer and use it in GitHub Desktop.
-- x원소를 n개만큼 갖고 있는 1차원 배열을 생성
CREATE OR REPLACE FUNCTION array_replicate(x anycompatible, n integer)
RETURNS anycompatiblearray AS $$
BEGIN
RETURN array_fill(x, ARRAY[n]);
END
$$ LANGUAGE plpgsql;
-- 배열 xs에서 최대 n개의 요소만 추출.
-- n개 이하 원소의 배열이라면 그대로 반환.
-- n개 초과 원소의 배열이라면, n개 만큼만 잘라서 반환
CREATE OR REPLACE FUNCTION array_take(xs anycompatiblearray, n integer)
RETURNS anycompatiblearray AS $$
BEGIN
RETURN trim_array(
xs,
GREATEST(0, array_length(xs, 1) - n)
);
END
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment