Skip to content

Instantly share code, notes, and snippets.

@jonasantonelli
Created July 14, 2021 17:14
Show Gist options
  • Save jonasantonelli/e4235535e65a49c7b5271b107075eb04 to your computer and use it in GitHub Desktop.
Save jonasantonelli/e4235535e65a49c7b5271b107075eb04 to your computer and use it in GitHub Desktop.
Dictionaries.ts
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}) {
// TODO: implement this function from the above function definition.
const result = {}
Object.keys(dict).forEach(key => {
if (dict[key] !== 'object') {
result[key] = dict[key]
} else {
result[key] = deepCopy(dict[key])
}
}, {})
return result
}
}
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