ReplaceModifiers returns a new map with applied modifier values based on the current record and the specified data. The resolved modifier keys will be removed. Multiple modifiers will be applied one after another, while reusing the previous base key value result (ex. 1; -5; +2 => -2). Note that b
(data map[string]any)
| 1358 | // // data: {"field+": 5} |
| 1359 | // // result: {"field": 15} |
| 1360 | func (m *Record) ReplaceModifiers(data map[string]any) map[string]any { |
| 1361 | if len(data) == 0 { |
| 1362 | return data |
| 1363 | } |
| 1364 | |
| 1365 | dataCopy := maps.Clone(data) |
| 1366 | |
| 1367 | recordCopy := m.Fresh() |
| 1368 | |
| 1369 | // key orders is not guaranteed so |
| 1370 | sortedDataKeys := make([]string, 0, len(data)) |
| 1371 | for k := range data { |
| 1372 | sortedDataKeys = append(sortedDataKeys, k) |
| 1373 | } |
| 1374 | sort.SliceStable(sortedDataKeys, func(i int, j int) bool { |
| 1375 | return len(sortedDataKeys[i]) < len(sortedDataKeys[j]) |
| 1376 | }) |
| 1377 | |
| 1378 | for _, k := range sortedDataKeys { |
| 1379 | field := recordCopy.SetIfFieldExists(k, data[k]) |
| 1380 | if field != nil { |
| 1381 | // delete the original key in case it is with a modifer (ex. "items+") |
| 1382 | delete(dataCopy, k) |
| 1383 | |
| 1384 | // store the transformed value under the field name |
| 1385 | dataCopy[field.GetName()] = recordCopy.Get(field.GetName()) |
| 1386 | } |
| 1387 | } |
| 1388 | |
| 1389 | return dataCopy |
| 1390 | } |
| 1391 | |
| 1392 | // ------------------------------------------------------------------- |
| 1393 |