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】数値範囲による分岐2

Posted at

【JavaScript】数値範囲による分岐
過去に書いた記事のコードを少しスッキリ(?)させただけです。

コード


//Object.entriesだけでも動作はする
const generations = new Map(Object.entries({
	12: 'under 12',
	20: 'teenager',
	30: '20s',
	40: '30s',
	50: '40s',
	60: '50s',
	70: '60s',
	80: '70s',
	90: '80s',
	100: '90s',
}));

const getGeneration = age => {
	if (!Number.isFinite(age) || age < 0) return; 
	
	for (const [key, value] of generations) {
		if (age < key) return value;
	}
	
	return 'over 100';
};

console.log( getGeneration(-1) );		// undefined
console.log( getGeneration('14') );		// undefined
console.log( getGeneration(14) );		// 'teenager'
console.log( getGeneration(28) );		// '20s'
console.log( getGeneration(200) );		// 'over 100'

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?