「JavaScript/Set」の版間の差分

削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
init.
タグ: 2017年版ソースエディター
 
Ef3 (トーク | 投稿記録)
タグ: 2017年版ソースエディター
11 行
Setオブジェクトにはリテラルはありません。
 
=== コード例 ===
JavaScriptのSetオブジェクトの要素のデータ型に関して制約がありません。
;[https://paiza.io/projects/xMVHzYIUhKz87MqhdPgqDQ?language=javascript コード例]:<syntaxhighlight lang="javascript">
const set1 = new Set() ; console.log(set1)
57 行
</syntaxhighlight>
:存在しない要素をdeleteしても例外は上がりません。
:Setオブジェクトは集合ですが、JavaScriptは演算子オーバーロードはできないので集合同士に比較演算子は適用できません。
:また、集合演算に対応しておらず、和集合(union)・積集合(intersection)・差集合(difference)・部分集合か判定(issubset)・上位集合(issuperset)・排他判定(isdisjoint)などのメソッド用意されていません<ref>{{Cite web
|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
|title=Set - JavaScript // MDN
63 ⟶ 64行目:
|accessdate=2021/12/26
}}</ref>。
 
=== Polyfill ===
集合演算関係のメソッド追加提案は既にTC39に提出されていますが<ref>{{Cite web
|url=https://tc39.es/proposal-set-methods/
|title=New Set methods
|date=2019
|accessdate=2021/12/26
}}</ref>、参考までに Polyfill を書いてみました。
;[https://paiza.io/projects/Zx6wmzOUm7IMcltSD14Cug?language=javascript Polyfill]:<syntaxhighlight lang="javascript">
Object.entries({
filter: function(callback, thisArg) {
if ( !typeof callback === 'function' )
throw new TypeError();
 
const result = new Set()
if (thisArg === 'undefined')
thisArg = this
for (const x of this)
if (callback.call(thisArg, x))
result.add(x)
return result },
map: function(callback, thisArg) {
if ( !typeof callback === 'function' )
throw new TypeError();
 
const result = new Set()
if (thisArg === 'undefined')
thisArg = this
for (const x of this)
result.add(callback.call(thisArg, x))
return result },
reduce: function(callback, initial) {
if ( !typeof callback === 'function' )
throw new TypeError();
let result = initial
for (const x of this) {
if (result === 'undefined')
result = x
else
result = callback(result, x, this)
}
return result },
union: function(other) {
const result = new Set(this)
for (const x of other) {
result.add(x)
}
return result },
intersection: function(other) {
return this.filter(e => (other.has(e))) },
difference: function(other) {
return this.filter(e => (!other.has(e))) },
superset_p: function(other) {
for (let elem of other) {
if (!this.has(elem)) {
return false
}
}
return true },
subset_p: function(other) {
return other.superset_p(this) },
}).forEach(pair => {
Object.defineProperty(Set.prototype, pair[0], {
value: pair[1]
})
})
 
let a = new Set([0,1,2]),
b = new Set([2,3,4]),
c = new Set([0,1,2,3,4,5,6])
console.log("a = ", a, ", b = ",b),
console.log(a.filter(x => x % 2))
console.log(a.filter(x => x % 2, b))
console.log(a.union(b))
console.log(a.intersection(b))
console.log(a.difference(b))
console.log(a.superset_p(c))
console.log(a.subset_p(c))
</syntaxhighlight>
;実行結果:<syntaxhighlight lang="text">
a = Set(3) { 0, 1, 2 } , b = Set(3) { 2, 3, 4 }
Set(1) { 1 }
Set(1) { 1 }
Set(5) { 0, 1, 2, 3, 4 }
Set(1) { 2 }
Set(2) { 0, 1 }
false
true
</syntaxhighlight>
 
=== プロパティ ===