0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【javascript】Symbol()を使ってfilterMap()

Last updated at Posted at 2021-05-14

#前置き

前回

フィルタでfalsyな要素はSymbol('ignore')を返すようにする。

#function

const APPS = {
	ignore: Symbol('ignore'),
	filterMap: (array, func) => {
		const arr = array.slice();
		const res = [];
		for (let i=0,len=arr.length; i<len; i++) {
			const v = func(arr[i], i, arr);
			if (v!==APPS.ignore) res.push(v);
		}
		return res;
	}
};

const arr = [...Array(10).keys()];
const chunk = APPS.filterMap(arr, (x,i,a) => i%3===0 ? a.slice(i,i+3) : APPS.ignore);
console.log( chunk );	//[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

これもdefinePropertyを使って設定したほうが良かったかも?

const APPS = {
	ignore: Symbol('ignore')
};
Object.defineProperties(APPS, {
	ignore: {
		writable: false,
	},
	filterMap: {
		value: (array, fn) => {
			const arr = array.slice();
			const res = [];
			for (let i=0,len=arr.length; i<len; i++) {
				const v = fn(arr[i], i, arr);
				if (v!==APPS.ignore) res.push(v);
			}
			return res;
		},
	},
});

#Array.prototype

if (!Array.prototype.filterMap && !this.ignore) {
	Object.defineProperty(Array.prototype, 'filterMap', {
		value: function(fn) {
			const arr = this;
			const res = [];
			for (let i=0,len=arr.length; i<len; i++) {
				const v = fn(arr[i], i, arr);
				if (v!==ignore) res.push(v);
			}
			return res;
		},
	});
	const ignore = Symbol('ignore');
	Object.defineProperty(this, 'ignore', {
		get() {
			return ignore;
		}
	});
};

const arr = [...Array(10).keys()];
const chunk = arr.filterMap((x,i,a) => i%3===0 ? a.slice(i,i+3) : ignore);
console.log( chunk );	//[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

ignorethis.ignoreではなくArray内部に留めたかったけど、しっくりこなかった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?