Transform runs the passed function on all the elements in the Object and returns a new object without effecting original object. The function is invoked for key value pairs sorted by keys in ascending order. Example: object := NewObject(t, []interface{}{"x": "foo", "y": "bar"}) transformedObjec
(fn func(key string, value interface{}) interface{})
| 504 | // }) |
| 505 | // transformedObject.IsEqual([]interface{}{"x": "FOO", "y": "BAR"}) |
| 506 | func (o *Object) Transform(fn func(key string, value interface{}) interface{}) *Object { |
| 507 | opChain := o.chain.enter("Transform()") |
| 508 | defer opChain.leave() |
| 509 | |
| 510 | if opChain.failed() { |
| 511 | return newObject(opChain, nil) |
| 512 | } |
| 513 | |
| 514 | if fn == nil { |
| 515 | opChain.fail(AssertionFailure{ |
| 516 | Type: AssertUsage, |
| 517 | Errors: []error{ |
| 518 | errors.New("unexpected nil function argument"), |
| 519 | }, |
| 520 | }) |
| 521 | return newObject(opChain, nil) |
| 522 | } |
| 523 | |
| 524 | transformedObject := map[string]interface{}{} |
| 525 | |
| 526 | for _, kv := range o.sortedKV() { |
| 527 | transformedObject[kv.key] = fn(kv.key, kv.val) |
| 528 | } |
| 529 | |
| 530 | return newObject(opChain, transformedObject) |
| 531 | } |
| 532 | |
| 533 | // Find accepts a function that returns a boolean, runs it over the object |
| 534 | // elements, and returns the first element on which it returned true. |