hegel icon indicating copy to clipboard operation
hegel copied to clipboard

How to write a clone function?

Open mohsen1 opened this issue 5 years ago • 5 comments

I would like to scope this only to arrays for now. How do I write a clone function that clones tuples and arrays while preserving types?

I get an array type back with this:

function clone<T>(arr:T): T {
    return [].concat(arr)
}

let cloned = clone([1,2,3])

mohsen1 avatar May 26 '20 17:05 mohsen1

this works

function clone<T>(arr: Array<T>): Array<T> {
    return Array.from(arr)
}

let cloned = clone([1, 2, 3])

try

but i don't think you can copy tuples for now

also concat on empty array should work i guess

thecotne avatar May 26 '20 18:05 thecotne

But the problem exists in the type inference algorithm. Will try to fix it.

JSMonk avatar May 26 '20 19:05 JSMonk

Interestingly, this simply crashes:

function clone<T>(arr: Array<T>): Array<T> {
    const array: Array<T> = Array.from(arr);
    return array;
}

vkurchatkin avatar May 27 '20 14:05 vkurchatkin

Fixed. And will be available in the next release. Thank you for the issue :3

JSMonk avatar Aug 18 '20 03:08 JSMonk


// Could not deduce type "(ArrayLike<T> | Iterable<T>) => Array<T>" arising from the arguments unknown,(ArrayLike<T> | Iterable<T>) => Array<T>.
// Please, provide type parameters for the call or provide default type value for parameters
// of "<T>(T, T) => T" function.
// WAT??
const clone01 = arr => Array.from(arr)

// (ArrayLike<T> | Iterable<T>) => Array<T>
// this is same but works
function clone01_1(arr) {
    return Array.from(arr)
}


// <T>(T) => $Immutable<Array<T | unknown>>
// this one looks wrong
const clone02 = arr => [].concat(arr)

try

thecotne avatar Aug 18 '20 10:08 thecotne