Last active
October 16, 2019 07:55
-
-
Save khades/a1450536478d08bce34404aef9a48658 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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