Count string elements
Source
Source: Adapted from Jeffrey Hu, Python programming exercises, Question 13
Description
Count letters and digits.
Given a string, return an array containing counts of
letters and digits, in the format [ls, ds]
.
1
'hello world! 123' ⟹ [10, 3]
My solution
1
2
3
4
5
6
7
8
9
10
11
const isAlpha = s => /^[a-zA-Z]+$/.test(s);
const isNumeric = s => /^[0-9]+$/.test(s);
const countLd = s => [
[...s].filter(isAlpha).length,
[...s].filter(isNumeric).length
];
module.exports = {countLd};
Tests
1
2
3
4
5
6
7
8
9
const assert = require('assert')
, countLd = require('./countLd.js').countLd;
describe('countLd()', function() {
it('should return the correct counts', function() {
const s = 'hello world! 123';
assert.deepEqual(countLd(s), [10, 3]);
});
});