codelist-diff
v1.0.2
Published
Library for creating small for making small diffs between CodeList arrays fast.
Readme
codelist-diff
Library for diffing CodeList tables which are defined like this:
interface CodeItem {
code: number | string;
category: string;
}
type CodeList = CodeItem[];Each code-value must be unique within a CodeList.
Install
Install the current version (and save it as a dependency):
$ npm install codelist-diff --saveUsage
const CodelistDiff = require("codelist-diff");
const arr1 = [
{
code: 2,
category: "Category 2"
},
{
code: 1,
category: "Category 1"
}
]
const arr2 = [
{
code: 1,
category: "Category 1"
},
{
code: 2,
category: "Category 2"
}
{
code: 3,
category: "Category 2"
}
]
const delta = CodeListDiff.diff(arr1, arr2);
const arr = CodeListDiff.patch(arr1, delta); // arr is now equal to arr2It is also possible to add a metadata prop as the 3rd parameter to the diff function. The metadata object will be part of the error thrown if duplicate code-values are detected.
interface Metadata {
prev: {
name: string;
index: number;
},
current: {
name: string;
index: number;
}
}
export function diff(prev: CodeItem[], current: CodeItem[], metadata?: Metadata): Delta
export function patch(prev: CodeItem[], delta: Delta)The format of the delta object returned by the diff function
// Operations should be performed in the order shown in this interface
export interface Delta {
/**
* Remove items at these index positions
*/
remove: number[];
/**
* For each index position replace the value with the specified CodeItem
*/
replace: { [index: number]: CodeItem };
/**
* Reorder by replacing values. Every 2 items are a pair: [v1a, v1b, v2a, v2b, ...]
* v1a: The index in the current array that needs to be replaced
* v1b: The index in the unmodified prev array to get the new item from
*/
reorder: number[];
/**
* For each index position the specified CodeItem should be inserted
*/
insert: { [index: number]: CodeItem };
}