sanity
Version:
Sanity is a real-time content infrastructure with a scalable, hosted backend featuring a Graph Oriented Query Language (GROQ), asset pipelines and fast edge caches
33 lines (25 loc) • 762 B
text/typescript
export const BEFORE = 'before'
export const AFTER = 'after'
export function arrayInsert(
array: unknown[],
position: 'after' | 'before',
index: number,
...args: unknown[][]
) {
if (position !== BEFORE && position !== AFTER) {
throw new Error(`Invalid position "${position}", must be either ${BEFORE} or ${AFTER}`)
}
const items = flatten(...args)
if (array.length === 0) {
return items
}
const len = array.length
const idx = Math.abs((len + index) % len) % len
const normalizedIdx = position === 'after' ? idx + 1 : idx
const copy = array.slice()
copy.splice(normalizedIdx, 0, ...flatten(items))
return copy
}
function flatten(...values: unknown[][]) {
return values.reduce((prev, item) => prev.concat(item), [])
}