Skip to content

Commit

Permalink
feat: Update "count" to also work for strings and objects
Browse files Browse the repository at this point in the history
  • Loading branch information
andreidmt committed May 15, 2020
1 parent e76caae commit 1002075
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 14 deletions.
58 changes: 44 additions & 14 deletions src/count/count.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
import { isMatch } from "../is-match/is-match"

const byFn = fn => source => {
let _count = 0

for (let i = 0, length = source.length; i < length; i++) {
if (fn.call(null, source[i]) === true) {
_count = _count + 1
}
}

return _count
}

const byObject = source => {
let result = 0

let key

for (key in source) {
if (source.hasOwnProperty(key)) {
result = result + 1
}
}

return result
}

/**
* Count the number of elements that satisfies a function
*
Expand Down Expand Up @@ -29,20 +55,24 @@ import { isMatch } from "../is-match/is-match"
* count(element => element.score === 10)(scores)
* // => 2
*/
const count = fn =>
Array.isArray(fn)
? fn.length
: source => {
let _count = 0

for (let i = 0, length = source.length; i < length; i++) {
if (fn.call(null, source[i]) === true) {
_count = _count + 1
}
}

return _count
}
const count = fn => {
const type = Array.isArray(fn) ? "array" : typeof fn

switch (type) {
case "array":
case "string":
return fn.length

case "function":
return byFn(fn)

case "object":
return fn === null ? 0 : byObject(fn)

default:
return 0
}
}

const countWith = subset => count(isMatch(subset))

Expand Down
8 changes: 8 additions & 0 deletions src/count/count.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ import test from "tape"
import { count, countWith } from ".."

test("count(With)", t => {
t.equal(count("123"), 3, "Count chars in string")

t.equal(
count({ 1: "1", 2: "2", 3: "3" }),
3,
"Count key/value pairs in object"
)

t.equal(count([1, 2, 3]), 3, "Count items of array")

t.equal(
Expand Down

0 comments on commit 1002075

Please sign in to comment.