Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
SBT - SLR - Reduce, TypeOf, TernOp solution in Clear category for Sum by Type by Taylor_Page
import assert from "assert";
function sumByTypes(values: Array): [string, number] {
return values.reduce( ([s, n], v) =>
typeof v === "string" // check type
? [(s + v), n] // add v to strings s
: [ s, (n + v)], // add v to numbers n
["", 0] // default value array
)
}
console.log('Example:');
console.log(sumByTypes([]));
// These "asserts" are used for self-checking
assert.deepEqual(sumByTypes([]), ['', 0]);
assert.deepEqual(sumByTypes([1, 2, 3]), ['', 6]);
assert.deepEqual(sumByTypes(['1', 2, 3]), ['1', 5]);
assert.deepEqual(sumByTypes(['1', '2', 3]), ['12', 3]);
assert.deepEqual(sumByTypes(['1', '2', '3']), ['123', 0]);
assert.deepEqual(sumByTypes(['size', 12, 'in', 45, 0]), ['sizein', 57]);
console.log("Coding complete? Click 'Check' to earn cool rewards!");
July 9, 2020
Comments: