回答編集履歴

1

コメントを受けてAnswer書き直しました。

2018/05/12 15:13

投稿

set0gut1
set0gut1

スコア2413

test CHANGED
@@ -1,10 +1,14 @@
1
- 最初のコードの `return _.includes(word, descword);` を `return word.indexOf(descword) === 0` に置換えると意図通りになるように見え
1
+ Answer直しした
2
2
 
3
3
 
4
4
 
5
5
  ```javascript
6
6
 
7
+ const _ = require('lodash')
8
+
9
+
10
+
7
- function filterBydesc3 (value) {
11
+ function filterBydesc (value) {
8
12
 
9
13
  return value == ''
10
14
 
@@ -14,7 +18,13 @@
14
18
 
15
19
  var ranges = {
16
20
 
17
- 1: { desc: 'いうえお' }
21
+ 1: { desc: 'いう' },
22
+
23
+ 2: { desc: 'うえ' },
24
+
25
+ 3: { desc: 'かい' },
26
+
27
+ 4: { desc: '^あい' } // <---- 条件追加しました。
18
28
 
19
29
  }
20
30
 
@@ -24,7 +34,7 @@
24
34
 
25
35
  return _.some(item.desc, function (word) {
26
36
 
27
- return word.indexOf(descword) === 0
37
+ return !!word.match(descword) // <---- ここを書き換えました。
28
38
 
29
39
  })
30
40
 
@@ -34,4 +44,52 @@
34
44
 
35
45
  }
36
46
 
47
+
48
+
49
+ /* 動作確認用 */
50
+
51
+ console.log(filterBydesc('1')({ desc: { word: 'あいうえお' } })) // true
52
+
53
+ console.log(filterBydesc('2')({ desc: { word: 'あいうえお' } })) // true
54
+
55
+ console.log(filterBydesc('3')({ desc: { word: 'あいうえお' } })) // false
56
+
57
+
58
+
59
+ /* 本題 */
60
+
61
+ console.log(filterBydesc('4')({ desc: { word: 'あいうえお' } })) // true
62
+
63
+ console.log(filterBydesc('4')({ desc: { word: '___あいうえお' } })) // false
64
+
37
65
  ```
66
+
67
+
68
+
69
+ `_.includes('foobar', 'foo')`は単に true か false を返すので、このケースでは lodash にこだわる必要なさそうでした。
70
+
71
+ `'foobar'.match('^foo')`とすると正規表現込みのマッチングが行われるので、これを使うと良いと思います。
72
+
73
+
74
+
75
+ ```javascript
76
+
77
+ 'foobar'.match('^foo') // [ 'foo', index: 0, input: 'foobar' ]
78
+
79
+ '___foobar'.match('^foo') // null
80
+
81
+ ```
82
+
83
+
84
+
85
+ このままだと返す値が若干怪しいので、`!!`を適用して true か false にしてから返すと良いと思いました。
86
+
87
+
88
+
89
+ ```javascript
90
+
91
+ !!'foobar'.match('^foo') // true
92
+
93
+ !!'___foobar'.match('^foo') // false
94
+
95
+ ```