Skip to content

Latest commit

 

History

History
116 lines (99 loc) · 3.67 KB

identity-function.md

File metadata and controls

116 lines (99 loc) · 3.67 KB

Identity Function

An identity function is a function that returns the exact same value that it received as input:

//
export const identity<T> = (x: T) => x;

They're more commonly seen in functional programming than in imperative programming.

In imperative programming, we mainly see them used as a [no-op][No-Op] when dealing with mandatory dependencies.

For example:

type TransformFn = (x: any) => string;

function normaliseToString(transform: TransformFn, input: any, ...normalisers: Identity<string>) {
    // our return value
    let retval = transform(input);

    // apply the normalisers (if we have any)
    normalisers.forEach((fn) => { retval = fn(retval); });

    // all done
    return retval;
}

// if we want to use `normaliseToString()` with a string,
// we would use the `identity()` function:
normaliseToString(identity, "HELLO WORLD", String.toLowerCase);

Without the identity function, we'd have to write an if statement instead:

type TransformFn = (x: any) => string;

function normaliseToString(transform: TransformFn, input: any, ...normalisers: Identity<string>) {
    // our return value
    let retval: string;

    // make sure we have a string
    if (typeof input === string) {
        retval = input;
    } else {
        retval = transform(input);
    }

    // do the normalisation
    normalisers.forEach((fn) => { retval = fn(retval); });

    // all done
    return retval;
}