File size: 2,074 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import flat from 'flat'

import { DELIMITER } from './constants.js'
import { FlattenParams } from './flat.types.js'
import { propertyKeyRegex } from './property-key-regex.js'
import { pathToParts } from './path-to-parts.js'

const isObject = (value: any): boolean => {
  // Node environment
  if (typeof File === 'undefined') {
    return typeof value === 'object' && value !== null
  }
  // Window environment
  return typeof value === 'object' && !(value instanceof File) && value !== null
}

/**
 * @load ./set.doc.md
 * @memberof module:flat
 * @param {FlattenParams} params
 * @param {string} propertyPath
 * @param {any} [value]       if not give function will only try to remove old keys
 * @returns {FlattenParams}
 */
const set = (params: FlattenParams = {}, propertyPath: string, value?: any): FlattenParams => {
  const regex = propertyKeyRegex(propertyPath)

  // remove all existing keys
  const paramsCopy = Object.keys(params)
    .filter((key) => !key.match(regex))
    .reduce((memo, key) => {
      memo[key] = params[key]

      return memo
    }, {} as FlattenParams)

  if (typeof value !== 'undefined') {
    if (isObject(value) && !(value instanceof Date)) {
      const flattened = flat.flatten(value) as any

      if (Object.keys(flattened).length) {
        Object.keys(flattened).forEach((key) => {
          paramsCopy[`${propertyPath}${DELIMITER}${key}`] = flattened[key]
        })
      } else if (Array.isArray(value)) {
        paramsCopy[propertyPath] = []
      } else {
        paramsCopy[propertyPath] = {}
      }
    } else {
      paramsCopy[propertyPath] = value
    }

    // when user gave { "nested.value": "something" } and had "nested" set to `null`, then
    // nested should be removed
    const parts = pathToParts(propertyPath).slice(0, -1)
    if (parts.length) {
      return Object.keys(paramsCopy)
        .filter((key) => !parts.includes(key))
        .reduce((memo, key) => {
          memo[key] = paramsCopy[key]

          return memo
        }, {} as FlattenParams)
    }
  }
  return paramsCopy
}

export { set }