All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.virtdata.libbasics.shared.from_long.to_long.Swap Maven / Gradle / Ivy

There is a newer version: 2.12.15
Show newest version
package io.virtdata.libbasics.shared.from_long.to_long;

import io.virtdata.annotations.Example;
import io.virtdata.annotations.ThreadSafeMapper;
import io.virtdata.libbasics.core.threadstate.SharedState;

import java.util.HashMap;
import java.util.function.LongFunction;
import java.util.function.LongUnaryOperator;

@ThreadSafeMapper
public class Swap implements LongUnaryOperator {

    private final String name;
    private final LongFunction nameGen;
    private final long defaultValue;

    @Example({"Swap('foo')","for the current thread, swap the input value with the named variable and returned the named variable."})
    public Swap(String name) {
        this.name = name;
        this.nameGen=null;
        this.defaultValue=0L;
    }

    @Example({"Swap('foo',234L)","for the current thread, swap the input value with the named variable and returned the named variable" +
            ",or the default value if the named variable is not defined."})
    public Swap(String name, long defaultValue) {
        this.name = name;
        this.nameGen=null;
        this.defaultValue=defaultValue;
    }

    @Example({"Swap(NumberNameToString())","for the current thread, swap the input value with the named variable and returned the named variable" +
            ", where the variable name is generated by the provided function."})
    public Swap(LongFunction nameFunc) {
        this.name=null;
        this.nameGen=nameFunc;
        defaultValue=0L;
    }

    @Example({"Swap(NumberNameToString(), 234L)","for the current thread, swap the input value with the named variable and returned the named variable" +
            ", where the variable name is generated by the provided function" +
            ", or the default value if the named variable is not defined."})
    public Swap(LongFunction nameFunc, long defaultValue) {
        this.name=null;
        this.nameGen=nameFunc;
        this.defaultValue=defaultValue;
    }

    @Override
    public long applyAsLong(long input) {
        HashMap map = SharedState.tl_ObjectMap.get();
        String varname=(nameGen!=null) ? nameGen.apply(input) : name;

        long output = map.containsKey(varname) ? (long) map.get(varname) : defaultValue;
        map.put(varname,input);

        return output;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy