StructMap

This BIF will iterate over each key-value pair in the struct and invoke the callback function for each item so you can do any operation on the key-value pair and return a new value that will be set in a new struct.

The callback function will be passed the key, the value, and the original struct.

  • If the callback requires strict arguments, it will only receive the key and value.

  • If the callback does not require strict arguments, it will receive the key, value, and the original struct.

Parallel Execution

If the parallel argument is set to true, and no max_threads are sent, the map will be executed in parallel using a ForkJoinPool with parallel streams. If max_threads is specified, it will create a new ForkJoinPool with the specified number of threads to run the map in parallel, and destroy it after the operation is complete. Please note that this may not be the most efficient way to map, as it will create a new ForkJoinPool for each invocation of the BIF. You may want to consider using a shared ForkJoinPool for better performance.

Method Signature

StructMap(struct=[structloose], callback=[function:BiFunction], parallel=[boolean], maxThreads=[integer])

Arguments

Argument
Type
Required
Description
Default

struct

struct

true

The target struct to test

callback

function:BiFunction

true

The function used to produce the right-hand value assignment in the new struct. The function will be passed 3 arguments: the key, the value, the struct. You can alternatively pass a Java BiFunction which will only receive the first 2 args.

parallel

boolean

false

Whether to run the filter in parallel. Defaults to false. If true, the filter will be run in parallel using a ForkJoinPool.

false

maxThreads

integer

false

The maximum number of threads to use when running the filter in parallel. If not passed it will use the default number of threads for the ForkJoinPool. If parallel is false, this argument is ignored.

Examples

Script Syntax

Run Example

original = { 
	"one" : {
		1 : "tahi"
	},
	"two" : {
		2 : "rua"
	},
	"three" : {
		3 : "toru"
	},
	"four" : {
		4 : "wha"
	}
};

function mapOriginal( Any k, Any v ) {
	return v[ ListFirst( v.keyList() ) ];
}
fixed = structMap( original, mapOriginal );
writeDump( [
	original,
	fixed
] );

Using Member Function

Run Example

original = { 
	"one" : {
		1 : "tahi"
	},
	"two" : {
		2 : "rua"
	},
	"three" : {
		3 : "toru"
	},
	"four" : {
		4 : "wha"
	}
};
fixed = original.map( ( Any k, Any v ) => {
	return v[ ListFirst( v.keyList() ) ];
} );
writeDump( [
	original,
	fixed
] );

Additional Examples

Run Example

sct = structNew( "linked" );
sct.A = 1;
sct.B = 2;
sct.C = 3;
writedump( var=sct, label="original struct" );
// base test
res = StructMap( sct, ( Any key, Any value ) => {
	return key & ":" & value;
}, true );
writedump( var=res, label="mapped struct" );

Last updated

Was this helpful?