Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 162 additions & 0 deletions lib/node_modules/@stdlib/utils/json-patch/base/insert/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
<!--

@license Apache-2.0

Copyright (c) 2026 The Stdlib Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->

# insert

> Immutably insert a value into an array at a path in a document using structural sharing.

<!-- Section to include introductory text. Make sure to keep an empty line after the intro `section` element and another before the `/section` close. -->

<section class="intro">

This function immutably inserts a value into an array at a specified path in a document. Only objects and arrays along the path are shallow-cloned; all other subtrees retain their original references (structural sharing).

</section>

<!-- /.intro -->

<!-- Package usage documentation. -->

<section class="usage">

## Usage

```javascript
var insert = require( '@stdlib/utils/json-patch/base/insert' );
```

#### insert( document, tokens, value )

Immutably inserts a value into an array at a path in a document using structural sharing.

```javascript
var doc = {
'a': [ 1, 2, 3 ]
};
var out = insert( doc, [ 'a', '1' ], 99 );
// returns { 'a': [ 1, 99, 2, 3 ] }

var bool = ( doc.a === out.a );
// returns false

bool = ( doc === out );
// returns false
```

The `-` token is resolved to the array length, appending the value to the end of the array.

```javascript
var doc = [ 1, 2, 3 ];
var out = insert( doc, [ '-' ], 4 );
// returns [ 1, 2, 3, 4 ]
```

</section>

<!-- /.usage -->

<!-- Package usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->

<section class="notes">

## Notes

- Only objects and arrays along the path are shallow-cloned. All other subtrees keep their original references (structural sharing).
- The final container must be an array. The value is inserted before the given index via `splice( index, 0, value )`, shifting existing elements right.
- The `-` token is resolved to `array.length` (append).
- The function throws an `Error` if any token is an unsafe value (e.g., `__proto__`, `constructor`).
- The function throws a `TypeError` if an intermediate path segment references a non-traversable value (e.g., a string or number).

</section>

<!-- /.notes -->

<!-- Package usage examples. -->

<section class="examples">

## Examples

<!-- eslint no-undef: "error" -->

```javascript
var insert = require( '@stdlib/utils/json-patch/base/insert' );

// Insert an element into an array:
var doc = [ 1, 2, 3 ];
var out = insert( doc, [ '1' ], 99 );
console.log( out );
// => [ 1, 99, 2, 3 ]

// Append an element to an array:
doc = [ 1, 2, 3 ];
out = insert( doc, [ '-' ], 4 );
console.log( out );
// => [ 1, 2, 3, 4 ]

// Insert into a nested array:
doc = {
'a': {
'b': [ 1, 2 ]
}
};
out = insert( doc, [ 'a', 'b', '1' ], 42 );
console.log( out );
/* =>
{
'a': {
'b': [ 1, 42, 2 ]
}
}
*/

// Structural sharing (unchanged subtrees keep references):
doc = {
'a': {
'b': [ 1, 2 ]
},
'c': {
'd': 3
}
};
out = insert( doc, [ 'a', 'b', '0' ], 99 );
console.log( out.c === doc.c );
// => true
```

</section>

<!-- /.examples -->

<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->

<section class="related">

</section>

<!-- /.related -->

<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->

<section class="links">

</section>

<!-- /.links -->
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/**
* @license Apache-2.0
*
* Copyright (c) 2026 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var format = require( '@stdlib/string/format' );
var isArray = require( '@stdlib/assert/is-array' );
var isPlainObject = require( '@stdlib/assert/is-plain-object' );
var pkg = require( './../package.json' ).name;
var insert = require( './../lib' );


// MAIN //

bench( format( '%s::shallow_path', pkg ), function benchmark( b ) {
var doc;
var out;
var i;

doc = [ 1, 2, 3 ];

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
out = insert( doc, [ '1' ], i );
if ( !isArray( out ) ) {
b.fail( 'should return an array' );
}
}
b.toc();
if ( !isArray( out ) ) {
b.fail( 'should return an array' );
}
b.pass( 'benchmark finished' );
b.end();
});

bench( format( '%s::append', pkg ), function benchmark( b ) {
var doc;
var out;
var i;

doc = [ 1, 2, 3 ];

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
out = insert( doc, [ '-' ], i );
if ( !isArray( out ) ) {
b.fail( 'should return an array' );
}
}
b.toc();
if ( !isArray( out ) ) {
b.fail( 'should return an array' );
}
b.pass( 'benchmark finished' );
b.end();
});

bench( format( '%s::deep_path', pkg ), function benchmark( b ) {
var doc;
var out;
var i;

doc = {
'a': {
'b': [ 1, 2, 3 ]
}
};

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
out = insert( doc, [ 'a', 'b', '1' ], i );
if ( !isPlainObject( out ) ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( !isPlainObject( out ) ) {
b.fail( 'should return a plain object' );
}
b.pass( 'benchmark finished' );
b.end();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

{{alias}}( document, tokens, value )
Immutably inserts a value into an array at a path in a document using
structural sharing.

Only objects and arrays along the path are shallow-cloned. All other
subtrees keep their original references.

The final container must be an array. The value is inserted before the
given index, shifting existing elements right. The `-` token is resolved
to `array.length` (append).

Parameters
----------
document: Object|Array
Source document.

tokens: Array<string>
Array of reference tokens.

value: any
The value to insert.

Returns
-------
out: Object|Array
New document with the value inserted.

Examples
--------
> var doc = { 'a': [ 1, 2, 3 ] };
> var out = {{alias}}( doc, [ 'a', '1' ], 99 )
{ 'a': [ 1, 99, 2, 3 ] }
> var bool = ( doc === out )
false

See Also
--------

Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* @license Apache-2.0
*
* Copyright (c) 2026 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// TypeScript Version: 4.1

/**
* Immutably inserts a value into an array at a path in a document using structural sharing.
*
* @param document - source document
* @param tokens - array of reference tokens
* @param value - value to insert
* @throws tokens must not be empty
* @throws tokens must not contain unsafe tokens
* @throws intermediate path segments must reference objects or arrays
* @throws target container must be an array
* @throws array index must be within bounds
* @returns new document with the value inserted
*
* @example
* var doc = {
* 'a': [ 1, 2, 3 ]
* };
* var out = insert( doc, [ 'a', '1' ], 99 );
* // returns { 'a': [ 1, 99, 2, 3 ] }
*
* var bool = ( doc.a === out.a );
* // returns false
*
* bool = ( doc === out );
* // returns false
*/
declare function insert( document: Array<any> | Record<string, any>, tokens: Array<string>, value: any ): any;


// EXPORTS //

export = insert;
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* @license Apache-2.0
*
* Copyright (c) 2026 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import insert = require( './index' );


// TESTS //

// The function returns any...
{
insert( [ 1, 2, 3 ], [ '0' ], 99 ); // $ExpectType any
insert( { 'a': [ 1, 2 ] }, [ 'a', '1' ], 99 ); // $ExpectType any
}

// The compiler throws an error if the function is provided an unsupported number of arguments...
{
insert(); // $ExpectError
insert( [ 1, 2 ] ); // $ExpectError
insert( [ 1, 2 ], [ '0' ] ); // $ExpectError
insert( [ 1, 2 ], [ '0' ], 99, 42 ); // $ExpectError
}
Loading
Loading