diff --git a/src/_insertAfter.js b/src/_insertAfter.js new file mode 100644 index 0000000..5c1e66c --- /dev/null +++ b/src/_insertAfter.js @@ -0,0 +1,14 @@ +import assert from 'assert'; +import Node from './Node.js'; +import _insertBetween from './_insertBetween.js'; + +/** + * _insertAfter. + * + * @param {Node} x + * @param {any} value + */ +export default function _insertAfter(x, value) { + assert(x instanceof Node); + return _insertBetween(x, x.next, value); +} diff --git a/src/_insertBefore.js b/src/_insertBefore.js new file mode 100644 index 0000000..b3127c9 --- /dev/null +++ b/src/_insertBefore.js @@ -0,0 +1,14 @@ +import assert from 'assert'; +import Node from './Node.js'; +import _insertBetween from './_insertBetween.js'; + +/** + * _insertBefore. + * + * @param {Node} x + * @param {any} value + */ +export default function _insertBefore(x, value) { + assert(x instanceof Node); + return _insertBetween(x.prev, x, value); +} diff --git a/src/_insertBetween.js b/src/_insertBetween.js new file mode 100644 index 0000000..21c215e --- /dev/null +++ b/src/_insertBetween.js @@ -0,0 +1,18 @@ +import assert from 'assert'; +import Node from './Node.js'; + +/** + * _insertBetween. + * + * @param {Node} x + * @param {Node} y + * @param {any} value + */ +export default function _insertBetween(x, y, value) { + assert(x instanceof Node); + assert(y instanceof Node); + const z = new Node(value, x, y); + x.next = z; + y.prev = z; + return z; +} diff --git a/src/index.js b/src/index.js index 6654aa7..879c158 100644 --- a/src/index.js +++ b/src/index.js @@ -2,6 +2,9 @@ export {default as Node} from './Node.js'; export {default as _concat} from './_concat.js'; export {default as _erase} from './_erase.js'; export {default as _extend} from './_extend.js'; +export {default as _insertAfter} from './_insertAfter.js'; +export {default as _insertBefore} from './_insertBefore.js'; +export {default as _insertBetween} from './_insertBetween.js'; export {default as _iter} from './_iter.js'; export {default as _iter_fast} from './_iter_fast.js'; export {default as _last} from './_last.js'; diff --git a/test/src/insert.js b/test/src/insert.js new file mode 100644 index 0000000..8ba3cf3 --- /dev/null +++ b/test/src/insert.js @@ -0,0 +1,19 @@ +import test from 'ava'; + +import {list} from '@iterable-iterator/list'; + +import {_insertAfter, _insertBefore, from, values} from '#module'; + +test('insertAfter', (t) => { + const x = from('abc'); + const y = _insertAfter(x, 'z'); + t.is(y.value, 'z'); + t.is(list(values(x)).join(''), 'azbc'); +}); + +test('insertBefore', (t) => { + const x = from('abc'); + const y = _insertBefore(x.next, 'z'); + t.is(y.value, 'z'); + t.is(list(values(x)).join(''), 'azbc'); +});