JavaScriptใฎ้ ๅใ่ฆ็ด ใฎๅ ๅฎนใซๅฟใใฆใ2ใคใฎใฐใซใผใใซไปๅใ(partitioning)ใใๆนๆณใงใใ
ไธใฎไพใงใฏใ่ฆ็ด ใ็ฌใ็ซใใซใใฃใฆไปๅใใใฆใใพใ:
const pets = ['๐', '๐', '๐', '๐', '๐', '๐']
const [cats, dogs] = pets.reduce(
([cats, dogs], pet) =>
pet === '๐' ? [[...cats, pet], dogs] : [cats, [...dogs, pet]],
[[], []]
)
console.log(cats, dogs)
//=> [ '๐', '๐', '๐' ] [ '๐', '๐', '๐' ]
ใกใชใฟใซTypeScriptใงใฏreduce
ใฎๅๅผๆฐใซ[string[], string[]]
ใๆๅฎใใพใ:
const pets = ['๐', '๐', '๐', '๐', '๐', '๐']
const [cats, dogs] = pets.reduce<[string[], string[]]>(
([cats, dogs], pet) =>
pet === '๐' ? [[...cats, pet], dogs] : [cats, [...dogs, pet]],
[[], []]
)
console.log(cats, dogs)
ไป่จณๅฆ็ใๆฑ็จๅใใใจ:
const partition = (array, predicate) =>
array.reduce(
([left, right], value) =>
predicate(value) ? [[...left, value], right] : [left, [...right, value]],
[[], []]
)
const pets = ['๐', '๐', '๐', '๐', '๐', '๐']
const [cats, dogs] = partition(pets, value => value === '๐')
const partition = <
T extends ReadonlyArray<any>,
U extends T[number],
V extends Exclude<T[number], U>
>(
array: T,
predicate: (value: T[number]) => value is U
): [U[], V[]] =>
array.reduce(
([left, right], value) =>
predicate(value) ? [[...left, value], right] : [left, [...right, value]],
[[], []]
)
const pets = ['๐', '๐', '๐', '๐', '๐', '๐'] as const
const [cats, dogs]: ['๐'[], '๐'[]] = partition(pets, (value): value is '๐' => value === '๐')
ๆๅพใพใงใ่ชญใฟใใ ใใใใใใจใใใใใพใใใTwitterใงใฏใQiitaใซๆธใใชใๆ่กใใฟใชใฉใใใคใผใใใฆใใใฎใงใใใใฃใใใใฉใญใผใใฆใใใใใจๅฌใใใงใโTwitter@suin