Skip to content

Instantly share code, notes, and snippets.

@Ridermansb
Forked from burtonator/Dictionaries.ts
Last active July 5, 2021 12:04
Show Gist options
  • Save Ridermansb/69d0ba505a95462ec6c41f8c81241649 to your computer and use it in GitHub Desktop.
Save Ridermansb/69d0ba505a95462ec6c41f8c81241649 to your computer and use it in GitHub Desktop.
import {assert} from 'chai';
export namespace Dictionaries {
/**
* Create a deep copy of a dictionary such that all of the origina keys are maintained
* and copied into a new dictionary.
*
* This is used when we have to create a copy of a dictionary to prevent concurrent mutation
* or when we need to copy it and then make changes to the new dictionary.
*
* The values in the map could be arrays, other dictionaries, sets, maps, strings, arrays, etc.
*
* Make sure to handle all cases.
*
* This needs to be fully recursive including dictionaries contain other dictionaries
* and arrays.
*/
export function deepCopy(dict: {[key: string]: any}) {
return JSON.parse(JSON.stringify(dict));
}
}
describe("Dictionaries", function() {
// TODO: make sure all of the following tests pass with your new code.
it("basic tests", function() {
const dict: any = {
"hello: "world"
};
const copy = Dictionaries.deepCopy(dict);
assert.deepEqual(dict, copy);
});
it("basic integrity", function() {
const dict: any = {
"hello: "world"
};
const copy = Dictionaries.deepCopy(dict);
dict['foo'] = 'bar';
assert.deepEqual(copy, {
"hello: "world"
});
});
it("inner integrity", function() {
const dict: any = {
"hello: "world",
"inner": {
"foo": "bar"
}
};
const copy = Dictionaries.deepCopy(dict);
dict['inner']['foo'] = 'cat';
assert.deepEqual(copy, {
"hello: "world",
"inner": {
"foo": "bar"
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment