dayphase
Version:
Determines the dayphase based on hour boundaries. It allows flexible time segmentation for different cultural or system-defined day phases.
74 lines (68 loc) • 2.18 kB
JavaScript
/* *******************************************************
* dayphase
*
* @license
*
* Apache-2.0
*
* Copyright 2015-2025 Alex Stevovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @meta
*
* package_name: dayphase
* file_name: src/index.js
* purpose: {{PURPOSE}}
*
* @system
*
* generated_on: 2025-03-15T05:55:23.877Z
* certified_version: 1.0.0
* file_uuid: 20cc4895-87f4-4045-83dc-4b7e9d310571
* file_size: 2178 bytes
* file_hash: aef7b316193eb3ba0a738e0efb36a0928478cef66d8eb35454139128925a957f
* mast_hash: e33e31aa9447acaf3dafcceaedec49debfe8fd092b26e6a40182b7fb2f390c94
* generated_by: preamble on npm!
*
* [Preamble Metadata]
********************************************************/
function dayphase(phases = [4, 17, 21], hour = new Date().getHours()) {
// Validate phases
if (
!Array.isArray(phases) ||
phases.length === 0 ||
phases.some((n) => n < 0 || n > 24)
) {
throw new Error(
'phases must be an ordered array of numbers between 0 and 24.',
);
}
// Validate hour
if (
typeof hour !== 'number' ||
!Number.isInteger(hour) ||
hour < 0 ||
hour > 24
) {
throw new Error('hour must be an integer between 0 and 24.');
}
// If hour is before the first phase OR after last phase, return 0
if (hour < phases[0] || hour > phases[phases.length - 1]) {
return 0;
}
// Find the correct phase index using findIndex (simpler than for-loop)
const index = phases.findIndex((phase) => hour < phase);
return index !== -1 ? index : phases.length - 1;
}
export default dayphase;