ast-delete-object examples

Table of Contents

Quick Take

import { strict as assert } from "assert";
import { deleteObj } from "ast-delete-object";

// if all keys in source object match target object's keys, the
// source object gets deleted:
assert.deepEqual(
  deleteObj(
    [
      "elem1",
      {
        findme1: "zzz",
        findme2: "yyy",
        somethingelse: "qqq",
      },
      "elem2",
    ],
    {
      findme1: "zzz",
      findme2: "yyy",
    }
  ),
  ["elem1", "elem2"]
);

opts.hungryForWhitespace

import { strict as assert } from "assert";
import { deleteObj } from "ast-delete-object";

assert.deepEqual(
  deleteObj(
    [
      { a: "\n" }, // that's empty
      {
        key3: "val3",
        key4: "val4",
      },
      { b: "   " }, // that's empty
      { c: "" }, // that's empty
    ],
    {}, // empty thing to match again - we match "empty" vs "empty"
    {
      matchKeysStrictly: false,
      hungryForWhitespace: true,
    }
  ),
  [
    {
      key3: "val3",
      key4: "val4",
    },
  ]
);

// but
assert.deepEqual(
  deleteObj(
    [
      { a: "\n" }, // that's empty
      {
        key3: "val3",
        key4: "val4",
      },
      { b: "   " }, // that's empty
      { c: "" }, // that's empty
    ],
    {}, // empty thing to match again - we match "empty" vs "empty"
    {
      matchKeysStrictly: false,
      hungryForWhitespace: false,
    }
  ),
  [
    { a: "\n" },
    {
      key3: "val3",
      key4: "val4",
    },
    { b: "   " },
    { c: "" },
  ]
);
// nothing happened because empty things were matched strictly, "==="

opts.matchKeysStrictly

import { strict as assert } from "assert";
import { deleteObj } from "ast-delete-object";

const source = [
  "elem1",
  {
    findme1: "zzz",
    findme2: "yyy",
    somethingelse: "qqq", // <--- this key will block deletion
  },
  "elem2",
];

// nothing happens - matching was strict
assert.deepEqual(
  deleteObj(
    source,
    {
      findme1: "zzz",
      findme2: "yyy",
    },
    {
      matchKeysStrictly: true, // <--- strict matching
    }
  ),
  source
);

// but
assert.deepEqual(
  deleteObj(
    source,
    {
      findme1: "zzz",
      findme2: "yyy",
    },
    {
      matchKeysStrictly: false,
    }
  ),
  ["elem1", "elem2"]
);