Skip to content

Commit

Permalink
feat(arrays): add insert/insertUnsafe()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 21, 2021
1 parent 39e5c37 commit 2a78598
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/arrays/src/index.ts
Expand Up @@ -8,6 +8,7 @@ export * from "./find";
export * from "./fill-range";
export * from "./fuzzy-match";
export * from "./is-sorted";
export * from "./insert";
export * from "./into";
export * from "./iterator";
export * from "./levenshtein";
Expand Down
35 changes: 35 additions & 0 deletions packages/arrays/src/insert.ts
@@ -0,0 +1,35 @@
/**
* Inserts `x` into `buf` at index `i` and ensures that array length doesn't
* grow beyond max `k` items (default: unbounded).
*
* @remarks
* The function will have no effect iff `i<0` or `i>=k` or `k<1`. If
* `buf.length` is larger than `k`, only the index range [i..k) will be
* modified.
*
* In benchmarking with 8, 16, 32, 64 element arrays, this function is
* consistently 7-16x faster than `Array.prototype.copyWithin`. See
* `/bench/insert.ts`
*
* @param buf
* @param x
* @param i
* @param k
*/
export const insert = <T>(buf: T[], x: T, i: number, k = Infinity) =>
i < 0 || i >= k || k < 1 ? buf : insertUnsafe(buf, x, i, k);

/**
* Same as {@link insert} but without any bounds/index checks.
*
* @param buf
* @param x
* @param i
* @param k
*/
export const insertUnsafe = <T>(buf: T[], x: T, i: number, k = Infinity) => {
let j = buf.length < k ? buf.length + 1 : k;
for (; --j > i; ) buf[j] = buf[j - 1];
buf[i] = x;
return buf;
};

0 comments on commit 2a78598

Please sign in to comment.