Skip to content

Replace an array | object's content with the other one's while keeping the reference

Notifications You must be signed in to change notification settings

kenberkeley/replace-with

Folders and files

NameName
Last commit message
Last commit date

Latest commit

author
Ken Berkeley
Apr 13, 2017
31c3a90 · Apr 13, 2017

History

3 Commits
Apr 13, 2017
Apr 13, 2017
Apr 13, 2017
Apr 13, 2017
Apr 13, 2017
Apr 13, 2017
Apr 13, 2017

Repository files navigation

replaceWith(orig, other)

npm version npm download build

Installation

npm i replace-with -S

Source (index.js)

/**
 * Replace an array|object's content with the other one's while keeping the reference
 * @param  {Array|Object} orig
 * @param  {Array|Object} other
 * @return {Array|Object} orig
 */
var keys = Object.keys;

module.exports = function replaceWith(orig, other) {
  if (Array.isArray(orig)) {
    // for Array
    orig.splice.apply(orig, [0, orig.length].concat(other));
  } else {
    // for Object
    keys(orig).forEach(function (k) { delete orig[k] });
    keys(other).forEach(function (k) { orig[k] = other[k] });
  }
  return orig;
};

Usage

Let's take a look at the test examples

test('replace array', t => {
  const orig = [1, 2, 3]
  const ref = orig
  replaceWith(orig, [4, 5, 6])
  t.is(ref, orig) // pass!
  t.deepEqual(orig, [4, 5, 6]) // pass!
})

test('replace object', t => {
  let orig = { a: 1, b: 2, c: 3 }
  const ref = orig
  orig = replaceWith(orig, { d: 4, e: 5, f: 6 })
  t.is(ref, orig) // pass!
  t.deepEqual(orig, { d: 4, e: 5, f: 6 }) // pass!
})

Test

npm test

About

Replace an array | object's content with the other one's while keeping the reference

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published