How to create function which gives 4 digits unique number for setting the SKU in Item record ( Any number between 1-9999 )

Solution:

    function getRandomNumberForKit() {
        var randomChars = '0123456789';
        do {
            var result = '';
            for (var i = 0; i < 4; i++) {
                result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
            }
            log.debug('getRandomString', result);
            var check = checkUnique(result);
        }
        while (check.length != 0);
        return result;
    }


    function checkUnique(itemId) {
        var returnValue = '';
        var itemSearchObj = search.create({
            type: "item",
            filters:
                [
                    ["name", "haskeywords", itemId]
                ],
            columns:
                [
                    "internalid"
                ]
        });

        var myPagedData = itemSearchObj.runPaged();
        myPagedData.pageRanges.forEach(function (pageRange) {
            var myPage = myPagedData.fetch({
                index: pageRange.index
            });
            myPage.data.forEach(function (result) {
                returnValue = result.getValue('internalid');
            });
        });
        log.debug('checkUnique', returnValue);
        return returnValue;
    }

Leave a comment

Your email address will not be published. Required fields are marked *