Disclosure

Most of the problems under my TypeHero Challenges folder were either obtained from typehero.dev or from type-challenges repo. Purpose of these articles are just to document my approaches for my easy reference. Please visit the respective links for more info.

Link to original

Problem Description

Find the elements in the target array that appear only once. For example:input: [1,2,2,3,3,4,5,6,6,6],ouput: [1,4,5].

Solutions

Approach 1: Loose equals

type Includes<Haystack extends any[], Needle> = Needle extends Haystack[number] ? true : false;
 
type FindEles<Suffix extends any[], Prefix extends any[] = [], Result extends any[] = []> =
	Suffix extends [infer First, ...infer Rest]
	?	Includes<[...Prefix, ...Rest], First> extends false
		? FindEles<Rest, [...Prefix, First], [...Result, First]>
		: FindEles<Rest, [...Prefix, First], Result>
	: Result;

Approach 2: Strict equals (Handles objects)

// type Equal = /* ... */
 
type IncludesStrict<Haystack extends any[], Needle> = Haystack extends [infer First, ...infer Rest]
	? Equal<First, Needle> extends true
		? true
		: IncludesStrict<Rest, Needle>
	: false
 
type FindEles<Suffix extends any[], Prefix extends any[] = [], Result extends any[] = []> =
	Suffix extends [infer First, ...infer Rest]
	?	IncludesStrict<[...Prefix, ...Rest], First> extends false
		? FindEles<Rest, [...Prefix, First], [...Result, First]>
		: FindEles<Rest, [...Prefix, First], Result>
	: Result;

TODO: There are more approaches to solving this in the Solutions tab.