-
-
Save Ridermansb/69d0ba505a95462ec6c41f8c81241649 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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