Skip to content

Commit

Permalink
Stringsのリファクタ
Browse files Browse the repository at this point in the history
  • Loading branch information
h-sugawara committed Nov 24, 2023
1 parent 00d4892 commit 3d17235
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions lib/strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

const { getValidNumber } = require('./common');

function getStringSegmentOf(text) {
const segmentation = new Intl.Segmenter('ja', { granularity: 'grapheme' });
return [...segmentation.segment(text)];
}

function stringLength(text) {
if (typeof text !== 'string') {
throw new Error('text is not string type.');
}

const segmentation = new Intl.Segmenter('ja', { granularity: 'grapheme' });
return [...segmentation.segment(text)].length;
return getStringSegmentOf(text).length;
}

function getStartIndex(start, strLength) {
Expand All @@ -33,19 +37,14 @@ function stringSlice(text, start, end) {
const startIndex = getStartIndex(start, strLength);
const endIndex = getEndIndex(end, strLength);

let strings = '';

if (startIndex >= strLength || endIndex <= startIndex) {
return strings;
return '';
}
const segmentation = new Intl.Segmenter('ja', { granularity: 'grapheme' });
[...segmentation.segment(text)]
.forEach((value, index) => {
if (startIndex <= index && index < endIndex) {
strings += value.segment;
}
});
return strings;
return getStringSegmentOf(text)
.map((element, index) => {
return startIndex <= index && index < endIndex ? element.segment : '';
})
.join('');
}

module.exports = {
Expand Down

0 comments on commit 3d17235

Please sign in to comment.