From ba2751eae00c4bcf10403edbd549ca70dc316cab Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Mon, 21 Nov 2022 21:48:31 -0400 Subject: new "empty" sugar.js util --- src/util/sugar.js | 14 ++++++++++++++ src/util/urls.js | 1 + src/util/wiki-data.js | 16 ++++++++++------ 3 files changed, 25 insertions(+), 6 deletions(-) (limited to 'src/util') diff --git a/src/util/sugar.js b/src/util/sugar.js index c836d0ce..24ae8639 100644 --- a/src/util/sugar.js +++ b/src/util/sugar.js @@ -30,6 +30,20 @@ export function* splitArray(array, fn) { } } +// Null-accepting function to check if an array is empty. Accepts null (and +// treats as empty) as a shorthand for "hey, check if this property is an array +// with/without stuff in it" for objects where properties that are PRESENT but +// don't currently have a VALUE are null (instead of undefined). +export function empty(arrayOrNull) { + if (arrayOrNull === null) { + return true; + } else if (Array.isArray(arrayOrNull)) { + return arrayOrNull.length === 0; + } else { + throw new Error(`Expected array or null`); + } +} + // Sums the values in an array, optionally taking a function which maps each // item to a number (handy for accessing a certain property on an array of like // objects). This also coalesces null values to zero, so if the mapping function diff --git a/src/util/urls.js b/src/util/urls.js index 45ec4c85..d86c047d 100644 --- a/src/util/urls.js +++ b/src/util/urls.js @@ -11,6 +11,7 @@ // the domain of link.js. import * as path from 'path'; + import {withEntries} from './sugar.js'; export function generateURLs(urlSpec) { diff --git a/src/util/wiki-data.js b/src/util/wiki-data.js index 97ffab76..b0b0b2e0 100644 --- a/src/util/wiki-data.js +++ b/src/util/wiki-data.js @@ -2,6 +2,8 @@ // Utility functions for interacting with wiki data. +import {empty} from './sugar.js'; + // Generic value operations export function getKebabCase(name) { @@ -16,9 +18,11 @@ export function getKebabCase(name) { } export function chunkByConditions(array, conditions) { - if (array.length === 0) { + if (empty(array)) { return []; - } else if (conditions.length === 0) { + } + + if (empty(conditions)) { return [array]; } @@ -469,7 +473,7 @@ export function getNewAdditions(numAlbums, {wikiData}) { // Then cycle over that sorted array, adding one al8um from each to // the main array until we've run out or have met the target num8er // of al8ums. - while (groupArray.length) { + while (!empty(groupArray)) { let j = 0; while (j < groupArray.length) { const entry = groupArray[j]; @@ -485,10 +489,10 @@ export function getNewAdditions(numAlbums, {wikiData}) { break outerLoop; } - if (entry.length) { - j++; - } else { + if (empty(entry)) { groupArray.splice(j, 1); + } else { + j++; } } } -- cgit 1.3.0-6-gf8a5