Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
AsyncBanana committed Jan 12, 2022
0 parents commit 09e7380
Show file tree
Hide file tree
Showing 11 changed files with 293 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pnpm-lock.yaml
package-lock.json
node_modules
dist
3 changes: 3 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"useTabs": true
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 AsyncBanana

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
5 changes: 5 additions & 0 deletions Logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<div align="center">

![Micropatch Logo](https://raw.githubusercontent.com/AsyncBanana/micropatch/master/Logo.svg)

Micropatch is a ![Microdiff](https://github.com/AsyncBanana/microdiff) compatible patching library that is small (<1kb minified) and simple to use.

![Minizipped Size (from Bundlephobia)](https://img.shields.io/bundlephobia/minzip/micropatch?style=flat-square) ![License](https://img.shields.io/npm/l/micropatch?style=flat-square) ![dependency Count](https://img.shields.io/badge/dependencies-0-green?style=flat-square)

</div>

# Get started

First, install Micropatch and [Microdiff]() if you want to generate patch statements

```
npm i micropatch
npm i microdiff <- only do this if you want diffing to generate patch statements
```

After you install it, simply import it and run it on two objects.

```js
import patch from "micropatch";
import diff from "microdiff";
const obj1 = {
originalProperty: true,
};
const obj2 = {
originalProperty: false,
newProperty: "new"
};
console.log(patch(obj1,[{type: "CREATE", path: ["newProperty"], value: "new"}])); // using diffs from other sources
/* {
originalProperty: true,
newProperty: "new"
} */
console.log(patch(obj1,diff(obj1,obj2))) // using Microdiff
/* {
originalProperty: true,
newProperty: "new"
} */
```

If you are using CommonJS, you can import it like this:

```js
const diff = require("micropatch").default;
```

Micropatch takes two parameters, the original/target object and an array of Microdiff diffs. It returns the new object with the diffs applied.

> ⚠️ Warning: The original object is mutated. If you wish for it to be immutable, you can pass a clone of the object. However, the mutations are unreliable, so you should rely on the return value rather than the mutations.
# Credits

@FluentCoding created the original implementation of this patch method.
52 changes: 52 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
interface Difference {
type: "CREATE" | "REMOVE" | "CHANGE";
path: (string | number)[];
value?: any;
oldValue?: any;
}
export default function patch(
obj: Record<string, any> | any[],
diffs: Difference[]
): Record<string, any> | any[] {
let arrayDelQueue = [];
const removeSymbol = Symbol("micropatch-delete");

for (const diff of diffs) {
if (!diff.path || diff.path.length === 0) continue;

let currObj = obj;
let diffPathLength = diff.path.length;
let lastPathElement = diff.path[diffPathLength - 1];
let secondLastPathElement = diff.path[diffPathLength - 2];
for (let i = 0; i < diffPathLength - 1; i++) {
currObj = currObj[diff.path[i]];
}

switch (diff.type) {
case "CREATE":
case "CHANGE":
currObj[lastPathElement] = diff.value;
break;
case "REMOVE":
if (Array.isArray(currObj)) {
(currObj as any)[lastPathElement] = removeSymbol;
arrayDelQueue.push(() => {
if (secondLastPathElement !== undefined) {
(currObj as any)[secondLastPathElement] = (currObj as any)[
secondLastPathElement
].filter((e: any) => e !== removeSymbol);
} else {
obj = obj.filter((e: any) => e !== removeSymbol);
}
});
} else {
delete currObj[lastPathElement];
}
break;
}
}

arrayDelQueue.forEach((arrayDeletion) => arrayDeletion());

return obj;
}
41 changes: 41 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "micropatch",
"version": "1.0.0",
"description": "Microdiff compatible object and array patching",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"default": "./dist/index.js"
},
"scripts": {
"build": "tsc --module CommonJS && cd dist && mv \"index.js\" \"index.cjs\" && cd ../ && tsc --module es2020 && npx prettier -w dist/* --loglevel warn",
"test": "npm run build && uvu tests",
"prepublish": "npm run build"
},
"keywords": [
"diff",
"comparison"
],
"author": "AsyncBanana",
"license": "MIT",
"files": [
"dist"
],
"devDependencies": {
"microdiff": "^1.3.0",
"picocolors": "^1.0.0",
"prettier": "^2.4.1",
"typescript": "^4.4.4",
"uvu": "^0.5.2"
},
"type": "module",
"repository": {
"type": "git",
"url": "https://github.com/AsyncBanana/micropatch"
},
"homepage": "https://github.com/AsyncBanana/micropatch#readme",
"bugs": "https://github.com/AsyncBanana/micropatch/issues"
}
28 changes: 28 additions & 0 deletions tests/arrays.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { test } from "uvu";
import * as assert from "uvu/assert";
import patch from "../dist/index.js";

test("top level array patch", () => {
assert.equal(patch(["one", "two"], [{ path: [1], type: "REMOVE" }]), ["one"]);
});

test("nested array patch", () => {
assert.equal(
patch(
["one", ["two-one", "two-two"]],
[{ path: [1, 2], type: "CREATE", value: "two-three" }]
),
["one", ["two-one", "two-two", "two-three"]]
);
});

test("array inside object", () => {
assert.equal(
patch({ main: ["one", "two"] }, [
{ path: ["main", 1], type: "CHANGE", value: "three" },
]),
{ main: ["one", "three"] }
);
});

test.run();
57 changes: 57 additions & 0 deletions tests/basic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { test } from "uvu";
import * as assert from "uvu/assert";
import patch from "../dist/index.js";

test("basic create patch", () => {
assert.equal(
patch({ test: true }, [{ path: ["test2"], type: "CREATE", value: "test" }]),
{
test: true,
test2: "test",
}
);
});

test("basic change patch", () => {
assert.equal(
patch({ test: true }, [{ path: ["test"], type: "CHANGE", value: false }]),
{
test: false,
}
);
});

test("basic remove patch", () => {
assert.equal(
patch({ test: true, bananas: true }, [{ path: ["test"], type: "REMOVE" }]),
{
bananas: true,
}
);
});

test("heavily nested patch", () => {
assert.equal(
patch(
{
test: true,
bananas: {
stock: {
geneva: true,
stockholm: false,
},
},
},
[{ path: ["bananas", "stock", "stockholm"], type: "REMOVE" }]
),
{
test: true,
bananas: {
stock: {
geneva: true,
},
},
}
);
});
test.run();
15 changes: 15 additions & 0 deletions tests/microdiff.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { test } from "uvu";
import * as assert from "uvu/assert";
import patch from "../dist/index.js";
import diff from "microdiff";

test("basic diff-patch", () => {
const obj1 = { one: true, two: true, three: false };
const obj2 = Object.assign({}, obj1);
obj2.one = false;
delete obj2.three;
obj2.four = true;
assert.equal(patch(obj2, diff(obj2, obj1)), obj1);
});

test.run();
11 changes: 11 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"files": ["index_old.tsd.ts"],
"buildOptions": {},
"compilerOptions": {
"outDir": "dist",
"declaration": true,
"target": "ES2020",
"moduleResolution": "node",
"module": "ES2020"
}
}

0 comments on commit 09e7380

Please sign in to comment.