Skip to content

Instantly share code, notes, and snippets.

@khades
Last active October 16, 2019 07:55
Show Gist options
  • Save khades/a1450536478d08bce34404aef9a48658 to your computer and use it in GitHub Desktop.
Save khades/a1450536478d08bce34404aef9a48658 to your computer and use it in GitHub Desktop.
function shallowClone(obj: any): any {
if (Array.isArray(obj)) {
return obj.slice();
}
return Object.assign({}, obj);
}
type Path = (number | string)[];
// set is immutable object modifier
// Logic is slightly different from "lodash/set"
// it DOESNT create new path if there's none
// if path does not exist on the object, it returns the same object.
// if path resolved path field is same as input value, returns the same object.
export default function set<T>(input: T, path: Path, value: any): T {
const newInput = shallowClone(input);
let currentObject = newInput;
const countTill = path.length - 1;
for (let index = 0; index < countTill; index++) {
const segment = path[index];
if (!currentObject[segment]) {
return input;
}
currentObject[segment] = shallowClone(currentObject[segment]);
currentObject = currentObject[segment];
}
if (Object.is(currentObject[path[countTill]], value)) {
return input;
}
currentObject[path[countTill]] = value;
return newInput;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment