Launch Week Day 1: Socket for Jira Is Now Available.Learn More
Socket
Book a DemoSign in
Socket

replace-with

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

replace-with

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

latest
Source
npmnpm
Version
1.0.0
Version published
Weekly downloads
51
-23.88%
Maintainers
1
Weekly downloads
 
Created
Source

replaceWith(orig <Array|Object>, other <Array|Object>)

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

Keywords

replace

FAQs

Package last updated on 13 Apr 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts