-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.ts
26 lines (24 loc) · 886 Bytes
/
set.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { copy } from './copy';
import { curry } from './curry';
interface SetFn {
(path: string | string[]): <B extends object>(value: unknown, source: B) => B;
<B extends object>(path: string | string[], value: unknown): (source: B) => B;
<B extends object>(path: string | string[], value: unknown, source: B): B;
}
/**
* https://github.com/fwilkerson/clean-set
*
* TODO: adicionar documentação
*/
export const set = curry((path: any, value: any, source: any) => {
typeof path === 'string' && (path = path.split(/[\]\.\[]/).filter(Boolean));
const src = copy(source);
let val = src;
for (let i = 0; i < path.length; i++) {
// prettier-ignore
val = val[path[i]] = i === path.length - 1
? typeof value === 'function' ? value(val[path[i]]) : value
: val[path[i]] ? copy(val[path[i]]) : path[i+1]*0 === 0 ? [] : {};
}
return src;
}) as SetFn;